Repository Public
1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// Mann–Whitney U, Wilcoxon signed-rank and Kruskal–Wallis tests.7enum NonparametricTool {8 private static let isKW: @Sendable (FormValues) -> Bool = { $0.choice("test") == "kruskalWallis" }910 static let descriptor: ToolDescriptor = {11 var t = ToolDescriptor(12 id: "compare.nonparametric", title: L("Nonparametric Tests"), group: Common.groupCompare, systemImage: "list.number",13 summary: L("Rank-based tests: Mann–Whitney U (two independent samples), Wilcoxon signed-rank (paired) and Kruskal–Wallis (several groups)."),14 fields: [15 .choice("test", L("Test"), [FieldOption("mannWhitney", L("Mann–Whitney U")), FieldOption("wilcoxon", L("Wilcoxon signed-rank (paired)")),16 FieldOption("kruskalWallis", L("Kruskal–Wallis"))]),17 .range("data", L("Data range")),18 ] + GroupFields.fields(visible: isKW) + [19 .column("x", L("Sample 1"), visible: { !isKW($0) }),20 .column("y", L("Sample 2"), visible: { !isKW($0) }),21 Common.alternativeField(visible: { !isKW($0) }),22 .toggle("continuity", L("Continuity correction"), true, visible: { !isKW($0) }),23 .alpha(L("Significance level α")),24 ],25 info: [26 L("Mann–Whitney U and Wilcoxon signed-rank use the normal approximation with tie correction; the exact small-sample distributions are not available, so very small samples should be interpreted with caution."),27 L("Wilcoxon: pairs with a zero difference are dropped before ranking."),28 L("Kruskal–Wallis: H with tie correction, compared with χ²(k − 1)."),29 ],30 run: run)31 t.demo = { _, v in v.set("data", range: "Groups!A1:F31"); v.set("x", column: 0); v.set("y", column: 1) }32 return t33 }()3435 static func run(_ input: ToolInput) throws -> ToolResult {36 let v = input.values37 let alpha = try Common.alpha(v)38 let frame = try input.frame()39 let test: HypothesisTest40 var null: String, subtitle = frame.label41 var samples: [(label: String, values: [Double])]42 var notes: [String?] = []43 switch v.choice("test") {44 case "kruskalWallis":45 let (groups, missing) = try GroupFields.read(input)46 test = try Inference.kruskalWallis(groups.map(\.values))47 null = L("all groups come from the same distribution")48 samples = groups49 notes.append(GroupFields.missingNote(missing))50 subtitle = L("%@ — %d groups", frame.label, groups.count)51 case "wilcoxon":52 let a = try input.column("x"), b = try input.column("y")53 guard a.index != b.index else { throw ToolError(L("Choose two different columns.")) }54 let (x, y) = Common.pairs(a, b)55 test = try Inference.wilcoxonSignedRank(x, y, alternative: Common.alternative(v), continuityCorrection: v.bool("continuity"))56 null = L("the paired differences are symmetric about zero")57 samples = [(a.name, x), (b.name, y)]58 notes.append(Common.pairedNote(a, b, kept: x.count))59 subtitle += " — " + a.name + " − " + b.name60 default:61 let a = try input.column("x"), b = try input.column("y")62 guard a.index != b.index else { throw ToolError(L("Choose two different columns.")) }63 test = try Inference.mannWhitneyU(a.present, b.present, alternative: Common.alternative(v), continuityCorrection: v.bool("continuity"))64 null = L("the two samples come from the same distribution")65 samples = [(a.name, a.present), (b.name, b.present)]66 notes.append(Common.missingNote([a, b]))67 subtitle += " — " + a.name + " / " + b.name68 }69 var rows: [[Value]] = [[.text(L("Sample")), .text(L("n")), .text(L("Median")), .text(L("First quartile")), .text(L("Third quartile")), .text(L("Mean"))]]70 for s in samples {71 rows.append([.text(s.label), .number(Double(s.values.count)), .finite(Descriptive.median(s.values)), .finite(Descriptive.quantile(s.values, 0.25)),72 .finite(Descriptive.quantile(s.values, 0.75)), .finite(Descriptive.mean(s.values))])73 }74 let extra: [ResultBlock] = [75 .table(ReportTable(title: L("Sample statistics"), rows: rows, columnFormats: [1: .integer])),76 .chart(Common.boxPlot(samples, title: L("Distribution of the samples"), yTitle: L("Value"), locale: input.locale)),77 ]78 return Common.testResult(test, title: Common.testName(test.name), subtitle: subtitle, alpha: alpha, null: null, locale: input.locale, notes: notes, extra: extra,79 sheetName: L("Nonparametric test"))80 }81}82