Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXGraph/Tests/ORIXGraphTests/Support.swift3// Description: Shared helpers of the graph tests: compiled functions and geometric checks against the true curve.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXExpression10import ORIXNumerics11@testable import ORIXGraph1213func fn(_ s: String, _ context: EvalContext = EvalContext()) -> RealFunction {14 let c = try! CompiledExpression(Parser.parse(s), variables: ["x"], context: context)15 return { c($0) }16}1718func fn2(_ s: String) -> RealFunction2 {19 let c = try! CompiledExpression(Parser.parse(s), variables: ["x", "y"])20 return { c($0, $1) }21}2223func plot(_ s: String, _ viewport: Viewport = .standard, _ options: SamplerOptions = .standard) -> ExplicitPlot {24 Sampler.sampleExplicit(fn(s), viewport: viewport, options: options)25}2627func close(_ a: Double, _ b: Double, _ tolerance: Double = 1e-9) -> Bool { abs(a - b) <= tolerance * max(1, abs(b)) }2829/// Screen distance from a point to a segment.30func distanceToSegment(_ p: Point2, _ a: Point2, _ b: Point2) -> Double {31 let dx = b.x - a.x, dy = b.y - a.y32 let l2 = dx * dx + dy * dy33 if l2 == 0 { return p.distance(to: a) }34 let t = min(max(((p.x - a.x) * dx + (p.y - a.y) * dy) / l2, 0), 1)35 return p.distance(to: Point2(a.x + t * dx, a.y + t * dy))36}3738/// The cardinal rule, checked numerically: between two consecutive vertices of every polyline the function must be defined39/// everywhere and must climb gradually. A segment that hides a jump or a pole fails, because one of the 64 sub-steps then40/// carries most of the rise (or the values leave the range of the two end points by far).41/// Returns the number of offending segments.42func hiddenBreaks(_ plot: ExplicitPlot, _ f: RealFunction, _ viewport: Viewport) -> Int {43 var bad = 044 let pixelY = viewport.unitsPerPixelY45 let clipLo = viewport.yMin - viewport.ySpan, clipHi = viewport.yMax + viewport.ySpan46 let holes = plot.discontinuities.filter { $0.kind == .removable }.map(\.x)47 for line in plot.polylines {48 for (p, q) in zip(line.points, line.points.dropFirst()) {49 guard q.x > p.x else { continue } // vertical extension towards an asymptote50 let rise = abs(q.y - p.y)51 var previous = f(p.x)52 var largestStep = 0.0, undefined = false, outside = false53 for k in 1...64 {54 let x = k == 64 ? q.x : p.x + (q.x - p.x) * Double(k) / 6455 let v = f(x)56 // a hole that the plot reports (removable discontinuity) is allowed inside a segment57 if v.isNaN, holes.contains(where: { abs($0 - x) <= 1e-12 * max(1, abs(x)) }) { continue }58 if v.isNaN { undefined = true; break }59 // only the part inside the clip range is represented by the segment60 let a = min(max(previous, clipLo), clipHi), b = min(max(v, clipLo), clipHi)61 largestStep = max(largestStep, abs(b - a))62 if b > max(p.y, q.y) + 3 * pixelY + rise || b < min(p.y, q.y) - 3 * pixelY - rise { outside = true }63 previous = v64 }65 if undefined || outside { bad += 1; continue }66 if rise > 3 * pixelY, largestStep > 0.5 * rise { bad += 1 }67 }68 }69 return bad70}7172/// No polyline may contain an abscissa of `locations` strictly between two of its consecutive vertices.73func spans(_ plot: ExplicitPlot, _ locations: [Double]) -> Bool {74 for line in plot.polylines {75 for (p, q) in zip(line.points, line.points.dropFirst()) {76 for c in locations where p.x < c && c < q.x { return true }77 }78 }79 return false80}8182/// Largest screen distance (pixels) between the true curve and the polylines, measured at 8 points inside every segment,83/// for the parts that are on screen.84func maxScreenError(_ plot: ExplicitPlot, _ f: RealFunction, _ viewport: Viewport) -> Double {85 var worst = 0.086 for line in plot.polylines {87 for (p, q) in zip(line.points, line.points.dropFirst()) where q.x > p.x {88 let a = viewport.toScreen(p), b = viewport.toScreen(q)89 for k in 1...8 {90 let x = p.x + (q.x - p.x) * Double(k) / 991 let y = f(x)92 guard y.isFinite, y >= viewport.yMin, y <= viewport.yMax else { continue }93 worst = max(worst, distanceToSegment(viewport.toScreen(Point2(x, y)), a, b))94 }95 }96 }97 return worst98}99100/// Fraction of 4000 abscissas where the function is visible on screen but no polyline (or band) covers that abscissa.101func uncovered(_ plot: ExplicitPlot, _ f: RealFunction, _ viewport: Viewport) -> Double {102 var intervals: [(Double, Double)] = plot.polylines.compactMap { l in l.points.first.flatMap { a in l.points.last.map { (a.x, $0.x) } } }103 for b in plot.bands { if let a = b.columns.first, let z = b.columns.last { intervals.append((a.x0, z.x1)) } }104 var missing = 0, total = 0105 for i in 0..<4000 {106 let x = viewport.xMin + viewport.xSpan * (Double(i) + 0.37) / 4000107 let y = f(x)108 guard y.isFinite, y > viewport.yMin, y < viewport.yMax else { continue }109 total += 1110 let slack = viewport.unitsPerPixelX * 1.01111 if !intervals.contains(where: { x >= $0.0 - slack && x <= $0.1 + slack }) { missing += 1 }112 }113 return total == 0 ? 0 : Double(missing) / Double(total)114}115116func bounded(_ plot: ExplicitPlot, _ viewport: Viewport) -> Bool {117 let lo = viewport.yMin - viewport.ySpan * 1.0001, hi = viewport.yMax + viewport.ySpan * 1.0001118 return plot.polylines.allSatisfy { $0.points.allSatisfy { $0.x.isFinite && $0.y >= lo && $0.y <= hi } }119}120121/// Smallest of `runs` wall-clock measurements, in milliseconds.122func bestMilliseconds(runs: Int = 7, _ body: () -> Void) -> Double {123 let clock = ContinuousClock()124 var best = Double.infinity125 for _ in 0..<runs {126 let d = clock.measure(body)127 best = min(best, Double(d.components.seconds) * 1e3 + Double(d.components.attoseconds) * 1e-15)128 }129 return best130}131132#if DEBUG133let buildConfiguration = "debug"134#else135let buildConfiguration = "release"136#endif137