Package {arcstat}


Type: Package
Title: Arc-Length Statistics, Equivalence Families and Induction Curves
Version: 0.4.0
Description: Inference from the arc length of statistical functions, and the curves of the induction-period standards. A goodness-of-fit test based on the arc length of the probability plot with an analytic saddlepoint null; distributions built from the arc length of their defining curve, estimated by L-moments; the characteristic-function arc length; a Bayesian nonparametric arc-length test; the equivalence families of the four-parameter kappa distribution of Hosking (1994) <doi:10.1147/rd.383.0251> and of the beta-companion family, on which the two standard induction-period readings coincide; and batched fits, bootstraps and permutation tests of induction curves. One pure-C back-end, parallel by 'OpenMP', serves this package and the 'Python' package 'arcstat'.
URL: https://github.com/mtloots/arcstat
BugReports: https://github.com/mtloots/arcstat/issues
License: GPL-3
Encoding: UTF-8
Language: en-GB
Imports: stats
NeedsCompilation: yes
Config/roxygen2/version: 8.0.0
Config/testthat/edition: 3
Suggests: MASS, knitr, rmarkdown, testthat (≥ 3.0.0)
VignetteBuilder: knitr
Packaged: 2026-11-27 08:21:54 UTC; home
Author: M. Theodor Loots ORCID iD [aut, cre]
Maintainer: M. Theodor Loots <theo.loots@gmail.com>
Repository: CRAN
Date/Publication: 2026-11-27 15:40:35 UTC

arcstat: Arc-Length Statistics, Equivalence Families and Induction Curves

Description

Inference from the arc length of statistical functions, and the curves of the induction-period standards. A goodness-of-fit test based on the arc length of the probability plot with an analytic saddlepoint null; distributions built from the arc length of their defining curve, estimated by L-moments; the characteristic-function arc length; a Bayesian nonparametric arc-length test; the equivalence families of the four-parameter kappa distribution of Hosking (1994) doi:10.1147/rd.383.0251 and of the beta-companion family, on which the two standard induction-period readings coincide; and batched fits, bootstraps and permutation tests of induction curves. One pure-C back-end, parallel by 'OpenMP', serves this package and the 'Python' package 'arcstat'.

Author(s)

Maintainer: M. Theodor Loots theo.loots@gmail.com (ORCID)

Authors:

See Also

Useful links:


Band arc length of the normal reference curve (C back-end)

Description

Band arc length of the normal reference curve (C back-end)

Usage

al_band_model(sigma, a = 0.05, b = 0.95, nodes = 400L)

Arguments

sigma

scale of the normal reference;

a, b

the probability band;

nodes

quadrature panels.

Value

the model band arc length.

Examples

## the normal reference band arc length grows with the scale
al_band_model(c(0.5, 1, 2))

Spacing-corrected model band arc length (C back-end)

Description

The sample band arc length does not converge to the population band arc length al_band_model. Consecutive order statistics inside the band are spaced like Q'(u)E/n with E standard exponential, so the polygonal sum converges instead to

S^*(\sigma) = \int_{z_a}^{z_b} E\sqrt{f_0(z)^2 + \sigma^2 E^2}\,dz = E\,S(\sigma E),

which differs from S(\sigma) by a constant factor because the square root is nonlinear and E[E^2] = 2. The gap does not close as the sample grows. This is the functional al_scale matches, and matching to it is what makes that estimator consistent.

Usage

al_band_model_star(sigma, a = 0.05, b = 0.95, nodes = 400)

Arguments

sigma

scale at which to evaluate the model band length.

a, b

the probability band.

nodes

number of Simpson nodes across the band; the exponential expectation uses a 64-point Gauss-Laguerre rule, which is exact to machine precision for this integrand.

Value

the spacing-corrected model band arc length at sigma.

Examples

al_band_model_star(1, 0.1, 0.9)

Sample band arc length of the empirical distribution curve (C back-end)

Description

Sample band arc length of the empirical distribution curve (C back-end)

Usage

al_band_sample(x, a = 0.05, b = 0.95)

Arguments

x

data;

a, b

the probability band.

Value

the sample band arc length, NA when fewer than two points fall in the band.

Examples

set.seed(1)
al_band_sample(rnorm(400, sd = 2))

Exact mean, variance and support of the arc-length statistic (C back-end)

Description

Exact mean, variance and support of the arc-length statistic (C back-end)

Usage

al_moments(n)

Arguments

n

sample size.

Value

list with mean, var, support.

Examples

m <- al_moments(100L)
m$mean; m$support

Saddlepoint right-tail probability of the arc-length statistic (C back-end)

Description

Saddlepoint right-tail probability of the arc-length statistic (C back-end)

Usage

al_pvalue(s, n)

Arguments

s

observed statistic value;

n

sample size.

Value

the right-tail p-value.

Examples

u <- sort(stats::runif(100))
al_pvalue(al_statistic(u), 100)

Scale by arc-length band matching, in the scale-equivariant standardised form (C back-end)

Description

The raw matching equation fixes an aspect ratio between the probability and response axes and is therefore unit dependent; this estimator divides by the MAD, matches on the standardised scale and rescales, which is exactly scale equivariant.

Usage

al_scale(x, a = 0.05, b = 0.95)

Arguments

x

data;

a, b

the probability band, whose tail mass sets the breakdown point.

Details

The sample band length is matched to al_band_model_star, not to al_band_model. Matching to the population band length is inconsistent: the sample quantity converges to S^* rather than to S, so that estimator is biased by a constant factor that does not vanish with the sample size, about five per cent high at the standard normal on the default band. al_scale_raw retains the uncorrected form for comparison.

Value

the estimated scale, NA when the MAD vanishes or the matching equation has no root.

Examples

set.seed(1)
x <- rnorm(400, sd = 3)
al_scale(x)
## scale equivariance
al_scale(7 * x) / al_scale(x)

The uncorrected band-matching scale estimator (C back-end)

Description

Matches the sample band arc length to the population band length al_band_model rather than to al_band_model_star. INCONSISTENT: it estimates the wrong quantity, by a constant factor that does not vanish as the sample grows. Retained only so that the size of the correction can be measured. Use al_scale.

Usage

al_scale_raw(x, a = 0.05, b = 0.95)

Arguments

x

data;

a, b

the probability band.

Value

the uncorrected scale estimate, NA when the MAD vanishes or there is no root.

Examples

set.seed(1)
al_scale_raw(rnorm(400, sd = 3))

Arc-length goodness-of-fit statistic (C back-end)

Description

Arc-length goodness-of-fit statistic (C back-end)

Usage

al_statistic(u)

Arguments

u

numeric probability-integral transforms in [0,1].

Value

the scalar arc length of the probability-plot ogive.

Examples

u <- sort(runif(100))
al_statistic(u)

Arc-length goodness-of-fit test

Description

Tests H0: F = F0 via the arc length of the probability plot, with the analytic saddlepoint null. Powerful against local density structure (multimodality, clustering, oscillation, heaping) that the empirical-distribution tests miss; weak against smooth location/scale departures.

Usage

al_test(x, null = stats::punif, nboot = NULL, rnull = NULL)

Arguments

x

data;

null

CDF F0 giving the PIT (default punif);

nboot

optional bootstrap reps.

rnull

generator matching null (needed with nboot).

Value

an object of class "htest".

Examples

set.seed(1)
al_test(runif(150))$p.value
al_test(rbeta(150, 0.5, 0.5))$p.value

Arc-length generator: transform a bounded-support base into a new distribution

Description

G(x) = S_F^[a,x] / S_F^[a,b], the normalised cumulative arc length of the base cumulative distribution function, whose density is proportional to sqrt(1 + f(x)^2). Requires bounded support.

Usage

arc_generator(dens, lower, upper, ngrid = 4000L)

pgen(q, obj)

dgen(q, obj)

rgen(n, obj)

Arguments

dens

base density function (vectorised).

lower, upper

bounded support.

ngrid

grid resolution.

q

quantiles.

obj

an "arcgen" object.

n

draws.

Value

an object of class "arcgen".

Functions

Examples

g <- arc_generator(function(z) dnorm(z), -6, 6)
pgen(0, g)
dgen(c(-1, 0, 1), g)

Number of threads used by the back end

Description

Every parallel loop of the package uses the same number of threads: the option arcstat.threads if it is set, otherwise the environment variable ARCSTAT_THREADS, otherwise at most two. Results do not depend on the number.

Usage

arc_threads(n)

Arguments

n

a positive integer to set the option, NULL to clear it; missing only asks.

Value

the number of threads in force (1 where the package was built without OpenMP), invisibly when it was set.

Examples

arc_threads()

Largest admissible shape parameter of the smooth circular family

Description

Largest admissible shape parameter of the smooth circular family

Usage

arcc_c3max()

Value

