SPB Git

Repository Public

ConfidenceIntervalTool.swift 6.9 KB 106 lines swift

1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// Confidence intervals: mean (t or z), variance, proportion, difference of two means.7enum ConfidenceIntervalTool {8    private static let needsData: @Sendable (FormValues) -> Bool = { $0.choice("kind") != "proportion" }910    static let descriptor: ToolDescriptor = {11        var t = ToolDescriptor(12            id: "compare.ci", title: L("Confidence Intervals"), group: Common.groupCompare, systemImage: "arrow.left.and.right",13            summary: L("Interval estimates for a mean, a variance, a proportion or a difference of two means."),14            fields: [15                .choice("kind", L("Interval for"), [16                    FieldOption("mean", L("Mean (Student t)")), FieldOption("meanZ", L("Mean with known σ (z)")), FieldOption("variance", L("Variance (χ²)")),17                    FieldOption("proportion", L("Proportion")), FieldOption("difference", L("Difference of two means")),18                ]),19                FormField("data", L("Data range"), .range(preset: true), visible: needsData),20                .column("x", L("Variable"), visible: needsData),21                .column("y", L("Second variable"), visible: { $0.choice("kind") == "difference" }),22                .number("sigma", L("Known standard deviation σ"), 1, min: 0, visible: { $0.choice("kind") == "meanZ" }),23                .toggle("pooled", L("Assume equal variances (pooled)"), false, visible: { $0.choice("kind") == "difference" }),24                .integer("successes", L("Successes"), 40, min: 0, max: 1_000_000_000, visible: { $0.choice("kind") == "proportion" }),25                .integer("trials", L("Trials"), 100, min: 1, max: 1_000_000_000, visible: { $0.choice("kind") == "proportion" }),26                .choice("pmethod", L("Method"), [FieldOption("wilson", L("Wilson score")), FieldOption("wald", L("Wald (normal approximation)")),27                                                FieldOption("clopperPearson", L("Clopper–Pearson (exact)"))],28                        visible: { $0.choice("kind") == "proportion" }),29                Common.levelField(),30            ],31            info: [32                L("Mean: x̄ ± t(1−α/2; n−1)·s/√n, or x̄ ± z·σ/√n when σ is known."),33                L("Variance: χ² interval ((n−1)s²/χ²(1−α/2), (n−1)s²/χ²(α/2)); it assumes a normal population."),34                L("Difference of means: pooled variance with n₁+n₂−2 degrees of freedom, or Welch's unequal-variance interval with Satterthwaite degrees of freedom."),35                L("Proportion intervals: Wilson score (default), Wald, or the exact Clopper–Pearson interval."),36            ],37            run: run)38        t.demo = { _, v in v.set("data", range: "Groups!A1:C31"); v.set("x", column: 0); v.set("y", column: 1) }39        return t40    }()4142    static func run(_ input: ToolInput) throws -> ToolResult {43        let v = input.values44        let level = try Common.level(v)45        let kind = v.choice("kind")46        let ci: ConfidenceInterval47        var subtitle: String48        var what: String49        var extra: [ResultBlock] = []50        var notes: [String?] = []51        switch kind {52        case "proportion":53            let method = ProportionIntervalMethod(rawValue: v.choice("pmethod")) ?? .wilson54            guard v.int("successes") <= v.int("trials") else { throw ToolError(L("The number of successes cannot exceed the number of trials.")) }55            ci = try Inference.proportionInterval(successes: v.int("successes"), trials: v.int("trials"), level: level, method: method)56            subtitle = L("%d successes in %d trials", v.int("successes"), v.int("trials"))57            what = L("Proportion")58        case "difference":59            let a = try input.column("x"), b = try input.column("y")60            guard a.index != b.index else { throw ToolError(L("Choose two different columns.")) }61            ci = try Inference.meanDifferenceInterval(a.present, b.present, equalVariances: v.bool("pooled"), level: level)62            subtitle = try input.frame().label + " — " + a.name + " − " + b.name63            what = L("Difference of means (%@ − %@)", a.name, b.name)64            extra.append(.table(Common.samplesTable([(a.name, a.present), (b.name, b.present)])))65            notes.append(Common.missingNote([a, b]))66        default:67            let a = try input.column("x")68            let x = a.present69            subtitle = try input.frame().label + " — " + a.name70            switch kind {71            case "meanZ":72                guard v.number("sigma") > 0 else { throw ToolError(L("The known standard deviation σ must be positive.")) }73                ci = try Inference.meanInterval(x, knownSigma: v.number("sigma"), level: level)74                what = L("Mean of %@", a.name)75            case "variance":76                ci = try Inference.varianceInterval(x, level: level)77                what = L("Variance of %@", a.name)78                extra.append(.note([L("Standard deviation interval: %@ to %@.", Fmt.number(ci.lower.squareRoot(), locale: input.locale),79                                      Fmt.number(ci.upper.squareRoot(), locale: input.locale))]))80            default:81                ci = try Inference.meanInterval(x, level: level)82                what = L("Mean of %@", a.name)83            }84            extra.insert(.table(Common.samplesTable([(a.name, x)])), at: 0)85            notes.append(Common.missingNote([a]))86        }87        let isProportion = kind == "proportion"88        let format: CellFormat = isProportion ? .percent(2) : .auto89        let levelText = Fmt.percent(level, level * 100 == (level * 100).rounded() ? 0 : 1, locale: input.locale)90        var blocks: [ResultBlock] = [91            .metrics([Metric(L("Estimate"), ci.estimate, format), Metric(L("Lower bound"), ci.lower, format), Metric(L("Upper bound"), ci.upper, format),92                      Metric(L("Margin of error"), (ci.upper - ci.lower) / 2, format, detail: kind == "variance" || kind == "proportion" ? L("(half-width)") : nil)]),93            .table(ReportTable.keyValue(title: what, header: (L("Quantity"), L("Value")), [94                (L("Estimate"), .finite(ci.estimate), format), (L("Lower bound"), .finite(ci.lower), format), (L("Upper bound"), .finite(ci.upper), format),95                (L("Confidence level"), .number(ci.level), .percent(1)), (L("Method"), .text(ci.method), .auto),96            ])),97            .interpretation(L("With %@ confidence, the interval from %@ to %@ covers the true value of the parameter (%@).", levelText,98                              Fmt.text(.number(ci.lower), format, locale: input.locale), Fmt.text(.number(ci.upper), format, locale: input.locale), what)),99        ]100        blocks += extra101        let lines = notes.compactMap { $0 }102        if !lines.isEmpty { blocks.append(.note(lines)) }103        return ToolResult(title: L("Confidence Interval"), subtitle: subtitle, blocks: blocks, sheetName: L("Confidence interval"))104    }105}106
Files main
Menu

Theme