SPB Git

Repository Public

Sandbox.swift 9.3 KB 218 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetAnalytics/Sources/WhatIf/Sandbox.swift10// Module           : WhatIf11// Repository       : https://git.spboucher.ai/orix-sheet12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import Foundation88import SheetCore8990/// Deep copy of a workbook for isolated what-if evaluation.91public enum WorkbookCloner {92    /// Copies sheets (same ids, names, order, metadata), cells (fresh `Formula` objects carrying the93    /// cached value and spill area), defined names, styles, attachments and settings.94    public static func clone(_ source: Workbook) -> Workbook {95        let copy = Workbook()96        for s in source.sheets {97            let sheet = Sheet(id: s.id, name: s.name)98            sheet.meta = s.meta99            var store = CellStore()100            for (c, column) in s.cells.columns {101                var cells = [Int: Cell]()102                cells.reserveCapacity(column.count)103                for (r, cell) in column {104                    var copied = cell105                    if let f = cell.formula {106                        let nf = Formula(expr: f.expr)107                        nf.value = f.value108                        nf.spill = f.spill109                        copied.formula = nf110                    }111                    cells[r] = copied112                }113                store.replaceColumn(c, with: cells)114            }115            sheet.cells = store116            copy.sheets.append(sheet)117        }118        copy.names = source.names119        copy.styles = source.styles120        copy.date1904 = source.date1904121        copy.properties = source.properties122        copy.activeSheet = source.activeSheet123        copy.defaultFontName = source.defaultFontName124        copy.defaultFontSize = source.defaultFontSize125        copy.attachments = source.attachments126        return copy127    }128}129130/// The place where a what-if tool makes its temporary edits: either a private clone of the model131/// or the live engine inside a transaction that is undone afterwards (see `WhatIfIsolation`).132public final class ModelSandbox {133    /// The engine the edits are applied to (the clone's engine, or the live one for `.inPlace`).134    public let engine: CalcEngine135    public let isolation: WhatIfIsolation136    private var originals: [ModelCell: CellInput] = [:]137    private var order: [ModelCell] = []138139    private init(engine: CalcEngine, isolation: WhatIfIsolation) { self.engine = engine; self.isolation = isolation }140141    /// Runs `body` with a sandbox on the model of `live`. Whatever `body` does through the sandbox —142    /// and whether it returns or throws — the live workbook ends with the values and formulas it had before.143    public static func run<T>(on live: CalcEngine, isolation: WhatIfIsolation = .clone, _ body: (ModelSandbox) throws -> T) throws -> T {144        switch isolation {145        case .clone:146            // cached values are reused only when the live model is fully calculated147            let trust = live.pendingCount == 0148            let engine = CalcEngine(workbook: WorkbookCloner.clone(live.workbook), registry: live.registry, trustCachedValues: trust)149            engine.maxDepth = live.maxDepth150            let box = ModelSandbox(engine: engine, isolation: .clone)151            // one open transaction keeps the clone's own undo bookkeeping to first/last states152            return try engine.transaction("What-If") { try body(box) }153        case .inPlace:154            let box = ModelSandbox(engine: live, isolation: .inPlace)155            let before = live.changeCount156            let outcome: Result<T, Error> = live.transaction("What-If") {157                let r = Result { try body(box) }158                box.resetAll()            // also covers the case of an enclosing transaction (nothing to undo then)159                return r160            }161            if live.changeCount != before { live.undo() }162            live.recalculate()163            return try outcome.get()164        }165    }166167    private func check(_ c: ModelCell) throws {168        guard c.isValid(in: engine.workbook) else { throw WhatIfError.invalidCell(c.label(in: engine.workbook)) }169    }170171    /// Current content of a cell as an input (formula, literal or blank).172    public func content(_ c: ModelCell) throws -> CellInput {173        try check(c)174        guard let cell = engine.workbook.sheets[c.sheet].cell(c.cell.row, c.cell.col) else { return .blank }175        if let f = cell.formula { return .formula(f.expr) }176        if cell.isSpill || cell.value.isBlank { return .blank }177        return .value(cell.value)178    }179180    /// True when the cell holds a formula.181    public func isFormula(_ c: ModelCell) throws -> Bool {182        if case .formula = try content(c) { return true }183        return false184    }185186    /// Replaces the content of a cell (remembering the original the first time).187    public func set(_ c: ModelCell, _ input: CellInput) throws {188        if originals[c] == nil {189            originals[c] = try content(c)190            order.append(c)191        }192        engine.set(sheet: c.sheet, row: c.cell.row, col: c.cell.col, input)193    }194195    public func set(_ c: ModelCell, _ value: Value) throws { try set(c, value.isBlank ? .blank : .value(value)) }196    public func set(_ c: ModelCell, number: Double) throws { try set(c, .value(.number(number))) }197198    /// Recalculates and returns the computed value of a cell.199    public func value(_ c: ModelCell) throws -> Value {200        try check(c)201        engine.recalculate()202        return engine.workbook.sheets[c.sheet].value(c.cell.row, c.cell.col)203    }204205    /// Recalculates and returns the numeric value of a cell; NaN when it is not a number206    /// (text, error, blank or boolean).207    public func number(_ c: ModelCell) throws -> Double { try value(c).numberValue ?? .nan }208209    /// Puts one edited cell back to its original content.210    public func reset(_ c: ModelCell) {211        guard let o = originals[c] else { return }212        engine.set(sheet: c.sheet, row: c.cell.row, col: c.cell.col, o)213    }214215    /// Puts every edited cell back to its original content (in reverse order of first edit).216    public func resetAll() { for c in order.reversed() { reset(c) } }217}218
Files main
Menu

Theme