the exact bound 3 sqrt(3) / 5 on |c3|, beyond which the quantile density goes negative.

Examples

arcc_c3max()

Exact confidence interval for the shape parameter of the wrapped order-three family

Description

Inverts a Monte Carlo test on a rotation-invariant statistic. The rotation is eliminated exactly by invariance, so no nuisance parameter is profiled; the level is exact for every sample size and every number of reference draws rather than asymptotically, which matters because the admissible boundary is attained and because the likelihood of this family is unbounded. Both statistics are reflection invariants, so the interval brackets |c3|; the sign requires a reflection-odd statistic. Recorded resolution is handled by grouping the reference draws as the data are grouped.

Usage

arcc_exact_ci(
  theta,
  cgrid = seq(0, arcc_c3max(), length.out = 81),
  B = 999L,
  stat = 0L,
  group = 0L,
  level = 0.1,
  seed = 4207L
)

Arguments

theta

observed angles in radians

cgrid

grid over the admissible |c3| interval; the grid is the parameter space, so it is exhaustive rather than a search

B

reference draws per grid point

stat

0 for the first trigonometric moment (about twice as efficient) or 1 for the arc-length spacings functional. Both are reflection invariants.

group

0 for continuous data, or the number of equal cells the data are grouped into (36 for ten-degree grouping)

level

test level, so the interval has coverage 1 - level

seed

seed for the splitmix64 stream, so a run reproduces exactly

Value

list with the interval, the observed statistic and the p-value curve that was inverted

Examples

set.seed(1)
th <- rarccirc(200, arccirc(0.4))
arcc_exact_ci(th, B = 99L)[c("lower", "upper")]

Goodness of fit of a fitted circular arc-length member

Description

The probability-integral transform through the fitted member sends the sample to uniform under the hypothesis, so the reference law of the arc-length spacings statistic is distribution-free and the Monte Carlo p-value is exact in level for any number of reference draws.

Usage

arcc_gof(theta, fit, B = 999L, seed = 4207L)

Arguments

theta

angles in radians

fit

a fitted object from fit_arccirc, supplying the member through which the probability-integral transform is taken

B

reference draws

seed

seed for the splitmix64 stream, so a run reproduces exactly

Value

A list of two numbers. stat is the observed arc-length spacings statistic of the angles after the probability-integral transform through the fitted member, and p is its Monte Carlo p-value against the distribution-free reference law. Because the transform sends the sample to uniform under the hypothesis, the p-value is exact in level for any B.

Examples

th <- rarccirc(200, arccirc(0.4, 0.3))
arcc_gof(th, fit_arccirc(th), B = 99L)

The smooth circular arc-length family

Description

The smooth circular arc-length family

Usage

arccirc(c3 = 0, mu = 0)

qd_arccirc(u, obj)

Q_arccirc(u, obj)

darccirc(theta, obj)

trigmom_arccirc(p, obj, nodes = 4096L)

rho_arccirc(obj, nodes = 4096L)

rarccirc(n, obj)

Arguments

c3

shape parameter, |c3| <= arcc_c3max(); c3 = 0 is the circular uniform.

mu

mean direction in radians.

u

probabilities in [0,1].

obj

an "arccirc" object.

theta

angles in radians.

p

integer order.

nodes

number of rectangle-rule nodes; the integrand is C^1 periodic, so convergence is geometric and the default is ample.

n

sample size.

Value

an object of class "arccirc".

Functions

Examples

o <- arccirc(0.4, mu = 0.3)
## the density integrates to one
stats::integrate(function(t) darccirc(t, o), 0, 2 * pi)$value
rho_arccirc(o)

Fejer-Riesz form of the circular arc-length family

Description

q(u) = |P(exp(2 pi i u))|^2 normalised to integrate to one. Every such q is non-negative and infinitely differentiable around the circle by construction, so neither an admissibility condition nor a smoothness constraint arises, and the coefficients are unrestricted.

Usage

arccirc_fr(p, mu = 0)

qd_arccirc_fr(u, obj)

trigmom_arccirc_fr(pord, obj, nodes = 4096L)

Q_arccirc_fr(u, obj, nodes = 4096L)

darccirc_fr(theta, obj, nodes = 4096L)

rarccirc_fr(n, obj, nodes = 4096L)

Arguments

p

complex vector of polynomial coefficients.

mu

mean direction.

u

probabilities in [0,1].

obj

an "arccirc_fr" object.

pord

integer order.

nodes

Simpson cells used to accumulate Q.

theta

angles in radians.

n

sample size.

Value

an object of class "arccirc_fr".

Functions

Examples

fr <- arccirc_fr(c(0.3 + 0.1i))
darccirc_fr(c(0, 1, 2), fr)

Construct a quantile arc-length distribution

Description

The quantile density is Q'(u) = sigma * [1 + sum_k coef[k] P_k(u)]_+, with P_k the shifted Legendre polynomials; the quantile function is Q(u) = mu + integral_0^u Q'(v) dv. Support is compact. coef = numeric(0) gives the uniform on [mu, mu+sigma].

Usage

arcq(coef = numeric(0), mu = 0, sigma = 1, ngrid = 4000L)

qarcq(p, obj)

parcq(x, obj)

darcq(x, obj)

rarcq(n, obj)

arclength(obj, exact = TRUE, nodes = 24L)

Arguments

coef

shape coefficients (c_1, c_2, ...); may be empty for the uniform.

mu

location (left endpoint of support).

sigma

positive scale.

ngrid

grid resolution for the internal numerics.

p

probabilities.

obj

an "arcq" object.

x

quantiles.

n

number of draws.

exact

use Gauss-Legendre quadrature (default) rather than the internal grid.

nodes

number of Gauss-Legendre nodes.

Value

an object of class "arcq".

A single number, the arc length of the quantile function.

Functions

Examples

## an empty coefficient vector gives the uniform on [mu, mu + sigma]
arclength(arcq(numeric(0), mu = 0, sigma = 1))

## the quantile function is increasing and the distribution function inverts it
o <- arcq(0.5)
pu <- c(0.1, 0.35, 0.6, 0.9)
max(abs(parcq(qarcq(pu, o), o) - pu))
## Arc length is a SHAPE functional, so shifting the distribution cannot change it.
arclength(arcq(0.5, mu = 0, sigma = 1))
arclength(arcq(0.5, mu = 17, sigma = 1))

## The quadrature route is spectral: the value is settled at a handful of nodes, where
## the equally spaced grid it replaced converges only linearly.
o <- arcq(c(0.5, -0.3))
sapply(c(8L, 16L, 32L), function(k) arclength(o, nodes = k))

Bayesian arc-length goodness-of-fit evidence

Description

The posterior probability that the discrepancy exceeds its (1 - level) quantile under the null; values near one are strong evidence against the hypothesised distribution. Sensitive to local density structure (multimodality, clustering, heaping) that the vertical discrepancies miss.

Usage

bb_evidence(u, which = "arc", level = 0.95, M = 1500L, ref = NULL, seed = 1L)

Arguments

u

numeric probability-integral transforms in [0,1].

which

discrepancy to use, "arc" (default) or "ks".

level

nominal level defining the reference quantile.

M

number of posterior draws.

ref

optional precomputed reference from bb_ref_disc; computed if NULL.

seed

integer seed for the C back-end.

Value

the posterior evidence against the null, in [0,1].

Examples

ref <- bb_ref_disc(60L)
bb_evidence((1:60 - 0.5) / 60, ref = ref, M = 300L)

Bayesian-bootstrap posterior arc-length discrepancies

Description

Draws M Bayesian-bootstrap (Dirichlet-process, concentration to zero) posterior samples of the arc-length and Kolmogorov–Smirnov discrepancies of the probability-plot ogive for the probability integral transforms u.

Usage

bb_post_disc(u, M, seed = 1L)

Arguments

u

numeric probability-integral transforms in [0,1].

M

number of posterior draws.

seed

integer seed for the C back-end.

Value

an M by 2 matrix with columns arc and ks.

Examples

p <- bb_post_disc((1:60 - 0.5) / 60, M = 200L)
summary(p)

Null reference distribution of the arc-length discrepancy

Description

Pools the posterior discrepancies of D uniform data sets (m draws each) to give the distribution of the discrepancy under the null hypothesis at sample size n.

Usage

bb_ref_disc(n, D = 300L, m = 16L, seed = 7L)

Arguments

n

sample size.

D

number of uniform reference data sets.

m

posterior draws per data set.

seed

integer seed for the C back-end.

Value

a matrix with columns arc and ks.

Examples

ref <- bb_ref_disc(60L)
str(ref)

Beta-companion distribution function

Description

The inverse of bc_q, obtained in the back-end by a continued-fraction incomplete beta and a safeguarded root find.

Usage

bc_cdf(x, alpha, beta)

Arguments

x

quantiles at which to evaluate.

alpha, beta

