Repository Public
1import Foundation2import SheetCore34/// Settings of a Monte Carlo run.5public struct MonteCarloOptions: Sendable, Hashable, Codable {6 /// Number of trials N.7 public var trials = 10_0008 /// Seed of the xoshiro256** generator: equal seeds (and inputs) give bit-identical results.9 public var seed: UInt64 = 110 /// Probabilities (0…1) of the percentiles to report (type 7, linear interpolation).11 public var percentiles: [Double] = [0.01, 0.05, 0.10, 0.25, 0.50, 0.75, 0.90, 0.95, 0.99]12 /// Number of equal-width histogram bins between the minimum and the maximum.13 public var histogramBins = 4014 /// Number of checkpoints of the running mean to report.15 public var convergencePoints = 10016 /// Optional rank-correlation target between the inputs.17 public var correlation: MonteCarloCorrelation?18 /// Keep the raw input and output samples in the result.19 public var keepSamples = true20 /// Trials between two calls of the progress / cancellation closures.21 public var progressInterval = 25622 public init() {}23 public init(trials: Int, seed: UInt64) { self.trials = trials; self.seed = seed }24}2526public struct MonteCarloHistogram: Sendable, Hashable, Codable {27 /// bins + 1 ascending edges; bin i covers [edges[i], edges[i+1]) and the last bin includes its right edge.28 public var edges: [Double]29 public var counts: [Int]30}3132public struct MonteCarloPercentile: Sendable, Hashable, Codable {33 /// Probability in 0…1.34 public var probability: Double35 public var value: Double36}3738public struct MonteCarloConvergencePoint: Sendable, Hashable, Codable {39 public var trials: Int40 /// Mean of the first `trials` valid outcomes.41 public var mean: Double42 /// Standard error of that mean: sample standard deviation / √trials.43 public var standardError: Double44}4546public struct MonteCarloSensitivity: Sendable, Hashable, Codable {47 public var input: String48 /// Spearman rank correlation between the input and the output across trials (NaN for a constant input).49 public var rankCorrelation: Double50 /// ρ² normalised to sum to 1 over the inputs ("contribution to variance" as reported by51 /// simulation add-ins; a heuristic that is exact only for additive models with independent inputs).52 public var contributionToVariance: Double53}5455/// Distribution summary of one simulated output.56public struct MonteCarloOutput: Sendable, Hashable, Codable, TableReport {57 public var name: String58 /// Trials with a finite outcome (the statistics below use only those).59 public var count: Int60 /// Trials whose outcome was NaN or infinite (e.g. a model error).61 public var invalidCount: Int62 public var mean: Double63 /// Sample standard deviation (n − 1).64 public var standardDeviation: Double65 /// Standard error of the mean: standardDeviation / √count.66 public var standardError: Double67 public var minimum: Double68 public var maximum: Double69 public var median: Double70 /// Population skewness g1 = m3 / m2^1.5.71 public var skewness: Double72 /// Population excess kurtosis g2 = m4 / m2² − 3.73 public var excessKurtosis: Double74 public var percentiles: [MonteCarloPercentile]75 public var histogram: MonteCarloHistogram76 public var convergence: [MonteCarloConvergencePoint]77 /// Tornado data: inputs sorted by decreasing |rank correlation| with this output.78 public var sensitivities: [MonteCarloSensitivity]7980 /// Share of valid outcomes ≤ x (empirical CDF), e.g. the probability of a loss with x = 0.81 public func probability(atMost x: Double, in samples: [Double]) -> Double {82 let valid = samples.filter(\.isFinite)83 guard !valid.isEmpty else { return .nan }84 return Double(valid.filter { $0 <= x }.count) / Double(valid.count)85 }8687 public func table() -> [[Value]] {88 var rows: [[Value]] = [89 [.text("Output"), .text(name)],90 Report.row("Trials", count),91 Report.row("Invalid trials", invalidCount),92 Report.row("Mean", mean),93 Report.row("Standard deviation", standardDeviation),94 Report.row("Standard error of mean", standardError),95 Report.row("Minimum", minimum),96 Report.row("Median", median),97 Report.row("Maximum", maximum),98 Report.row("Skewness", skewness),99 Report.row("Excess kurtosis", excessKurtosis),100 ]101 for p in percentiles { rows.append(Report.row(String(format: "P%g", p.probability * 100), p.value)) }102 if !sensitivities.isEmpty {103 rows.append([.blank, .blank])104 rows.append([.text("Sensitivity (input)"), .text("Rank correlation"), .text("Contribution to variance")])105 for s in sensitivities { rows.append([.text(s.input), Report.num(s.rankCorrelation), Report.num(s.contributionToVariance)]) }106 }107 return Report.rectangular(rows)108 }109}110111/// Result of a Monte Carlo simulation.112///113/// Note for persistence: undefined statistics are NaN; configure `JSONEncoder.nonConformingFloatEncodingStrategy`114/// when encoding results that may contain them.115public struct MonteCarloResult: Sendable, Hashable, Codable, TableReport {116 public var inputs: [MonteCarloInput]117 public var outputs: [MonteCarloOutput]118 public var trialsRequested: Int119 public var trialsCompleted: Int120 public var cancelled: Bool121 public var seed: UInt64122 /// Spearman rank-correlation matrix actually achieved between the inputs (nil without a correlation target).123 public var achievedInputRankCorrelation: [[Double]]?124 /// One column per input (empty when `keepSamples` is false).125 public var inputSamples: [[Double]]126 /// One column per output (empty when `keepSamples` is false).127 public var outputSamples: [[Double]]128129 public func table() -> [[Value]] {130 var rows: [[Value]] = [131 [.text("Monte Carlo simulation"), .blank],132 Report.row("Trials requested", trialsRequested),133 Report.row("Trials completed", trialsCompleted),134 Report.row("Status", cancelled ? "cancelled" : "completed"),135 [.text("Seed"), .text(String(seed))],136 [.blank, .blank],137 [.text("Input"), .text("Distribution")],138 ]139 for i in inputs { rows.append([.text(i.name), .text(i.distribution.label)]) }140 for o in outputs {141 rows.append([.blank, .blank])142 rows.append(contentsOf: o.table())143 }144 return Report.rectangular(rows)145 }146}147148/// Monte Carlo simulation engine: seeded sampling of the inputs, evaluation of a model closure for149/// each trial, and summaries of every output.150public enum MonteCarlo {151 /// Runs a simulation with one output.152 public static func run(inputs: [MonteCarloInput], outputName: String = "Output", options: MonteCarloOptions = MonteCarloOptions(),153 progress: ((_ done: Int, _ total: Int) -> Void)? = nil, isCancelled: (() -> Bool)? = nil,154 model: ([Double]) throws -> Double) throws -> MonteCarloResult {155 try run(inputs: inputs, outputNames: [outputName], options: options, progress: progress, isCancelled: isCancelled) { [try model($0)] }156 }157158 /// Runs a simulation with several outputs. `model` receives the input values of one trial (in the159 /// order of `inputs`) and returns one value per output name. Non-finite outcomes are counted as160 /// invalid and left out of the statistics. `isCancelled` is polled every `progressInterval` trials;161 /// a cancelled run returns the summary of the trials completed so far with `cancelled = true`.162 public static func run(inputs: [MonteCarloInput], outputNames: [String], options: MonteCarloOptions = MonteCarloOptions(),163 progress: ((_ done: Int, _ total: Int) -> Void)? = nil, isCancelled: (() -> Bool)? = nil,164 model: ([Double]) throws -> [Double]) throws -> MonteCarloResult {165 guard !inputs.isEmpty else { throw StatError.invalidInput("a simulation needs at least one input") }166 guard !outputNames.isEmpty else { throw StatError.invalidInput("a simulation needs at least one output") }167 let n = options.trials168 var columns = try sampleInputs(inputs, trials: n, seed: options.seed, correlation: options.correlation)169 var outs = Array(repeating: [Double](), count: outputNames.count)170 for j in outs.indices { outs[j].reserveCapacity(n) }171 var x = [Double](repeating: 0, count: inputs.count)172 var done = 0173 var cancelled = false174 let interval = max(1, options.progressInterval)175 for t in 0..<n {176 if t % interval == 0 {177 if isCancelled?() == true { cancelled = true; break }178 progress?(t, n)179 }180 for j in x.indices { x[j] = columns[j][t] }181 let y = try model(x)182 guard y.count == outputNames.count else { throw StatError.invalidInput("the model returned \(y.count) values for \(outputNames.count) outputs") }183 for j in outs.indices { outs[j].append(y[j]) }184 done += 1185 }186 if !cancelled { progress?(n, n) }187 if done < n { for j in columns.indices { columns[j].removeLast(n - done) } }188 let names = inputs.map(\.name)189 let summaries = outputNames.indices.map { summarize(name: outputNames[$0], samples: outs[$0], inputNames: names, inputSamples: columns, options: options) }190 let achieved = options.correlation != nil && inputs.count > 1 && done > 2 ? ResamplingMath.spearmanMatrix(columns) : nil191 return MonteCarloResult(inputs: inputs, outputs: summaries, trialsRequested: n, trialsCompleted: done, cancelled: cancelled,192 seed: options.seed, achievedInputRankCorrelation: achieved,193 inputSamples: options.keepSamples ? columns : [], outputSamples: options.keepSamples ? outs : [])194 }195196 /// Summarises the simulated values of one output (and its rank-correlation sensitivity to each input column).197 public static func summarize(name: String, samples: [Double], inputNames: [String] = [], inputSamples: [[Double]] = [],198 options: MonteCarloOptions = MonteCarloOptions()) -> MonteCarloOutput {199 let validIdx = samples.indices.filter { samples[$0].isFinite }200 let v = validIdx.map { samples[$0] }201 let n = v.count202 let sorted = v.sorted()203 let mean = Descriptive.mean(v)204 let sd = Descriptive.standardDeviation(v)205 let shape = ResamplingMath.shape(v, mean: mean)206 let pcts = options.percentiles.map { MonteCarloPercentile(probability: $0, value: ResamplingMath.quantileSorted(sorted, $0)) }207 var sens = [MonteCarloSensitivity]()208 if n > 2 {209 let yr = Descriptive.ranks(v)210 for (j, col) in inputSamples.enumerated() where col.count == samples.count {211 let xs = validIdx.map { col[$0] }212 let rho = Descriptive.pearson(Descriptive.ranks(xs), yr)213 sens.append(MonteCarloSensitivity(input: j < inputNames.count ? inputNames[j] : "Input \(j + 1)", rankCorrelation: rho, contributionToVariance: 0))214 }215 let total = sens.reduce(0.0) { $0 + ($1.rankCorrelation.isFinite ? $1.rankCorrelation * $1.rankCorrelation : 0) }216 for i in sens.indices {217 let r = sens[i].rankCorrelation218 sens[i].contributionToVariance = total > 0 && r.isFinite ? r * r / total : 0219 }220 // stable sort: decreasing |ρ|, undefined correlations last, ties in input order221 sens = sens.enumerated().sorted { a, b in222 let x = a.element.rankCorrelation.isFinite ? abs(a.element.rankCorrelation) : -1223 let y = b.element.rankCorrelation.isFinite ? abs(b.element.rankCorrelation) : -1224 return x != y ? x > y : a.offset < b.offset225 }.map(\.element)226 }227 return MonteCarloOutput(name: name, count: n, invalidCount: samples.count - n, mean: mean, standardDeviation: sd,228 standardError: n > 1 ? sd / Double(n).squareRoot() : .nan,229 minimum: sorted.first ?? .nan, maximum: sorted.last ?? .nan,230 median: ResamplingMath.quantileSorted(sorted, 0.5), skewness: shape.skewness, excessKurtosis: shape.excessKurtosis,231 percentiles: pcts, histogram: histogram(sorted: sorted, bins: options.histogramBins),232 convergence: convergence(v, points: options.convergencePoints), sensitivities: sens)233 }234235 /// Equal-width histogram between the smallest and largest value (NumPy conventions: the last bin236 /// is closed on the right; a constant sample gets the range [v − ½, v + ½]).237 static func histogram(sorted: [Double], bins requested: Int) -> MonteCarloHistogram {238 let bins = max(1, requested)239 guard var lo = sorted.first, var hi = sorted.last else { return MonteCarloHistogram(edges: [], counts: []) }240 if lo == hi { lo -= 0.5; hi += 0.5 }241 let step = (hi - lo) / Double(bins)242 var edges = (0...bins).map { lo + Double($0) * step }243 edges[bins] = hi244 var counts = [Int](repeating: 0, count: bins)245 for v in sorted {246 var i = Swift.min(bins - 1, Swift.max(0, Int((v - lo) / (hi - lo) * Double(bins))))247 if v < edges[i], i > 0 { i -= 1 } else if i < bins - 1, v >= edges[i + 1] { i += 1 }248 counts[i] += 1249 }250 return MonteCarloHistogram(edges: edges, counts: counts)251 }252253 /// Running mean and its standard error at `points` evenly spaced trial counts (from 2 trials on).254 static func convergence(_ v: [Double], points: Int) -> [MonteCarloConvergencePoint] {255 let n = v.count256 guard n >= 2, points >= 1 else { return [] }257 var checkpoints = [Int]()258 for j in 1...points {259 let c = Swift.max(2, Int((Double(j) * Double(n) / Double(points)).rounded()))260 if checkpoints.last != c { checkpoints.append(c) }261 }262 var out = [MonteCarloConvergencePoint]()263 var mean = 0.0, m2 = 0.0 // Welford264 var next = 0265 for (i, x) in v.enumerated() {266 let k = Double(i + 1)267 let d = x - mean268 mean += d / k269 m2 += d * (x - mean)270 if next < checkpoints.count, i + 1 == checkpoints[next] {271 out.append(MonteCarloConvergencePoint(trials: i + 1, mean: mean, standardError: (m2 / (k - 1)).squareRoot() / k.squareRoot()))272 next += 1273 }274 }275 return out276 }277}278