Repository Public
1import Foundation2import SheetCore3import SheetUI4import Statistics5import WhatIf6import AnalysisKit78/// One input cell bound to a probability distribution, as edited in the form and stored (JSON) in the form values.9struct MCBinding: Codable, Hashable, Identifiable {10 enum Kind: String, Codable, CaseIterable, Identifiable {11 case normal, lognormal, uniform, triangular, pert, discrete12 var id: String { rawValue }13 var title: String {14 switch self {15 case .normal: L("Normal")16 case .lognormal: L("Lognormal")17 case .uniform: L("Uniform")18 case .triangular: L("Triangular")19 case .pert: L("PERT")20 case .discrete: L("Discrete")21 }22 }23 /// Labels of the numeric parameters p1…p3, in order.24 var parameters: [String] {25 switch self {26 case .normal, .lognormal: [L("Mean"), L("Std. deviation")]27 case .uniform: [L("Minimum"), L("Maximum")]28 case .triangular, .pert: [L("Minimum"), L("Most likely"), L("Maximum")]29 case .discrete: []30 }31 }32 }3334 var id = UUID()35 /// Cell reference text ("Model!B4").36 var cell = ""37 /// Display name; empty = the label next to the cell.38 var name = ""39 var kind = Kind.normal40 var p1 = 0.0, p2 = 1.0, p3 = 2.041 /// Discrete distribution: values and probabilities as typed lists.42 var valuesText = ""43 var probabilitiesText = ""4445 /// The distribution, or a localized error when the parameters are unusable.46 func distribution(locale: Locale) throws -> InputDistribution {47 let d: InputDistribution48 switch kind {49 case .normal: d = .normal(mean: p1, sd: p2)50 case .lognormal:51 guard p1 > 0, p2 > 0 else { throw ToolError(L("%@: a lognormal distribution needs a positive mean and standard deviation.", displayCell)) }52 d = .lognormal(mean: p1, sd: p2)53 case .uniform: d = .uniform(min: p1, max: p2)54 case .triangular: d = .triangular(min: p1, mode: p2, max: p3)55 case .pert: d = .pert(min: p1, mode: p2, max: p3, lambda: 4)56 case .discrete:57 guard let v = FormValues.numberList(valuesText, locale: locale) else { throw ToolError(L("%@: enter the values of the discrete distribution.", displayCell)) }58 let p = FormValues.numberList(probabilitiesText, locale: locale) ?? Array(repeating: 1 / Double(v.count), count: v.count)59 guard p.count == v.count else { throw ToolError(L("%@: give one probability per value (%d values, %d probabilities).", displayCell, v.count, p.count)) }60 d = .discrete(values: v, probabilities: p)61 }62 if let problem = d.validationError { throw ToolError(L("%@: invalid distribution — %@", displayCell, problem)) }63 return d64 }6566 var displayCell: String { cell.isEmpty ? L("(no cell)") : cell }6768 /// Normal(mean = current value, sd = 10 % of |value|), the preset of "Add Selected Cells".69 static func preset(cell: String, name: String, value: Double) -> MCBinding {70 var b = MCBinding()71 b.cell = cell; b.name = name; b.kind = .normal72 b.p1 = value; b.p2 = value == 0 ? 1 : abs(value) * 0.173 return b74 }7576 /// Keeps the parameters meaningful when the kind changes (centre and spread are carried over).77 mutating func convert(to new: Kind) {78 guard new != kind else { return }79 let (centre, spread): (Double, Double) = {80 switch kind {81 case .normal, .lognormal: (p1, p2 * 2)82 case .uniform: ((p1 + p2) / 2, (p2 - p1) / 2)83 case .triangular, .pert: (p2, (p3 - p1) / 2)84 case .discrete: (FormValues.numberList(valuesText, locale: Locale(identifier: "en_US")).map { $0.reduce(0, +) / Double($0.count) } ?? 0, 1)85 }86 }()87 let s = spread > 0 ? spread : max(abs(centre) * 0.2, 1)88 switch new {89 case .normal, .lognormal: p1 = centre; p2 = s / 290 case .uniform: p1 = centre - s; p2 = centre + s91 case .triangular, .pert: p1 = centre - s; p2 = centre; p3 = centre + s92 case .discrete:93 valuesText = [centre - s, centre, centre + s].map { Value.generalString($0) }.joined(separator: "; ")94 probabilitiesText = "0.25; 0.5; 0.25"95 }96 kind = new97 }9899 // MARK: Storage in the form values100101 static func decode(_ text: String) -> [MCBinding] {102 guard let data = text.data(using: .utf8), let list = try? JSONDecoder().decode([MCBinding].self, from: data) else { return [] }103 return list104 }105106 static func encode(_ list: [MCBinding]) -> String {107 let enc = JSONEncoder()108 enc.outputFormatting = [.sortedKeys]109 return (try? enc.encode(list)).flatMap { String(data: $0, encoding: .utf8) } ?? "[]"110 }111112 /// Bindings for the numeric, non-formula cells of the selection (at most 50), skipping cells already bound.113 @MainActor static func fromSelection(_ session: WorkbookSession, existing: [MCBinding]) -> [MCBinding] {114 let wb = session.workbook, si = session.sheetIndex115 let sheet = wb.sheets[si]116 var out = [MCBinding]()117 var seen = Set(existing.compactMap { RangeReader.cells($0.cell, workbook: wb, sheet: si)?.first })118 for rg in session.selection.ranges {119 guard let clipped = RangeReader.clip(rg, sheet: sheet) ?? (rg.isSingleCell ? rg : nil) else { continue }120 for r in clipped.r0...clipped.r1 { for c in clipped.c0...clipped.c1 {121 let address = CellAddress(sheet: si, cell: CellRef(r, c))122 guard out.count < 50, !seen.contains(address), let cell = sheet.cell(r, c), cell.formula == nil, case .number(let v) = cell.value else { continue }123 seen.insert(address)124 let name = WhatIfSupport.name(address, in: wb)125 let label = WhatIfSupport.label(address, in: wb)126 out.append(.preset(cell: label, name: name == label ? "" : name, value: v))127 } }128 }129 return out130 }131}132133/// Rank correlation between the inputs, as chosen in the form.134enum MCCorrelation {135 /// n × n matrix with 1 on the diagonal and ρ elsewhere.136 static func common(_ rho: Double, count n: Int) -> [[Double]] {137 (0..<n).map { i in (0..<n).map { j in i == j ? 1 : rho } }138 }139140 /// Parses "1 0.5; 0.5 1" (rows separated by ";" or new lines). Must be n × n, symmetric, with a unit diagonal and entries in [−1, 1].141 static func parse(_ text: String, count n: Int, locale: Locale) throws -> [[Double]] {142 let decimalComma = (locale.decimalSeparator ?? ".") == ","143 let rows = text.split(whereSeparator: { $0 == ";" || $0 == "\n" }).map { row -> [Double?] in144 row.split(whereSeparator: { $0 == " " || $0 == "\t" || (!decimalComma && $0 == ",") })145 .map { Double(decimalComma ? $0.replacingOccurrences(of: ",", with: ".") : String($0)) }146 }.filter { !$0.isEmpty }147 guard rows.count == n, rows.allSatisfy({ $0.count == n && !$0.contains(nil) }) else {148 throw ToolError(L("The correlation matrix must have %d rows of %d numbers (rows separated by “;”).", n, n))149 }150 let m = rows.map { $0.map { $0! } }151 for i in 0..<n { for j in 0..<n {152 guard abs(m[i][j]) <= 1, abs(m[i][j] - m[j][i]) < 1e-9, i != j || abs(m[i][j] - 1) < 1e-9 else {153 throw ToolError(L("The correlation matrix must be symmetric with 1 on the diagonal and entries between −1 and 1."))154 }155 } }156 return m157 }158}159