SPB Git

Repository Public MIT

API.md 17.0 KB

# ORIXStatistics — API reference

Swift 6 package, no UI, no external dependency except the sibling ORIXNumerics (for Explanation, VerificationReport, RootFinder). Platforms: iOS 26, macOS 15. import ORIXStatistics (and import ORIXNumerics to name Explanation / VerificationReport types).

# Rules that hold everywhere

Rule Detail
Value types Every public type is a Sendable struct or enum; every function is pure. Safe to call from any actor or Task.
Errors Invalid input throws StatisticsError (description / errorDescription are user-facing sentences). Nothing returns NaN for a valid request.
NaN A NaN argument of pdf/cdf/survival propagates as NaN (IEEE). Data lists containing NaN or ±∞ throw .nonFiniteValue.
Undefined vs infinite mean/variance of a distribution are Double?: nil = undefined, .infinity = infinite. Summary fields that do not exist for the sample are nil.
Levels Confidence level and significance alpha are in the open interval (0, 1): 0.95, not 95.
Decision rejectNull == (pValue <= alpha).
Explain / Verify Inference, regression and bootstrap results carry explanation: Explanation (formula, inputs, steps, result, assumptions — all computed values) and verification: VerificationReport (checks that were executed). Show the "verified" badge only when verification.isVerified; list verification.warnings otherwise.
Reproducibility Anything random takes a seed: UInt64 or an inout generator. Same seed ⇒ identical result.

StatisticsError cases: emptyData, insufficientSample(required:actual:), parameterOutOfDomain(name:value:requirement:), probabilityOutOfRange, nonFiniteValue, dimensionMismatch, singularDesignMatrix, nonConvergence, undefined, overflow, invalidArgument.

# 1. Special functions — enum SpecialFunctions

All static, all throws.

Function Meaning
logGamma(x), gamma(x) ln|Γ(x)|, Γ(x) (poles and overflow throw)
logBeta(a, b), beta(a, b) a, b > 0
logFactorial(n), factorial(n) n! exact to 22!, up to 170!
binomialCoefficient(n, k), permutations(n, k) nCr, nPr as Double (exact below 2⁵³)
erf(x), erfc(x), inverseErf(y), inverseErfc(q)
normalCDF(z), normalSurvival(z) Φ(z), 1 − Φ(z)
normalQuantile(p), normalQuantile(upperTail: q) Φ⁻¹
regularizedGammaP(a:x:), regularizedGammaQ(a:x:) P(a, x), Q(a, x) = 1 − P
inverseRegularizedGammaP(a:p:), inverseRegularizedGammaQ(a:q:)
regularizedBeta(x:a:b:), regularizedBetaComplement(x:a:b:) I_x(a, b), 1 − I_x(a, b)
inverseRegularizedBeta(p:a:b:), inverseRegularizedBetaComplement(q:a:b:)
swift
let p = try SpecialFunctions.regularizedGammaQ(a: 2.5, x: 7)      // upper tail, computed directly
let z = try SpecialFunctions.normalQuantile(upperTail: 0.025)     // 1.959963984540054

Use the complementary form (Q, Complement, upperTail:) for small upper tails: it keeps full relative accuracy.

# 2. Descriptive statistics — enum Descriptive

Input: [Double]. Conventions: "sample" = n − 1 denominator (default), "population" = n.

