Repository Public
1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// z-tests of means (known or estimated σ) and of proportions.7enum ZTestTool {8 private static let isMean: @Sendable (FormValues) -> Bool = { $0.choice("kind") == "mean1" || $0.choice("kind") == "mean2" }910 static let descriptor: ToolDescriptor = {11 var t = ToolDescriptor(12 id: "compare.ztest", title: L("z-Tests"), group: Common.groupCompare, systemImage: "z.square",13 summary: L("Normal-theory tests of one or two means with known σ, and of one or two proportions."),14 fields: [15 .choice("kind", L("Test"), [FieldOption("mean1", L("One mean")), FieldOption("mean2", L("Two means")),16 FieldOption("prop1", L("One proportion")), FieldOption("prop2", L("Two proportions"))]),17 FormField("data", L("Data range"), .range(preset: true), visible: isMean),18 .column("x", L("Sample 1"), visible: isMean),19 .column("y", L("Sample 2"), visible: { $0.choice("kind") == "mean2" }),20 .number("mu", L("Hypothesised mean"), 0, visible: { $0.choice("kind") == "mean1" }),21 .number("difference", L("Hypothesised difference"), 0, visible: { $0.choice("kind") == "mean2" }),22 .number("sigmaX", L("Known σ of sample 1"), 0, min: 0, help: L("Enter 0 to use the sample standard deviation (large-sample test)."), visible: isMean),23 .number("sigmaY", L("Known σ of sample 2"), 0, min: 0, visible: { $0.choice("kind") == "mean2" }),24 .integer("k1", L("Successes (sample 1)"), 45, min: 0, max: 1_000_000_000, visible: { !isMean($0) }),25 .integer("n1", L("Trials (sample 1)"), 100, min: 1, max: 1_000_000_000, visible: { !isMean($0) }),26 .integer("k2", L("Successes (sample 2)"), 30, min: 0, max: 1_000_000_000, visible: { $0.choice("kind") == "prop2" }),27 .integer("n2", L("Trials (sample 2)"), 100, min: 1, max: 1_000_000_000, visible: { $0.choice("kind") == "prop2" }),28 .percent("p0", L("Hypothesised proportion"), 0.5, min: 0.0001, max: 0.9999, visible: { $0.choice("kind") == "prop1" }),29 Common.alternativeField(),30 Common.levelField(),31 .alpha(L("Significance level α")),32 ],33 info: [34 L("Means: z = (x̄ − μ₀)/(σ/√n). When σ is not given the sample standard deviation is used, which is only justified for large samples."),35 L("One proportion: the standard error uses the hypothesised proportion. Two proportions: the pooled proportion is used under the null hypothesis."),36 ],37 run: run)38 t.demo = { _, v in v.set("kind", choice: "mean2"); v.set("data", range: "Groups!A1:C31"); v.set("x", column: 0); v.set("y", column: 2) }39 return t40 }()4142 static func run(_ input: ToolInput) throws -> ToolResult {43 let v = input.values44 let alpha = try Common.alpha(v), level = try Common.level(v)45 let alt = Common.alternative(v)46 func sigma(_ id: String) -> Double? { v.number(id) > 0 ? v.number(id) : nil }47 func checkCounts(_ k: Int, _ n: Int) throws {48 guard k <= n else { throw ToolError(L("The number of successes cannot exceed the number of trials.")) }49 }50 let test: HypothesisTest51 var subtitle: String, null: String52 var extra: [ResultBlock] = []53 var notes: [String?] = []54 switch v.choice("kind") {55 case "prop1":56 try checkCounts(v.int("k1"), v.int("n1"))57 test = try Inference.proportionZTest(successes: v.int("k1"), trials: v.int("n1"), p0: v.number("p0"), alternative: alt, level: level)58 subtitle = L("%d successes in %d trials", v.int("k1"), v.int("n1"))59 null = L("the population proportion equals %@", Fmt.percent(v.number("p0"), 2, locale: input.locale))60 case "prop2":61 try checkCounts(v.int("k1"), v.int("n1")); try checkCounts(v.int("k2"), v.int("n2"))62 test = try Inference.proportionZTest(successes1: v.int("k1"), trials1: v.int("n1"), successes2: v.int("k2"), trials2: v.int("n2"),63 alternative: alt, level: level)64 subtitle = L("%d/%d against %d/%d", v.int("k1"), v.int("n1"), v.int("k2"), v.int("n2"))65 null = L("the two population proportions are equal")66 case "mean2":67 let a = try input.column("x"), b = try input.column("y")68 guard a.index != b.index else { throw ToolError(L("Choose two different columns.")) }69 test = try Inference.zTest(a.present, b.present, sigmaX: sigma("sigmaX"), sigmaY: sigma("sigmaY"), difference: v.number("difference"),70 alternative: alt, level: level)71 subtitle = try input.frame().label + " — " + a.name + " / " + b.name72 null = L("the difference of the two population means equals %@", Fmt.number(v.number("difference"), locale: input.locale))73 extra.append(.table(Common.samplesTable([(a.name, a.present), (b.name, b.present)])))74 notes.append(Common.missingNote([a, b]))75 if sigma("sigmaX") == nil || sigma("sigmaY") == nil { notes.append(L("No known σ was given for at least one sample: its sample standard deviation was used (large-sample approximation).")) }76 default:77 let a = try input.column("x")78 test = try Inference.zTest(a.present, mu: v.number("mu"), sigma: sigma("sigmaX"), alternative: alt, level: level)79 subtitle = try input.frame().label + " — " + a.name80 null = L("the population mean equals %@", Fmt.number(v.number("mu"), locale: input.locale))81 extra.append(.table(Common.samplesTable([(a.name, a.present)])))82 notes.append(Common.missingNote([a]))83 if sigma("sigmaX") == nil { notes.append(L("No known σ was given for at least one sample: its sample standard deviation was used (large-sample approximation).")) }84 }85 return Common.testResult(test, title: Common.testName(test.name), subtitle: subtitle, alpha: alpha, null: null, locale: input.locale, notes: notes, extra: extra,86 sheetName: L("z-test"))87 }88}89