Repository Public
1import Foundation2import SheetCore34/// Errors thrown by the numeric routines of the analytics packages.5public enum StatError: Error, Sendable, Hashable, CustomStringConvertible {6 case invalidInput(String)7 case insufficientData(String)8 case singular(String)9 case notConverged(String)1011 public var description: String {12 switch self {13 case .invalidInput(let m): "Invalid input: \(m)"14 case .insufficientData(let m): "Insufficient data: \(m)"15 case .singular(let m): "Singular or ill-conditioned problem: \(m)"16 case .notConverged(let m): "Did not converge: \(m)"17 }18 }19}2021/// A result that can be written into a sheet as a formatted report (row-major grid of values).22public protocol TableReport {23 func table() -> [[Value]]24}2526/// Which tail(s) a p-value refers to.27public enum Alternative: String, Sendable, Codable, CaseIterable {28 /// H1: parameter ≠ hypothesised value (two-sided p-value).29 case twoSided30 /// H1: parameter < hypothesised value (lower-tail p-value).31 case less32 /// H1: parameter > hypothesised value (upper-tail p-value).33 case greater3435 public var label: String {36 switch self {37 case .twoSided: "two-sided"38 case .less: "one-sided (less)"39 case .greater: "one-sided (greater)"40 }41 }42}4344/// Small helpers for building report grids.45public enum Report {46 @inlinable public static func num(_ d: Double) -> Value { d.isFinite ? .number(d) : (d.isNaN ? .error(.na) : .error(.num)) }47 @inlinable public static func num(_ d: Double?) -> Value { d.map { num($0) } ?? .blank }48 @inlinable public static func int(_ i: Int) -> Value { .number(Double(i)) }49 @inlinable public static func text(_ s: String) -> Value { .text(s) }5051 /// `[label, value]` row.52 public static func row(_ label: String, _ d: Double) -> [Value] { [.text(label), num(d)] }53 public static func row(_ label: String, _ s: String) -> [Value] { [.text(label), .text(s)] }54 public static func row(_ label: String, _ i: Int) -> [Value] { [.text(label), int(i)] }5556 /// Pads every row with blanks so the grid is rectangular.57 public static func rectangular(_ rows: [[Value]]) -> [[Value]] {58 let w = rows.map(\.count).max() ?? 059 return rows.map { $0.count < w ? $0 + Array(repeating: Value.blank, count: w - $0.count) : $0 }60 }6162 /// A labelled matrix: header row of column names, then one row per row name.63 public static func labelled(corner: String = "", rows: [String], cols: [String], _ m: (Int, Int) -> Double) -> [[Value]] {64 var out: [[Value]] = [[.text(corner)] + cols.map { .text($0) }]65 for (i, r) in rows.enumerated() { out.append([.text(r)] + cols.indices.map { num(m(i, $0)) }) }66 return out67 }68}69