Function Notes
count, sum (Neumaier), mean, median, minimum, maximum, range
modes(x) -> [Double] all modes ascending; [] when every value is unique (n > 1)
variance(x, sample: true), standardDeviation(x, sample: true), standardError(x), coefficientOfVariation(x)
quantile(x, p, method: .linear), quantiles(x, ps, method:), percentile(x, k, method:) QuantileMethod: R-1 … R-9 (table below)
quartiles(x, method:) -> (first, third), interquartileRange, fiveNumberSummary QuartileMethod: .quantile(QuantileMethod) (default R-7), .tukeyHinges, .medianOfHalvesExclusive (TI-83/84)
populationSkewness (g₁), sampleSkewness (G₁, Excel SKEW)
populationExcessKurtosis (g₂), sampleExcessKurtosis (G₂, Excel KURT) always excess kurtosis (normal = 0)
centralMoment(x, order:)
geometricMean, harmonicMean, weightedMean(x, weights:) positive data for the first two
covariance(x, y, sample: true), correlation(x, y) (Pearson), spearmanCorrelation(x, y)
ranks(x) average ranks for ties
zScores(x, sample: true)
frequencyTable(x) -> [FrequencyRow] value, count, relative, cumulative
histogram(x, rule: .sturges, range: nil) -> Histogram BinningRule: .sturges, .freedmanDiaconis, .fixedCount(n), .fixedWidth(w, origin:); bins are [a, b), the last one [a, b]
expand(values:frequencies:) turns a value list + frequency list (TI FreqList) into raw data
summary(x, quartileMethod:) -> DescriptiveSummary everything for a "1-Var Stats" screen
QuantileMethod R type Same as
.invertedCDF, .averagedInvertedCDF, .closestObservation 1, 2, 3 numpy inverted_cdf, averaged_inverted_cdf, closest_observation
.interpolatedInvertedCDF, .hazen 4, 5 numpy interpolated_inverted_cdf, hazen
.weibull 6 Excel PERCENTILE.EXC, Minitab, SPSS, numpy weibull (clamped at the ends instead of failing)
.linear (default) 7 numpy default, R default, Excel PERCENTILE.INC
.medianUnbiased, .normalUnbiased 8, 9 numpy median_unbiased, normal_unbiased
swift
let s = try Descriptive.summary(data)                          // s.mean, s.sampleStandardDeviation, s.fiveNumber…
let q1 = try Descriptive.quantile(data, 0.25, method: .weibull)
let h = try Descriptive.histogram(data, rule: .freedmanDiaconis)   // h.edges, h.counts, h.densities

# 3. Distributions

Protocols: ProbabilityDistribution → ContinuousDistribution (pdf, logPDF) / DiscreteDistribution (pmf(Int), logPMF(Int), pmf(at: Double), sampleInteger(using:)). Initialisers throw on invalid parameters.

Common members: name, mean, variance, standardDeviation, supportLowerBound, supportUpperBound, cdf(x) = P(X ≤ x), survival(x) = P(X > x), probabilityBelow(x) = P(X < x), probabilityAtLeast(x) = P(X ≥ x), probability(from: a, to: b) = P(a ≤ X ≤ b) (both ends included), quantile(p), quantile(upperTail: q), median(), verifiedQuantile(p) (value + round-trip report), sample(using: &g), samples(n, using: &g).

Type Initialiser Parameterisation
NormalDistribution (mean:standardDeviation:), .standard σ, not σ²
StandardNormalDistribution ()
StudentTDistribution (degreesOfFreedom:) ν > 0, fractional allowed
ChiSquareDistribution (degreesOfFreedom:)
FDistribution (numeratorDegreesOfFreedom:denominatorDegreesOfFreedom:)
GammaDistribution (shape:rate:) or (shape:scale:) stored as shape + rate; mean = shape/rate
BetaDistribution (alpha:beta:)
ExponentialDistribution (rate:) or (mean:) mean = 1/rate
UniformDistribution (lowerBound:upperBound:) continuous
BinomialDistribution (trials:probability:)
PoissonDistribution (mean:)
GeometricDistribution (probability:counting: .trials) .trials = 1, 2, … (TI); .failures = 0, 1, … (R/Excel)
NegativeBinomialDistribution (successes:probability:) failures before the r-th success; r may be fractional
DiscreteUniformDistribution (lowerBound:upperBound:) integers a…b

Discrete quantile = smallest k with cdf(k) ≥ p (a 64-ulp fuzz absorbs a p that is itself a rounded CDF value, as R does). quantile(0) / quantile(1) return the support bounds (possibly ±∞).

swift
let t = try StudentTDistribution(degreesOfFreedom: 12)
let crit = try t.quantile(upperTail: 0.025)                 // 2.178812829667228
let b = try BinomialDistribution(trials: 20, probability: 0.3)
let p = b.probability(from: 4, to: 7)                       // P(4 ≤ X ≤ 7), binomcdf-style
let k = try b.quantile(0.9)                                 // smallest k with P(X ≤ k) ≥ 0.9

# 4. Random numbers

  • SeededGenerator(seed:stream:) — xoshiro256** seeded through SplitMix64; conforms to RandomNumberGenerator; Equatable. stream gives independent sequences for the same seed. Not cryptographic.
  • SplitMix64(seed:) — the seeding generator, also usable directly.
  • enum Sampling — uniform, openUniform, uniformInteger(below:), standardNormal (Marsaglia polar), standardExponential, gamma(shape:) (Marsaglia–Tsang), beta(a, b), binomial(n:p:) (inversion / beta splitting, exact), poisson(mean:) (inversion / Ahrens–Dieter gamma method, exact), geometricFailures(p:), negativeBinomial(r:p:), shuffled(_:), resample(_:count:). All take using: inout G.
