SPB Git

Repository Public

TestResult.swift 5.1 KB 101 lines swift

1import Foundation2import SheetCore34/// A labelled number (ordered, Codable) used for the extra figures of a report.5public struct NamedValue: Sendable, Hashable, Codable {6    public var name: String7    public var value: Double8    public init(_ name: String, _ value: Double) { self.name = name; self.value = value }9}1011/// A two-sided confidence interval.12public struct ConfidenceInterval: Sendable, Hashable, Codable, TableReport {13    /// Point estimate the interval is built around.14    public var estimate: Double15    public var lower: Double16    public var upper: Double17    /// Confidence level, e.g. 0.95.18    public var level: Double19    /// How it was computed, e.g. "Student t, df = 9".20    public var method: String2122    public func table() -> [[Value]] {23        [Report.row("Estimate", estimate), Report.row("Lower bound", lower), Report.row("Upper bound", upper),24         Report.row("Confidence level", level), Report.row("Method", method)]25    }26}2728/// Result of a hypothesis test.29public struct HypothesisTest: Sendable, Hashable, Codable, TableReport {30    public var name: String31    /// Symbol of the statistic: "t", "z", "F", "χ²", "W", "U", "H", "JB"…32    public var statisticName: String33    public var statistic: Double34    /// Degrees of freedom (numerator df for F tests); nil when the reference distribution has none.35    public var df: Double?36    /// Denominator degrees of freedom of F tests.37    public var df2: Double?38    public var pValue: Double39    /// The alternative hypothesis the p-value refers to. Tests that reject only for large statistics40    /// (χ², F in ANOVA, normality tests…) report `.greater`: the p-value is the upper-tail probability.41    public var alternative: Alternative42    /// Plain statement of what the p-value is, e.g. "two-sided" or "upper tail of χ²(3)".43    public var pValueDescription: String44    /// Estimated quantity under test (mean difference, variance ratio…), when there is one.45    public var estimate: NamedValue?46    public var confidenceInterval: ConfidenceInterval?47    /// Standard effect size, when one exists (Cohen's d, η², Cramér's V, rank-biserial r…).48    public var effectSize: NamedValue?49    /// Supporting figures (sample sizes, means, standard errors…).50    public var details: [NamedValue]51    /// What must hold for the p-value to be valid.52    public var assumptions: [String]53    public var notes: [String]5455    public init(name: String, statisticName: String, statistic: Double, df: Double? = nil, df2: Double? = nil, pValue: Double,56                alternative: Alternative, pValueDescription: String? = nil, estimate: NamedValue? = nil,57                confidenceInterval: ConfidenceInterval? = nil, effectSize: NamedValue? = nil, details: [NamedValue] = [],58                assumptions: [String] = [], notes: [String] = []) {59        self.name = name; self.statisticName = statisticName; self.statistic = statistic; self.df = df; self.df2 = df260        self.pValue = pValue; self.alternative = alternative61        self.pValueDescription = pValueDescription ?? alternative.label62        self.estimate = estimate; self.confidenceInterval = confidenceInterval; self.effectSize = effectSize63        self.details = details; self.assumptions = assumptions; self.notes = notes64    }6566    /// True when p < alpha.67    public func rejects(alpha: Double = 0.05) -> Bool { pValue < alpha }6869    public func table() -> [[Value]] {70        var out: [[Value]] = [[.text(name), .blank]]71        out.append(Report.row("Statistic (\(statisticName))", statistic))72        if let df { out.append(Report.row(df2 == nil ? "df" : "df (numerator)", df)) }73        if let df2 { out.append(Report.row("df (denominator)", df2)) }74        out.append(Report.row("p-value", pValue))75        out.append(Report.row("p-value is", pValueDescription))76        if let e = estimate { out.append(Report.row(e.name, e.value)) }77        if let ci = confidenceInterval {78            out.append(Report.row(String(format: "%g%% CI lower", ci.level * 100), ci.lower))79            out.append(Report.row(String(format: "%g%% CI upper", ci.level * 100), ci.upper))80        }81        if let e = effectSize { out.append(Report.row("Effect size: " + e.name, e.value)) }82        for d in details { out.append(Report.row(d.name, d.value)) }83        for (i, a) in assumptions.enumerated() { out.append(Report.row(i == 0 ? "Assumptions" : "", a)) }84        for (i, n) in notes.enumerated() { out.append(Report.row(i == 0 ? "Notes" : "", n)) }85        return out86    }87}8889/// Namespace of the inference routines (confidence intervals and hypothesis tests).90public enum Inference {91    static func clean(_ x: [Double], min n: Int, _ what: String) throws -> [Double] {92        guard !x.contains(where: { $0.isNaN }) else { throw StatError.invalidInput("\(what) contains missing values (NaN)") }93        guard x.count >= n else { throw StatError.insufficientData("\(what) needs at least \(n) observations") }94        return x95    }9697    static func checkLevel(_ level: Double) throws {98        guard level > 0, level < 1 else { throw StatError.invalidInput("confidence level must be strictly between 0 and 1") }99    }100}101
Files main
Menu

Theme