SPB Git

Repository Public

ModelSimulation.swift 2.9 KB 48 lines swift

1import Foundation2import SheetCore3import Statistics45/// An input cell bound to a probability distribution.6public struct ModelInput: Sendable, Hashable, Codable {7    public var cell: ModelCell8    /// Display name; empty = the cell label.9    public var name: String10    public var distribution: InputDistribution11    public init(cell: ModelCell, name: String = "", distribution: InputDistribution) { self.cell = cell; self.name = name; self.distribution = distribution }12}1314/// An output cell tracked by a simulation.15public struct ModelOutput: Sendable, Hashable, Codable {16    public var cell: ModelCell17    /// Display name; empty = the cell label.18    public var name: String19    public init(cell: ModelCell, name: String = "") { self.cell = cell; self.name = name }20}2122/// Monte Carlo simulation of a workbook model: each trial writes sampled values into the input23/// cells, recalculates through the engine and records the output cells.24public enum ModelSimulation {25    /// - Parameters:26    ///   - options: trials, seed, optional rank correlation between the inputs (see `MonteCarloOptions`).27    ///   - progress: called every `options.progressInterval` trials.28    ///   - isCancelled: polled at the same interval; a cancelled run returns the trials completed so far.29    /// Outputs that are not numbers in a trial (errors, text) are counted in `invalidCount`.30    /// The live workbook keeps its values and formulas in every case (completion, cancellation, error).31    public static func run(engine: CalcEngine, inputs: [ModelInput], outputs: [ModelOutput], options: MonteCarloOptions = MonteCarloOptions(),32                           isolation: WhatIfIsolation = .clone, progress: ((_ done: Int, _ total: Int) -> Void)? = nil,33                           isCancelled: (() -> Bool)? = nil) throws -> MonteCarloResult {34        let wb = engine.workbook35        guard !inputs.isEmpty, !outputs.isEmpty else { throw WhatIfError.invalidOptions("a simulation needs at least one input and one output") }36        for c in inputs.map(\.cell) + outputs.map(\.cell) { guard c.isValid(in: wb) else { throw WhatIfError.invalidCell(c.label(in: wb)) } }37        guard Set(inputs.map(\.cell)).count == inputs.count else { throw WhatIfError.invalidOptions("an input cell is bound to two distributions") }38        let mcInputs = inputs.map { MonteCarloInput(name: $0.name.isEmpty ? $0.cell.label(in: wb) : $0.name, distribution: $0.distribution) }39        let names = outputs.map { $0.name.isEmpty ? $0.cell.label(in: wb) : $0.name }40        return try ModelSandbox.run(on: engine, isolation: isolation) { box in41            try MonteCarlo.run(inputs: mcInputs, outputNames: names, options: options, progress: progress, isCancelled: isCancelled) { x in42                for (i, input) in inputs.enumerated() { try box.set(input.cell, number: x[i]) }43                return try outputs.map { try box.number($0.cell) }44            }45        }46    }47}48
Files main
Menu

Theme