swift
var g = SeededGenerator(seed: 2026)
let draws = try NormalDistribution(mean: 100, standardDeviation: 15).samples(1000, using: &g)

# 5. Inference

SampleSummary(count:mean:standardDeviation:) or SampleSummary(data:) is the "Stats" input; most functions also have a data: overload. Alternative: .twoSided (default), .less, .greater.

# Confidence intervals — enum ConfidenceIntervals → ConfidenceInterval

ConfidenceInterval: estimate, lower, upper, level, marginOfError, standardError?, criticalValue?, degreesOfFreedom?, method, contains(_:), explanation, verification.

Function Method
meanZ(mean:sigma:n:level:), meanZ(data:sigma:level:) z, σ known
meanT(_ summary, level:), meanT(data:level:) t, df = n − 1
pairedMean(first, second, level:) t on differences first − second
differenceOfMeans(a, b, level:, method: .welch), differenceOfMeans(data:_:…) TwoSampleMethod: .welch (default) / .pooled
differenceOfMeansZ(mean1:sigma1:n1:mean2:sigma2:n2:level:) σ's known
proportion(successes:trials:level:method: .wilson) ProportionIntervalMethod: .wilson (default), .wald (not clipped), .agrestiCoull (clipped), .clopperPearson
differenceOfProportions(successes1:trials1:successes2:trials2:level:) Wald, unpooled
variance(_ summary, level:), variance(data:), standardDeviation(_ summary, level:) chi-square
correlation(r:n:level:), correlation(x, y, level:) Fisher z

# Tests — enum HypothesisTests → HypothesisTestResult

HypothesisTestResult: name, statisticSymbol ("z", "t", "χ²", "F", "x"), statistic, degreesOfFreedom: [Double], pValue, alternative, alpha, criticalValue (+ lowerCriticalValue for the two-sided F test), rejectNull, estimate?, nullValue?, standardError?, confidenceInterval? (always two-sided at level 1 − α), effectSize? (name, value), conclusion, explanation, verification.

Function Returns Effect size
oneSampleZ(mean:n:sigma:mu0:…), oneSampleZ(data:sigma:mu0:…) result Cohen's d
oneSampleT(_ summary, mu0:…), oneSampleT(data:mu0:…) result Cohen's d
pairedT(first, second, difference: 0, …) result Cohen's d_z
twoSampleT(a, b, method: .welch, difference: 0, …), twoSampleT(data:_:…) result (Welch–Satterthwaite df) Cohen's d (pooled SD)
twoSampleZ(mean1:sigma1:n1:mean2:sigma2:n2:…) result —
oneProportionZ(successes:trials:p0:continuityCorrection: false, …) result (Wilson CI) Cohen's h
binomialExact(successes:trials:p0:…) result (Clopper–Pearson CI) Cohen's h
twoProportionZ(successes1:trials1:successes2:trials2:…) result (pooled SE; unpooled Wald CI) Cohen's h
chiSquareGoodnessOfFit(observed:expectedProportions:estimatedParameters:alpha:), …(observed:expectedCounts:…) GoodnessOfFitResult (test, expected, contributions, residuals) Cohen's w
chiSquareIndependence(table:yatesCorrection: false, alpha:) IndependenceTestResult (test, expected, contributions, totals, cramersV, yatesApplied) Cramér's V
oneWayANOVA(groups:alpha:), oneWayANOVA(summaries:alpha:) AnovaResult (SS/df/MS between & within, etaSquared, pooledStandardDeviation, test) η²
fTestVariances(a, b, …), fTestVariances(data:_:…) result (CI for σ₁²/σ₂²) —
correlationTest(r:n:…), correlationTest(x, y, …) result (Fisher CI) r

All take alternative: (where meaningful) and alpha: 0.05.

swift
let r = try HypothesisTests.twoSampleT(data: groupA, groupB, method: .welch, alternative: .greater, alpha: 0.05)
r.statistic; r.degreesOfFreedom[0]; r.pValue; r.criticalValue; r.rejectNull; r.confidenceInterval; r.effectSize
r.explanation.plainText                   // ORIX Explain
r.verification.warnings                   // e.g. "Sample size (n₁) … < 30"
let chi = try HypothesisTests.chiSquareIndependence(table: [[12, 5], [7, 14]])
chi.expected; chi.cramersV; chi.test.verification.warnings   // "Expected counts ≥ 5" warning when it applies

