SPB Git

Repository Public

Bootstrap.swift 7.9 KB 147 lines swift

1import Foundation2import SheetCore34/// A two-sided confidence interval produced by the bootstrap.5public struct BootstrapInterval: Sendable, Hashable, Codable {6    public var lower: Double7    public var upper: Double8    public init(lower: Double, upper: Double) { self.lower = lower; self.upper = upper }9}1011/// Result of a non-parametric bootstrap.12public struct BootstrapResult: Sendable, Hashable, Codable, TableReport {13    /// The statistic evaluated on the original sample.14    public var estimate: Double15    /// The statistic on each resample, in generation order.16    public var replicates: [Double]17    /// Bootstrap standard error: sample standard deviation (n − 1) of the replicates.18    public var standardError: Double19    /// Bootstrap bias estimate: mean of the replicates − estimate.20    public var bias: Double21    public var confidenceLevel: Double22    /// Percentile interval: the α/2 and 1 − α/2 quantiles (type 7) of the replicates.23    public var percentile: BootstrapInterval24    /// Bias-corrected and accelerated interval (Efron 1987); nil when the jackknife acceleration25    /// is undefined (constant leave-one-out statistics) or the bias correction is infinite.26    public var bca: BootstrapInterval?27    /// Bias-correction constant z₀ = Φ⁻¹(share of replicates below the estimate; ties count ½).28    public var biasCorrection: Double29    /// Acceleration â from the jackknife: Σ(θ̄ − θ₍ᵢ₎)³ / (6·[Σ(θ̄ − θ₍ᵢ₎)²]^1.5).30    public var acceleration: Double31    public var resamples: Int32    public var sampleSize: Int33    public var seed: UInt64?3435    public func table() -> [[Value]] {36        var rows: [[Value]] = [37            [.text("Bootstrap"), .blank],38            Report.row("Observations", sampleSize),39            Report.row("Resamples", resamples),40            Report.row("Estimate", estimate),41            Report.row("Bootstrap standard error", standardError),42            Report.row("Bias", bias),43            Report.row("Confidence level", confidenceLevel),44            Report.row("Percentile lower", percentile.lower),45            Report.row("Percentile upper", percentile.upper),46        ]47        if let bca {48            rows.append(Report.row("BCa lower", bca.lower))49            rows.append(Report.row("BCa upper", bca.upper))50        } else {51            rows.append(Report.row("BCa interval", "undefined"))52        }53        rows.append(Report.row("Bias correction z0", biasCorrection))54        rows.append(Report.row("Acceleration", acceleration))55        if let seed { rows.append([.text("Seed"), .text(String(seed))]) }56        return rows57    }58}5960/// Non-parametric bootstrap with percentile and BCa confidence intervals.61///62/// Resampling is by observation index, so the same engine serves one-sample statistics, paired data63/// and any row-wise structure (the closure receives the indices of the rows drawn with replacement).64/// Runs are deterministic for a given seed (xoshiro256**). The interval formulas are those of65/// `scipy.stats.bootstrap` (two-sided intervals only).66public enum Bootstrap {67    /// Bootstrap of a statistic of one sample.68    /// - Parameters:69    ///   - resamples: number of bootstrap resamples B (≥ 2).70    ///   - confidenceLevel: e.g. 0.95.71    ///   - seed: seed of the generator; equal seeds give identical results.72    public static func run(_ data: [Double], resamples: Int = 9999, confidenceLevel: Double = 0.95, seed: UInt64,73                           statistic: ([Double]) throws -> Double) throws -> BootstrapResult {74        try run(count: data.count, resamples: resamples, confidenceLevel: confidenceLevel, seed: seed) { idx in75            try statistic(idx.map { data[$0] })76        }77    }7879    /// Bootstrap of a statistic of paired observations (pairs are resampled together).80    public static func runPaired(_ x: [Double], _ y: [Double], resamples: Int = 9999, confidenceLevel: Double = 0.95, seed: UInt64,81                                 statistic: ([Double], [Double]) throws -> Double) throws -> BootstrapResult {82        guard x.count == y.count else { throw StatError.invalidInput("paired bootstrap needs series of equal length") }83        return try run(count: x.count, resamples: resamples, confidenceLevel: confidenceLevel, seed: seed) { idx in84            try statistic(idx.map { x[$0] }, idx.map { y[$0] })85        }86    }8788    /// Index-based bootstrap: `statistic` receives `count` row indices drawn with replacement89    /// (or, for the original estimate, 0..<count; for the jackknife, all indices but one).90    public static func run(count n: Int, resamples: Int = 9999, confidenceLevel: Double = 0.95, seed: UInt64,91                           statistic: ([Int]) throws -> Double) throws -> BootstrapResult {92        guard n >= 2 else { throw StatError.insufficientData("bootstrap needs at least 2 observations") }93        guard resamples >= 2 else { throw StatError.invalidInput("bootstrap needs at least 2 resamples") }94        var rng = Xoshiro256StarStar(seed: seed)95        var sets = [[Int]]()96        sets.reserveCapacity(resamples)97        for _ in 0..<resamples { sets.append((0..<n).map { _ in rng.nextInt(below: n) }) }98        var r = try evaluate(count: n, indexSets: sets, confidenceLevel: confidenceLevel, statistic: statistic)99        r.seed = seed100        return r101    }102103    /// Computes the bootstrap summary for explicit resample index sets (used by `run` and by the104    /// reference tests, which feed the index matrix drawn by NumPy).105    static func evaluate(count n: Int, indexSets: [[Int]], confidenceLevel: Double,106                         statistic: ([Int]) throws -> Double) throws -> BootstrapResult {107        guard confidenceLevel > 0, confidenceLevel < 1 else { throw StatError.invalidInput("confidence level must be in (0, 1)") }108        guard n >= 2, indexSets.count >= 2 else { throw StatError.insufficientData("bootstrap needs ≥ 2 observations and ≥ 2 resamples") }109        let estimate = try statistic(Array(0..<n))110        let reps = try indexSets.map { try statistic($0) }111        let sorted = reps.sorted()112        let alpha = (1 - confidenceLevel) / 2113        let pct = BootstrapInterval(lower: ResamplingMath.quantileSorted(sorted, alpha),114                                    upper: ResamplingMath.quantileSorted(sorted, 1 - alpha))115        // bias correction: percentile of the estimate among the replicates ("mean" kind: ties count half)116        var below = 0, atOrBelow = 0117        for v in reps { if v < estimate { below += 1 }; if v <= estimate { atOrBelow += 1 } }118        let z0 = SpecialFunctions.normalQuantile(Double(below + atOrBelow) / Double(2 * reps.count))119        // acceleration from the jackknife120        var jack = [Double]()121        jack.reserveCapacity(n)122        var idx = Array(1..<n)123        for i in 0..<n {124            if i > 0 { idx[i - 1] = i - 1 }125            jack.append(try statistic(idx))126        }127        let jm = Descriptive.mean(jack)128        var num = 0.0, den = 0.0129        for t in jack { let u = jm - t; num += u * u * u; den += u * u }130        let acc = num / (6 * den * den.squareRoot())131        var bca: BootstrapInterval?132        if acc.isFinite, z0.isFinite {133            let za = SpecialFunctions.normalQuantile(alpha)134            let n1 = z0 + za, n2 = z0 - za135            let a1 = SpecialFunctions.normalCDF(z0 + n1 / (1 - acc * n1))136            let a2 = SpecialFunctions.normalCDF(z0 + n2 / (1 - acc * n2))137            if a1.isFinite, a2.isFinite {138                bca = BootstrapInterval(lower: ResamplingMath.quantileSorted(sorted, a1), upper: ResamplingMath.quantileSorted(sorted, a2))139            }140        }141        let mean = Descriptive.mean(reps)142        return BootstrapResult(estimate: estimate, replicates: reps, standardError: Descriptive.standardDeviation(reps),143                               bias: mean - estimate, confidenceLevel: confidenceLevel, percentile: pct, bca: bca,144                               biasCorrection: z0, acceleration: acc, resamples: reps.count, sampleSize: n, seed: nil)145    }146}147
Files main
Menu

Theme