SPB Git

Repository Public MIT

AnalysisTests.swift 18.1 KB 325 lines swift

1// ORIX Calc2// File: Packages/ORIXGraph/Tests/ORIXGraphTests/AnalysisTests.swift3// Description: Roots, extrema, intersections, tangents, integrals with shading, arc length, trace and tables against analytic values.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXExpression10import ORIXNumerics11@testable import ORIXGraph1213private let range = -10.0...10.01415@Suite struct RootsAndIntersections {16    @Test func cubicRoots() {17        let r = GraphAnalysis.roots(of: fn("x^3 - x"), in: range)18        #expect(r.map(\.x).count == 3)19        for (found, expected) in zip(r.map(\.x), [-1.0, 0, 1]) { #expect(abs(found - expected) < 1e-12) }20        #expect(r.allSatisfy { $0.kind == .root && $0.y == 0 && $0.residual < 1e-12 && $0.report.isVerified })21    }2223    @Test func irrationalAndTangentRoots() {24        let r = GraphAnalysis.roots(of: fn("x^2 - 2"), in: range).map(\.x)25        #expect(r.count == 2 && abs(r[0] + 2.0.squareRoot()) < 1e-13 && abs(r[1] - 2.0.squareRoot()) < 1e-13)26        let touch = GraphAnalysis.roots(of: fn("(x - 1)^2"), in: range)27        #expect(touch.count == 1 && abs(touch[0].x - 1) < 1e-6)28        #expect(touch[0].report.checks.contains { $0.name == "Tangent root" })29        #expect(GraphAnalysis.roots(of: fn("x^2 + 1"), in: range).isEmpty)30        let cosine = GraphAnalysis.roots(of: fn("cos(x)"), in: range).map(\.x)31        #expect(cosine.count == 6 && zip(cosine, [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]).allSatisfy { abs($0 - $1 * .pi) < 1e-12 })32    }3334    @Test func polesAreNeverRoots() {35        #expect(GraphAnalysis.roots(of: fn("1/x"), in: range).isEmpty)36        #expect(GraphAnalysis.roots(of: fn("1/(x - 0.3)"), in: range).isEmpty)37        let tangent = GraphAnalysis.roots(of: fn("tan(x)"), in: range).map(\.x)38        #expect(tangent.count == 7)39        for (found, k) in zip(tangent, -3...3) { #expect(abs(found - Double(k) * .pi) < 1e-9) }40        // a jump through zero is not a root either41        #expect(GraphAnalysis.roots(of: fn("floor(x) + 0.5"), in: range).isEmpty)42        #expect(GraphAnalysis.roots(of: fn("abs(x)/x"), in: range).isEmpty)43        // 1/x - 1 has a genuine root at 1 and a pole at 044        let mixed = GraphAnalysis.roots(of: fn("1/x - 1"), in: range).map(\.x)45        #expect(mixed.count == 1 && abs(mixed[0] - 1) < 1e-12)46    }4748    @Test func zeroOnAnIntervalIsReportedOnce() {49        let r = GraphAnalysis.roots(of: fn("floor(x)"), in: range)50        #expect(r.count == 1 && r[0].x == 0)51        #expect(r[0].report.warnings.contains { $0.name == "Zero on an interval" })52    }5354    @Test func sineMeetsCosine() {55        let pts = GraphAnalysis.intersections(fn("sin(x)"), fn("cos(x)"), in: (-2 * .pi)...(2 * .pi))56        let expected = [-7, -3, 1, 5].map { Double($0) * .pi / 4 }57        #expect(pts.count == 4)58        for (p, e) in zip(pts, expected) {59            #expect(abs(p.x - e) < 1e-12)60            #expect(abs(p.y - sin(e)) < 1e-12)61            #expect(p.kind == .intersection && p.residual < 1e-12 && p.report.isVerified)62        }63    }6465    @Test func sharedPolesAreNotIntersections() {66        #expect(GraphAnalysis.intersections(fn("1/x"), fn("2/x"), in: range).isEmpty)67        #expect(GraphAnalysis.intersections(fn("tan(x)"), fn("tan(x) + 1"), in: range).isEmpty)68        // 1/x and x meet at ±1 and share nothing at the pole69        let pts = GraphAnalysis.intersections(fn("1/x"), fn("x"), in: range).map(\.x)70        #expect(pts.count == 2 && abs(pts[0] + 1) < 1e-12 && abs(pts[1] - 1) < 1e-12)71        // parabola and line72        let q = GraphAnalysis.intersections(fn("x^2"), fn("x + 2"), in: range)73        #expect(q.map(\.x).count == 2 && abs(q[0].x + 1) < 1e-12 && abs(q[1].x - 2) < 1e-12 && abs(q[1].y - 4) < 1e-11)74    }7576    @Test func yIntercept() {77        #expect(GraphAnalysis.yIntercept(of: fn("x^2 + 3"))?.y == 3)78        #expect(GraphAnalysis.yIntercept(of: fn("1/x")) == nil)79        #expect(GraphAnalysis.yIntercept(of: fn("ln(x)")) == nil)80    }81}8283@Suite struct Extrema {84    @Test func cubic() {85        let e = GraphAnalysis.extrema(of: fn("x^3 - 3x"), in: range)86        #expect(e.count == 2)87        #expect(e[0].kind == .maximum && abs(e[0].x + 1) < 1e-9 && abs(e[0].y - 2) < 1e-12)88        #expect(e[1].kind == .minimum && abs(e[1].x - 1) < 1e-9 && abs(e[1].y + 2) < 1e-12)89        #expect(e.allSatisfy { $0.report.isVerified && $0.residual < 1e-6 })90    }9192    @Test func sine() {93        let e = GraphAnalysis.extrema(of: fn("sin(x)"), in: range)94        #expect(e.count == 6)95        for (p, k) in zip(e, [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]) {96            #expect(abs(p.x - k * .pi) < 1e-9)97            #expect(abs(abs(p.y) - 1) < 1e-14)98        }99        #expect(e.map(\.kind) == [.minimum, .maximum, .minimum, .maximum, .minimum, .maximum])100    }101102    @Test func cornersAreReportedAsNonSmooth() {103        let e = GraphAnalysis.extrema(of: fn("abs(x - 1)"), in: range)104        #expect(e.count == 1 && e[0].kind == .minimum && abs(e[0].x - 1) < 1e-7 && abs(e[0].y) < 1e-7)105        let cusp = GraphAnalysis.extrema(of: fn("sqrt(abs(x))"), in: range)106        #expect(cusp.count == 1 && abs(cusp[0].x) < 1e-6)107    }108109    @Test func thingsThatAreNotExtrema() {110        #expect(GraphAnalysis.extrema(of: fn("x"), in: range).isEmpty)                 // end points111        #expect(GraphAnalysis.extrema(of: fn("exp(x)"), in: range).isEmpty)112        #expect(GraphAnalysis.extrema(of: fn("3 + 0x"), in: range).isEmpty)            // plateau113        #expect(GraphAnalysis.extrema(of: fn("floor(x)"), in: range).isEmpty)          // plateaus with jumps114        #expect(GraphAnalysis.extrema(of: fn("max(x^2, 1)"), in: range).isEmpty)       // flat bottom115        #expect(GraphAnalysis.extrema(of: fn("1/x^2"), in: range).isEmpty)             // pole116        #expect(GraphAnalysis.extrema(of: fn("1/x"), in: range).isEmpty)117        #expect(GraphAnalysis.extrema(of: fn("tan(x)"), in: range).isEmpty)118        #expect(GraphAnalysis.extrema(of: fn("frac(x)"), in: 0.5...9.5).isEmpty)       // saw-tooth: jumps, no attained extremum inside119        #expect(GraphAnalysis.extrema(of: fn("sqrt(x)"), in: range).isEmpty)           // boundary of the domain120    }121122    @Test func extremumBetweenSamples() {123        // symmetric about a point that falls exactly between two samples124        let e = GraphAnalysis.extrema(of: fn("(x - 0.005)^2"), in: range)125        #expect(e.count == 1 && abs(e[0].x - 0.005) < 1e-9)126    }127128    @Test func inflections() {129        let i = GraphAnalysis.inflections(of: fn("x^3 - 3x"), in: range)130        #expect(i.count == 1 && abs(i[0].x) < 1e-6)131        #expect(GraphAnalysis.inflections(of: fn("2x + 1"), in: range).isEmpty)        // rounding noise is not an inflection132        #expect(GraphAnalysis.inflections(of: fn("x^2"), in: range).isEmpty)133        let s = GraphAnalysis.inflections(of: fn("sin(x)"), in: -4.0...4.0).map(\.x)134        #expect(s.count == 3 && abs(s[0] + .pi) < 1e-6 && abs(s[1]) < 1e-6 && abs(s[2] - .pi) < 1e-6)135    }136}137138@Suite struct Derivatives {139    @Test func tangentOfParabola() throws {140        let t = try GraphAnalysis.tangent(of: fn("x^2"), at: 1)141        #expect(abs(t.slope - 2) < 1e-11 && abs(t.intercept + 1) < 1e-11 && t.y0 == 1 && t.x0 == 1)142        #expect(t.slopeError < 1e-9 && t.report.isVerified)143        #expect(abs(t.y(at: 3) - 5) < 1e-10)144        let (a, b) = t.segment(in: .standard)145        #expect(a.x == -10 && b.x == 10 && abs(a.y + 21) < 1e-9 && abs(b.y - 19) < 1e-9)146    }147148    @Test func tangentsOfOtherFunctions() throws {149        let s = try GraphAnalysis.tangent(of: fn("sin(x)"), at: 0)150        #expect(abs(s.slope - 1) < 1e-11 && abs(s.intercept) < 1e-12)151        let e = try GraphAnalysis.tangent(of: fn("exp(x)"), at: 2, scale: 20)152        #expect(abs(e.slope - exp(2)) < 1e-9)153        // far from the origin, with a sensible scale154        let far = try GraphAnalysis.tangent(of: fn("sin(x)"), at: 1e9 + 2, scale: 10)155        #expect(abs(far.slope - cos(1e9 + 2)) < 1e-6)156        // next to the boundary of the domain the stencil shrinks instead of failing157        let root = try GraphAnalysis.tangent(of: fn("sqrt(x)"), at: 0.01, scale: 20)158        #expect(abs(root.slope - 5) < 1e-6)159    }160161    @Test func tangentRefusesWhereThereIsNone() {162        #expect(throws: GraphError.self) { try GraphAnalysis.tangent(of: fn("abs(x)"), at: 0) }163        #expect(throws: GraphError.self) { try GraphAnalysis.tangent(of: fn("1/x"), at: 0) }164        #expect(throws: GraphError.self) { try GraphAnalysis.tangent(of: fn("sqrt(x)"), at: -1) }165        #expect(throws: GraphError.self) { try GraphAnalysis.tangent(of: fn("floor(x)"), at: 2) }166        #expect(throws: Never.self) { try GraphAnalysis.tangent(of: fn("abs(x)"), at: 0.5) }167    }168169    @Test func derivativeCurveCanBeSampled() {170        let d = GraphAnalysis.derivativeFunction(of: fn("sin(x)"), scale: 20)171        for x in stride(from: -9.0, through: 9, by: 0.37) { #expect(abs(d(x) - cos(x)) < 1e-9) }172        let p = Sampler.sampleExplicit(d, viewport: .standard)173        #expect(p.polylines.count == 1 && p.discontinuities.isEmpty)174        #expect(maxScreenError(p, { cos($0) }, .standard) < 0.5)175        // derivative of a function with a pole has the pole too, and is not bridged176        let r = GraphAnalysis.derivativeFunction(of: fn("1/x"), scale: 20)177        let q = Sampler.sampleExplicit(r, viewport: .standard)178        #expect(q.polylines.count == 2 && q.poles.count == 1 && abs(q.poles[0]) < 1e-3)179        #expect(abs(r(2) + 0.25) < 1e-9)180        // undefined where the function is undefined; one-sided at the edge of the domain181        let s = GraphAnalysis.derivativeFunction(of: fn("sqrt(x)"), scale: 20)182        #expect(s(-1).isNaN && abs(s(4) - 0.25) < 1e-9)183        #expect(abs(GraphAnalysis.derivativeFunction(of: fn("sin(x)"), scale: 10)(1e9 + 3) - cos(1e9 + 3)) < 1e-8)184        #expect(abs(GraphAnalysis.derivative(of: fn("x^3"), at: 2).value - 12) < 1e-9)185    }186}187188@Suite struct Integrals {189    @Test func sineOverHalfAPeriod() throws {190        let r = try GraphAnalysis.integral(of: fn("sin(x)"), from: 0, to: .pi)191        #expect(abs(r.value - 2) < 1e-12 && r.errorEstimate < 1e-9 && r.report.isVerified)192        #expect(r.regions.count == 1 && r.regions[0].sign == 1 && abs(r.regions[0].area - 2) < 1e-12)193        let polygon = r.regions[0].polygon194        #expect(polygon.first == Point2(0, 0) && polygon.last!.y == 0 && abs(polygon.last!.x - .pi) < 1e-12)195        #expect(polygon.dropFirst().dropLast().allSatisfy { abs($0.y - sin($0.x)) < 1e-12 })196        // the polygon itself has (almost) the area of the integral197        var shoelace = 0.0198        for i in 0..<polygon.count { let a = polygon[i], b = polygon[(i + 1) % polygon.count]; shoelace += a.x * b.y - b.x * a.y }199        #expect(abs(abs(shoelace) / 2 - 2) < 1e-4)200    }201202    @Test func signedRegionsAreSplitAtTheRoots() throws {203        let r = try GraphAnalysis.integral(of: fn("sin(x)"), from: 0, to: 2 * .pi, viewport: Viewport(xMin: -1, xMax: 7, yMin: -2, yMax: 2))204        #expect(abs(r.value) < 1e-12 && abs(r.totalArea - 4) < 1e-11)205        #expect(r.regions.map(\.sign) == [1, -1])206        #expect(abs(r.regions[0].x1 - .pi) < 1e-12 && abs(r.regions[1].x0 - .pi) < 1e-12)207        #expect(r.regions[1].polygon.allSatisfy { $0.y <= 1e-12 })208        let cubic = try GraphAnalysis.integral(of: fn("x^3 - x"), from: -1, to: 1)209        #expect(abs(cubic.value) < 1e-13 && cubic.regions.map(\.sign) == [1, -1] && abs(cubic.regions[0].area - 0.25) < 1e-13)210    }211212    @Test func orientationAndStandardValues() throws {213        #expect(abs(try GraphAnalysis.integral(of: fn("x^2"), from: 1, to: 0).value + 1.0 / 3) < 1e-14)214        #expect(try GraphAnalysis.integral(of: fn("x^2"), from: 1, to: 1).value == 0)215        #expect(abs(try GraphAnalysis.integral(of: fn("exp(-x^2)"), from: -8, to: 8).value - Double.pi.squareRoot()) < 1e-12)216        #expect(abs(try GraphAnalysis.integral(of: fn("1/x"), from: 1, to: M_E).value - 1) < 1e-13)217        // a hole in the middle does not disturb the quadrature218        #expect(abs(try GraphAnalysis.integral(of: fn("sin(x)/x"), from: -1, to: 1).value - 1.8921661407343662) < 1e-12)219        // jumps are integrable: the integral is split there220        let steps = try GraphAnalysis.integral(of: fn("floor(x)"), from: 0, to: 3)221        #expect(abs(steps.value - 3) < 1e-12)222        #expect(steps.report.checks.contains { $0.name == "Jump discontinuities" })223        #expect(abs(try GraphAnalysis.integral(of: fn("abs(x)/x"), from: -1, to: 2).value - 1) < 1e-12)224    }225226    @Test func refusesAcrossAPole() {227        func refused(_ expression: String, _ a: Double, _ b: Double) -> String? {228            do { _ = try GraphAnalysis.integral(of: fn(expression), from: a, to: b); return nil }229            catch let e as GraphError { if case .refused(let m) = e { return m }; return nil }230            catch { return nil }231        }232        #expect(refused("1/x", -1, 1)?.contains("pole") == true)233        #expect(refused("1/x", -1, 2.5)?.contains("pole") == true)234        #expect(refused("1/(x - 0.3)^2", -1, 1)?.contains("pole") == true)          // even order: no sign change to betray it235        #expect(refused("1/(x - 1/3)^2", -1, 1)?.contains("pole") == true)236        #expect(refused("tan(x)", 0, 2)?.contains("pole") == true)237        #expect(refused("1/sin(x)", 1, 4)?.contains("pole") == true)238        #expect(refused("sqrt(x)", -1, 1)?.contains("undefined") == true)239        #expect(refused("1/x", 0, 1) != nil)                                        // divergent improper integral240        #expect(refused("1/x^2", 0, 1) != nil)241        #expect(refused("tan(x)", 0, 1.5) == nil)                                   // no pole inside: fine242    }243244    @Test func convergentEndPointSingularities() throws {245        let r = try GraphAnalysis.integral(of: fn("ln(x)"), from: 0, to: 1)246        #expect(abs(r.value + 1) < 1e-9)247        #expect(r.report.status == .warning)                                        // flagged as improper, not silently "verified"248        #expect(abs(try GraphAnalysis.integral(of: fn("1/sqrt(x)"), from: 0, to: 4).value - 4) < 1e-7)249    }250251    @Test func areaBetweenLineAndParabola() throws {252        let r = try GraphAnalysis.areaBetween(fn("x"), fn("x^2"), from: 0, to: 1)253        #expect(abs(r.value - 1.0 / 6) < 1e-14 && abs(r.totalArea - 1.0 / 6) < 1e-14)254        #expect(r.regions.count == 1 && r.regions[0].sign == 1)255        let polygon = r.regions[0].polygon256        #expect(polygon.allSatisfy { abs($0.y - $0.x) < 1e-12 || abs($0.y - $0.x * $0.x) < 1e-12 })257        var shoelace = 0.0258        for i in 0..<polygon.count { let a = polygon[i], b = polygon[(i + 1) % polygon.count]; shoelace += a.x * b.y - b.x * a.y }259        #expect(abs(abs(shoelace) / 2 - 1.0 / 6) < 1e-5)260    }261262    @Test func areaBetweenCurvesThatCross() throws {263        let r = try GraphAnalysis.areaBetween(fn("sin(x)"), fn("cos(x)"), from: 0, to: 2 * .pi)264        #expect(abs(r.value) < 1e-12)265        #expect(abs(r.totalArea - 4 * 2.0.squareRoot()) < 1e-11)266        #expect(r.regions.map(\.sign) == [-1, 1, -1])267        #expect(throws: GraphError.self) { try GraphAnalysis.areaBetween(fn("1/x"), fn("x"), from: -1, to: 1) }268    }269270    @Test func arcLength() throws {271        #expect(abs(try GraphAnalysis.arcLength(of: fn("x"), from: 0, to: 1).estimate.value - 2.0.squareRoot()) < 1e-12)272        #expect(abs(try GraphAnalysis.arcLength(of: fn("sqrt(1 - x^2)"), from: -0.5, to: 0.5).estimate.value - .pi / 3) < 1e-9)273        // y = x^(3/2) from 0 to 4: (8/27)(10^(3/2) − 1)274        #expect(abs(try GraphAnalysis.arcLength(of: fn("x^1.5"), from: 0, to: 4).estimate.value - 8.0 / 27 * (pow(10, 1.5) - 1)) < 1e-7)275        #expect(throws: GraphError.self) { try GraphAnalysis.arcLength(of: fn("1/x"), from: -1, to: 1) }276        #expect(throws: GraphError.self) { try GraphAnalysis.arcLength(of: fn("floor(x)"), from: 0, to: 3) }277    }278279    @Test func discontinuityScan() {280        let d = GraphAnalysis.discontinuities(of: fn("tan(x)"), in: 0...5)281        #expect(d.map(\.kind) == [.pole, .pole] && abs(d[0].x - .pi / 2) < 1e-12 && abs(d[1].x - 1.5 * .pi) < 1e-12)282        #expect(GraphAnalysis.discontinuities(of: fn("x^2"), in: -5...5).isEmpty)283    }284}285286@Suite struct TraceAndTable {287    @Test func traceFollowsTheCurve() {288        let f = fn("x^2 - 4")289        let t = GraphAnalysis.trace(f, screenX: 600, viewport: .standard)290        #expect(t.x == 5 && t.y == 21 && t.snapped == nil)291        #expect(t.screen == Viewport.standard.toScreen(Point2(5, 21)))292        let undefined = GraphAnalysis.trace(fn("sqrt(x)"), screenX: 100, viewport: .standard)293        #expect(undefined.y == nil && undefined.screen == nil && undefined.x == -7.5)294        let pole = GraphAnalysis.trace(fn("1/x"), screenX: 400, viewport: .standard)295        #expect(pole.y == nil)296    }297298    @Test func traceSnapsToPointsOfInterest() {299        let f = fn("x^2 - 4")300        let poi = GraphAnalysis.pointsOfInterest(of: f, viewport: .standard)301        #expect(poi.map(\.kind) == [.root, .minimum, .yIntercept, .root] || poi.map(\.kind) == [.root, .yIntercept, .minimum, .root])302        // the root at x = 2 is at screen x = 480; 6 pixels away snaps, 20 pixels away does not303        let near = GraphAnalysis.trace(f, screenX: 486, viewport: .standard, pointsOfInterest: poi, snapRadius: 12)304        #expect(near.snapped?.kind == .root && abs(near.x - 2) < 1e-12 && near.y == 0)305        let far = GraphAnalysis.trace(f, screenX: 500, viewport: .standard, pointsOfInterest: poi, snapRadius: 12)306        #expect(far.snapped == nil && far.x == 2.5)307        // closest target wins308        let vertex = GraphAnalysis.trace(f, screenX: 401, viewport: .standard, pointsOfInterest: poi)309        #expect(vertex.snapped != nil && abs(vertex.x) < 1e-6 && abs(vertex.y! + 4) < 1e-9)310    }311312    @Test func tableOfValues() {313        let rows = GraphAnalysis.table(of: fn("1/x"), start: -1, step: 0.5, count: 5)314        #expect(rows.map(\.x) == [-1, -0.5, 0, 0.5, 1])315        #expect(rows.map(\.y) == [-1, -2, nil, 2, 1])316        #expect(rows[2].text == "undefined")317        // no accumulated rounding in x318        let fine = GraphAnalysis.table(of: fn("x"), start: 0, step: 0.1, count: 1001)319        #expect(fine.last!.x == 100 && fine[3].x == 0.1 * 3)320        #expect(GraphAnalysis.table(of: fn("x"), start: 0, step: 1, count: 0).isEmpty)321        let csv = CSVExport.table(rows)322        #expect(csv == "x,y\n-1.0,-1.0\n-0.5,-2.0\n0.0,undefined\n0.5,2.0\n1.0,1.0\n")323    }324}325
Files main
Menu

Theme