the two exponents of the quantile density.

Value

A numeric vector of probabilities, the same length as x.

Examples

bc_cdf(bc_q(c(0.3, 0.7), -0.60, -0.35), -0.60, -0.35)

Beta-companion fits with drift, free and equivalence-constrained, many runs in one call

Description

Fits y = g_0 + m x + g_1 F((x-s)/w;\alpha,\beta), F the inverse of the regularised incomplete beta function with parameters \alpha+1,\beta+1, once with \alpha,\beta free in [-1+eps, 20] and once with \beta on the equivalence curve. F is exactly 0 and 1 off the support. The method is that of k4eq_fit. The constrained optimum is a point of the free family and is also a start of the free fit, so the constrained sum of squares is never below the free one.

Usage

bc_host_fit(
  x,
  y,
  curve = NULL,
  it1 = 15L,
  it2 = 200L,
  keep = 6L,
  eps = 1e-06,
  dense = TRUE
)

Arguments

x, y

one run as two vectors, or many runs as two lists of vectors.

curve

NULL for the whole equivalence curve with beta of at least -1 + eps, computed inside (eq_bstar); or a two-column matrix (alpha, beta) of it, increasing in alpha, interpolated linearly, in which alpha is held.

it1, it2

Levenberg–Marquardt steps per start, and for the best starts.

keep

how many distinct best starts of each run are carried to convergence.

eps

how close to -1 the exponents may come.

dense

TRUE (the default) uses 16 (free) and 8 (constrained) times as many starts as FALSE, which is about three times faster. On the 98 induction runs of the archive the quick search stopped above the dense one on 84 constrained fits (by up to a factor of 14 on one run); the dense search left no gap of more than 7.4e-6 relative to a heavier search (16 kept starts, 600 iterations) except where the fit runs along a boundary ridge: an exponent tending to -1 while the scale w grows, on which the sum of squares falls slowly and the minimum is an infimum. There the heavier search went lower by at most 0.16 per cent on 27 constrained fits (24 with beta at the boundary) and 0.65 per cent on 3 free fits. The readings moved by less than 4e-4 except on the degenerate Marula runs, whose readings lie far before the data (below -37) and moved by up to 240; on such runs a reading is not determined by the data.

Value

a list of two matrices, free and con, with one row per run and columns g0, m, g1, s, w, alpha, beta, rss, a, b; a and b are the two readings.

Examples

curve <- cbind(a <- seq(-0.62, -0.51, length.out = 6), sapply(a, eq_bstar))
x <- seq(0, 20, length.out = 50)
y <- 2 + 0.1 * x + 250 * bc_cdf((x - 1) / 17 * beta(0.4, 0.6), -0.6, -0.4) + cos(999 * x)
h <- bc_host_fit(x, y, curve)
h$con[, "rss"] / h$free[, "rss"]

Beta-companion density

Description

The derivative of bc_cdf, equal to the reciprocal of the quantile density evaluated at the corresponding probability.

Usage

bc_pdf(x, alpha, beta)

Arguments

x

points at which to evaluate the density.

alpha, beta

the two exponents of the quantile density.

Value

A numeric vector of density values, the same length as x.

Examples

## the density is the derivative of the distribution function
xx <- bc_q(0.3, -0.60, -0.35); eps <- 1e-6
(bc_cdf(xx + eps, -0.60, -0.35) - bc_cdf(xx - eps, -0.60, -0.35)) / (2 * eps)
bc_pdf(xx, -0.60, -0.35)

Beta-companion quantile function (standardised support)

Description

The two-exponent quantile density q(u) = u^{\alpha}(1-u)^{\beta} integrated from the origin, so bc_q is the quantile function of the beta-companion family on its standardised support. Both exponents are negative on the family of interest.

Usage

bc_q(u, alpha, beta)

Arguments

u

probabilities in (0,1).

alpha, beta

the two exponents of the quantile density.

Value

A numeric vector of quantiles, the same length as u.

Examples

## the quantile function is increasing, and the distribution function inverts it
u <- c(0.05, 0.25, 0.5, 0.75, 0.95)
x <- bc_q(u, alpha = -0.60, beta = -0.35)
all(diff(x) > 0)
max(abs(bc_cdf(x, -0.60, -0.35) - u))

Arc length of the empirical characteristic function (C back-end)

Description

The empirical characteristic function of a sample traces a curve in the complex plane; this returns the arc length of that curve over a window [0, T], doubled for the symmetric half. The sample is standardised internally, so the value is scale free. It is a descriptive, asymmetry-sensitive summary: a symmetric law tends to the value two, and asymmetry adds length.

Usage

cf_arclength(x, T = 6, ngrid = 1200L)

Arguments

x

numeric data vector.

T

upper end of the frequency window.

ngrid

number of grid points on [0, T].

Value

the windowed arc length of the empirical characteristic function.

Examples

set.seed(1)
## the normal carries arc length 2 (see cf_arclength_family)
cf_arclength(rnorm(5000))

Closed-form characteristic-function arc length for named families

Description

Total arc length of the characteristic-function curve for the families with a closed form: "exponential" (\pi), "gamma" (shape k), "normal" (drift ratio delta), "cauchy" (drift ratio delta), "skewstable" (index alpha, skewness beta), and "poisson" (rate lambda, per period). Total arc length is scale free; a symmetric monotone (Polya) law carries the value two.

Usage

cf_arclength_family(
  family = c("exponential", "gamma", "normal", "cauchy", "skewstable", "poisson"),
  k = 1,
  delta = 0,
  alpha = 1.5,
  beta = 0,
  lambda = 1
)

Arguments

family

one of the names above.

k

gamma shape.

delta

location-to-scale ratio for the normal and Cauchy.

alpha, beta

stability index and skewness for the skew-stable family.

lambda

Poisson rate (per-period arc length).

Value

the closed-form arc length.

Examples

## two closed forms that anchor the whole construction
cf_arclength_family("normal")                    # exactly 2
cf_arclength_family("exponential", lambda = 1)   # exactly pi

## total arc length is scale free, so the exponential rate cannot matter
cf_arclength_family("exponential", lambda = 2)

Arc-length tempering of a von Mises base

Description

The generator of the linear theory applied to a circular base, with the scale the construction implicitly carries. Arc length adds a length to a density and is therefore not scale invariant; on a circle of circumference 2\pi a density is of order 1/(2\pi), so without the scale the constant dominates and the transform returns the circular uniform. With it, the family interpolates from the uniform at s\to0 to the base itself as s\to\infty, monotonically in concentration, preserving the mode throughout.

Usage

dtemper_vm(theta, kappa, mu = 0, s = 1, nodes = 4096L)

trigmom_temper_vm(p, kappa, mu = 0, s = 1, nodes = 4096L)

Arguments

theta

angles in radians.

kappa

von Mises concentration of the base.

mu

mean direction.

s

tempering scale.

nodes

quadrature nodes for the normaliser.

p

integer order.

Value

density values at theta.

Functions

Examples

stats::integrate(function(t) dtemper_vm(t, kappa = 1), 0, 2 * pi)$value
trigmom_temper_vm(1, kappa = 1)

Closed-form equivalence discrepancy

Description

The signed amount by which the area identity \int q = u_c q(u_c) fails at (\alpha, \beta). Equivalence holds where it vanishes.

Usage

eq_E(alpha, beta)

Arguments

alpha, beta

the two exponents of the quantile density.

Value

A single number, the discrepancy.

Examples

## the discrepancy vanishes on the equivalence curve and changes sign across it
bs <- eq_bstar(-0.60)
eq_E(-0.60, bs)
eq_E(-0.60, bs - 0.05) * eq_E(-0.60, bs + 0.05) < 0

Equivalence curve

Description

Solves eq_E for \beta at a given \alpha by a deterministic scan followed by bisection, so the returned curve is reproducible rather than dependent on a starting value.

Usage

eq_bstar(alpha)

Arguments

alpha

the first exponent of the quantile density. Documented here rather than inherited, because a combined two-name parameter tag cannot be inherited one name at a time.

Value

A single number, \beta^*(\alpha).

Examples

## the solution curve is increasing in alpha, as the global theorem states
als <- seq(-0.62, -0.54, by = 0.02)
bss <- sapply(als, eq_bstar)
all(diff(bss) > 0)

Quantile-domain induction readings and equivalence discrepancy for tilted beta-kernel quantile densities q(u) = u^alpha (1-u)^beta exp(sum theta_j P_j(u))

Description

Quantile-domain induction readings and equivalence discrepancy for tilted beta-kernel quantile densities q(u) = u^alpha (1-u)^beta exp(sum theta_j P_j(u))

Usage

eq_readings(alpha, beta, theta = numeric(0), ngrid = 20001L)

eq_readings_vsl(lambda, delta, ngrid = 20001L)

Arguments

alpha, beta

kernel exponents

