andrey.cpcm#
- andrey.cpcm(data, *, alpha=None, family='gaussian', seed=None)[source]#
Test the direction of a variable pair with CPCM, a conditionally parametric causal model.
CPCM [1] models the effect given its cause by a known parametric family whose parameters are smooth functions of the cause, such as a Gaussian whose mean and scale change with it, an exponential or Pareto law whose rate does, or a Poisson count. In each direction it fits the family and maps each value through the fitted distribution function; that residual is independent of the cause only in the causal direction, which an HSIC test [2] checks.
- Parameters:
data (
ArrayLike) – The two variables, one per column: column 0 isxand column 1 isy. Coerced tofloat64. A DataFrame’s column names become the structure’slabels.alpha (
float|None) –Nonechooses the direction with the larger p-value, or with the smaller test statistic when the p-values are equal (the paper’s forced estimate). A significance level such as0.05gives no edge when the two columns test independent at that level, and otherwise draws an edge only when exactly one direction’s p-value exceeds it (the paper’s conservative estimate). See Notes.family (
str|list[str]) – The family of each variable given the other, one name for both columns or a list of two names, one per column:"gaussian"(mean and scale change with the cause),"gaussian_fixed_scale"(the mean alone),"exponential","pareto"(scale 1, values of at least 1),"poisson","gamma"(mean and shape),"gamma_fixed_shape"(the mean alone),"gumbel"(location and scale),"gumbel_fixed_scale"(the location alone), or"negative_binomial"(the mean, one size for all rows). See Families. in Notes.seed (
int|None) –None, the default, is the configured seed,ANDREY_SEEDor0when it is unset, not a fresh random one, so a fit repeats. Seed for the random draws of the count families,"poisson"and"negative_binomial"; the other families draw nothing.
- Returns:
Contains a two-node
GraphStructureof kinddagwith the chosen edge, or no edge.metadata["algorithm"]is"cpcm".metadata["p_values"]holds the p-value of the test ofy’s residual againstx(x -> y) under"forward"and ofx’s residual againstyunder"backward";metadata["statistics"]holds the HSIC statistics of the same two tests, each divided by its mean under independence, under the same keys.metadata["independence_p_value"]is the p-value of the test thatxandyare independent, andmetadata["families"]the family of each column.- Return type:
- Raises:
TypeError – If an argument has the wrong type, such as a string for a number; the message names the method, the argument, what it accepts, and the value.
ValueError – If an argument lies outside its range or is not one of its choices; the message names the method, the argument, what it accepts, and the value. Also if
datadoes not have 2 columns, holdsNaNorinf, or has fewer than 20 rows, iffamilynames an unknown family or does not give one name per column, or if a column holds a value outside its family’s support, such as a non-integer under"poisson"or a value below 1 under"pareto". Also if a column’s residual is the same on every row, as when the column is an exact function of the other, or if a fit ends away from a maximum; the message names the columns.
- Warns:
ExperimentalWarning – On the first call in a process: the method is not supported (see Limitations), and its API may change without deprecation.
DataTypeWarning – When a column holds at most 10 distinct whole numbers and so may hold category codes, which the fit reads as numbers. Each message warns once per process.
Notes
When to use. CPCM decides the direction between two variables observed i.i.d. when the effect given its cause follows a known parametric family, with no hidden common cause of the two [1]. The direction is identifiable outside special cases tied to the family’s sufficient statistics: under the Gaussian family with mean
mu(x)and scalesigma(x), unless1 / sigma^2is quadratic andmu / sigma^2linear in the cause with a matching cause density; under a one-parameter exponential family, unless the parameter is linear in the sufficient statistic [1]. It is designed for effects whose whole distribution, not only the mean and spread, changes with the cause, such as counts, positive or heavy-tailed effects, and for mixed pairs where each column gets its own family. For an effect with additive noise useanm(); for more than two variables,cpcm_graph().In each direction the effect’s family is fitted on the cause and each value mapped through its fitted distribution function,
eps = F(y; theta(x)). A count family’s function is randomized between its steps,F(y - 1) + u f(y)withuuniform, so the residual is continuous. The residual is tested against the proposed cause by the gamma HSIC test with Gaussian kernels whose bandwidth is the median heuristic over all rows [2] [3]. Withalpha=Nonethe larger p-value, compared through their logarithms, names the direction, and on equal p-values the smaller statistic, with no edge when those are equal too, two values equal when they differ by at most1e-9times the larger of 1 and their absolute values. With a level, the pair is first tested for independence, which gives no edge, and an edge is drawn only when exactly one direction’s residual tests independent; both or neither give no edge, which the paper reads as an unidentifiable pair or a family that fits neither way [1].Families. Each parameter is a smooth function of the cause through the family’s usual link: the identity for a Gaussian or Gumbel location, the logarithm for a scale, a mean, a rate, or a shape.
"pareto"is the Pareto law of scale 1, whose logarithm is exponential, so its column must hold values of at least 1; the paper calls"gamma_fixed_shape"the gamma family with a fixed scale, the scale of its fitting software, which is one over the shape. The paper advises families with the same number of parameters in both directions, since the more flexible one fits either way more often [1]. A family applies to the column when it is the effect; the cause’s own distribution is not modeled.Estimation. Each parameter is a constant plus a rank-10 thin plate regression spline of the cause, as in [1], or indicators when the cause holds at most 9 distinct values, as in the authors’ code. The coefficients maximize the log-likelihood penalized by the spline’s wiggliness, and the smoothing parameter of each spline maximizes the Laplace approximate marginal likelihood [4], the estimator the paper cites, over a lattice of steps of 1/16 in its logarithm around a start that follows the data. A scale fitted as a function of the cause stays above a floor, without which the likelihood has no maximum where the location fits a row exactly: 0.01 of the column’s standard deviation under
"gaussian",exp(-7)of it under"gumbel", and a dispersion ofexp(-7)under"gamma". Such a scale approaches the floor without reaching it, so rows on which it falls to withinexp(-12)of the floor are held at the floor itself, outside the fit and its Laplace determinant; the rows of one cause value share their scale and are held together. Likewise, under a count family the mean of a cause value whose counts are all 0 is 0, and those rows leave the fit, their residual a uniform draw. The size of"negative_binomial"has an upper bound ofexp(5)times the column’s largest count, kept betweenexp(12)andexp(20); a size at that bound is read as the Poisson limit, whose variance is then within 1 part in 148 for counts up toexp(15), about 3.3 million, and less close above. A fit that ends away from a maximum, or at a point where the coefficients are not determined to working precision, raisesValueError. The fit draws no random numbers except a count family’s uniforms, which followseedand the column’s values.Units. A column in other units stays in the Gaussian, Gumbel, exponential, and gamma families, so under them the result is the same in any units, to rounding. The Gaussian and Gumbel families do not depend on the column’s origin either; the exponential and gamma families do, since their support starts at 0.
"pareto", whose scale is fixed at 1, and the count families, whose values step by 1, read the units: the same column in other units is another model there, or fails the support check. The cause’s units never matter: its spline is the same in any unit.Missing values. A
NaNindataraisesValueError: every fit reads every row of both columns, so a row with a missing value has no place in it. Drop the incomplete rows first, which suits values missing completely at random, or usepc()orfci(), whose tests delete rows per test.Limitations. Not benchmarked yet. Each HSIC test builds matrices with one row and one column per sample, so time and memory grow with the square of
n_samples. Under the count families the rank-10 spline must follow the mean to within the counts’ own noise, about1 / sqrt(mean)of it, which it does for means up to a few hundred: from means of a few thousand that vary strongly with the cause, the true direction’s test rejects too. The family must be chosen: the paper’s rule that picks one from each column’s support, and its sequential choice between one- and two-parameter families, are not offered. The numbers are a reference, not a hard limit: they change with the data generator, the density, the method’s settings, and the machine.References
Examples
>>> import numpy as np >>> from andrey import cpcm >>> rng = np.random.default_rng(0) >>> x = rng.normal(0, 1.4, 400) >>> y = rng.poisson(np.exp(1 + np.sin(2 * x))) >>> family = ["gaussian_fixed_scale", "poisson"] >>> out = cpcm(np.column_stack([x, y]), family=family, seed=0) >>> out.structure.oriented_edges() [(0, 1, 'directed')]