SPB Git

Repository Public

InputDistribution.swift 8.9 KB 185 lines swift

1import Foundation23/// A simulation input distribution. Sampling is done by inversion (`quantile(u)`), which makes4/// seeded runs reproducible and lets rank-correlation methods reuse the same marginals.5public enum InputDistribution: Sendable, Hashable, Codable {6    /// Always the same value.7    case constant(Double)8    case normal(mean: Double, sd: Double)9    /// exp(N(mu, sigma²)): `mu` and `sigma` are the parameters of the underlying normal.10    case lognormal(mu: Double, sigma: Double)11    case uniform(min: Double, max: Double)12    case triangular(min: Double, mode: Double, max: Double)13    /// Beta-PERT: min + (max − min)·Beta(α, β) with α = 1 + λ(mode − min)/(max − min), β = 1 + λ(max − mode)/(max − min); λ = 4 is the classic PERT.14    case pert(min: Double, mode: Double, max: Double, lambda: Double)15    /// Finite set of values with probabilities (normalised to sum to 1).16    case discrete(values: [Double], probabilities: [Double])17    /// Resampling of observed data with replacement (each observation has probability 1/n).18    case empirical([Double])1920    /// Lognormal parameterised by the mean and standard deviation of the variable itself.21    public static func lognormal(mean: Double, sd: Double) -> InputDistribution {22        let s2 = log(1 + (sd * sd) / (mean * mean))23        return .lognormal(mu: log(mean) - s2 / 2, sigma: s2.squareRoot())24    }2526    /// Describes why the parameters are unusable, or nil when they are valid.27    public var validationError: String? {28        switch self {29        case .constant(let v): return v.isFinite ? nil : "constant must be finite"30        case .normal(let m, let s): return m.isFinite && s.isFinite && s >= 0 ? nil : "normal needs sd ≥ 0"31        case .lognormal(let m, let s): return m.isFinite && s.isFinite && s >= 0 ? nil : "lognormal needs sigma ≥ 0"32        case .uniform(let a, let b): return a.isFinite && b.isFinite && a <= b ? nil : "uniform needs min ≤ max"33        case .triangular(let a, let c, let b), .pert(let a, let c, let b, _):34            if !(a.isFinite && b.isFinite && c.isFinite && a <= c && c <= b && a < b) { return "needs min ≤ mode ≤ max and min < max" }35            if case .pert(_, _, _, let l) = self, !(l > 0) { return "PERT needs lambda > 0" }36            return nil37        case .discrete(let v, let p):38            if v.isEmpty || v.count != p.count { return "discrete needs as many probabilities as values" }39            if p.contains(where: { !($0 >= 0) }) || !(p.reduce(0, +) > 0) { return "discrete probabilities must be ≥ 0 and not all zero" }40            return nil41        case .empirical(let d): return d.isEmpty ? "empirical needs at least one observation" : nil42        }43    }4445    private var pertShape: (a: Double, b: Double)? {46        guard case .pert(let lo, let mode, let hi, let lambda) = self else { return nil }47        return (1 + lambda * (mode - lo) / (hi - lo), 1 + lambda * (hi - mode) / (hi - lo))48    }4950    /// Inverse CDF at u ∈ (0, 1). For discrete/empirical inputs this is the generalised inverse51    /// (smallest value whose cumulative probability reaches u).52    public func quantile(_ u: Double) -> Double {53        switch self {54        case .constant(let v): return v55        case .normal(let m, let s): return m + s * SpecialFunctions.normalQuantile(u)56        case .lognormal(let m, let s): return exp(m + s * SpecialFunctions.normalQuantile(u))57        case .uniform(let a, let b): return a + (b - a) * u58        case .triangular(let a, let c, let b):59            let fc = (c - a) / (b - a)60            return u < fc ? a + (u * (b - a) * (c - a)).squareRoot() : b - ((1 - u) * (b - a) * (b - c)).squareRoot()61        case .pert(let lo, _, let hi, _):62            let sh = pertShape!63            return lo + (hi - lo) * BetaDistribution(a: sh.a, b: sh.b).quantile(u)64        case .discrete(let values, let probs):65            let total = probs.reduce(0, +)66            var acc = 0.067            for (v, p) in zip(values, probs) {68                acc += p / total69                if u <= acc { return v }70            }71            return values.last ?? .nan72        case .empirical(let data):73            guard !data.isEmpty else { return .nan }74            return InputDistribution.empiricalQuantile(sorted: data.sorted(), u)75        }76    }7778    /// Generalised inverse of the empirical CDF: the ⌈u·n⌉-th smallest observation.79    static func empiricalQuantile(sorted: [Double], _ u: Double) -> Double {80        let n = sorted.count81        let k = Int((u * Double(n)).rounded(.up)) - 182        return sorted[Swift.min(n - 1, Swift.max(0, k))]83    }8485    /// Draws one value (inversion of one open-interval uniform). `empirical` sorts its data on86    /// every call: in loops use `DistributionSampler`, which prepares the distribution once.87    public func sample(using rng: inout Xoshiro256StarStar) -> Double { quantile(rng.nextOpenUniform()) }8889    /// Theoretical mean.90    public var mean: Double {91        switch self {92        case .constant(let v): return v93        case .normal(let m, _): return m94        case .lognormal(let m, let s): return exp(m + s * s / 2)95        case .uniform(let a, let b): return (a + b) / 296        case .triangular(let a, let c, let b): return (a + b + c) / 397        case .pert(let lo, let mode, let hi, let lambda): return (lo + lambda * mode + hi) / (lambda + 2)98        case .discrete(let v, let p):99            let t = p.reduce(0, +)100            return zip(v, p).reduce(0) { $0 + $1.0 * $1.1 } / t101        case .empirical(let d): return d.reduce(0, +) / Double(d.count)102        }103    }104105    /// Theoretical variance (population variance of the data for `empirical`).106    public var variance: Double {107        switch self {108        case .constant: return 0109        case .normal(_, let s): return s * s110        case .lognormal(let m, let s): return (exp(s * s) - 1) * exp(2 * m + s * s)111        case .uniform(let a, let b): return (b - a) * (b - a) / 12112        case .triangular(let a, let c, let b): return (a * a + b * b + c * c - a * b - a * c - b * c) / 18113        case .pert(let lo, _, let hi, _):114            let sh = pertShape!115            let ab = sh.a + sh.b116            return (hi - lo) * (hi - lo) * sh.a * sh.b / (ab * ab * (ab + 1))117        case .discrete(let v, let p):118            let t = p.reduce(0, +), mu = mean119            return zip(v, p).reduce(0) { $0 + ($1.0 - mu) * ($1.0 - mu) * $1.1 } / t120        case .empirical(let d):121            let mu = mean122            return d.reduce(0) { $0 + ($1 - mu) * ($1 - mu) } / Double(d.count)123        }124    }125126    /// Short human-readable description, e.g. "Normal(μ=10, σ=2)".127    public var label: String {128        func f(_ d: Double) -> String { String(format: "%g", d) }129        switch self {130        case .constant(let v): return "Constant(\(f(v)))"131        case .normal(let m, let s): return "Normal(μ=\(f(m)), σ=\(f(s)))"132        case .lognormal(let m, let s): return "Lognormal(μ=\(f(m)), σ=\(f(s)))"133        case .uniform(let a, let b): return "Uniform(\(f(a)), \(f(b)))"134        case .triangular(let a, let c, let b): return "Triangular(\(f(a)), \(f(c)), \(f(b)))"135        case .pert(let a, let c, let b, let l): return "PERT(\(f(a)), \(f(c)), \(f(b)); λ=\(f(l)))"136        case .discrete(let v, _): return "Discrete(\(v.count) values)"137        case .empirical(let d): return "Empirical(n=\(d.count))"138        }139    }140}141142/// An `InputDistribution` prepared for repeated sampling (sorted data, cumulative probabilities and143/// PERT shape computed once). Produces exactly the same values as `InputDistribution.quantile`.144public struct DistributionSampler: Sendable {145    public let distribution: InputDistribution146    private let sorted: [Double]147    private let cumulative: [Double]148    private let values: [Double]149150    public init(_ d: InputDistribution) {151        distribution = d152        switch d {153        case .empirical(let data):154            sorted = data.sorted(); cumulative = []; values = []155        case .discrete(let v, let p):156            let total = p.reduce(0, +)157            var acc = 0.0158            var cum = [Double]()159            for x in p { acc += x / total; cum.append(acc) }160            sorted = []; cumulative = cum; values = v161        default:162            sorted = []; cumulative = []; values = []163        }164    }165166    public func quantile(_ u: Double) -> Double {167        switch distribution {168        case .empirical:169            return sorted.isEmpty ? .nan : InputDistribution.empiricalQuantile(sorted: sorted, u)170        case .discrete:171            // first index whose cumulative probability reaches u172            var lo = 0, hi = cumulative.count - 1173            while lo < hi {174                let mid = (lo + hi) / 2175                if u <= cumulative[mid] { hi = mid } else { lo = mid + 1 }176            }177            return values.isEmpty ? .nan : values[lo]178        default:179            return distribution.quantile(u)180        }181    }182183    public func sample(using rng: inout Xoshiro256StarStar) -> Double { quantile(rng.nextOpenUniform()) }184}185
Files main
Menu

Theme