Repository Public
1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// Helpers shared by the tools of this target.7enum Sup {8 /// Significance level of the interpretation, kept inside (0, 0.5].9 static func alpha(_ input: ToolInput) -> Double {10 let a = input.values.number("alpha")11 return a.isFinite ? min(max(a, 0.0001), 0.5) : 0.0512 }1314 /// Confidence level kept inside [0.5, 0.9999].15 static func level(_ input: ToolInput, _ id: String = "level") -> Double {16 let l = input.values.number(id)17 return l.isFinite ? min(max(l, 0.5), 0.9999) : 0.9518 }1920 static func seed(_ input: ToolInput) -> UInt64 { UInt64(max(input.values.int("seed"), 0)) }2122 /// "Reject H₀" / "Fail to reject H₀" cell for a table (blank when there is no p-value).23 static func decision(_ p: Double?, _ alpha: Double) -> Value {24 guard let p, p.isFinite else { return .blank }25 return .text(p < alpha ? L("Reject H₀") : L("Fail to reject H₀"))26 }2728 static func decisionHeader(_ alpha: Double, _ locale: Locale) -> String {29 L("Decision at α = %@", Fmt.fixed(alpha, alpha < 0.01 ? 4 : 2, locale: locale))30 }3132 /// Display name of a coefficient ("const" is the engine's name of the intercept).33 static func term(_ name: String) -> String { name == "const" ? L("Intercept") : name }3435 /// Coefficient table: estimate, standard error, statistic, p-value, confidence bounds (+ optional extra columns).36 static func coefficientTable(title: String, names: [String], estimates: [Double], se: [Double?], statistics: [Double?], pValues: [Double?],37 lower: [Double?], upper: [Double?], usesT: Bool, level: Double, locale: Locale,38 extra: [(header: String, values: [Double?])] = []) -> ReportTable {39 let pct = Fmt.percent(level, level * 100 == (level * 100).rounded() ? 0 : 1, locale: locale)40 var rows: [[Value]] = [[.text(L("Term")), .text(L("Estimate")), .text(L("Std. error")), .text(usesT ? "t" : "z"), .text(L("p-value")),41 .text(L("%@ CI lower", pct)), .text(L("%@ CI upper", pct))] + extra.map { .text($0.header) }]42 for i in names.indices {43 rows.append([.text(term(names[i])), .finite(estimates[i]), .finite(se[i]), .finite(statistics[i]), .finite(pValues[i]),44 .finite(lower[i]), .finite(upper[i])] + extra.map { .finite($0.values[i]) })45 }46 var t = ReportTable(title: title, rows: rows, columnFormats: [1: .fixed(4), 2: .fixed(4), 3: .fixed(3), 4: .pValue, 5: .fixed(4), 6: .fixed(4)])47 for k in extra.indices { t.columnFormats[7 + k] = .fixed(4) }48 return t49 }5051 /// A numeric series with its missing rows removed.52 struct Series {53 var name: String54 var values: [Double]55 /// Offsets of the kept rows inside the frame.56 var rows: [Int]57 var frame: DataFrame58 var dropped: Int { frame.rowCount - rows.count }59 }6061 static func series(_ input: ToolInput, _ id: String = "series", minimum: Int) throws -> Series {62 let frame = try input.frame()63 let col = try input.column(id)64 let rows = col.numbers.indices.filter { !col.numbers[$0].isNaN }65 guard rows.count >= minimum else { throw ToolError(L("“%@” has %d numeric observations; at least %d are needed.", col.name, rows.count, minimum)) }66 return Series(name: col.name, values: rows.map { col.numbers[$0] }, rows: rows, frame: frame)67 }6869 /// Note stating that missing observations were skipped (nil when none).70 static func droppedNote(_ s: Series) -> String? {71 s.dropped > 0 ? L("%d rows without a number were skipped; the remaining %d observations are treated as equally spaced.", s.dropped, s.values.count) : nil72 }7374 /// Optional x axis taken from a column (dates or any increasing numbers); nil → 1…n.75 struct Axis {76 var x: [Double]77 var isDate: Bool78 var title: String79 /// x positions of `h` further periods, continuing the last step.80 func extended(_ h: Int) -> [Double] {81 guard let last = x.last, h > 0 else { return [] }82 if isDate, x.count > 2 {83 // calendar steps: monthly / quarterly / yearly dates keep their day of the month84 let parts = x.map { DateSerial.components($0) }85 let months = zip(parts, parts.dropFirst()).map { ($1.year - $0.year) * 12 + $1.month - $0.month }86 if let m = months.first, m >= 1, months.allSatisfy({ $0 == m }), parts.allSatisfy({ $0.day == parts[0].day }), let end = parts.last {87 return (1...h).map { k in88 let total = end.year * 12 + (end.month - 1) + k * m89 return DateSerial.serial(year: total / 12, month: total % 12 + 1, day: end.day)90 }91 }92 }93 let step = x.count > 1 ? last - x[x.count - 2] : 194 return (1...h).map { last + Double($0) * step }95 }96 }9798 static func axis(_ input: ToolInput, _ id: String, rows: [Int]) -> Axis {99 if let col = input.optionalColumn(id) {100 let x = rows.map { col.numbers[$0] }101 if x.allSatisfy(\.isFinite), zip(x, x.dropFirst()).allSatisfy({ $0 < $1 }) {102 let dates = x.allSatisfy { $0 >= 20_000 && $0 <= 80_000 && $0 == $0.rounded() }103 return Axis(x: x, isDate: dates, title: col.name)104 }105 }106 return Axis(x: (0..<rows.count).map { Double($0 + 1) }, isDate: false, title: L("Observation"))107 }108109 /// Data matrix (observations in rows) from the chosen columns after listwise deletion.110 static func matrix(_ input: ToolInput, _ id: String = "vars", atLeast minimum: Int, standardize: Bool) throws111 -> (data: Matrix, names: [String], rows: [Int], frame: DataFrame) {112 let frame = try input.frame()113 let cols = try input.columns(id, atLeast: minimum)114 let (rows, kept) = DataFrame.listwise(cols.map(\.numbers))115 guard rows.count >= 2 else { throw ToolError(L("At least two complete rows are needed.")) }116 var columns = kept117 if standardize {118 columns = try kept.enumerated().map { i, c in119 let sd = Descriptive.standardDeviation(c)120 guard sd > 0, sd.isFinite else { throw ToolError(L("“%@” is constant and cannot be standardized.", cols[i].name)) }121 return Descriptive.standardized(c)122 }123 }124 return (Matrix(columns: columns), cols.map(\.name), rows, frame)125 }126127 static func listwiseNote(used: Int, of total: Int) -> String {128 used == total ? L("All %d rows were used.", total)129 : L("Listwise deletion: %d of %d rows are complete and were used.", used, total)130 }131132 /// Maps labels to integer codes in order of first appearance.133 static func codes(_ labels: [String]) -> (codes: [Int], levels: [String]) {134 var index = [String: Int](), levels = [String](), out = [Int]()135 for l in labels {136 if let i = index[l] { out.append(i) } else { index[l] = levels.count; out.append(levels.count); levels.append(l) }137 }138 return (out, levels)139 }140141 /// Action writing computed columns next to the data (one undoable step).142 static func writeColumns(id: String, title: String, label: String, frame: DataFrame, names: [String], columns: [[Value]]) -> ResultAction {143 ResultAction(id: id, title: title, systemImage: "tablecells.badge.ellipsis", help: L("Adds the columns to the right of the data range. One step to undo.")) { session in144 guard let rg = ReportWriter.appendColumns(session: session, label: label, frame: frame, names: names, columns: columns) else {145 throw ToolError(L("The columns could not be written."))146 }147 return L("Columns written to %@", frame.sheetName + "!" + rg.a1)148 }149 }150151 static let alternatives: [FieldOption] = [FieldOption("twoSided", L("Two-sided")), FieldOption("less", L("Less (lower tail)")), FieldOption("greater", L("Greater (upper tail)"))]152 static func alternative(_ input: ToolInput) -> Alternative { Alternative(rawValue: input.values.choice("alternative")) ?? .twoSided }153}154