theta

tilt coefficients on shifted Legendre polynomials (orders 1 to 3)

ngrid

evaluation grid size

lambda, delta

van Staden-Loots parameters (kurtosis and skew weights)

Details

The quantile function Q(u) is the integral of q from zero, so a (tangent reading) and b (derivative reading) are quantile values on the same footing as bc_q. Without a tilt (and for \alpha > -1) everything is in closed form and ngrid has no effect. With a tilt the readings are located on a grid from 10^{-5} to 1 - 10^{-5} and refined; for \alpha > -1 the mass below the first node is added and the singular power factor is integrated exactly on every cell, with an error of about 10^{-8}; a derivative reading below u = 3\times 10^{-4} is not found there. Versions up to 0.3.1 started the integral at the first node with a trapezoid, which lowered a and b by up to 5 per cent for \alpha between -0.6435 and -0.505; the gap D was almost unaffected.

Value

c(D, a, b, u_c, u_b); NA when the geometry is invalid

Examples

## on the equivalence curve the two readings coincide
al <- -0.60
r <- eq_readings(al, eq_bstar(al))
r

Quadratic shoulder and mode of the kernel family

Description

The shoulder is the root of 3q'^2 = q q'', transcendental on a general family. On this one it reduces to a quadratic Au^2 + Bu + C = 0, whose constant term C = \alpha(2\alpha+1) is positive exactly when \alpha < -1/2: that inequality is the family's existence condition for a shoulder.

Usage

eq_ub_quad(alpha, beta)

Arguments

alpha, beta

the two exponents of the quantile density.

Value

A length-two vector, the shoulder u_b and the mode u_c.

Examples

## the returned root satisfies the ORIGINAL transcendental equation, in the log form
## 2g'^2 = g'', not merely the quadratic that replaced it
al <- -0.60; be <- -0.35
ub <- eq_ub_quad(al, be)[1]
gp <- al / ub - be / (1 - ub); gpp <- -al / ub^2 - be / (1 - ub)^2
abs(2 * gp^2 - gpp)

The equivalence-system paper's fitting and simulation loops, in the back end

Description

eqfit_bc fits the beta-companion sigmoid by deterministic Nelder–Mead from a matrix of starts (free: six columns; constrained to the equivalence curve: five), returning the fitted six-parameter theta, the SSE and both readings. eqfit_bc_boot runs the iid residual bootstrap of the constrained fit, warm-started, OpenMP over replicates with per-replicate splitmix64 streams. eqfit_k4eq and eqfit_k4eq_boot are the kappa-family analogues constrained to a locus table h -> k. eqfit_msim runs the complete manifold-test simulation (truth and two displacement arms, with the optimiser audit certificate). eqfit_estsim runs the three-estimator study. All outputs are byte-identical across thread counts and between the R and Python fronts.

Usage

eqfit_bc(x, y, starts, curve, maxit = 4000L)

eqfit_bc_boot(x, y, th, curve, B = 30L, seed = 4207L, maxit = 2000L)

eqfit_k4eq(x, y, starts, locus, maxit = 4000L)

eqfit_k4eq_boot(x, y, th, p0, locus, B = 25L, seed = 4207L, maxit = 2000L)

eqfit_msim(
  nM,
  sde,
  Rm,
  th0,
  st5,
  curve,
  awin,
  thref,
  seed = 4207L,
  maxit = 2000L
)

eqfit_score_at(x, y, mu, sg, al, be)

eqfit_blocklen(res)

eqfit_nullT(nM, sde, R2, th0, st5, curve, awin, seed = 4207L, maxit = 2000L)

eqfit_estsim(a0, b0, R, nsizes, seed = 4207L, maxit = 500L)

k4_b_sweep(k, h)

eqfit_taus(a0, b0, R, n, seed = 4207L)

k4_ab_sweep(k, h)

eq_E_sweep(alpha, betas)

Arguments

x, y

the curve being fitted

starts

matrix of optimiser starts, one per row

curve

two-column matrix (alpha, beta) of the traced equivalence curve

maxit

Nelder–Mead iteration cap per pass. Kept but without effect in eqfit_msim and eqfit_nullT, whose profiled minimum is a global search with fixed internal limits.

th

a fitted theta, used to warm-start the bootstrap

B

bootstrap or reference replicates

seed

seed for the per-replicate splitmix64 streams, so a run reproduces exactly

locus

two-column matrix (h, k) of the kappa equivalence locus

p0

warm-start parameter vector for the bootstrap refits

nM, sde, Rm

design size, noise standard deviation and replicates of the manifold study

th0

the true manifold member; st5 the three profiling start transforms (mu, sigma, alpha-centre); thref a 3 x 4 matrix of reference manifold members (mu, sigma, alpha, beta) for the three displaced arms, used for the power certificate; awin the profiling alpha window c(alo, ahi)

st5

the constrained five-parameter start, held on the equivalence curve

awin

two-element admissible window in alpha, passed as lower and upper bounds

thref

three by four matrix of reference thetas, one row per reference member

mu, sg, al, be

a single parameter point for eqfit_score_at

res

a residual vector

a0, b0

beta parameters of the sampled member

R, R2

replicate counts for the estimator simulation and for the null simulation

k, h

shape grid for the wall sweep; betas the beta grid of an E section

n, nsizes

the sample size, and the vector of sample sizes swept over

alpha, betas

a single alpha, and the vector of betas swept across it

Value

All of these return plain R objects rather than a class, so they can be compared element by element against the Python front end. eqfit_bc returns a list with th, the fitted six-parameter vector, sse, the residual sum of squares at that fit, and a and b, the two curve readings; eqfit_k4eq returns the same list without b. eqfit_bc_boot, eqfit_k4eq_boot and eqfit_nullT return a numeric vector holding one statistic per replicate, of length B for the first two and R2 for the third. eqfit_msim returns a list of eight numeric vectors, each of length Rm: the test statistic under the truth (Tlev), under the displacement arms (Taud, Tp2, Tp15, Tp4) and at the three reference members (Tref2, Tref15, Tref4). eqfit_estsim returns a numeric array of dimension c(R, 3, 2, length(nsizes)), indexed by replicate, estimator, parameter and sample size. eqfit_taus returns a numeric matrix of R rows with columns t3, t4, al and be, the two L-moment ratios and the parameter pair they map to. k4_ab_sweep returns a list of the two numeric vectors a and b, one entry per element of k; k4_b_sweep and eq_E_sweep return a single numeric vector of the same length as k and betas respectively. eqfit_score_at returns a single number, the score at the given parameter point, and eqfit_blocklen a single integer, the selected moving-block length.

Examples

curve <- cbind(a <- seq(-0.62, -0.51, length.out = 8), sapply(a, eq_bstar))
x <- 20 * (0:119) / 119
y <- 1 + 300 * (1:120) / 121 + 3 * sin(4321 * (1:120))
st <- rbind(c(1, log(300), 0, log(20), 0.3, 0.5))
f <- eqfit_bc(x, y, st, curve, maxit = 400L)
f$sse
eqfit_blocklen(sin(0.05 * (1:300)))

Method-of-moments fit of the smooth circular arc-length family

Description

The modulus of the first trigonometric moment is even in c3 and strictly increasing in |c3|, so it identifies the magnitude; the rotation-invariant psi = arg(phi_2) - 2 arg(phi_1), reduced to the principal branch, identifies the sign. Reliable sign recovery needs a few thousand observations.

Usage

fit_arccirc(theta, nodes = 4096L)

Arguments

theta

angles in radians.

nodes

rectangle-rule nodes used inside the inversion.

Value

a list with mu, c3, the observed |phi_1|, and whether the inversion stayed interior.

Examples

th <- rarccirc(300, arccirc(0.5, 0.2))
fit_arccirc(th)[c("c3", "mu")]

Closed-form fit of the Fejer-Riesz circular arc-length family

Description

Sort, apply the circular L-moment weights, invert the exact linear map, factorise: no numerical search enters anywhere. The pair (p, mu) is not identified, because shifting the cut is absorbed exactly by a phase ramp on the coefficients, so the gauge is fixed by cutting at the sample mean direction; compare two fits by the density they imply, not by their coefficients. Following the practice of the linear family, an estimate that leaves the admissible set is reported rather than silently replaced; the shrunken spectrum is returned as a labelled fallback because, unlike the linear case, the factorisation itself fails without one.

Usage

fit_arccirc_fr(theta, nm = 3L, margin = 0, nodes = 4096L)

Arguments

theta

angles in radians.

nm

number of circular L-moments, equal to the degree of the fitted family.

margin

required minimum of the implied quantile density.

nodes

quadrature nodes.

Value

a list with the coefficients, mean direction, shrink factor and admissibility.

Examples

th <- rarccirc(300, arccirc(0.5, 0.2))
str(fit_arccirc_fr(th))

