Repository Public
1import Foundation2import Testing3import SheetCore4import SheetUI5import Statistics6import AnalysisKit7@testable import StatsBasic89@MainActor func makeSession(_ rows: [[String]]) -> WorkbookSession {10 let session = WorkbookSession(workbook: Workbook(sheetNames: ["Data"]), locale: Locale(identifier: "en_US"))11 session.perform("Fill") { e in12 for (r, row) in rows.enumerated() { for (c, text) in row.enumerated() where !text.isEmpty {13 try? e.setInput(sheet: 0, row: r, col: c, text, parser: session.parser)14 } }15 }16 session.engine.clearUndoHistory()17 return session18}1920/// Columns given as arrays (nil = blank cell), written under a header row.21@MainActor func columnSession(_ columns: [(String, [Double?])], text: [(String, [String])] = []) -> WorkbookSession {22 let n = max(columns.map(\.1.count).max() ?? 0, text.map(\.1.count).max() ?? 0)23 var rows = [columns.map(\.0) + text.map(\.0)]24 for r in 0..<n {25 rows.append(columns.map { r < $0.1.count ? ($0.1[r].map { String($0) } ?? "") : "" } + text.map { r < $0.1.count ? $0.1[r] : "" })26 }27 return makeSession(rows)28}2930/// Runs a tool on a session with the given form values.31@MainActor func run(_ tool: ToolDescriptor, on session: WorkbookSession, range: String? = nil, header: Bool = true,32 _ configure: (inout FormValues) -> Void = { _ in }) throws -> ToolResult {33 var v = FormValues(defaults: tool.fields)34 if let range { v.set("data", range: range, hasHeader: header) }35 configure(&v)36 return try tool.run(try ToolInputResolver.resolve(tool, values: v, session: session))37}3839extension ToolResult {40 var metrics: [Metric] { blocks.flatMap { b -> [Metric] in if case .metrics(let m) = b { m } else { [] } } }41 func metric(_ label: String) -> Double? { metrics.first { $0.label == label }?.value.numberValue }42 var interpretations: [String] {43 blocks.flatMap { b -> [String] in if case .text(let t) = b, t.kind == .interpretation { t.lines } else { [] } }44 }45 var warnings: [String] { blocks.flatMap { b -> [String] in if case .text(let t) = b, t.kind == .warning { t.lines } else { [] } } }46 var notes: [String] { blocks.flatMap { b -> [String] in if case .text(let t) = b, t.kind == .note { t.lines } else { [] } } }47}4849extension ReportTable {50 /// Value in the row whose first cell is `label`, at column `col`.51 func value(_ label: String, _ col: Int = 1) -> Double? {52 rows.first { $0.first == .text(label) }?[col].numberValue53 }54 func text(_ label: String, _ col: Int = 1) -> String? { rows.first { $0.first == .text(label) }?[col].textValue }55}5657func close(_ a: Double?, _ b: Double, _ tol: Double = 1e-12) -> Bool {58 guard let a else { return false }59 return abs(a - b) <= tol * max(1, abs(b))60}6162let sampleA: [Double] = [12.1, 14.3, 11.8, 15.2, 13.9, 12.7, 16.1, 14.8, 13.3, 15.6]63let sampleB: [Double] = [15.4, 17.2, 16.8, 14.9, 18.3, 17.7, 16.1, 19.0, 15.8, 17.4]64let sampleC: [Double] = [11.0, 12.4, 10.9, 13.1, 12.2, 11.7, 12.9, 10.4, 11.5, 12.6]65