Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Calc9// File : Packages/ORIXSymbolic/Tests/ORIXSymbolicTests/ReferenceTests.swift10// Description : Semantic comparison of the symbolic engine with sympy /11// mpmath reference values at sample points.12// Module : ORIXSymbolicTests13// Repository : https://git.spboucher.ai/orix-calc14// Created : 2026-11-2015// Last Modified : 2026-11-2016//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : Proprietary, all rights reserved (see license file)82// License File : LICENSE83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import Testing92import BigInt93import ORIXExpression94import ORIXNumerics95@testable import ORIXSymbolic9697@Suite struct ReferenceComparison {98 let ref = Reference.shared99100 @Test func derivativesMatchSympy() {101 #expect(ref.derivatives.count >= 60)102 for c in ref.derivatives {103 let r = Symbolic.differentiate(P(c.expr), variable: c.variable, order: c.order)104 guard let e = r.expression else { Issue.record("d/d\(c.variable) \(c.expr): \(r.kind) \(r.note)"); continue }105 #expect(r.kind == .symbolic || r.kind == .exact, "\(c.expr)")106 #expect(!r.explanation.steps.isEmpty, "\(c.expr) has no explanation")107 #expect(r.verification.checks.allSatisfy { $0.status == .passed }, "\(c.expr): \(r.verification.checks)")108 for s in c.samples {109 let v = value(e, s.point)110 #expect(close(v, s.value, 1e-9), "d^\(c.order)/d\(c.variable) \(c.expr) = \(pretty(e)) gives \(v) at \(s.point), sympy (\(c.sympy)) gives \(s.value)")111 }112 }113 }114115 @Test func antiderivativesMatchQuadrature() {116 #expect(ref.integrals.count >= 60)117 for c in ref.integrals {118 let r = Symbolic.integrate(P(c.expr), variable: c.variable)119 guard let F = r.expression else { Issue.record("∫ \(c.expr): \(r.kind) \(r.note)"); continue }120 #expect(r.kind == .symbolic, "\(c.expr)")121 #expect(r.hasConstantOfIntegration && r.text.hasSuffix("+ C"))122 // the engine's own verification by differentiation ran and passed123 #expect(r.verification.checks.contains { $0.name == "Differentiate the antiderivative" && $0.status == .passed }, "\(c.expr)")124 // independent check: differentiate the result here and compare with the integrand125 let d = Symbolic.differentiate(F, variable: c.variable)126 var point = c.parameters127 point[c.variable] = c.base128 let base = value(F, point)129 for s in c.samples {130 point[c.variable] = s.x131 #expect(close(value(F, point) - base, s.value, 1e-8), "∫ \(c.expr) = \(pretty(F)): F(\(s.x)) − F(\(c.base)) = \(value(F, point) - base), quadrature \(s.value)")132 if let de = d.expression { #expect(close(value(de, point), value(P(c.expr), point), 1e-8), "d/dx of ∫ \(c.expr)") }133 }134 }135 }136137 @Test func definiteIntegralsMatchQuadrature() {138 for c in ref.definite {139 let r = Symbolic.integrate(P(c.expr), variable: "x", from: P(c.from), to: P(c.to))140 guard let v = r.doubleValue else { Issue.record("∫ \(c.expr) from \(c.from) to \(c.to): \(r.kind) \(r.note)"); continue }141 #expect(r.kind == .exact || r.kind == .numerical)142 #expect(close(v, c.value, r.kind == .exact ? 1e-10 : 1e-8), "∫ \(c.expr) [\(c.from), \(c.to)] = \(v) (\(r.kind)), reference \(c.value)")143 if r.kind == .numerical { #expect(r.errorEstimate != nil && r.expression == nil) }144 }145 }146147 @Test func simplificationPreservesValuesAndIsIdempotent() {148 #expect(ref.simplify.count >= 100)149 for c in ref.simplify {150 let r = Symbolic.simplify(P(c.expr))151 guard let e = r.expression else { Issue.record("simplify \(c.expr): \(r.kind) \(r.note)"); continue }152 let again = Symbolic.simplify(e)153 #expect(again.expression == e, "simplify is not idempotent on \(c.expr): \(pretty(e)) → \(pretty(again.expression))")154 for s in c.samples {155 let v = value(e, s.point)156 #expect(close(v, s.value, 1e-9), "simplify(\(c.expr)) = \(pretty(e)) gives \(v) at \(s.point), sympy gives \(s.value)")157 }158 }159 }160161 @Test func limitsMatchSympy() {162 for c in ref.limits {163 let direction: LimitDirection = c.direction == "left" ? .left : (c.direction == "right" ? .right : .both)164 let r = Symbolic.limit(P(c.expr), variable: "x", to: P(c.point), direction: direction)165 let label = "lim \(c.expr) as x → \(c.point) (\(c.direction)): got \(r.kind) \(r.text), sympy \(c.sympy)"166 switch c.kind {167 case "inf": #expect(r.behavior == .positiveInfinity, "\(label)")168 case "-inf": #expect(r.behavior == .negativeInfinity, "\(label)")169 case "dne": #expect(r.behavior == .doesNotExist, "\(label)")170 default:171 #expect(r.behavior == .finite, "\(label)")172 if let v = r.value, let expected = c.value {173 #expect(abs(v - expected) <= (r.kind == .exact ? 1e-10 : 1e-5) * max(1, abs(expected)), "\(label)")174 if r.kind == .exact, let e = r.expression { #expect(close(value(e), expected, 1e-10), "\(label)") }175 } else { Issue.record("\(label)") }176 }177 }178 }179180 @Test func taylorCoefficientsMatchSympy() {181 for c in ref.series {182 let r = Symbolic.taylor(P(c.expr), variable: "x", around: P(c.point), order: c.order)183 guard r.expression != nil else { Issue.record("taylor \(c.expr): \(r.note)"); continue }184 #expect(r.coefficients.count == c.order + 1)185 #expect(r.kind == .symbolic)186 for (k, expected) in c.coefficients.enumerated() {187 guard let expected, k < r.coefficients.count else { continue }188 #expect(close(value(r.coefficients[k]), expected, 1e-10), "taylor \(c.expr) at \(c.point): c\(k) = \(pretty(r.coefficients[k])), sympy \(c.sympy[k])")189 }190 #expect(r.remainder.hasPrefix("O("))191 }192 }193194 @Test func polynomialEquationsMatchSympy() {195 for c in ref.equations {196 let r = Symbolic.solve(P(c.equation), for: "x")197 #expect(r.kind == .exact || r.kind == .numerical, "\(c.equation): \(r.note)")198 let reals = r.realSolutions.map(\.real)199 for expected in c.real_roots { #expect(reals.contains { abs($0 - expected) <= 1e-6 * max(1, abs(expected)) }, "\(c.equation): root \(expected) missing from \(reals)") }200 for found in reals { #expect(c.real_roots.contains { abs($0 - found) <= 1e-6 * max(1, abs(found)) }, "\(c.equation): spurious root \(found)") }201 let total = r.solutions.reduce(0) { $0 + $1.multiplicity }202 #expect(total == c.degree, "\(c.equation): \(total) roots with multiplicity for degree \(c.degree)")203 let complexCount = r.solutions.filter { !$0.isReal }.reduce(0) { $0 + $1.multiplicity }204 #expect(complexCount == c.complex_count, "\(c.equation)")205 for s in r.solutions where s.isReal {206 #expect(s.residual <= 1e-6)207 if let e = s.expression { #expect(close(value(e), s.real, 1e-10)); #expect(s.kind == .exact) } else { #expect(s.kind == .numerical) }208 }209 }210 }211212 @Test func polynomialDivisionAndGcdMatchSympy() throws {213 for c in ref.polynomials.division {214 let a = try #require(Polynomial(P(c.a), variable: "x")), b = try #require(Polynomial(P(c.b), variable: "x"))215 let (q, r) = a.dividing(by: b)216 #expect(q.coefficients == c.quotient.map(rational), "\(c.a) ÷ \(c.b)")217 #expect(r.coefficients == c.remainder.map(rational), "\(c.a) mod \(c.b)")218 #expect(q * b + r == a)219 #expect(r.degree < b.degree)220 #expect(Polynomial.gcd(a, b).coefficients == c.gcd.map(rational), "gcd(\(c.a), \(c.b)) = \(Polynomial.gcd(a, b))")221 }222 }223224 @Test func factorisationMatchesSympy() throws {225 for c in ref.polynomials.factor {226 let p = try #require(Polynomial(P(c.expr), variable: "x"))227 let fz = p.factorized()228 #expect(fz.product == p, "\(c.expr)")229 #expect(fz.content == rational(c.content), "\(c.expr): content \(fz.content), sympy \(c.content)")230 let ours = Set(fz.factors.map { "\($0.polynomial.coefficients)^\($0.multiplicity)" })231 let theirs = Set(c.factors.map { "\($0.coefficients.map(rational))^\($0.multiplicity)" })232 #expect(ours == theirs, "\(c.expr): \(fz.factors.map { "\($0.polynomial)^\($0.multiplicity)" }), sympy \(c.sympy)")233 #expect(fz.isComplete, "\(c.expr): irreducibility not proven")234 // factor(expand(p)) round trip through the public API235 let r = Symbolic.factor(P(c.expr))236 let e = try #require(r.expression)237 let back = try #require(Symbolic.expand(e).expression)238 #expect(Polynomial(back, variable: "x") == p, "\(c.expr) → \(pretty(e))")239 #expect(r.verification.checks.contains { $0.name == "Multiply back" && $0.status == .passed })240 }241 }242243 @Test func sumsMatchSympy() {244 for c in ref.sums {245 let r = Symbolic.sum(P(c.term), index: "k", from: P(c.from), to: P(c.to))246 guard let e = r.expression else { Issue.record("Σ \(c.term): \(r.note)"); continue }247 #expect(r.kind == .symbolic)248 for s in c.samples {249 guard let expected = s.value else { continue }250 #expect(close(value(e, ["n": Double(s.n)]), expected, 1e-10), "Σ \(c.term) = \(pretty(e)) at n = \(s.n): sympy \(c.sympy)")251 }252 }253 }254}255