Repository Public
1import Foundation23/// Centre used for the absolute deviations of Levene-type tests.4public enum LeveneCenter: String, Sendable, Codable, CaseIterable {5 /// Original Levene test (deviations from the group means).6 case mean7 /// Brown–Forsythe test (deviations from the group medians): robust to non-normality. SciPy's default.8 case median9}1011extension Inference {12 /// F-test of equality of two variances, F = s²x / s²y with (n₁−1, n₂−1) df.13 /// Two-sided p-value = 2·min(lower tail, upper tail). Very sensitive to non-normality.14 public static func varianceFTest(_ x: [Double], _ y: [Double], alternative: Alternative = .twoSided, level: Double = 0.95) throws -> HypothesisTest {15 let a = try clean(x, min: 2, "first sample"), b = try clean(y, min: 2, "second sample")16 try checkLevel(level)17 let v1 = Descriptive.variance(a), v2 = Descriptive.variance(b)18 guard v1 > 0, v2 > 0 else { throw StatError.invalidInput("a sample is constant: the variance ratio is undefined") }19 let d1 = Double(a.count - 1), d2 = Double(b.count - 1)20 let f = v1 / v221 let dist = FisherFDistribution(d1: d1, d2: d2)22 let alpha = (1 - level) / 223 let ci = ConfidenceInterval(estimate: f, lower: f / dist.isf(alpha), upper: f / dist.quantile(alpha), level: level, method: "F distribution (normal data)")24 return HypothesisTest(name: "F-test for equality of variances", statisticName: "F", statistic: f, df: d1, df2: d2,25 pValue: dist.pValue(f, alternative: alternative), alternative: alternative,26 pValueDescription: alternative == .twoSided ? "two-sided (twice the smaller tail)" : alternative.label,27 estimate: NamedValue("Variance ratio", f), confidenceInterval: ci,28 details: [NamedValue("Variance 1", v1), NamedValue("Variance 2", v2), NamedValue("n1", Double(a.count)), NamedValue("n2", Double(b.count))],29 assumptions: ["The two samples are independent", "Both populations are normal (the test is not robust to departures)"])30 }3132 /// Levene's test (`center: .mean`) or the Brown–Forsythe test (`center: .median`, default) of equal33 /// variances across k groups: a one-way ANOVA on |x − centre|. W ~ F(k−1, N−k); upper-tail p-value.34 public static func leveneTest(_ groups: [[Double]], center: LeveneCenter = .median) throws -> HypothesisTest {35 guard groups.count >= 2 else { throw StatError.insufficientData("need at least two groups") }36 let gs = try groups.enumerated().map { try clean($1, min: 1, "group \($0 + 1)") }37 let z = gs.map { g -> [Double] in38 let c = center == .mean ? Descriptive.mean(g) : Descriptive.median(g)39 return g.map { abs($0 - c) }40 }41 let n = Double(z.reduce(0) { $0 + $1.count }), k = Double(z.count)42 guard n > k else { throw StatError.insufficientData("need more observations than groups") }43 let grand = Descriptive.mean(z.flatMap { $0 })44 var num = 0.0, den = 0.045 for g in z {46 let m = Descriptive.mean(g)47 num += Double(g.count) * (m - grand) * (m - grand)48 den += g.reduce(0) { $0 + ($1 - m) * ($1 - m) }49 }50 guard den > 0 else { throw StatError.invalidInput("no variation in the absolute deviations") }51 let w = (n - k) / (k - 1) * num / den52 return HypothesisTest(name: center == .mean ? "Levene's test for equality of variances" : "Brown–Forsythe test for equality of variances",53 statisticName: "W", statistic: w, df: k - 1, df2: n - k,54 pValue: FisherFDistribution(d1: k - 1, d2: n - k).sf(w), alternative: .greater,55 pValueDescription: "upper tail of F(\(Int(k - 1)), \(Int(n - k)))",56 details: [NamedValue("Groups", k), NamedValue("Observations", n)],57 assumptions: ["Observations are independent", "Absolute deviations from the group \(center.rawValue) are compared, so normality is not required"])58 }5960 /// Bartlett's test of equal variances across k normal samples. T ~ χ²(k−1); upper-tail p-value.61 public static func bartlettTest(_ groups: [[Double]]) throws -> HypothesisTest {62 guard groups.count >= 2 else { throw StatError.insufficientData("need at least two groups") }63 let gs = try groups.enumerated().map { try clean($1, min: 2, "group \($0 + 1)") }64 let k = Double(gs.count), n = Double(gs.reduce(0) { $0 + $1.count })65 let vars = gs.map { Descriptive.variance($0) }66 guard vars.allSatisfy({ $0 > 0 }) else { throw StatError.invalidInput("a group is constant") }67 var pooled = 0.0, sumLog = 0.0, sumInv = 0.068 for (g, v) in zip(gs, vars) {69 let d = Double(g.count - 1)70 pooled += d * v; sumLog += d * log(v); sumInv += 1 / d71 }72 pooled /= (n - k)73 let t = ((n - k) * log(pooled) - sumLog) / (1 + (sumInv - 1 / (n - k)) / (3 * (k - 1)))74 return HypothesisTest(name: "Bartlett's test for equality of variances", statisticName: "T", statistic: t, df: k - 1,75 pValue: ChiSquaredDistribution(df: k - 1).sf(t), alternative: .greater, pValueDescription: "upper tail of χ²(\(Int(k - 1)))",76 details: [NamedValue("Groups", k), NamedValue("Pooled variance", pooled)],77 assumptions: ["Observations are independent", "Every population is normal (use Levene/Brown–Forsythe otherwise)"])78 }79}80