Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXFeatureStatistics/Tests/ORIXFeatureStatisticsTests/TestSupport.swift3// Description: Shared helpers of the Statistics feature tests — isolated app models, tolerances, and the engine's reference JSON (scipy/numpy/statsmodels values).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import ORIXUI9@testable import ORIXFeatureStatistics1011@MainActor func makeApp() -> AppModel {12 AppModel(settings: AppSettings(defaults: UserDefaults(suiteName: "orix.statistics.tests.\(UUID().uuidString)")!), inMemory: true)13}1415func close(_ a: Double, _ b: Double, _ tol: Double = 1e-9) -> Bool {16 if a == b { return true }17 return abs(a - b) <= tol * max(1, abs(b))18}1920/// Reference values generated by ORIXStatistics/Reference/*.py with scipy, numpy and statsmodels (independent of the Swift engine).21enum Reference {22 static func cases(_ name: String, file: String = #filePath) throws -> [[String: Any]] {23 let url = URL(fileURLWithPath: file).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()24 .appendingPathComponent("ORIXStatistics/Reference/output/\(name).json")25 let object = try JSONSerialization.jsonObject(with: Data(contentsOf: url))26 return ((object as? [String: Any])?["cases"] as? [[String: Any]]) ?? []27 }28}2930extension Dictionary where Key == String, Value == Any {31 func double(_ key: String) -> Double { (self[key] as? NSNumber)?.doubleValue ?? .nan }32 func int(_ key: String) -> Int { (self[key] as? NSNumber)?.intValue ?? 0 }33 func bool(_ key: String) -> Bool { (self[key] as? NSNumber)?.boolValue ?? false }34 func string(_ key: String) -> String { self[key] as? String ?? "" }35 func doubles(_ key: String) -> [Double] { (self[key] as? [NSNumber])?.map(\.doubleValue) ?? [] }36 func matrix(_ key: String) -> [[Double]] { (self[key] as? [[NSNumber]])?.map { $0.map(\.doubleValue) } ?? [] }37 func has(_ key: String) -> Bool { self[key] != nil && !(self[key] is NSNull) }38}3940/// Composite Simpson integration, used to check shaded areas independently of the engine's CDF.41func simpson(_ f: (Double) -> Double, _ a: Double, _ b: Double, intervals: Int = 20_000) -> Double {42 guard b > a else { return 0 }43 let n = intervals % 2 == 0 ? intervals : intervals + 144 let h = (b - a) / Double(n)45 var sum = f(a) + f(b)46 for i in 1..<n { sum += f(a + Double(i) * h) * (i % 2 == 0 ? 2 : 4) }47 return sum * h / 348}49