Fit an arcq distribution to data by matching L-moments

Description

Matches the first (order+2) L-moments: mu and sigma absorb L_1 and L_2, and the 'order' shape coefficients are chosen to match tau_3, tau_4, ... by least squares.

Usage

fit_arcq(x, order = 2L)

Arguments

x

data.

order

number of shape coefficients (>=1).

Value

An arcq object with the fitted location, scale and shape coefficients.

Examples

set.seed(1)
fit <- fit_arcq(rnorm(500), order = 2L)
arclength(fit)

Closed-form L-moment fit of the order-two arcq family

Description

The family's L-moments are an exact linear function of its shape coefficients, so matching them inverts explicitly: c2 = 35 t4 / (3 + 7 t4) and c1 = t3 (5 - c2), with sigma and mu then absorbing the sample L-mean and L-scale. No optimisation, starting value or tolerance is involved, and the estimator is consistent and asymptotically normal by the delta method. This is the estimator of record for the order-two family; 'fit_arcq' remains available for higher orders, where the inversion is done numerically.

Usage

fit_arcq_cf(x)

Arguments

x

data.

Value

an 'arcq' object, with a 'fit' component holding the coefficients, 'mu', 'sigma' and an 'admissible' flag; a warning is issued when the estimate leaves the admissible set.

Examples

set.seed(1)
fit_arcq_cf(rnorm(400))

Band arc lengths of a scaled kappa curve and of a data polyline

Description

The arc-length element is a norm of the vector (dx, dy). Which norm is a modelling choice: p = 1 gives the ordinary sum, p = 2 the Euclidean arc length, and p = Inf the max-plus (tropical) form \max(|dx|, |dy|). The three agree to within a factor of \sqrt{2}.

Usage

k4_band_model(theta, breaks, nodes = 60L, p = 2)

k4_band_sample(x, y, breaks, p = 2)

Arguments

theta

c(g0, g1, mu, sg, k, h)

breaks

band break points (length J+1)

nodes

number of Gauss-Legendre nodes per band

p

the norm used for the arc-length element; 2 is the Euclidean default, Inf the tropical.

x, y

data ordered in x

Value

A numeric vector of band arc lengths, one per band.

Examples

th <- c(0, 300, 8, 2, -0.3, 0.2)
br <- seq(0, 20, by = 5)
k4_band_model(th, br)
x <- seq(0, 20, length.out = 200)
k4_band_sample(x, th[1] + th[2] * k4_cdf(x, 8, 2, -0.3, 0.2), br)

Exact mean of the tropical band arc length under Gaussian error

Description

The tropical (max-plus) arc-length element \max(dx, |dy|) has an expectation elementary in \Phi and \varphi when the curve is observed with independent Gaussian error, whereas the Euclidean element's expectation is a confluent hypergeometric function. The observed band arc length can therefore be compared with its own mean rather than with a clean-curve quantity it does not estimate.

Usage

k4_band_trop_mean(x, theta, sigma, breaks)

Arguments

x

ordered design points.

theta

the six-vector (g0, g1, mu, sg, k, h).

sigma

error standard deviation of a single observation.

breaks

the J+1 band edges.

Details

Only the mean is returned. The variance of a band sum is not the sum of the elements' variances: consecutive increments share an observation, and although the noise increments correlate at -1/2 the absolute value discards the sign and leaves the elements positively correlated, so summing as if independent understates a band's variance by roughly a fifth. That correction is not elementary and is deliberately not supplied.

Value

the J expected band arc lengths.

Examples

x <- seq(0, 20, length.out = 200)
k4_band_trop_mean(x, c(0, 300, 8, 2, -0.3, 0.2), sigma = 1, breaks = c(0, 10, 20))

Residual bootstraps of kappa fits with drift, many runs in one call

Description

k4_boot resamples the residuals of a fitted free kappa curve in moving blocks and refits it by k4_fit_varpro from the fitted shape, each run in its own box and, where the point fit is the generalised extreme value submodel, with h held at zero. k4eq_boot does the same for a fit of k4eq_fit, refitted on the piece of the locus it lies on. Replicate b of a run draws from its own stream, determined by the run's seed and b alone, so the result does not depend on the number of threads or on which other runs are in the call.

Usage

k4_boot(
  x,
  y,
  fit,
  box,
  gev = FALSE,
  B = 400L,
  seed = 4207L,
  block = 0L,
  maxit = 800L
)

k4eq_boot(
  x,
  y,
  fit,
  locus = NULL,
  bounds = c(-0.98, 0.95, -60, 4),
  B = 400L,
  seed = 4207L,
  block = 0L,
  it2 = 100L,
  gate = FALSE
)

Arguments

x, y

one run as two vectors, or many runs as two lists of vectors.

fit

a matrix with one row per run whose columns g0, m, g1, mu, sigma, k, h are the fit (for k4eq_boot the fit of k4eq_fit, with its piece).

box

a matrix with one row per run, or one row for all: the box (k_lo, k_hi, h_lo, h_hi) of the run's own point fit.

gev

logical, one per run: the point fit holds h = 0.

B

replicates.

seed

one seed per run, or one for all, in which case run r uses seed + r - 1.

block

0 for the block length of the residual autocorrelation, 1 for single resampling, or a block length.

maxit, it2

Nelder–Mead iterations per pass of a free refit; Levenberg–Marquardt steps of a constrained one.

locus

NULL for the whole locus, computed inside (k4_locus_k); or a two-column matrix (h, k), or a list of such matrices (pieces), interpolated linearly and not extrapolated. An interpolated table puts a kink in the objective at each of its nodes; all nodes are scanned, so the best one is found, but the fit is then a property of the table.

bounds

the box (k_lo, k_hi, h_lo, h_hi) the shape must lie in.

gate

"best" keeps a constrained replicate only if its refit, a local search from the fitted point, ends at an interior physical minimum; the others are NaN.

Details

The block length is the first lag at which the residual autocorrelation is inside \pm 2/\sqrt n (at least 2; n^{1/3} if none of the first 200 is); block = 1 resamples singly and any larger value fixes the length.

Value

a list: boot, an array of B rows by columns by runs. The columns are the two readings a and b, the fitted k and h, and for k4_boot also sel, 1 if n\log(rss_0/rss)-2<0 would choose h=0 on that replicate and NaN where h is held; and block, the block length of every run. k4eq_boot adds lost, the number of replicates of every run without a refit.

Examples

x <- seq(0, 20, length.out = 120)
y <- 1 + 300 * k4_cdf(x, 9, 2, -0.3, 0.2) + sin(4321 * seq_along(x))
f <- k4_fit_varpro(x, y, rbind(c(9, log(2), -0.3, 0.2)), bounds = c(-0.98, 0.95, -60, 4))
fit <- rbind(c(f$theta[1], f$drift, f$theta[2:6]))
b <- k4_boot(x, y, fit, box = c(-0.98, 0.95, -60, 4), B = 5)
b$boot[, c("a", "b"), 1]

Free kappa fits with drift, many runs in one call

Description

The fit of k4_fit_varpro from a built-in start grid, by the method of k4eq_fit (Levenberg–Marquardt on the projected residual, best starts carried to convergence and polished), with the submodel selection and the rule on acceptable fits as options.

Usage

k4_fit(
  x,
  y,
  bounds = c(-0.98, 0.95, -60, 4),
  floors = c(-60, -8, -3, -1.2, -0.5, 0),
  gate = FALSE,
  gev = FALSE,
  hfix = NA_real_,
  drift = TRUE,
  it1 = 12L,
  it2 = 200L,
  keep = 8L,
  infimum = FALSE,
  dense = FALSE
)

Arguments

x, y

one run as two vectors, or many runs as two lists of vectors.

bounds

the box (k_lo, k_hi, h_lo, h_hi); the submodel is always fitted in it.

floors

lower bounds on h, deepest first, tried in turn when gate = TRUE; otherwise bounds[3] is used.

gate

FALSE takes the lowest minimum whatever it is; TRUE takes the first of floors whose best fit is physical, meaning that g1 > 0 and the tangent reading lies between 0 and max(x), and the fit at the last floor if none is; "best" takes the lowest minimum that is physical in the box bounds, and NaN where none is found. TRUE depends on the search: the better it is, the more often an unphysical minimum is the lowest at every floor.

gev

fit also the generalised extreme value submodel h=0 and choose it when n\log(rss_0/rss)-2<0 (with gate, only if it is physical).

hfix

hold h there; NA searches it.

drift

FALSE holds the slope m at zero.

it1, it2

Levenberg–Marquardt steps per start, and for the best starts.

keep

how many distinct best starts of each run are carried to convergence.

infimum

with gate = "best", also report the status and the infimum over the physical set of the four-parameter family, as columns status, inf_rss, inf_k, inf_h, inf_a (see k4eq_fit). They describe the search with h free; the fit does not change.

