Repository Public MIT
1<!--2ORIX Calc3File: Packages/ORIXStatistics/API.md4Description: Public API reference of the statistics & probability engine, for the UI layer.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# ORIXStatistics — API reference910Swift 6 package, no UI, no external dependency except the sibling `ORIXNumerics` (for `Explanation`, `VerificationReport`,11`RootFinder`). Platforms: iOS 26, macOS 15. `import ORIXStatistics` (and `import ORIXNumerics` to name `Explanation` /12`VerificationReport` types).1314## Rules that hold everywhere1516| Rule | Detail |17|---|---|18| Value types | Every public type is a `Sendable` struct or enum; every function is pure. Safe to call from any actor or `Task`. |19| Errors | Invalid input throws `StatisticsError` (`description` / `errorDescription` are user-facing sentences). Nothing returns NaN for a valid request. |20| NaN | A NaN *argument* of `pdf`/`cdf`/`survival` propagates as NaN (IEEE). Data lists containing NaN or ±∞ throw `.nonFiniteValue`. |21| 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`. |22| Levels | Confidence `level` and significance `alpha` are in the open interval (0, 1): 0.95, not 95. |23| Decision | `rejectNull == (pValue <= alpha)`. |24| 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. |25| Reproducibility | Anything random takes a `seed: UInt64` or an `inout` generator. Same seed ⇒ identical result. |2627`StatisticsError` cases: `emptyData`, `insufficientSample(required:actual:)`, `parameterOutOfDomain(name:value:requirement:)`,28`probabilityOutOfRange`, `nonFiniteValue`, `dimensionMismatch`, `singularDesignMatrix`, `nonConvergence`, `undefined`,29`overflow`, `invalidArgument`.3031## 1. Special functions — `enum SpecialFunctions`3233All `static`, all `throws`.3435| Function | Meaning |36|---|---|37| `logGamma(x)`, `gamma(x)` | ln\|Γ(x)\|, Γ(x) (poles and overflow throw) |38| `logBeta(a, b)`, `beta(a, b)` | a, b > 0 |39| `logFactorial(n)`, `factorial(n)` | n! exact to 22!, up to 170! |40| `binomialCoefficient(n, k)`, `permutations(n, k)` | nCr, nPr as `Double` (exact below 2⁵³) |41| `erf(x)`, `erfc(x)`, `inverseErf(y)`, `inverseErfc(q)` | |42| `normalCDF(z)`, `normalSurvival(z)` | Φ(z), 1 − Φ(z) |43| `normalQuantile(p)`, `normalQuantile(upperTail: q)` | Φ⁻¹ |44| `regularizedGammaP(a:x:)`, `regularizedGammaQ(a:x:)` | P(a, x), Q(a, x) = 1 − P |45| `inverseRegularizedGammaP(a:p:)`, `inverseRegularizedGammaQ(a:q:)` | |46| `regularizedBeta(x:a:b:)`, `regularizedBetaComplement(x:a:b:)` | I_x(a, b), 1 − I_x(a, b) |47| `inverseRegularizedBeta(p:a:b:)`, `inverseRegularizedBetaComplement(q:a:b:)` | |4849```swift50let p = try SpecialFunctions.regularizedGammaQ(a: 2.5, x: 7) // upper tail, computed directly51let z = try SpecialFunctions.normalQuantile(upperTail: 0.025) // 1.95996398454005452```53Use the complementary form (`Q`, `Complement`, `upperTail:`) for small upper tails: it keeps full relative accuracy.5455## 2. Descriptive statistics — `enum Descriptive`5657Input: `[Double]`. Conventions: "sample" = n − 1 denominator (default), "population" = n.5859| Function | Notes |60|---|---|61| `count`, `sum` (Neumaier), `mean`, `median`, `minimum`, `maximum`, `range` | |62| `modes(x) -> [Double]` | all modes ascending; `[]` when every value is unique (n > 1) |63| `variance(x, sample: true)`, `standardDeviation(x, sample: true)`, `standardError(x)`, `coefficientOfVariation(x)` | |64| `quantile(x, p, method: .linear)`, `quantiles(x, ps, method:)`, `percentile(x, k, method:)` | `QuantileMethod`: R-1 … R-9 (table below) |65| `quartiles(x, method:) -> (first, third)`, `interquartileRange`, `fiveNumberSummary` | `QuartileMethod`: `.quantile(QuantileMethod)` (default R-7), `.tukeyHinges`, `.medianOfHalvesExclusive` (TI-83/84) |66| `populationSkewness` (g₁), `sampleSkewness` (G₁, Excel SKEW) | |67| `populationExcessKurtosis` (g₂), `sampleExcessKurtosis` (G₂, Excel KURT) | always *excess* kurtosis (normal = 0) |68| `centralMoment(x, order:)` | |69| `geometricMean`, `harmonicMean`, `weightedMean(x, weights:)` | positive data for the first two |70| `covariance(x, y, sample: true)`, `correlation(x, y)` (Pearson), `spearmanCorrelation(x, y)` | |71| `ranks(x)` | average ranks for ties |72| `zScores(x, sample: true)` | |73| `frequencyTable(x) -> [FrequencyRow]` | value, count, relative, cumulative |74| `histogram(x, rule: .sturges, range: nil) -> Histogram` | `BinningRule`: `.sturges`, `.freedmanDiaconis`, `.fixedCount(n)`, `.fixedWidth(w, origin:)`; bins are `[a, b)`, the last one `[a, b]` |75| `expand(values:frequencies:)` | turns a value list + frequency list (TI FreqList) into raw data |76| `summary(x, quartileMethod:) -> DescriptiveSummary` | everything for a "1-Var Stats" screen |7778| `QuantileMethod` | R type | Same as |79|---|---|---|80| `.invertedCDF`, `.averagedInvertedCDF`, `.closestObservation` | 1, 2, 3 | numpy `inverted_cdf`, `averaged_inverted_cdf`, `closest_observation` |81| `.interpolatedInvertedCDF`, `.hazen` | 4, 5 | numpy `interpolated_inverted_cdf`, `hazen` |82| `.weibull` | 6 | Excel PERCENTILE.EXC, Minitab, SPSS, numpy `weibull` (clamped at the ends instead of failing) |83| `.linear` **(default)** | 7 | numpy default, R default, Excel PERCENTILE.INC |84| `.medianUnbiased`, `.normalUnbiased` | 8, 9 | numpy `median_unbiased`, `normal_unbiased` |8586```swift87let s = try Descriptive.summary(data) // s.mean, s.sampleStandardDeviation, s.fiveNumber…88let q1 = try Descriptive.quantile(data, 0.25, method: .weibull)89let h = try Descriptive.histogram(data, rule: .freedmanDiaconis) // h.edges, h.counts, h.densities90```9192## 3. Distributions9394Protocols: `ProbabilityDistribution` → `ContinuousDistribution` (`pdf`, `logPDF`) / `DiscreteDistribution` (`pmf(Int)`,95`logPMF(Int)`, `pmf(at: Double)`, `sampleInteger(using:)`). Initialisers throw on invalid parameters.9697Common members: `name`, `mean`, `variance`, `standardDeviation`, `supportLowerBound`, `supportUpperBound`, `cdf(x)` = P(X ≤ x),98`survival(x)` = P(X > x), `probabilityBelow(x)` = P(X < x), `probabilityAtLeast(x)` = P(X ≥ x), `probability(from: a, to: b)` =99P(a ≤ X ≤ b) (both ends included), `quantile(p)`, `quantile(upperTail: q)`, `median()`, `verifiedQuantile(p)` (value + round-trip100report), `sample(using: &g)`, `samples(n, using: &g)`.101102| Type | Initialiser | Parameterisation |103|---|---|---|104| `NormalDistribution` | `(mean:standardDeviation:)`, `.standard` | σ, not σ² |105| `StandardNormalDistribution` | `()` | |106| `StudentTDistribution` | `(degreesOfFreedom:)` | ν > 0, fractional allowed |107| `ChiSquareDistribution` | `(degreesOfFreedom:)` | |108| `FDistribution` | `(numeratorDegreesOfFreedom:denominatorDegreesOfFreedom:)` | |109| `GammaDistribution` | `(shape:rate:)` or `(shape:scale:)` | stored as shape + rate; mean = shape/rate |110| `BetaDistribution` | `(alpha:beta:)` | |111| `ExponentialDistribution` | `(rate:)` or `(mean:)` | mean = 1/rate |112| `UniformDistribution` | `(lowerBound:upperBound:)` | continuous |113| `BinomialDistribution` | `(trials:probability:)` | |114| `PoissonDistribution` | `(mean:)` | |115| `GeometricDistribution` | `(probability:counting: .trials)` | `.trials` = 1, 2, … (TI); `.failures` = 0, 1, … (R/Excel) |116| `NegativeBinomialDistribution` | `(successes:probability:)` | failures before the r-th success; r may be fractional |117| `DiscreteUniformDistribution` | `(lowerBound:upperBound:)` | integers a…b |118119Discrete quantile = smallest k with `cdf(k) ≥ p` (a 64-ulp fuzz absorbs a p that is itself a rounded CDF value, as R does).120`quantile(0)` / `quantile(1)` return the support bounds (possibly ±∞).121122```swift123let t = try StudentTDistribution(degreesOfFreedom: 12)124let crit = try t.quantile(upperTail: 0.025) // 2.178812829667228125let b = try BinomialDistribution(trials: 20, probability: 0.3)126let p = b.probability(from: 4, to: 7) // P(4 ≤ X ≤ 7), binomcdf-style127let k = try b.quantile(0.9) // smallest k with P(X ≤ k) ≥ 0.9128```129130## 4. Random numbers131132- `SeededGenerator(seed:stream:)` — xoshiro256** seeded through SplitMix64; conforms to `RandomNumberGenerator`; `Equatable`.133 `stream` gives independent sequences for the same seed. Not cryptographic.134- `SplitMix64(seed:)` — the seeding generator, also usable directly.135- `enum Sampling` — `uniform`, `openUniform`, `uniformInteger(below:)`, `standardNormal` (Marsaglia polar),136 `standardExponential`, `gamma(shape:)` (Marsaglia–Tsang), `beta(a, b)`, `binomial(n:p:)` (inversion / beta splitting, exact),137 `poisson(mean:)` (inversion / Ahrens–Dieter gamma method, exact), `geometricFailures(p:)`, `negativeBinomial(r:p:)`,138 `shuffled(_:)`, `resample(_:count:)`. All take `using: inout G`.139140```swift141var g = SeededGenerator(seed: 2026)142let draws = try NormalDistribution(mean: 100, standardDeviation: 15).samples(1000, using: &g)143```144145## 5. Inference146147`SampleSummary(count:mean:standardDeviation:)` or `SampleSummary(data:)` is the "Stats" input; most functions also have a148`data:` overload. `Alternative`: `.twoSided` (default), `.less`, `.greater`.149150### Confidence intervals — `enum ConfidenceIntervals` → `ConfidenceInterval`151152`ConfidenceInterval`: `estimate`, `lower`, `upper`, `level`, `marginOfError`, `standardError?`, `criticalValue?`,153`degreesOfFreedom?`, `method`, `contains(_:)`, `explanation`, `verification`.154155| Function | Method |156|---|---|157| `meanZ(mean:sigma:n:level:)`, `meanZ(data:sigma:level:)` | z, σ known |158| `meanT(_ summary, level:)`, `meanT(data:level:)` | t, df = n − 1 |159| `pairedMean(first, second, level:)` | t on differences first − second |160| `differenceOfMeans(a, b, level:, method: .welch)`, `differenceOfMeans(data:_:…)` | `TwoSampleMethod`: `.welch` (default) / `.pooled` |161| `differenceOfMeansZ(mean1:sigma1:n1:mean2:sigma2:n2:level:)` | σ's known |162| `proportion(successes:trials:level:method: .wilson)` | `ProportionIntervalMethod`: `.wilson` (default), `.wald` (not clipped), `.agrestiCoull` (clipped), `.clopperPearson` |163| `differenceOfProportions(successes1:trials1:successes2:trials2:level:)` | Wald, unpooled |164| `variance(_ summary, level:)`, `variance(data:)`, `standardDeviation(_ summary, level:)` | chi-square |165| `correlation(r:n:level:)`, `correlation(x, y, level:)` | Fisher z |166167### Tests — `enum HypothesisTests` → `HypothesisTestResult`168169`HypothesisTestResult`: `name`, `statisticSymbol` ("z", "t", "χ²", "F", "x"), `statistic`, `degreesOfFreedom: [Double]`, `pValue`,170`alternative`, `alpha`, `criticalValue` (+ `lowerCriticalValue` for the two-sided F test), `rejectNull`, `estimate?`, `nullValue?`,171`standardError?`, `confidenceInterval?` (always two-sided at level 1 − α), `effectSize?` (`name`, `value`), `conclusion`,172`explanation`, `verification`.173174| Function | Returns | Effect size |175|---|---|---|176| `oneSampleZ(mean:n:sigma:mu0:…)`, `oneSampleZ(data:sigma:mu0:…)` | result | Cohen's d |177| `oneSampleT(_ summary, mu0:…)`, `oneSampleT(data:mu0:…)` | result | Cohen's d |178| `pairedT(first, second, difference: 0, …)` | result | Cohen's d_z |179| `twoSampleT(a, b, method: .welch, difference: 0, …)`, `twoSampleT(data:_:…)` | result (Welch–Satterthwaite df) | Cohen's d (pooled SD) |180| `twoSampleZ(mean1:sigma1:n1:mean2:sigma2:n2:…)` | result | — |181| `oneProportionZ(successes:trials:p0:continuityCorrection: false, …)` | result (Wilson CI) | Cohen's h |182| `binomialExact(successes:trials:p0:…)` | result (Clopper–Pearson CI) | Cohen's h |183| `twoProportionZ(successes1:trials1:successes2:trials2:…)` | result (pooled SE; unpooled Wald CI) | Cohen's h |184| `chiSquareGoodnessOfFit(observed:expectedProportions:estimatedParameters:alpha:)`, `…(observed:expectedCounts:…)` | `GoodnessOfFitResult` (`test`, `expected`, `contributions`, `residuals`) | Cohen's w |185| `chiSquareIndependence(table:yatesCorrection: false, alpha:)` | `IndependenceTestResult` (`test`, `expected`, `contributions`, totals, `cramersV`, `yatesApplied`) | Cramér's V |186| `oneWayANOVA(groups:alpha:)`, `oneWayANOVA(summaries:alpha:)` | `AnovaResult` (SS/df/MS between & within, `etaSquared`, `pooledStandardDeviation`, `test`) | η² |187| `fTestVariances(a, b, …)`, `fTestVariances(data:_:…)` | result (CI for σ₁²/σ₂²) | — |188| `correlationTest(r:n:…)`, `correlationTest(x, y, …)` | result (Fisher CI) | r |189190All take `alternative:` (where meaningful) and `alpha: 0.05`.191192```swift193let r = try HypothesisTests.twoSampleT(data: groupA, groupB, method: .welch, alternative: .greater, alpha: 0.05)194r.statistic; r.degreesOfFreedom[0]; r.pValue; r.criticalValue; r.rejectNull; r.confidenceInterval; r.effectSize195r.explanation.plainText // ORIX Explain196r.verification.warnings // e.g. "Sample size (n₁) … < 30"197let chi = try HypothesisTests.chiSquareIndependence(table: [[12, 5], [7, 14]])198chi.expected; chi.cramersV; chi.test.verification.warnings // "Expected counts ≥ 5" warning when it applies199```200201## 6. Regression202203### `LinearRegression.simple(x:y:level:) -> SimpleRegressionResult`204`slope`, `intercept` (`RegressionCoefficient`: `estimate`, `standardError`, `tStatistic`, `pValue`, `lower`, `upper`),205`correlation`, `rSquared`, `adjustedRSquared`, `residualStandardError`, `degreesOfFreedom`, `fStatistic`, `fPValue`, `fitted`,206`residuals`, `value(at:)`, `predict(at:level:) -> RegressionPrediction` (`fitted`, mean-response interval, prediction interval).207208### `LinearRegression.multiple(y:predictors:names:intercept:level:) -> MultipleRegressionResult`209`predictors` is an array of **columns**. Result: `coefficients` (intercept first), `rSquared`, `adjustedRSquared`,210`residualStandardError`, `fStatistic?`, `fPValue?`, `fDegreesOfFreedom`, `fitted`, `residuals`, `leverage`,211`standardizedResiduals` (internal), `studentizedResiduals` (external), `cooksDistance`, `durbinWatson`,212`varianceInflationFactors`, `logLikelihood`, `aic`, `bic` (k = p + 1, R convention), `covarianceMatrix`, `conditionEstimate`,213`value(at:)`, `predict(at:level:)`. Collinear predictors throw `.singularDesignMatrix` naming the redundant columns.214215### `CurveFit.fit(x:y:model:level:) -> CurveFitResult`216`CurveModel`: `.linear`, `.quadratic`, `.cubic`, `.polynomial(degree:)` (1…12), `.exponential` (y = a·bˣ), `.logarithmic`217(y = a + b·ln x), `.power` (y = a·xᵇ). Result: `coefficients` (polynomials: ascending powers c₀, c₁, …; others: [a, b]),218`coefficientNames`, `equation`, `rSquared`, **`rSquaredScale`** (`.transformed` for exponential/power: R² of ln y),219`rSquaredOriginalScale`, `regression?` (full diagnostics; `nil` for an exact interpolation), `value(at:)`.220221```swift222let fit = try LinearRegression.simple(x: xs, y: ys)223let at10 = try fit.predict(at: 10, level: 0.95) // .fitted, .meanLower/.meanUpper, .predictionLower/.predictionUpper224let m = try LinearRegression.multiple(y: y, predictors: [x1, x2], names: ["price", "ads"])225let e = try CurveFit.fit(x: xs, y: ys, model: .exponential) // label R² with e.rSquaredScale226```227228## 7. Simulation229230| API | Purpose |231|---|---|232| `MonteCarlo.run(trials:seed:quantiles:binning:progressInterval:event:progress:_ trial)` | synchronous; `trial: (inout SeededGenerator) throws -> Double` |233| `MonteCarlo.runAsync(…)` | same result; checks `Task.checkCancellation()` every `progressInterval` trials (throws `CancellationError`), `@Sendable` closures |234| `MonteCarlo.summarize(values, …)` | summary of outcomes produced elsewhere |235| `MonteCarlo.samplingDistribution(of:sampleSize:replications:seed:from:)` / `…fromPopulation:` | sampling distribution of a statistic |236| `ScenarioAnalysis.evaluate(scenarios, outputs:, model:) -> ScenarioTable` | named scenarios → outputs table (`rows`, `output(_:in:)`, `column(_:)`, `changesFromBase`) |237| `ScenarioAnalysis.sensitivity(base:varying:values:outputs:model:)` | one-way data table |238| `Bootstrap.confidenceInterval(data:level:resamples:seed:method:statistic:)` | `BootstrapMethod`: `.bca` (default), `.percentile`, `.basic` |239| `Bootstrap.confidenceInterval(count:…statistic: ([Int]) -> Double)` | index form for paired / multivariate data |240| `Bootstrap.interval(replicates:estimate:jackknife:level:method:)` | interval arithmetic on existing replicates |241242`MonteCarloSummary`: `trials`, `seed`, `mean`, `standardDeviation`, `standardError`, `meanLower`/`meanUpper` (95%), `minimum`,243`maximum`, `quantiles` (R-7), `histogram`, `eventProbability?`, `eventStandardError?`, `values`, `quantile(p)`,244`probability(where:)`, `verification`.245246```swift247let demand = try NormalDistribution(mean: 1200, standardDeviation: 180)248let sim = try await MonteCarlo.runAsync(trials: 100_000, seed: 42, event: { $0 < 0 }, progress: { p in /* p.fraction */ }) { g in249 let units = demand.sample(using: &g)250 return units * 12.5 - 14_000 // profit of one trial251}252sim.mean; sim.standardError; sim.eventProbability; sim.histogram253let boot = try Bootstrap.confidenceInterval(data: data, seed: 7) { try Descriptive.median($0) } // BCa, 2000 resamples254```255