Repository Public
1import Foundation23/// One uncertain input of a simulation.4public struct MonteCarloInput: Sendable, Hashable, Codable {5 public var name: String6 public var distribution: InputDistribution7 public init(name: String, distribution: InputDistribution) { self.name = name; self.distribution = distribution }8}910/// Target dependence between the inputs of a simulation, expressed as a Spearman rank-correlation matrix.11public struct MonteCarloCorrelation: Sendable, Hashable, Codable {12 public enum Method: String, Sendable, Codable, CaseIterable {13 /// Iman & Conover (1982): the independently drawn columns are re-ordered so that their ranks follow14 /// correlated normal scores. Every marginal sample is preserved exactly (same values, new order).15 case imanConover16 /// Gaussian copula: correlated normals → uniforms → each input's inverse CDF.17 case gaussianCopula18 }19 /// Symmetric k×k matrix with unit diagonal, in the order of the inputs.20 public var matrix: [[Double]]21 public var method: Method22 public init(matrix: [[Double]], method: Method = .imanConover) { self.matrix = matrix; self.method = method }23}2425extension MonteCarlo {26 /// Draws `trials` values of every input; returns one column per input.27 ///28 /// Independent inputs are drawn by inversion, one uniform per value, trial by trial, so trial *t*29 /// of input *j* depends only on the seed. With a correlation target, the Spearman matrix ρ is first30 /// converted to the Pearson correlation of the underlying normals, r = 2·sin(πρ/6) (the exact relation31 /// for a bivariate normal), so that the achieved *rank* correlation matches ρ; an32 /// error is thrown when that matrix is not positive definite.33 public static func sampleInputs(_ inputs: [MonteCarloInput], trials: Int, seed: UInt64,34 correlation: MonteCarloCorrelation? = nil) throws -> [[Double]] {35 guard trials >= 1 else { throw StatError.invalidInput("trials must be ≥ 1") }36 for i in inputs { if let e = i.distribution.validationError { throw StatError.invalidInput("\(i.name): \(e)") } }37 let k = inputs.count38 var rng = Xoshiro256StarStar(seed: seed)39 let samplers = inputs.map { DistributionSampler($0.distribution) }40 var columns = Array(repeating: [Double](repeating: 0, count: trials), count: k)41 guard let correlation, k > 1 else {42 for t in 0..<trials { for j in 0..<k { columns[j][t] = samplers[j].sample(using: &rng) } }43 return columns44 }45 let factor = try normalFactor(correlation.matrix, k: k)46 switch correlation.method {47 case .gaussianCopula:48 var e = [Double](repeating: 0, count: k)49 for t in 0..<trials {50 for j in 0..<k { e[j] = rng.nextNormal() }51 for j in 0..<k {52 var z = 0.053 for l in 0...j { z += factor[j, l] * e[l] }54 let u = Swift.min(Swift.max(SpecialFunctions.normalCDF(z), 0x1.0p-54), 1 - 0x1.0p-53)55 columns[j][t] = samplers[j].quantile(u)56 }57 }58 case .imanConover:59 for t in 0..<trials { for j in 0..<k { columns[j][t] = samplers[j].sample(using: &rng) } }60 guard trials > k + 1 else { throw StatError.insufficientData("Iman–Conover needs more trials than inputs") }61 // van der Waerden scores, independently shuffled per column62 let scores = (1...trials).map { SpecialFunctions.normalQuantile(Double($0) / Double(trials + 1)) }63 var m = [[Double]]()64 for _ in 0..<k { var c = scores; rng.shuffle(&c); m.append(c) }65 // remove the accidental correlation of the scores, then impose the target: M* = M·(Q⁻¹)ᵀ·Pᵀ66 var t = Matrix.identity(k)67 for i in 0..<k { for j in 0..<i { let r = Descriptive.pearson(m[i], m[j]); t[i, j] = r; t[j, i] = r } }68 let q = try LinearAlgebra.cholesky(t)69 let s = factor * (try LinearAlgebra.inverse(q))70 var row = [Double](repeating: 0, count: k)71 var target = Array(repeating: [Double](repeating: 0, count: trials), count: k)72 for i in 0..<trials {73 for j in 0..<k { row[j] = m[j][i] }74 for j in 0..<k {75 var v = 0.076 for l in 0..<k { v += s[j, l] * row[l] }77 target[j][i] = v78 }79 }80 for j in 0..<k {81 let sortedValues = columns[j].sorted()82 let order = (0..<trials).sorted { target[j][$0] != target[j][$1] ? target[j][$0] < target[j][$1] : $0 < $1 }83 for (rank, trial) in order.enumerated() { columns[j][trial] = sortedValues[rank] }84 }85 }86 return columns87 }8889 /// Lower Cholesky factor of the normal-score correlation implied by a Spearman target.90 private static func normalFactor(_ target: [[Double]], k: Int) throws -> Matrix {91 guard target.count == k, target.allSatisfy({ $0.count == k }) else {92 throw StatError.invalidInput("correlation matrix must be \(k)×\(k)")93 }94 var r = Matrix.identity(k)95 for i in 0..<k {96 guard abs(target[i][i] - 1) < 1e-9 else { throw StatError.invalidInput("correlation matrix needs a unit diagonal") }97 for j in 0..<i {98 let v = target[i][j]99 guard v.isFinite, abs(v) <= 1, abs(v - target[j][i]) < 1e-9 else {100 throw StatError.invalidInput("correlation matrix must be symmetric with entries in [−1, 1]")101 }102 let p = 2 * sin(Double.pi * v / 6)103 r[i, j] = p; r[j, i] = p104 }105 }106 do { return try LinearAlgebra.cholesky(r) } catch {107 throw StatError.invalidInput("correlation matrix is not positive definite")108 }109 }110}111