dense

use about ten times as many starts at negative k (in the coordinates of the lower end of the support, which the search also uses for k < -0.15).

Value

a matrix with one row per run and columns g0, m, g1, mu, sigma, k, h, rss, a, b, gev, dAIC, h_floor, physical. gev is 1 where the submodel was chosen.

Examples

x <- seq(0, 20, length.out = 120)
y <- 1 + 0.2 * x + 300 * k4_cdf(x, 9, 2, -0.3, -0.5) + sin(4321 * seq_along(x))
k4_fit(x, y)[1, c("k", "h", "rss", "a", "b")]

Deterministic kappa fits: L-moment shape inversion, quantile-domain arc-length shape fit, curve-domain NLS and NALR (banded arc lengths of the running-median presmoothed polyline)

Description

Deterministic kappa fits: L-moment shape inversion, quantile-domain arc-length shape fit, curve-domain NLS and NALR (banded arc lengths of the running-median presmoothed polyline)

Usage

k4_fit_lmom(t3, t4, nodes = 200L)

k4_fit_aleq(y, bands, start = c(0, 0, log(0.3)))

k4_fit_nls(x, y, start, drift = FALSE)

k4_fit_nalr(x, y, start, J = 12L, lambda = 1, w = 9L, p = 2)

Arguments

t3, t4

target sample L-moment ratios

nodes

number of quadrature nodes for the theoretical ratios (at least 200 are used)

y

response vector (sorted internally where required)

bands

two-column matrix of quantile bands. A band that ends at one has infinite model length unless k > 0, so such a band excludes k \le 0.

start

transformed start vector

x

data vector

drift

model the slow linear rise of the Rancimat water-trap conductivity, y = g0 + m x + g1 F(x). Both induction-period readings are invariant to it, so the equivalence theory is unaffected and only the fit improves.

J

number of curve bands

lambda

anchor weight

w

running-median window

p

the norm used for the arc-length element; 2 is the Euclidean default, Inf the tropical

Value

A list of fitted parameters, whose components depend on which fitting routine is called; all return the six-vector theta of the scaled kappa curve.

Examples

## invert the L-moment ratios of a member
tt <- k4_tau34(0.1, 0.4)
k4_fit_lmom(tt[1], tt[2])

Variable-projection fit of the drifted kappa response

Description

Fits y = g_0 + m x + g_1 F(x;\mu,\sigma,k,h). The mean curve is linear in the three coefficients, so they are solved exactly for any shape and only the four shape parameters are searched; the multi-start is run in the C back end, in parallel over starts, and the best is chosen serially so the answer does not depend on the thread count (see arc_threads).

Usage

k4_fit_varpro(
  x,
  y,
  starts,
  maxit = 1500L,
  bounds = c(-0.98, 0.95, 0, 4),
  hfix = NA_real_
)

Arguments

x, y

the curve.

starts

a matrix with four columns, (mu, log sigma, k, h), one row per start; h is carried directly so negative values are admissible.

maxit

iterations per Nelder-Mead descent.

bounds

admissible shape box c(k_lo, k_hi, h_lo, h_hi). The default lower bound on k is the one the edible-oil analysis settled on: a wider box lowers the residual sum of squares but moves the fitted induction periods away from the laboratory values, so the choice is the analyst's and is stated here rather than fixed in the back end. A lower bound of zero on h is admissible and meaningful: it admits the generalised extreme value distribution, the h \to 0 member of the family, and with k = 0 the Gumbel.

hfix

hold h at this value and fit the remaining three parameters, which is how a submodel is fitted in its own right; NA (the default) fits all four. h is searched directly, so h = 0 is an ordinary point of the free search. Choosing between the two fits is model selection between a nested pair, and is left to the caller.

Value

a list with theta in the six-vector convention (g0, g1, mu, sg, k, h), the fitted drift, and the residual sum of squares rss.

Examples

x <- seq(0, 20, length.out = 120)
y <- 1 + 0.2 * x + 300 * k4_cdf(x, 9, 2, -0.3, -0.5) + sin(4321 * seq_along(x))
st <- as.matrix(expand.grid(c(8, 10), log(c(1, 3)), c(-0.5, 0), c(-1, 0.2)))
f <- k4_fit_varpro(x, y, st, bounds = c(-0.98, 0.95, -60, 4))
f$theta; f$rss

One-way variance components and the intraclass correlation

Description

Decomposes the variance of y into within-group and between-group parts under a one-way random-effects model, and returns the intraclass correlation. Groups may be of unequal size; the between-group mean square is divided by the unbalanced constant k_0 = (N - \sum n_i^2 / N)/(G-1) rather than by the mean group size, which is the balanced-design shortcut and biases the ratio when group sizes differ.

Usage

k4_icc(y, g)

Arguments

y

numeric observations.

g

grouping vector; coerced with factor, so any labels will do.

Details

A negative between-group variance estimate is truncated at zero, the usual convention.

Value

named numeric vector: icc, sd_within, sd_between.

Examples

## replicate runs on the same specimen agree more closely than runs on different specimens
y <- c(1.1, 1.2, 1.0,  5.1, 5.3, 4.9,  9.0, 9.2, 8.8)
g <- rep(1:3, each = 3)
k4_icc(y, g)["icc"] > 0.9

Windowed L-moment matching of kappa shapes, many runs in one call

Description

Puts each run on the probability scale by the linear part of a fit only, takes the third and fourth L-moment ratios of its quantile function over the observed window of levels, and finds the kappa shape whose quantile function has the same ratios over the same window. The fitted shape is not used. h is searched on both sides of zero.

Usage

k4_lmom_window(
  x,
  y,
  lin,
  bounds = c(-0.98, 0.95, -8, 4),
  window = 21L,
  ngrid = 3000L,
  nmodel = 4000L
)

Arguments

x, y

one run as two vectors, or many runs as two lists of vectors.

lin

a matrix with one row per run whose columns g0, m, g1 (or the first three) are the linear part.

bounds

the box (k_lo, k_hi, h_lo, h_hi) the shape must lie in.

window

running-median window (odd; the ends as in runmed).

ngrid, nmodel

number of equally spaced levels for the data and for the model.

Value

a matrix with one row per run and columns k, h, obj, t3, t4, lo, hi, nsol, h_min, h_max: the shape, the squared distance left, the two ratios of the data, the window, the number of distinct exact matches found and their smallest and largest h. Two ratios over a window do not always determine the shape: where nsol exceeds one the shape returned is only the one with the smallest |h|. NaN where fewer than 100 points lie inside the window.

Examples

x <- seq(0, 20, length.out = 300)
y <- 1 + 300 * k4_cdf(x, 9, 2, -0.2, 0.3)
k4_lmom_window(x, y, c(1, 0, 300))

Distance from fitted shapes to the equivalence locus

Description

Shortest Euclidean distance in the (h,k) shape plane from each fitted shape to the equivalence locus, supplied as a polyline. Distance is measured to the segments of the polyline rather than to its vertices: a vertex-only search overstates the distance by up to half the vertex spacing, which matters when the distance is compared against the price of the constraint.

Usage

k4_locus_dist(h, k, locus_h, locus_k)

Arguments

h, k

numeric vectors of fitted shape parameters, of equal length.

locus_h, locus_k

the locus polyline, of equal length.

Value

numeric vector of distances, NA where the shape is not finite.

Examples

## a shape sitting on the locus is at distance zero
lh <- seq(0.05, 0.39, length.out = 20); lk <- seq(-0.04, 0.81, length.out = 20)
k4_locus_dist(lh[5], lk[5], lh, lk) < 1e-12

The equivalence locus of the four-parameter kappa family

Description

For every h<1/2 there is one k at which the tangent reading and the third-derivative reading coincide. The locus is a single curve through h=0; it tends to the corner (h,k)=(1/2,1), and for h<0 it approaches the frontier hk=1/2 from inside, exponentially fast in h: below h of about -15 the value returned is the double nearest to 1/(2h).

Usage

k4_locus_k(h)

Arguments

h

shape values.

Value

the k of each, NaN where h\ge 1/2.

Examples

k <- k4_locus_k(c(-1, 0, 0.3))
r <- k4_readings(c(0, 1, 0, 1, k[3], 0.3))
r[["a"]] - r[["b"]]

The fitting-method multiverse of one induction run: eight admissible pipelines under one moving-block residual bootstrap

Description

All eight pipelines report the standard tangent reading from the same trace: the variable-projection least-squares fit with its GEV submodel selection (LS), running medians of window nine and twenty-one followed by least squares of the curve without drift (med9-LS, med21-LS), the banded arc-length estimator (arc), the GEV submodel in its own right (GEV-LS), the selection fit past the run's measured transient cutoff (transient-excised), and the selection fit on each half-density index grid (grid-odd, grid-even). Every pipeline searches the box bounds, with h itself as the coordinate and starts on both sides of zero, so pass the box of the run's own point fit. Point estimates use the full start grid; a replicate starts from its pipeline's own point fit. Resampling indices come from per-replicate splitmix64 streams, so the result is identical whatever the OpenMP thread count and identical between the R and Python fronts.

