SPB Git

Repository Public

TukeyTests.swift 7.1 KB 157 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetAnalytics/Tests/StatisticsTests/TukeyTests.swift10// Module           : StatisticsTests11// Repository       : https://git.spboucher.ai/orix-sheet12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import Foundation88import Testing89import SheetCore90import AnalyticsTestSupport91@testable import Statistics9293@Suite struct TukeyTests {94    let f = Fixture.load("tukey", .module)9596    @Test func gaussLegendreIsExactForPolynomials() {97        let (x, w) = GaussLegendre.rule(16)98        #expect(isClose(w.reduce(0, +), 2, rel: 1e-14))99        // ∫ x^30 dx over [−1,1] = 2/31: a 16-point rule is exact up to degree 31100        #expect(isClose(zip(x, w).reduce(0) { $0 + $1.1 * pow($1.0, 30) }, 2.0 / 31, rel: 1e-12))101        #expect(abs(zip(x, w).reduce(0) { $0 + $1.1 * $1.0 }) < 1e-15)102    }103104    @Test func studentizedRangeCDF() {105        var worst = 0.0106        for row in f["cdf"].list {107            let r = row.arr108            let d = StudentizedRangeDistribution(k: Int(r[0]), df: r[1])109            let c = d.cdf(r[2])110            worst = max(worst, abs(c - r[3]))111            #expect(isClose(c, r[3], rel: 1e-8, abs: 1e-10), "cdf k=\(r[0]) df=\(r[1]) q=\(r[2]): \(c) vs \(r[3])")112            #expect(isClose(1 - c, r[4], rel: 1e-6, abs: 1e-10), "sf k=\(r[0]) df=\(r[1]) q=\(r[2]): \(1 - c) vs \(r[4])")113        }114        #expect(worst < 1e-9)115        // k = 2, infinite df: the range of two normals is |N(0, 2)| → P = 2Φ(q/√2) − 1116        #expect(isClose(StudentizedRangeDistribution.rangeCDF(1.3, k: 2), 2 * NormalDistribution.standard.cdf(1.3 / 2.0.squareRoot()) - 1, rel: 1e-13))117        // k = 2: Q/√2 is |t(df)|118        let t = StudentTDistribution(df: 9)119        #expect(isClose(StudentizedRangeDistribution(k: 2, df: 9).cdf(3.0), 1 - 2 * t.sf(3.0 / 2.0.squareRoot()), rel: 1e-11))120        #expect(StudentizedRangeDistribution(k: 3, df: 9).cdf(0) == 0 && StudentizedRangeDistribution(k: 3, df: 9).cdf(.infinity) == 1)121    }122123    @Test func studentizedRangeQuantile() {124        for row in f["ppf"].list {125            let r = row.arr126            let q = StudentizedRangeDistribution(k: Int(r[0]), df: r[1]).quantile(r[2])127            #expect(isClose(q, r[3], rel: 1e-7), "ppf k=\(r[0]) df=\(r[1]) p=\(r[2]): \(q) vs \(r[3])")128        }129        // classic table value q(0.95; 3, 10) = 3.877130        #expect(abs(StudentizedRangeDistribution(k: 3, df: 10).quantile(0.95) - 3.877) < 5e-4)131    }132133    @Test func tukeyHSDMatchesSciPy() throws {134        let groups = f["groups"].mat135        let r = try Inference.tukeyHSD(groups, labels: ["A", "B", "C", "D"])136        #expect(r.comparisons.count == 6 && r.groupCount == 4 && r.dfError == 34)137        var idx = 0138        for i in 0..<3 {139            for j in (i + 1)..<4 {140                let c = r.comparisons[idx]; idx += 1141                #expect(isClose(c.difference, f["stat"][i][j].d, rel: 1e-12), "diff \(i),\(j)")142                #expect(isClose(c.pValue, f["p"][i][j].d, rel: 1e-6, abs: 1e-9), "p \(i),\(j): \(c.pValue) vs \(f["p"][i][j].d)")143                #expect(isClose(c.lower, f["low"][i][j].d, rel: 1e-6, abs: 1e-7) && isClose(c.upper, f["high"][i][j].d, rel: 1e-6, abs: 1e-7), "ci \(i),\(j)")144                #expect(c.significant == (c.pValue < 0.05))145                #expect((c.lower > 0 || c.upper < 0) == c.significant)146            }147        }148        let r90 = try Inference.tukeyHSD(groups, level: 0.9)149        #expect(isClose(r90.comparisons[0].lower, f["low90"][0][1].d, rel: 1e-6, abs: 1e-7) && isClose(r90.comparisons[5].upper, f["high90"][2][3].d, rel: 1e-6, abs: 1e-7))150        #expect(r90.criticalQ < r.criticalQ)151        let t = r.table()152        #expect(t[1][3] == .text("q") && t[2][0] == .text("A") && t[2][1] == .text("B") && t.count == 13)153        #expect(throws: StatError.self) { try Inference.tukeyHSD([[1, 2, 3]]) }154        #expect(throws: StatError.self) { try Inference.tukeyHSD([[1, 1], [2, 2]]) }155    }156}157
Files main
Menu

Theme