# 6. Regression

# LinearRegression.simple(x:y:level:) -> SimpleRegressionResult

slope, intercept (RegressionCoefficient: estimate, standardError, tStatistic, pValue, lower, upper), correlation, rSquared, adjustedRSquared, residualStandardError, degreesOfFreedom, fStatistic, fPValue, fitted, residuals, value(at:), predict(at:level:) -> RegressionPrediction (fitted, mean-response interval, prediction interval).

# LinearRegression.multiple(y:predictors:names:intercept:level:) -> MultipleRegressionResult

predictors is an array of columns. Result: coefficients (intercept first), rSquared, adjustedRSquared, residualStandardError, fStatistic?, fPValue?, fDegreesOfFreedom, fitted, residuals, leverage, standardizedResiduals (internal), studentizedResiduals (external), cooksDistance, durbinWatson, varianceInflationFactors, logLikelihood, aic, bic (k = p + 1, R convention), covarianceMatrix, conditionEstimate, value(at:), predict(at:level:). Collinear predictors throw .singularDesignMatrix naming the redundant columns.

# CurveFit.fit(x:y:model:level:) -> CurveFitResult

CurveModel: .linear, .quadratic, .cubic, .polynomial(degree:) (1…12), .exponential (y = a·bˣ), .logarithmic (y = a + b·ln x), .power (y = a·xᵇ). Result: coefficients (polynomials: ascending powers c₀, c₁, …; others: [a, b]), coefficientNames, equation, rSquared, rSquaredScale (.transformed for exponential/power: R² of ln y), rSquaredOriginalScale, regression? (full diagnostics; nil for an exact interpolation), value(at:).

swift
let fit = try LinearRegression.simple(x: xs, y: ys)
let at10 = try fit.predict(at: 10, level: 0.95)          // .fitted, .meanLower/.meanUpper, .predictionLower/.predictionUpper
let m = try LinearRegression.multiple(y: y, predictors: [x1, x2], names: ["price", "ads"])
let e = try CurveFit.fit(x: xs, y: ys, model: .exponential)   // label R² with e.rSquaredScale

# 7. Simulation

API Purpose
MonteCarlo.run(trials:seed:quantiles:binning:progressInterval:event:progress:_ trial) synchronous; trial: (inout SeededGenerator) throws -> Double
MonteCarlo.runAsync(…) same result; checks Task.checkCancellation() every progressInterval trials (throws CancellationError), @Sendable closures
MonteCarlo.summarize(values, …) summary of outcomes produced elsewhere
MonteCarlo.samplingDistribution(of:sampleSize:replications:seed:from:) / …fromPopulation: sampling distribution of a statistic
ScenarioAnalysis.evaluate(scenarios, outputs:, model:) -> ScenarioTable named scenarios → outputs table (rows, output(_:in:), column(_:), changesFromBase)
ScenarioAnalysis.sensitivity(base:varying:values:outputs:model:) one-way data table
Bootstrap.confidenceInterval(data:level:resamples:seed:method:statistic:) BootstrapMethod: .bca (default), .percentile, .basic
Bootstrap.confidenceInterval(count:…statistic: ([Int]) -> Double) index form for paired / multivariate data
Bootstrap.interval(replicates:estimate:jackknife:level:method:) interval arithmetic on existing replicates

MonteCarloSummary: trials, seed, mean, standardDeviation, standardError, meanLower/meanUpper (95%), minimum, maximum, quantiles (R-7), histogram, eventProbability?, eventStandardError?, values, quantile(p), probability(where:), verification.

swift
let demand = try NormalDistribution(mean: 1200, standardDeviation: 180)
let sim = try await MonteCarlo.runAsync(trials: 100_000, seed: 42, event: { $0 < 0 }, progress: { p in /* p.fraction */ }) { g in
    let units = demand.sample(using: &g)
    return units * 12.5 - 14_000                              // profit of one trial
}
sim.mean; sim.standardError; sim.eventProbability; sim.histogram
let boot = try Bootstrap.confidenceInterval(data: data, seed: 7) { try Descriptive.median($0) }   // BCa, 2000 resamples
Files main
Menu

Theme