Usage

k4_mv_boot(
  x,
  y,
  cut = -Inf,
  B = 50L,
  seed = 4207L,
  bounds = c(-0.98, 0.95, 0, 4),
  maxit = 1500L,
  drift = FALSE
)

Arguments

x, y

the logged curve

cut

transient cutoff in the units of x; -Inf excises nothing

B

bootstrap replicates; 0 returns point estimates only

seed

integer seed for the per-replicate streams

bounds

the admissible shape box (k_lo, k_hi, h_lo, h_hi)

maxit

Nelder–Mead iteration cap of a replicate refit

drift

TRUE lets med9-LS, med21-LS and arc carry the linear drift that the other five pipelines always carry. With FALSE the spread between pipelines is mostly the effect of leaving the drift out.

Value

list(a_pt, A): the eight named point estimates, and the B by eight matrix of replicate readings (NULL when B = 0)

Examples

x <- seq(0, 20, length.out = 120)
y <- 1 + 300 * k4_cdf(x, 8, 2.5, 0.2, 0.4) + 2 * sin(9871 * seq_along(x))
k4_mv_boot(x, y, B = 0L, maxit = 300L)$a_pt

Variance components of a multiverse of pipelines

Description

From the replicate readings of k4_mv_boot. All pipelines are refitted on the same replicates, so the column means share their resampling error. With v the mean variance of a column over replicates and w that mean less the mean covariance of two columns (the method-by-replicate variance), the variance of the M column means has expectation \delta^2 + w/B, where \delta^2 is the variance of the pipelines' differences on this curve. Subtracting v/B, as for independent methods, is too much when the columns are positively correlated. \delta^2 still contains the sampling error of the curve itself, which affects the pipelines differently: E\delta^2 = \tau^2 + w. Use delta2 to describe the spread on the curve at hand and tau2 for a method component that would remain with the sampling error taken out. The step from \delta^2 to \tau^2 takes the bootstrap covariance as that of the estimates.

Usage

k4_mv_share(A, frac = 0.6)

Arguments

A

a matrix of readings, replicates by pipelines.

frac

pipelines with a smaller share of finite readings are left out; then only replicates finite in all the others are used.

Value

a named vector: M and B used, v, w, delta2, share_delta (\delta^2/(\delta^2+v)), tau2 and share_tau; NaN with fewer than three pipelines or replicates.

Examples

set.seed(1); e <- rnorm(200)
A <- cbind(e, e + 0.1, e + 0.2)      # differences without error: w = 0
k4_mv_share(A)

Four-parameter kappa quantile, distribution and density functions

Description

Four-parameter kappa quantile, distribution and density functions

Usage

k4_q(u, mu = 0, sg = 1, k, h)

k4_cdf(x, mu = 0, sg = 1, k, h)

k4_pdf(x, mu = 0, sg = 1, k, h)

Arguments

u, x

numeric vectors of probabilities or quantiles

mu, sg, k, h

kappa parameters (location, scale, two shapes)

Value

numeric vector

Examples

u <- c(0.1, 0.5, 0.9)
x <- k4_q(u, 8, 2, -0.3, 0.2)
k4_cdf(x, 8, 2, -0.3, 0.2)
k4_pdf(x, 8, 2, -0.3, 0.2)

The two standard induction-period readings of a fitted kappa curve

Description

Both readings are closed forms. The steepest point mode exists exactly when k < 1, h < 1 and hk < 1; the third-derivative reading b exists when in addition h < 1/2 and hk < 1/2. Where a reading does not exist it is NaN. Versions up to 0.3.1 searched a grid between the 0.1 and 99.9 per cent quantiles; with a heavy right tail (k near -1) the grid missed the steepest point and the tangent reading came out too low.

Usage

k4_readings(theta, grid = 4000L)

Arguments

theta

c(g0, g1, mu, sg, k, h)

grid

ignored, kept so that existing calls work; the result does not depend on a grid

Value

c(a = tangent reading, b = third-derivative reading, mode)

Examples

## the tangent at the steepest point meets the baseline at a
th <- c(1, 400, 8, 2.5, -0.9, 0.2)
r <- unname(k4_readings(th)); cdf <- k4_cdf(r[3], 8, 2.5, -0.9, 0.2)
r[3] - cdf / k4_pdf(r[3], 8, 2.5, -0.9, 0.2) - r[1]

Running median with shrinking symmetric windows at the edges

Description

Running median with shrinking symmetric windows at the edges

Usage

k4_runmed(y, w = 9L)

Arguments

y

numeric vector

w

odd window width

Value

A numeric vector the same length as y.

Examples

## the window shrinks symmetrically at the ends rather than padding, so the smoothed
## series keeps the length of the original
y <- c(1, 8, 2, 9, 3, 10, 4)
length(k4_runmed(y, 3L)) == length(y)

Kappa curves that share one shape, for many sets of runs in one call

Description

Every run has its own baseline, drift, plateau, location and scale, and the runs of a set share one shape: y = g_{0j} + m_j x + g_{1j} F((x-\mu_j)/\sigma_j; k, h). This is the model of time rescaling, in which the curves differ in the clock and the amplitude only. The sum of squares is minimised over all of it. At a fixed shape the runs separate, so the profile of every run over a grid of shapes is computed once and shared by all the sets; the lowest minima of the summed profile start a joint search, and the best results are checked run by run from cold starts and polished.

Usage

k4_shared_fit(
  x,
  y,
  sets = NULL,
  bounds = c(-0.98, 0.95, -3, 4),
  drift = TRUE,
  dense = FALSE
)

Arguments

x, y

many runs as two lists of vectors.

sets

a list of integer vectors, each the indices of the runs of one set; by default one set of all the runs.

bounds

the box (k_lo, k_hi, h_lo, h_hi) the shape must lie in.

drift

FALSE holds every m_j at zero.

dense

a grid four times as fine, with more starts.

Details

The search is not certified. Its known weak case is a run that is fitted best by a curve with a very long scale and a plateau far beyond the data, so that the curve is close to a power of a linear function and its sum of squares falls slowly along a ridge (plateaux of 10^4 to 10^8 times the rise observed). On sets containing such runs the result can lie above the minimum, by up to 1.3 per cent on the archive sets where this was measured (0.9 per cent with dense = TRUE); sets of ordinary runs were not affected.

Value

a list: fit, a matrix with one row per set and columns rss, k, h; and runs, a list with one matrix per set, its rows the runs of the set and its columns g0, m, g1, mu, sigma, rss. No run is refused on physical grounds.

Examples

x <- seq(0, 20, length.out = 60)
f <- function(mu, s, g) 1 + 0.2 * x + g * k4_cdf(x, mu, s, -0.4, 0.3) + sin(4321 * mu * x)
r <- k4_shared_fit(list(x, x), list(f(8, 2, 300), f(10, 2.5, 280)),
                   bounds = c(-0.9, 0.5, -1, 1))
r$fit

Permutation test of one shared kappa shape against a shape per group

Description

For the runs of each problem, RSS_{TR} is the sum of squares of one shape for all of them and RSS_W that of a shape for each group, \Lambda_T = RSS_{TR}/RSS_W and, given the sum of squares of the free fits, \Lambda_W = RSS_W/RSS_{free}. Every set of runs of a group's size is fitted once by the search of k4_shared_fit and every assignment of the group labels is evaluated from those fits; the p-value is the share of assignments with an RSS_W not above the observed one (\Lambda_T decreases in it).

Usage

k4_shared_perm(
  x,
  y,
  group,
  problem = NULL,
  rss_free = NULL,
  bounds = c(-0.98, 0.95, -3, 4),
  drift = TRUE,
  slack = c(1e-09, 0.01),
  dense = FALSE,
  maxalloc = 2e+06
)

Arguments

x, y

many runs as two lists of vectors.

group

a group label per run.

problem

a problem label per run, when many tests are made in one call; the runs of a problem must be consecutive.

rss_free

sum of squares of the free fits, one per problem, or NULL.

bounds

the box (k_lo, k_hi, h_lo, h_hi) the shape must lie in.

drift

FALSE holds every m_j at zero.

slack

numerical allowances: for each, assignments with an RSS_W of at most (1 + slack) times the observed one are counted against rejection. The fits are the minima a search found, and an allowance shows whether the verdict depends on its last per cent.

dense

a grid four times as fine, with more starts.

maxalloc

no p-value with more assignments than this, or with more than 14 runs.

Value

a list: stat, a matrix with one row per problem and columns rss_tr, rss_w, lambda_t, lambda_w, n_alloc, min_rss_w; and p, a matrix with one column per slack.

