SPB Git

Repository Public

InferenceTests.swift 23.4 KB 351 lines swift

1import Foundation2import Testing3import SheetCore4import AnalyticsTestSupport5@testable import Statistics67private let alternatives: [(String, Alternative)] = [("twoSided", .twoSided), ("less", .less), ("greater", .greater)]89@Suite struct ConfidenceIntervalTests {10    let f = diFixture["ci"]1112    @Test func meanAndVariance() throws {13        let x = diData("x")14        let c95 = try Inference.meanInterval(x)15        #expect(isClose(c95.lower, f["mean95"][0].d, rel: 1e-11) && isClose(c95.upper, f["mean95"][1].d, rel: 1e-11))16        let c99 = try Inference.meanInterval(x, level: 0.99)17        #expect(isClose(c99.lower, f["mean99"][0].d, rel: 1e-11) && isClose(c99.upper, f["mean99"][1].d, rel: 1e-11))18        let z = try Inference.meanInterval(x, knownSigma: 12, level: 0.9)19        #expect(isClose(z.lower, f["mean_z"][0].d, rel: 1e-12) && isClose(z.upper, f["mean_z"][1].d, rel: 1e-12))20        let v = try Inference.varianceInterval(x)21        #expect(isClose(v.lower, f["var95"][0].d, rel: 1e-11) && isClose(v.upper, f["var95"][1].d, rel: 1e-11))22        #expect(v.lower < v.estimate && v.estimate < v.upper)23        #expect(throws: StatError.self) { try Inference.meanInterval([1]) }24        #expect(throws: StatError.self) { try Inference.meanInterval(x, level: 1) }25        #expect(throws: StatError.self) { try Inference.meanInterval([1, .nan, 3]) }26        #expect(c95.table().count == 5)27    }2829    @Test func proportions() throws {30        for c in f["prop"].list {31            let k = c["k"].i, n = c["n"].i, lvl = c["level"].d32            let w = try Inference.proportionInterval(successes: k, trials: n, level: lvl)33            #expect(isClose(w.lower, c["wilson"][0].d, rel: 1e-11, abs: 1e-15) && isClose(w.upper, c["wilson"][1].d, rel: 1e-11), "wilson \(k)/\(n) \(lvl)")34            let wald = try Inference.proportionInterval(successes: k, trials: n, level: lvl, method: .wald)35            #expect(isClose(wald.lower, max(0, c["wald"][0].d), rel: 1e-11, abs: 1e-15) && isClose(wald.upper, min(1, c["wald"][1].d), rel: 1e-11), "wald \(k)/\(n)")36            let cp = try Inference.proportionInterval(successes: k, trials: n, level: lvl, method: .clopperPearson)37            #expect(isClose(cp.lower, c["cp"][0].d, rel: 1e-10, abs: 1e-15) && isClose(cp.upper, c["cp"][1].d, rel: 1e-10), "cp \(k)/\(n) \(lvl): \(cp.lower), \(cp.upper)")38        }39        #expect(throws: StatError.self) { try Inference.proportionInterval(successes: 5, trials: 3) }40    }4142    @Test func differenceOfMeans() throws {43        let g1 = diData("g1"), g2 = diData("g2")44        let p = try Inference.meanDifferenceInterval(g1, g2, equalVariances: true)45        #expect(isClose(p.lower, f["diff_pooled"][0].d, rel: 1e-11) && isClose(p.upper, f["diff_pooled"][1].d, rel: 1e-11))46        let w = try Inference.meanDifferenceInterval(g1, g2)47        #expect(isClose(w.lower, f["diff_welch"][0].d, rel: 1e-11) && isClose(w.upper, f["diff_welch"][1].d, rel: 1e-11))48        let w90 = try Inference.meanDifferenceInterval(g1, g2, level: 0.9)49        #expect(isClose(w90.lower, f["diff_welch90"][0].d, rel: 1e-11) && isClose(w90.upper, f["diff_welch90"][1].d, rel: 1e-11))50    }51}5253@Suite struct ParametricTestTests {54    let f = diFixture["ttests"]5556    @Test func tTests() throws {57        let x = diData("x"), y = diData("y"), g1 = diData("g1"), g2 = diData("g2")58        for (key, alt) in alternatives {59            let r = f[key]60            let one = try Inference.tTest(x, mu: 47, alternative: alt)61            #expect(isClose(one.statistic, r["one"][0].d, rel: 1e-12) && isClose(one.pValue, r["one"][1].d, rel: 1e-10) && one.df == r["one"][2].d, "one \(key)")62            let pooled = try Inference.tTest(g1, g2, equalVariances: true, alternative: alt)63            #expect(isClose(pooled.statistic, r["pooled"][0].d, rel: 1e-12) && isClose(pooled.pValue, r["pooled"][1].d, rel: 1e-10) && pooled.df == r["pooled"][2].d, "pooled \(key)")64            let welch = try Inference.tTest(g1, g2, alternative: alt)65            #expect(isClose(welch.statistic, r["welch"][0].d, rel: 1e-12) && isClose(welch.pValue, r["welch"][1].d, rel: 1e-10), "welch \(key)")66            #expect(isClose(welch.df ?? 0, r["welch"][2].d, rel: 1e-12))67            let paired = try Inference.pairedTTest(x, y, alternative: alt)68            #expect(isClose(paired.statistic, r["paired"][0].d, rel: 1e-12) && isClose(paired.pValue, r["paired"][1].d, rel: 1e-10), "paired \(key)")69            #expect(one.alternative == alt && one.pValueDescription == alt.label)70        }71        let one = try Inference.tTest(x, mu: 47)72        #expect(isClose(one.confidenceInterval!.lower, f["one_ci"][0].d, rel: 1e-11) && isClose(one.confidenceInterval!.upper, f["one_ci"][1].d, rel: 1e-11))73        #expect(isClose(one.effectSize!.value, f["cohen_d_one"].d, rel: 1e-12))74        let paired = try Inference.pairedTTest(x, y)75        #expect(isClose(paired.confidenceInterval!.lower, f["paired_ci"][0].d, rel: 1e-11) && isClose(paired.confidenceInterval!.upper, f["paired_ci"][1].d, rel: 1e-11))76        #expect(paired.name == "Paired t-test" && paired.details[0].name == "Pairs")77        let two = try Inference.tTest(g1, g2, equalVariances: true)78        #expect(isClose(two.effectSize!.value, f["cohen_d_two"].d, rel: 1e-12))79        let welchDefault = try Inference.tTest(g1, g2)80        #expect(two.assumptions.count == 3 && welchDefault.assumptions.count == 2)81        // hypothesised difference shifts the statistic: testing the observed difference gives t = 0, p = 182        let shifted = try Inference.tTest(g1, g2, difference: Descriptive.mean(g1) - Descriptive.mean(g2))83        #expect(abs(shifted.statistic) < 1e-12 && isClose(shifted.pValue, 1, rel: 1e-12))84        #expect(throws: StatError.self) { try Inference.tTest([3, 3, 3]) }85        #expect(throws: StatError.self) { try Inference.pairedTTest([1, 2, 3], [1, 2]) }86        #expect(throws: StatError.self) { try Inference.tTest([1], [1, 2]) }87        let table = one.table()88        #expect(table[0][0] == .text("One-sample t-test") && table[1] == [.text("Statistic (t)"), .number(one.statistic)])89        #expect(table.contains { $0[0] == .text("Assumptions") })90        #expect(one.rejects(alpha: 0.05) == (one.pValue < 0.05))91    }9293    @Test func zTests() throws {94        let x = diData("x"), g1 = diData("g1"), g2 = diData("g2")95        for (key, alt) in alternatives {96            let r = f[key]97            let one = try Inference.zTest(x, mu: 47, alternative: alt)98            #expect(isClose(one.statistic, r["z_one"][0].d, rel: 1e-12) && isClose(one.pValue, r["z_one"][1].d, rel: 1e-11), "z one \(key)")99            let two = try Inference.zTest(g1, g2, difference: -1, alternative: alt)100            #expect(isClose(two.statistic, r["z_two"][0].d, rel: 1e-12) && isClose(two.pValue, r["z_two"][1].d, rel: 1e-11), "z two \(key)")101            let p1 = try Inference.proportionZTest(successes: 37, trials: 120, p0: 0.25, alternative: alt)102            #expect(isClose(p1.statistic, r["prop_one"][0].d, rel: 1e-12) && isClose(p1.pValue, r["prop_one"][1].d, rel: 1e-11), "prop one \(key)")103            let p2 = try Inference.proportionZTest(successes1: 37, trials1: 120, successes2: 52, trials2: 130, alternative: alt)104            #expect(isClose(p2.statistic, r["prop_two"][0].d, rel: 1e-12) && isClose(p2.pValue, r["prop_two"][1].d, rel: 1e-11), "prop two \(key)")105        }106        let known = try Inference.zTest(x, mu: 47, sigma: 12)107        #expect(isClose(known.statistic, f["z_known"][0].d, rel: 1e-12) && isClose(known.pValue, f["z_known"][1].d, rel: 1e-11))108        let known2 = try Inference.zTest(g1, g2, sigmaX: 4, sigmaY: 4, alternative: .less)109        #expect(isClose(known2.statistic, f["z_two_known"][0].d, rel: 1e-12) && isClose(known2.pValue, f["z_two_known"][1].d, rel: 1e-11))110        #expect(throws: StatError.self) { try Inference.proportionZTest(successes: 3, trials: 10, p0: 1) }111        #expect(throws: StatError.self) { try Inference.proportionZTest(successes1: 0, trials1: 10, successes2: 0, trials2: 10) }112    }113}114115@Suite struct ChiSquareTests {116    let f = diFixture["chi2"]117118    @Test func goodnessOfFit() throws {119        let obs = f["obs"].arr120        let eq = try Inference.chiSquareGoodnessOfFit(observed: obs)121        #expect(isClose(eq.statistic, f["gof_eq"][0].d, rel: 1e-12) && isClose(eq.pValue, f["gof_eq"][1].d, rel: 1e-10) && eq.df == 5)122        let p = try Inference.chiSquareGoodnessOfFit(observed: obs, probabilities: f["probs"].arr)123        #expect(isClose(p.statistic, f["gof_p"][0].d, rel: 1e-12) && isClose(p.pValue, f["gof_p"][1].d, rel: 1e-10))124        let dd = try Inference.chiSquareGoodnessOfFit(observed: obs, probabilities: f["probs"].arr, estimatedParameters: 2)125        #expect(isClose(dd.statistic, f["gof_dd"][0].d, rel: 1e-12) && isClose(dd.pValue, f["gof_dd"][1].d, rel: 1e-10) && dd.df == 3)126        #expect(eq.alternative == .greater && eq.pValueDescription == "upper tail of χ²(5)")127        // unnormalised probabilities are rescaled128        let scaled = try Inference.chiSquareGoodnessOfFit(observed: obs, probabilities: f["probs"].arr.map { $0 * 7 })129        #expect(isClose(scaled.statistic, p.statistic, rel: 1e-12))130        #expect(throws: StatError.self) { try Inference.chiSquareGoodnessOfFit(observed: obs, expected: obs.map { $0 + 1 }) }131        #expect(throws: StatError.self) { try Inference.chiSquareGoodnessOfFit(observed: [5]) }132        #expect(throws: StatError.self) { try Inference.chiSquareGoodnessOfFit(observed: [5, 6], estimatedParameters: 1) }133    }134135    @Test func independence() throws {136        let r = try Inference.chiSquareIndependence(f["table"].mat)137        #expect(isClose(r.test.statistic, f["ind"][0].d, rel: 1e-12) && isClose(r.test.pValue, f["ind"][1].d, rel: 1e-10) && r.test.df == f["ind"][2].d)138        #expect(allClose(r.expected.data, f["expected"].mat.flatMap { $0 }, rel: 1e-12))139        #expect(isClose(r.cramersV, f["cramer"].d, rel: 1e-12) && r.test.effectSize?.value == r.cramersV)140        #expect(isClose(r.minimumExpected, f["expected"].mat.flatMap { $0 }.min()!, rel: 1e-12))141        #expect(isClose(Descriptive.sum(r.residuals.data.map { $0 * $0 }), r.test.statistic, rel: 1e-12))142        #expect(r.rowTotals == [80, 87, 71] && r.total == 238)143        let a = try Inference.chiSquareIndependence(f["t22"].mat)144        #expect(isClose(a.test.statistic, f["i22"][0].d, rel: 1e-12) && isClose(a.test.pValue, f["i22"][1].d, rel: 1e-10))145        #expect(isClose(a.cramersV, f["cramer22"].d, rel: 1e-12))146        let y = try Inference.chiSquareIndependence(f["t22"].mat, yatesCorrection: true)147        #expect(isClose(y.test.statistic, f["i22y"][0].d, rel: 1e-12) && isClose(y.test.pValue, f["i22y"][1].d, rel: 1e-10))148        #expect(y.cramersV == a.cramersV)                                   // V always from the uncorrected statistic149        // Yates is ignored beyond 2×2150        #expect(try Inference.chiSquareIndependence(f["table"].mat, yatesCorrection: true).test.statistic == r.test.statistic)151        #expect(throws: StatError.self) { try Inference.chiSquareIndependence([[1, 2], [0, 0]]) }152        #expect(throws: StatError.self) { try Inference.chiSquareIndependence([[1, 2, 3]]) }153        let t = r.table()154        #expect(t.contains { $0[0] == .text("Expected counts") } && t.last?.count == 3)155    }156}157158@Suite struct AnovaTests {159    let f = diFixture["anova"]160    var groups: [[Double]] { ["g1", "g2", "g3", "g4"].map(diData) }161162    @Test func oneWay() throws {163        let a = try Inference.oneWayANOVA(groups, labels: ["A", "B", "C", "D"])164        let b = a.row("Between Groups")!, w = a.row("Within Groups")!, t = a.row("Total")!165        let r = f["one"]166        #expect(isClose(b.f!, r["F"].d, rel: 1e-11) && isClose(b.pValue!, r["p"].d, rel: 1e-9))167        #expect(isClose(b.sumOfSquares, r["ss"][0].d, rel: 1e-11) && isClose(w.sumOfSquares, r["ss"][1].d, rel: 1e-11))168        #expect(b.df == r["df"][0].d && w.df == r["df"][1].d && t.df == 64)169        #expect(isClose(b.meanSquare!, r["ms"][0].d, rel: 1e-11) && isClose(w.meanSquare!, r["ms"][1].d, rel: 1e-11))170        #expect(isClose(b.etaSquared!, b.sumOfSquares / t.sumOfSquares, rel: 1e-14) && b.etaSquared == b.partialEtaSquared)171        #expect(isClose(t.sumOfSquares, Descriptive.sumSquaredDeviations(groups.flatMap { $0 }), rel: 1e-12))172        #expect(a.groups.map(\.label) == ["A", "B", "C", "D"] && a.groups[1].count == 18)173        // two groups: F = t² of the pooled t-test174        let two = try Inference.oneWayANOVA([groups[0], groups[1]])175        let tt = try Inference.tTest(groups[0], groups[1], equalVariances: true)176        #expect(isClose(two.row("Between Groups")!.f!, tt.statistic * tt.statistic, rel: 1e-11))177        #expect(isClose(two.row("Between Groups")!.pValue!, tt.pValue, rel: 1e-10))178        let table = a.table()179        #expect(table[1][0] == .text("Groups") && table[7][0] == .text("Source of Variation") && table[8][0] == .text("Between Groups"))180        #expect(throws: StatError.self) { try Inference.oneWayANOVA([[1, 2, 3]]) }181        #expect(throws: StatError.self) { try Inference.oneWayANOVA([[1, 1], [2, 2]]) }182    }183184    @Test func twoWayWithoutReplication() throws {185        let a = try Inference.twoWayANOVA(f["block"].mat)186        let r = f["two"]187        let rows = a.row("Rows")!, cols = a.row("Columns")!, err = a.row("Error")!188        #expect(isClose(rows.sumOfSquares, r["ss"][0].d, rel: 1e-11) && isClose(cols.sumOfSquares, r["ss"][1].d, rel: 1e-11) && isClose(err.sumOfSquares, r["ss"][2].d, rel: 1e-10))189        #expect(rows.df == 4 && cols.df == 3 && err.df == 12)190        #expect(isClose(rows.f!, r["F"][0].d, rel: 1e-10) && isClose(cols.f!, r["F"][1].d, rel: 1e-10))191        #expect(isClose(rows.pValue!, r["p"][0].d, rel: 1e-9) && isClose(cols.pValue!, r["p"][1].d, rel: 1e-9))192        #expect(isClose(a.row("Total")!.sumOfSquares, rows.sumOfSquares + cols.sumOfSquares + err.sumOfSquares, rel: 1e-12))193        #expect(throws: StatError.self) { try Inference.twoWayANOVA([[1, 2, 3]]) }194    }195196    @Test func twoWayWithReplication() throws {197        let cells = f["rep"].list.map { $0.mat }198        let a = try Inference.twoWayANOVA(replicated: cells)199        let r = f["three"]200        let names = ["Rows", "Columns", "Interaction"]201        for (i, n) in names.enumerated() {202            let row = a.row(n)!203            #expect(isClose(row.sumOfSquares, r["ss"][i].d, rel: 1e-10), "\(n) SS")204            #expect(row.df == r["df"][i].d, "\(n) df")205            #expect(isClose(row.f!, r["F"][i].d, rel: 1e-10), "\(n) F")206            #expect(isClose(row.pValue!, r["p"][i].d, rel: 1e-9), "\(n) p")207        }208        #expect(isClose(a.row("Within")!.sumOfSquares, r["ss"][3].d, rel: 1e-10) && a.row("Within")!.df == 48)209        var unbalanced = cells210        unbalanced[0][0].removeLast()211        #expect(throws: StatError.self) { try Inference.twoWayANOVA(replicated: unbalanced) }212    }213}214215@Suite struct VarianceAndNormalityTests {216    @Test func varianceTests() throws {217        let f = diFixture["variance"]218        let g1 = diData("g1"), g3 = diData("g3")219        let two = try Inference.varianceFTest(g1, g3)220        #expect(isClose(two.statistic, f["F"].d, rel: 1e-12) && isClose(two.pValue, f["p_two"].d, rel: 1e-10))221        #expect(two.df == Double(g1.count - 1) && two.df2 == Double(g3.count - 1))222        #expect(isClose(try Inference.varianceFTest(g1, g3, alternative: .less).pValue, f["p_less"].d, rel: 1e-10))223        #expect(isClose(try Inference.varianceFTest(g1, g3, alternative: .greater).pValue, f["p_greater"].d, rel: 1e-10))224        #expect(isClose(two.confidenceInterval!.lower, f["ci"][0].d, rel: 1e-10) && isClose(two.confidenceInterval!.upper, f["ci"][1].d, rel: 1e-10))225        let groups = ["g1", "g2", "g3", "g4"].map(diData)226        let lm = try Inference.leveneTest(groups, center: .mean)227        #expect(isClose(lm.statistic, f["levene_mean"][0].d, rel: 1e-11) && isClose(lm.pValue, f["levene_mean"][1].d, rel: 1e-9))228        let bf = try Inference.leveneTest(groups)229        #expect(isClose(bf.statistic, f["levene_median"][0].d, rel: 1e-11) && isClose(bf.pValue, f["levene_median"][1].d, rel: 1e-9))230        #expect(bf.name.hasPrefix("Brown–Forsythe") && lm.name.hasPrefix("Levene") && bf.df == 3 && bf.df2 == 61)231        let b = try Inference.bartlettTest(groups)232        #expect(isClose(b.statistic, f["bartlett"][0].d, rel: 1e-11) && isClose(b.pValue, f["bartlett"][1].d, rel: 1e-9))233        #expect(throws: StatError.self) { try Inference.varianceFTest([1, 1, 1], [1, 2, 3]) }234        #expect(throws: StatError.self) { try Inference.leveneTest([[1, 2, 3]]) }235    }236237    @Test func jarqueBera() throws {238        for (key, f) in diFixture["normality"].dict where f["data"].list.count >= 3 {239            let r = try Inference.jarqueBera(f["data"].arr)240            #expect(isClose(r.statistic, f["JB"].d, rel: 1e-10) && isClose(r.pValue, f["jb_p"].d, rel: 1e-9), "JB \(key)")241            #expect(r.df == 2 && r.alternative == .greater)242        }243        #expect(throws: StatError.self) { try Inference.jarqueBera([2, 2, 2, 2]) }244    }245246    @Test func shapiroWilk() throws {247        for (key, f) in diFixture["normality"].dict {248            let r = try Inference.shapiroWilk(f["data"].arr)249            #expect(isClose(r.statistic, f["W"].d, rel: 2e-9), "W \(key): \(r.statistic) vs \(f["W"].d)")250            #expect(isClose(r.pValue, f["p"].d, rel: 2e-8, abs: 1e-13), "p \(key): \(r.pValue) vs \(f["p"].d)")251        }252        #expect(throws: StatError.self) { try Inference.shapiroWilk([1, 2]) }253        #expect(throws: StatError.self) { try Inference.shapiroWilk([4, 4, 4, 4]) }254        #expect(throws: StatError.self) { try Inference.shapiroWilk(Array(repeating: 1.0, count: 5001)) }255        // exactly normal scores give W very close to 1 and a large p-value256        let scores = (1...50).map { SpecialFunctions.normalQuantile((Double($0) - 0.375) / 50.25) }257        let perfect = try Inference.shapiroWilk(scores)258        #expect(perfect.statistic > 0.995 && perfect.pValue > 0.9)259    }260}261262@Suite struct NonparametricTests {263    let f = diFixture["nonparam"]264265    @Test func mannWhitney() throws {266        let g1 = diData("g1"), g2 = diData("g2"), ties = diData("ties")267        let tiesB = ties.prefix(7).map { $0 + 1 }268        for (key, alt) in alternatives {269            let r = f[key]270            let c = try Inference.mannWhitneyU(g1, g2, alternative: alt)271            #expect(c.statistic == r["mw_c"][0].d && isClose(c.pValue, r["mw_c"][1].d, rel: 1e-10), "MW cc \(key)")272            let n = try Inference.mannWhitneyU(g1, g2, alternative: alt, continuityCorrection: false)273            #expect(isClose(n.pValue, r["mw_n"][1].d, rel: 1e-10), "MW \(key)")274            let t = try Inference.mannWhitneyU(ties, Array(tiesB), alternative: alt)275            #expect(t.statistic == r["mw_t"][0].d && isClose(t.pValue, r["mw_t"][1].d, rel: 1e-10), "MW ties \(key)")276        }277        let r = try Inference.mannWhitneyU(g1, g2)278        let u2 = r.details.first { $0.name == "U2" }!.value279        #expect(r.statistic + u2 == Double(g1.count * g2.count))280        #expect(isClose(r.effectSize!.value, 2 * r.statistic / Double(g1.count * g2.count) - 1, rel: 1e-14))281        // complete separation: U1 = 0 and rank-biserial = −1282        let sep = try Inference.mannWhitneyU([1, 2, 3], [10, 11, 12, 13])283        #expect(sep.statistic == 0 && sep.effectSize!.value == -1)284        #expect(throws: StatError.self) { try Inference.mannWhitneyU([2, 2], [2, 2, 2]) }285    }286287    @Test func wilcoxon() throws {288        let pa = f["pa"].arr, pb = f["pb"].arr, x = diData("x")289        for (key, alt) in alternatives {290            let r = f[key]291            let w = try Inference.wilcoxonSignedRank(pa, pb, alternative: alt)292            #expect(w.statistic == r["wx"][0].d && isClose(w.pValue, r["wx"][1].d, rel: 1e-10), "W \(key): \(w.statistic) \(w.pValue) vs \(r["wx"].arr)")293            let wc = try Inference.wilcoxonSignedRank(pa, pb, alternative: alt, continuityCorrection: true)294            #expect(isClose(wc.pValue, r["wxc"][1].d, rel: 1e-10), "W cc \(key)")295            let one = try Inference.wilcoxonSignedRank(x.map { $0 - 47 }, alternative: alt)296            #expect(one.statistic == r["w1"][0].d && isClose(one.pValue, r["w1"][1].d, rel: 1e-10), "W one-sample \(key)")297        }298        let w = try Inference.wilcoxonSignedRank(pa, pb)299        let n = w.details[0].value, plus = w.details[2].value, minus = w.details[3].value300        #expect(plus + minus == n * (n + 1) / 2)301        #expect(w.details[1].value == Double(zip(pa, pb).filter { $0 == $1 }.count))302        #expect(throws: StatError.self) { try Inference.wilcoxonSignedRank([1, 2, 3], [1, 2, 3]) }303        #expect(throws: StatError.self) { try Inference.wilcoxonSignedRank([1, 2, 3], [1, 2]) }304    }305306    @Test func kruskalWallis() throws {307        let groups = ["g1", "g2", "g3", "g4"].map(diData)308        let k = try Inference.kruskalWallis(groups)309        #expect(isClose(k.statistic, f["kw"][0].d, rel: 1e-11) && isClose(k.pValue, f["kw"][1].d, rel: 1e-9) && k.df == 3)310        let t = diData("ties")311        let kt = try Inference.kruskalWallis([Array(t[0..<4]), Array(t[4..<8]), Array(t[8...])])312        #expect(isClose(kt.statistic, f["kw_ties"][0].d, rel: 1e-11) && isClose(kt.pValue, f["kw_ties"][1].d, rel: 1e-9))313        #expect(kt.details[2].value < 1)314        #expect(throws: StatError.self) { try Inference.kruskalWallis([[1, 1], [1, 1]]) }315    }316317    @Test func correlationTests() throws {318        let c = diFixture["corrtests"]319        let x = diData("x"), y = diData("y"), ties = diData("ties"), ty = diFixture["matrix"]["ties_y"].arr320        for (key, alt) in alternatives {321            let r = c[key]322            let p = try Inference.correlationTest(x, y, alternative: alt)323            #expect(isClose(p.estimate!.value, r["pearson"][0].d, rel: 1e-12) && isClose(p.pValue, r["pearson"][1].d, rel: 1e-9), "pearson \(key)")324            let s = try Inference.correlationTest(x, y, method: .spearman, alternative: alt)325            #expect(isClose(s.estimate!.value, r["spearman"][0].d, rel: 1e-12) && isClose(s.pValue, r["spearman"][1].d, rel: 1e-9), "spearman \(key)")326            let k = try Inference.correlationTest(x, y, method: .kendall, alternative: alt)327            #expect(isClose(k.estimate!.value, r["kendall"][0].d, rel: 1e-12) && isClose(k.pValue, r["kendall"][1].d, rel: 1e-9), "kendall \(key)")328            let kt = try Inference.correlationTest(ties, ty, method: .kendall, alternative: alt)329            #expect(isClose(kt.estimate!.value, r["kendall_ties"][0].d, rel: 1e-12) && isClose(kt.pValue, r["kendall_ties"][1].d, rel: 1e-9), "kendall ties \(key)")330        }331        let p = try Inference.correlationTest(x, y)332        #expect(isClose(p.confidenceInterval!.lower, c["pearson_ci"][0].d, rel: 1e-10) && isClose(p.confidenceInterval!.upper, c["pearson_ci"][1].d, rel: 1e-10))333        #expect(throws: StatError.self) { try Inference.correlationTest([1, 2, 3], [5, 5, 5]) }334        #expect(throws: StatError.self) { try Inference.correlationTest([1, 2], [2, 1]) }335        let perfect = try Inference.correlationTest([1, 2, 3, 4], [2, 4, 6, 8])336        #expect(perfect.pValue == 0 && perfect.estimate!.value == 1)337    }338339    @Test func resultsAreCodable() throws {340        let t = try Inference.tTest(diData("g1"), diData("g2"))341        let t2 = try JSONDecoder().decode(HypothesisTest.self, from: JSONEncoder().encode(t))342        #expect(t2 == t)343        let a = try Inference.oneWayANOVA([diData("g1"), diData("g2")])344        let a2 = try JSONDecoder().decode(AnovaResult.self, from: JSONEncoder().encode(a))345        #expect(a2 == a)346        let c = try Inference.chiSquareIndependence([[10, 20], [30, 25]])347        let c2 = try JSONDecoder().decode(ContingencyResult.self, from: JSONEncoder().encode(c))348        #expect(c2 == c)349    }350}351
Files main
Menu

Theme