Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/SheetAnalytics/Tests/WhatIfTests/ModelHarness.swift10// Module : WhatIfTests11// 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 Testing89import SheetCore90@testable import WhatIf9192/// Test workbook with three small models:93/// • "Loan": B1 annual rate, B2 months, B3 principal, B4 = level payment (annuity formula written with operators)94/// • "Profit": B1 price, B2 volume, B3 unit cost, B4 fixed cost, B5 revenue, B6 total cost, B7 profit95/// • "DCF": B1 discount rate (defined name Disc), B2:B4 cash flows, B5 = NPV, B6 = 2 × Profit!B7, D1:E2 spilled array96final class Model {97 let wb = Workbook(sheetNames: ["Loan", "Profit", "DCF"])98 let engine: CalcEngine99 let parser = InputParser(locale: Locale(identifier: "en_US"))100101 init() {102 engine = CalcEngine(workbook: wb)103 set("A1", "Rate"); set("B1", "0.06"); set("A2", "Months"); set("B2", "360"); set("A3", "Principal"); set("B3", "300000")104 set("B4", "=B3*(B1/12)/(1-(1+B1/12)^(-B2))")105 set("B1", "25", sheet: 1); set("B2", "1000", sheet: 1); set("B3", "15", sheet: 1); set("B4", "8000", sheet: 1)106 set("B5", "=B1*B2", sheet: 1); set("B6", "=B3*B2+B4", sheet: 1); set("B7", "=B5-B6", sheet: 1)107 engine.setDefinedName(DefinedName(name: "Disc", formula: "DCF!$B$1"))108 set("B1", "0.1", sheet: 2); set("B2", "-1000", sheet: 2); set("B3", "600", sheet: 2); set("B4", "600", sheet: 2)109 set("B5", "=B2+B3/(1+Disc)+B4/(1+Disc)^2", sheet: 2)110 set("B6", "=2*Profit!B7", sheet: 2)111 set("D1", "={1,2;3,4}", sheet: 2)112 engine.recalculate()113 }114115 func set(_ a1: String, _ text: String, sheet: Int = 0) {116 let ref = CellRef(a1: a1)!117 try! engine.setInput(sheet: sheet, row: ref.row, col: ref.col, text, parser: parser)118 }119 func num(_ a1: String, sheet: Int = 0) -> Double {120 engine.recalculate()121 let ref = CellRef(a1: a1)!122 return wb.sheets[sheet].value(ref.row, ref.col).numberValue ?? .nan123 }124 func cell(_ a1: String, sheet: Int = 0) -> ModelCell { ModelCell(sheet: sheet, a1: a1)! }125126 /// Leaves the engine with both an undo and a redo entry, like a document in the middle of editing.127 func seedHistory() {128 set("F1", "note", sheet: 0)129 set("F2", "7", sheet: 0)130 engine.undo()131 engine.recalculate()132 }133}134135/// Every cell with content on every sheet: computed value, formula text and spill flag.136func snapshot(_ engine: CalcEngine) -> [String: String] {137 engine.recalculate()138 var out = [String: String]()139 for (si, sheet) in engine.workbook.sheets.enumerated() {140 sheet.cells.forEachAll { r, c, cell in141 guard cell.hasContent else { return }142 let formula = cell.formula.map { "=" + $0.expr.formulaText() } ?? ""143 let bits = cell.computed.numberValue.map { String($0.bitPattern) } ?? cell.computed.description144 out["\(si):\(sheet.name)!\(CellRef(r, c).a1)"] = "\(bits)|\(formula)|\(cell.isSpill)"145 }146 }147 return out148}149150struct History: Equatable {151 var canUndo: Bool, canRedo: Bool152 var undoLabel: String?, redoLabel: String?153 var changeCount: Int154 init(_ e: CalcEngine) {155 canUndo = e.canUndo; canRedo = e.canRedo; undoLabel = e.undoLabel; redoLabel = e.redoLabel; changeCount = e.changeCount156 }157}158159/// Runs a tool and checks the isolation contract: values and formulas identical afterwards; in clone160/// mode the whole undo/redo state is untouched; in-place mode keeps the undo stack (documented side161/// effect: redo is replaced and changeCount grows by 2 when the tool edited something).162@discardableResult163func expectUntouched<T>(_ m: Model, _ isolation: WhatIfIsolation, edits: Bool = true, _ label: String,164 sourceLocation: SourceLocation = #_sourceLocation, _ tool: () throws -> T) rethrows -> T {165 let before = snapshot(m.engine), history = History(m.engine)166 defer {167 #expect(snapshot(m.engine) == before, "\(label) [\(isolation)]: workbook changed", sourceLocation: sourceLocation)168 let after = History(m.engine)169 switch isolation {170 case .clone:171 #expect(after == history, "\(label): undo/redo state changed in clone mode", sourceLocation: sourceLocation)172 case .inPlace:173 #expect(after.canUndo == history.canUndo && after.undoLabel == history.undoLabel, "\(label): undo stack changed", sourceLocation: sourceLocation)174 if edits {175 #expect(after.changeCount == history.changeCount + 2, "\(label): changeCount", sourceLocation: sourceLocation)176 #expect(after.redoLabel == "What-If", "\(label): redo side effect", sourceLocation: sourceLocation)177 } else {178 #expect(after == history, "\(label): nothing edited, nothing may change", sourceLocation: sourceLocation)179 }180 }181 }182 return try tool()183}184185func annuity(_ principal: Double, _ annualRate: Double, _ months: Double) -> Double {186 let r = annualRate / 12187 return principal * r / (1 - pow(1 + r, -months))188}189