Examples

x <- seq(0, 20, length.out = 50)
f <- function(mu, h) 1 + 300 * k4_cdf(x, mu, 2, -0.4, h) + sin(4321 * mu * x)
k4_shared_perm(rep(list(x), 4), list(f(8, 0.3), f(8.4, 0.3), f(6, -0.4), f(6.3, -0.4)),
               group = c(1, 1, 2, 2), bounds = c(-0.9, 0.5, -1, 1))

Theoretical L-moment ratios of the standard kappa distribution

Description

Theoretical L-moment ratios of the standard kappa distribution

Usage

k4_tau34(k, h, nodes = 200L)

Arguments

k, h

shape parameters

nodes

number of quadrature nodes, at least 200. The rule is the trapezoid after a map that removes both end singularities, and 200 nodes give full double precision.

Value

c(tau3, tau4, l1, l2); NaN where the moments do not exist (k \le -1 or hk \le -1 with h < 0)

Examples

k4_tau34(0.1, 0.4)

Equivalence-constrained kappa fits with drift, many runs in one call

Description

Fits y = g_0 + m x + g_1 F(x;\mu,\sigma,k,h) with (h,k) held on the equivalence locus, so that the two standard readings coincide. The linear part (g_0,m,g_1) is solved exactly at every trial shape; (\mu,\log\sigma,h) is searched by Levenberg–Marquardt from a grid of starts, the best of which are carried to convergence and polished by a simplex. The starts of all runs share one pool of threads (arc_threads); results do not depend on the number.

Usage

k4eq_fit(
  x,
  y,
  locus = NULL,
  bounds = c(-0.98, 0.95, -60, 4),
  drift = TRUE,
  gate = FALSE,
  it1 = 12L,
  it2 = 150L,
  keep = 6L
)

Arguments

x, y

one run as two vectors, or many runs as two lists of vectors.

locus

NULL for the whole locus, computed inside (k4_locus_k); or a two-column matrix (h, k), or a list of such matrices (pieces), interpolated linearly and not extrapolated. An interpolated table puts a kink in the objective at each of its nodes; all nodes are scanned, so the best one is found, but the fit is then a property of the table.

bounds

the box (k_lo, k_hi, h_lo, h_hi) the shape must lie in.

drift

FALSE holds the slope m at zero.

gate

FALSE takes the lowest minimum on the locus; "best" the lowest interior minimum that is physical: g1 > 0 and the tangent reading between 0 and max(x). Where there is none the fit is NaN: the edge of the physical set, or the end of the searched part of the locus, is never returned as a fit. The result then has physical, one row per run: status, 1 for an interior minimum that is the lowest physical value found, 2 for an interior minimum with lower physical values towards the edge of the set, 3 for physical points without an interior minimum, 0 for no physical point; and inf_rss, inf_k, inf_h, inf_a, the lowest physical sum of squares found and the shape and reading there, which in states 2 and 3 is a limit and not a fit.

it1, it2

Levenberg–Marquardt steps per start, and for the best starts.

keep

how many distinct best starts of each run are carried to convergence.

Details

Unless gate = "best", no fit is refused on physical grounds. The sign of g_1 and the position of the reading are the caller's to judge; a caller who gates the free fit in that way must gate both fits, or a ratio of the two sums of squares can fall below one.

Value

a list: fit, a matrix with one row per run and columns g0, m, g1, mu, sigma, k, h, rss, a, b and piece (the table piece chosen; for the whole locus, which is searched from both sides of zero, 1 for h\le 0 and 2 for h\ge 0); a and b are the two readings of the fitted shape, whatever the sign of g1; and pieces, the best fit on every piece in the same columns (runs by columns by pieces), from which a caller can take the best one that is acceptable on other grounds.

Examples

x <- seq(0, 20, length.out = 150)
y <- 1 + 0.2 * x + 300 * k4_cdf(x, 9, 2, k4_locus_k(0.2), 0.2) + sin(4321 * seq_along(x))
f <- k4eq_fit(x, y)
f$fit[1, c("k", "h", "rss", "a", "b")]

Circular L-moments

Description

On the line the L-moments are Legendre projections of the quantile function and are linear in the Legendre coefficients of the quantile density. On the circle the natural basis is Fourier, and the m-th circular L-moment is the Fourier projection \ell_m = \int_0^1 Q(u) e^{-2\pi i m u}\,du. With the empirical quantile function this is a linear combination of order statistics with fixed complex weights, hence a genuine L-statistic. The map to the quantile-density spectrum is exact and inverts, \ell_m = i(1-\rho_m)/(2\pi m), equivalently \rho_m = 1 + 2\pi i m \ell_m.

Usage

lmom_circ(x, nm = 3L)

rho_from_lmom(ell)

qmin_rho(rho, nodes = 4096L)

admiss_rho(rho, margin = 0, nodes = 4096L)

factorise_rho(rho, margin = 0, nodes = 4096L)

Arguments

x

observations on the unit interval, obtained by cutting the circle at the mean direction.

nm

number of L-moments.

ell

complex vector of circular L-moments.

rho

complex vector of spectrum values.

nodes

grid points.

margin

required minimum of the implied quantile density.

Details

The general device of projecting a quantile function onto an orthogonal basis is not new: it is Sillitto (1969) in one dimension and Decurninge (2014) for multivariate quantile maps. What is specific here is the Fourier form and its exact inversion to the Fejer-Riesz parameters.

Value

complex vector of length nm.

a list with the coefficient vector p, the shrink factor applied to the spectrum (one when nothing was needed), and the admissible flag for the spectrum AS SUPPLIED.

Functions

Examples

l <- lmom_circ(rarccirc(500L, arccirc(0.8, 0.3)), 3L)
l
qmin_rho(0.4)

Theoretical L-moments of an arcq distribution

Description

L_r is the shifted-Legendre projection of Q (Hosking's convention): L_r = integral_0^1 Q(u) P*_(r-1)(u) du, r>=1, with P*_r the shifted Legendre polynomial (P*_r(1)=1).

Usage

lmoments(obj, nmom = 4L)

Arguments

obj

an "arcq" object.

nmom

number of L-moments.

Value

the first nmom L-moments; ratios tau_r = L_r/L_2 for r>=3 via lmratios().

Examples

lmoments(arcq(0.5))

L-moment ratios (tau_3, tau_4, ...) from a vector of L-moments

Description

L-moment ratios (tau_3, tau_4, ...) from a vector of L-moments

Usage

lmratios(L)

Arguments

L

L-moments.

Value

A numeric vector: the first two entries are the location and scale L-moments themselves, followed by the ratios \tau_3, \tau_4, \ldots.

Examples

## a symmetric sample has vanishing L-skewness
u <- (seq_len(20000) - 0.5) / 20000
lmratios(sample_lmoments(u, 4L))[3]

Sample L-moments of data

Description

Sample L-moments of data

Usage

sample_lmoments(x, nmom = 4L)

Arguments

x

data.

nmom

number of L-moments.

Value

A numeric vector of nmom sample L-moments.

Examples

## for a uniform grid on (0,1) the first L-moment is 1/2 and the second is 1/6
u <- (seq_len(20000) - 0.5) / 20000
sample_lmoments(u, 4L)[1:2]

Wald (inverse Gaussian) curve fits, many runs in one call

Description

Fits y = g_0 + m x + g_1 F(x;\mu,\lambda) with F the inverse Gaussian distribution function, by the method of k4eq_fit, and reads the fitted curve exactly. Time is measured from zero, so x must be in the units and from the origin the curve is meant in.

Usage

wald_fit(x, y, drift = TRUE, it1 = 25L, it2 = 200L, keep = 6L)

wald_cdf(x, mu, lambda)

wald_readings(mu, lambda)

Arguments

x, y

one run as two vectors, or many runs as two lists of vectors.

drift

FALSE holds the slope m at zero.

it1, it2

Levenberg–Marquardt steps per start, and for the best starts.

keep

how many distinct best starts of each run are carried to convergence.

mu, lambda

positive parameters, one pair for wald_cdf, any number for wald_readings.

Value

wald_fit: a matrix with one row per run and columns g0, m, g1, mu, lambda, phi, rss, a, b, mode; phi is \lambda/\mu; a and b are the tangent and the third-derivative reading of the fitted shape, whatever the sign of g1 and wherever they lie, and can be of any size when the fit runs to the end of its range (\mu up to 10^8). wald_cdf: a vector. wald_readings: a matrix with columns a, b, mode; both readings exist for every \phi>0.

Examples

x <- seq(0, 20, length.out = 120)
y <- 1 + 0.2 * x + 300 * wald_cdf(x, 9, 150) + sin(4321 * seq_along(x))
wald_fit(x, y)[1, c("mu", "lambda", "a", "b")]
wald_readings(9, 150)