SPB Git

Repository Public MIT

ViewportAndParserTests.swift 23.3 KB 362 lines swift

1// ORIX Calc2// File: Packages/ORIXGraph/Tests/ORIXGraphTests/ViewportAndParserTests.swift3// Description: Viewport mapping, pan / zoom, auto-fit, tick generation over every scale, plot-text parsing, data fit and CSV export.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXExpression10@testable import ORIXGraph1112@Suite struct ViewportTests {13    @Test func mappingRoundTrip() {14        let v = Viewport.standard15        #expect(v.toScreen(Point2(-10, 7.5)) == Point2(0, 0) && v.toScreen(Point2(10, -7.5)) == Point2(800, 600))16        #expect(v.toScreen(.zero) == Point2(400, 300))17        #expect(v.toFunction(Point2(200, 150)) == Point2(-5, 3.75))18        #expect(v.unitsPerPixelX == 0.025 && v.unitsPerPixelY == 0.025)19        // large offset: one pixel is 1.25e-3 units at x ≈ 1e9 and survives the round trip20        let far = Viewport(xMin: 1e9, xMax: 1e9 + 1, yMin: -1, yMax: 1)21        for sx in [0.0, 1, 399.5, 800] { #expect(abs(far.screenX(far.functionX(sx)) - sx) < 1e-3) }22        #expect(far.screenX(1e9 + 0.5) == 400)23        let tiny = Viewport(xMin: -1e-12, xMax: 1e-12, yMin: -1e-12, yMax: 1e-12)24        #expect(abs(tiny.screenX(5e-13) - 600) < 1e-9)25    }2627    @Test func sanitising() {28        let inverted = Viewport(xMin: 5, xMax: -5, yMin: 2, yMax: -2)29        #expect(inverted.xMin == -5 && inverted.xMax == 5 && inverted.yMin == -2 && inverted.yMax == 2)30        let degenerate = Viewport(xMin: 3, xMax: 3, yMin: 0, yMax: 0)31        #expect(degenerate.xMin < 3 && degenerate.xMax > 3 && degenerate.yMin == -1 && degenerate.yMax == 1)32        let broken = Viewport(xMin: .nan, xMax: 1, yMin: -.infinity, yMax: .infinity, width: 0, height: -.infinity)33        #expect(broken.xMin == -10 && broken.xMax == 10 && broken.yMin == -Viewport.limit && broken.yMax == Viewport.limit)34        #expect(broken.width == 1 && broken.height == 600 && broken.xSpan.isFinite && broken.ySpan.isFinite)35        let atLimit = Viewport(xMin: 1e15, xMax: 1e15 + 0.25, yMin: 0, yMax: 1)36        #expect(atLimit.xSpan == 512)                    // 4096 distinct doubles37    }3839    @Test func panAndZoom() {40        let v = Viewport.standard41        let p = v.panned(byScreen: 80, -60)                  // drag right and up42        #expect(p.xMin == -12 && p.xMax == 8 && p.yMin == -9 && p.yMax == 6)43        #expect(v.panned(byUnits: 1, 2).center == Point2(1, 2))44        // zoom about a point: that point keeps its screen position45        let anchor = Point2(3, -2)46        let z = v.zoomed(by: 4, aboutFunctionPoint: anchor)47        #expect(abs(z.xSpan - 5) < 1e-12 && abs(z.ySpan - 3.75) < 1e-12)48        #expect(z.toScreen(anchor).distance(to: v.toScreen(anchor)) < 1e-9)49        let s = Point2(123, 456)50        let zs = v.zoomed(by: 0.5, aboutScreenPoint: s)51        #expect(zs.toFunction(s).distance(to: v.toFunction(s)) < 1e-12 && abs(zs.xSpan - 40) < 1e-12)52        #expect(v.zoomed(by: 0) == v && v.zoomed(by: .nan) == v)53        #expect(v.zoomed(by: 2, aboutFunctionPoint: .zero, xOnly: true).ySpan == 15)54        // zooming in a million times a million times still gives a valid window55        var deep = v56        for _ in 0..<40 { deep = deep.zoomed(by: 1e6, aboutFunctionPoint: Point2(1.0 / 3, 0)) }57        #expect(deep.xSpan > 0 && deep.xSpan.isFinite && deep.xMin < deep.xMax)58        var wide = v59        for _ in 0..<80 { wide = wide.zoomed(by: 1e-6) }60        #expect(wide.xSpan.isFinite && wide.xMax <= Viewport.limit)61    }6263    @Test func equalAspect() {64        let v = Viewport(xMin: -10, xMax: 10, yMin: -1, yMax: 1, width: 800, height: 400).equalAspect()65        #expect(abs(v.unitsPerPixelX - v.unitsPerPixelY) < 1e-15)66        #expect(v.xMin == -10 && v.xMax == 10 && abs(v.yMin + 5) < 1e-12 && abs(v.yMax - 5) < 1e-12)67        let w = Viewport(xMin: -1, xMax: 1, yMin: -10, yMax: 10, width: 800, height: 400).equalAspect()68        #expect(abs(w.unitsPerPixelX - w.unitsPerPixelY) < 1e-15 && w.yMin == -10 && abs(w.xMax - 20) < 1e-12)69    }7071    @Test func autoFitIsRobustToPoles() throws {72        let v = Viewport.standard73        let sine = v.autoFitY([fn("sin(x)")])74        #expect(sine.yMax > 1 && sine.yMax < 1.3 && sine.yMin < -1 && sine.yMin > -1.3 && sine.xMin == -10 && sine.xMax == 10)75        let parabola = v.autoFitY([fn("x^2")])76        #expect(parabola.yMax > 99 && parabola.yMax < 120 && parabola.yMin < 0 && parabola.yMin > -12)77        // poles do not blow the scale up78        for expression in ["1/x", "tan(x)", "1/(x-1)^2", "1/sin(x)", "x + 1/(x - 3)"] {79            let fit = v.autoFitY([fn(expression)])80            #expect(fit.ySpan < 60 && fit.ySpan > 0.5, "\(expression): \(fit.yMin) … \(fit.yMax)")81        }82        // constant, nowhere defined83        let flat = v.autoFitY([fn("3 + 0x")])84        #expect(flat.yMin < 3 && flat.yMax > 3 && flat.ySpan <= 2.0001)85        #expect(v.autoFitY([fn("sqrt(-1 - x^2)")]) == v)86        // several items through the engine87        let items = [try PlotParser.parse("sin(x)"), try PlotParser.parse("3cos(x)"), try PlotParser.parse("1/x")]88        let both = GraphEngine.autoFit(items, viewport: v)89        #expect(both.yMax > 3 && both.yMax < 8 && both.yMin < -3)90        // only a parametric curve: both ranges are fitted91        let circle = GraphEngine.autoFit([try PlotParser.parse("(5 + 2cos(t), 2 sin(t))")], viewport: v)92        #expect(circle.xMin < 3 && circle.xMin > 2 && circle.xMax > 7 && circle.xMax < 8 && circle.yMax > 2 && circle.yMax < 3)93        let data = GraphEngine.autoFit([.scatter([Point2(1, 10), Point2(2, 20), Point2(4, 15)])], viewport: v)94        #expect(data.xMin < 1 && data.xMax > 4 && data.yMin < 10 && data.yMax > 20 && data.xSpan < 4)95    }96}9798@Suite struct Ticks {99    @Test func oneTwoFive() {100        let t = AxisTicks.make(min: -10, max: 10, pixelLength: 800)101        #expect(t.major.map(\.label) == ["-10", "-8", "-6", "-4", "-2", "0", "2", "4", "6", "8", "10"] && t.step == 2)102        #expect(t.minor.count == 30 && t.minor.contains(0.5) && !t.minor.contains(2))103        let unit: [String] = AxisTicks.make(min: 0, max: 1, pixelLength: 800).major.map(\.label)104        #expect(unit == ["0", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0"])105        #expect(AxisTicks.make(min: 0, max: 7, pixelLength: 600).step == 1)106        #expect(AxisTicks.make(min: 0, max: 30, pixelLength: 600).step == 5)107        #expect(AxisTicks.make(min: 0, max: 0.03, pixelLength: 600).major.map(\.label) == ["0", "0.005", "0.010", "0.015", "0.020", "0.025", "0.030"])108        // values are exact multiples of the step, no 0.30000000000000004109        #expect(AxisTicks.make(min: 0, max: 1, pixelLength: 800).major.map(\.value) == [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])110    }111112    @Test func labelsAtExtremeScales() {113        #expect(AxisTicks.make(min: 1e9, max: 1e9 + 1, pixelLength: 800).major.map(\.label).prefix(3) == ["1000000000.0", "1000000000.1", "1000000000.2"])114        #expect(AxisTicks.make(min: -1e-9, max: 1e-9, pixelLength: 800).major.map(\.label).prefix(3) == ["-1e-9", "-8e-10", "-6e-10"])115        #expect(AxisTicks.make(min: 0, max: 3e12, pixelLength: 600).major.map(\.label) == ["0", "5e11", "1e12", "1.5e12", "2e12", "2.5e12", "3e12"])116        #expect(AxisTicks.label(-0.0, decimals: 2, step: 0.01) == "0")117        #expect(AxisTicks.label(1234.5, decimals: 1, step: 0.5) == "1234.5")118    }119120    @Test func piMultiples() {121        let t = AxisTicks.make(min: -7, max: 7, pixelLength: 800, mode: .piMultiples)122        #expect(t.mode == .piMultiples)123        #expect(t.major.map(\.label) == ["−2π", "−3π/2", "−π", "−π/2", "0", "π/2", "π", "3π/2", "2π"])124        #expect(zip(t.major.map(\.value), [-2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2]).allSatisfy { abs($0 - $1 * .pi) < 1e-12 })125        #expect(AxisTicks.piLabel(numerator: 3, denominator: 4) == "3π/4" && AxisTicks.piLabel(numerator: -2, denominator: 4) == "−π/2")126        #expect(AxisTicks.piLabel(numerator: 6, denominator: 3) == "2π" && AxisTicks.piLabel(numerator: 0, denominator: 5) == "0")127        let wide = AxisTicks.make(min: 0, max: 40, pixelLength: 800, mode: .piMultiples)128        #expect(wide.mode == .piMultiples && wide.major.count <= 25 && wide.major.last!.label.hasSuffix("π"))129        // out of the useful range the decimal ticks take over130        #expect(AxisTicks.make(min: 0, max: 1e6, pixelLength: 800, mode: .piMultiples).mode == .decimal)131        #expect(AxisTicks.make(min: 0, max: 1e-3, pixelLength: 800, mode: .piMultiples).mode == .decimal)132    }133134    @Test func neverTooManyAndAlwaysTerminates() {135        var checked = 0136        let centres: [Double] = [0, 1, -1, 3.7, 1e3, -1e6, 1e9, 1e15, 1e100, -1e200, 1e-5, 1e-200]137        for exponent in stride(from: -300, through: 300, by: 3) {138            for mantissa in [1.0, 2.3, 4.9, 7.77] {139                let span = mantissa * pow(10, Double(exponent))140                for centre in centres {141                    for pixels in [60.0, 300, 800, 4000] {142                        for mode in [AxisTicks.Mode.decimal, .piMultiples] {143                            let t = AxisTicks.make(min: centre - span / 2, max: centre + span / 2, pixelLength: pixels, mode: mode)144                            checked += 1145                            #expect(t.major.count <= AxisTicks.maximumMajorCount)146                            #expect(t.major.count >= 1)147                            #expect(t.minor.count <= 200)148                            let values = t.major.map(\.value)149                            if !(zip(values, values.dropFirst()).allSatisfy { $0 < $1 }) || !values.allSatisfy(\.isFinite) || t.major.contains(where: { $0.label.isEmpty }) {150                                Issue.record("bad ticks for span \(span) centre \(centre): \(t.major)")151                            }152                        }153                    }154                }155            }156        }157        #expect(checked > 70_000)158        // degenerate, inverted and non-finite input159        for (a, b) in [(0.0, 0.0), (5, 5), (-3, -3), (1e300, 1e300), (10, -10), (.nan, 1), (-.infinity, .infinity), (1e-320, 2e-320), (-1e308, 1e308), (0, 5e-324)] {160            for pixels in [0.0, -5, .nan, .infinity, 800] {161                let t = AxisTicks.make(min: a, max: b, pixelLength: pixels, targetSpacing: pixels)162                #expect(t.major.count >= 1 && t.major.count <= AxisTicks.maximumMajorCount && t.major.allSatisfy { $0.value.isFinite })163            }164        }165        let g = GridLines(viewport: .standard, xMode: .piMultiples)166        #expect(g.x.mode == .piMultiples && g.y.mode == .decimal && g.y.step == 2.5 || g.y.step == 2)167    }168169    @Test func ticksLieInsideTheRange() {170        for (a, b) in [(-10.0, 10.0), (0.13, 0.97), (1e9, 1e9 + 10), (-1e-9, 1e-9), (123.456, 123.457), (-5e20, 7e20)] {171            let t = AxisTicks.make(min: a, max: b, pixelLength: 800)172            #expect(t.major.count >= 3)173            #expect(t.major.allSatisfy { $0.value >= a - t.step * 1e-6 && $0.value <= b + t.step * 1e-6 })174            #expect(t.minor.allSatisfy { $0 >= a - t.step * 1e-6 && $0 <= b + t.step * 1e-6 })175            let gaps = zip(t.major, t.major.dropFirst()).map { $1.value - $0.value }176            #expect(gaps.allSatisfy { abs($0 - t.step) <= 1e-6 * t.step })177            #expect(Set(t.major.map(\.label)).count == t.major.count, "labels must distinguish the ticks: \(t.major.map(\.label))")178        }179    }180}181182@Suite struct ParserTests {183    private func kind(_ s: String, _ context: EvalContext = EvalContext()) throws -> String { try PlotParser.parse(s, context: context).kind.name }184185    @Test func classification() throws {186        #expect(try kind("sin(x)") == "explicit")187        #expect(try kind("y = x^2") == "explicit")188        #expect(try kind("x^2 = y") == "explicit")189        #expect(try kind("f(x) = x^2 + 1") == "explicit")190        #expect(try kind("g(u) = u^2") == "explicit")191        #expect(try kind("3") == "explicit")192        #expect(try kind("y = 3") == "explicit")193        #expect(try kind("x = y^2") == "explicitX")194        #expect(try kind("x = 3") == "explicitX")195        #expect(try kind("(cos(t), sin(t))") == "parametric")196        #expect(try kind("(cos(θ), sin(θ))") == "parametric")197        #expect(try kind("r = 1 - cos(θ)") == "polar")198        #expect(try kind("r = 1 - cos(theta)") == "polar")199        #expect(try kind("r = sin(2t)") == "polar")200        #expect(try kind("2 sin(3θ)") == "polar")201        #expect(try kind("x^2 + y^2 = 25") == "implicit")202        #expect(try kind("sin(x) = cos(y)") == "implicit")203        #expect(try kind("xy = 1") == "implicit")204        #expect(try kind("y = x + y^3") == "implicit")205        #expect(try kind("x^2 = 4") == "implicit")206        #expect(try kind("y < x^2") == "inequality")207        #expect(try kind("x^2 + y^2 <= 4") == "inequality")208        #expect(try kind("y >= 1 and x < 2") == "inequality")209        #expect(try kind("(1, 2)") == "points")210        #expect(try kind("(1, 2), (3, 4), (pi, sqrt(2))") == "points")211        #expect(try kind("z = x y") == "surface")212        #expect(try kind("x^2 - y^2") == "surface")213        #expect(try kind("h(x, y) = x + y") == "surface")214        #expect(try kind("a = 3") == "parameter")215        #expect(try kind("piecewise(x < 0, -x, x^2)") == "explicit")216        #expect(try kind("if(x > 0, 1, -1)") == "explicit")217        #expect(try kind("(x - 1)(x + 2)") == "explicit")              // parentheses, not a tuple218        #expect(try kind("|x| - 1") == "explicit")219    }220221    @Test func expressionsAreNormalised() throws {222        // f(u) = u² is plotted against x223        guard case .explicit(let e) = try PlotParser.parse("g(u) = u^2").kind else { Issue.record("not explicit"); return }224        #expect(e.variables == ["x"])225        let definition = try PlotParser.parse("f(x) = x^2 + 1")226        #expect(definition.definedFunction?.name == "f" && definition.definedFunction?.parameters == ["x"])227        guard case .polar(let p) = try PlotParser.parse("r = sin(2t) + theta").kind else { Issue.record("not polar"); return }228        #expect(p.variables == ["θ", "t"] || p.variables == ["θ"])229        guard case .polar(let q) = try PlotParser.parse("r = sin(2t)").kind else { Issue.record("not polar"); return }230        #expect(q.variables == ["θ"])231        guard case .surface(let s) = try PlotParser.parse("h(v, u) = u - v").kind else { Issue.record("not a surface"); return }232        let c = try CompiledExpression(s, variables: ["x", "y"])233        #expect(c(1, 5) == 4)                                             // first parameter → x, second → y234        guard case .points(let pts, let connected) = try PlotParser.parse("(1, 2), (3, 2+2)").kind else { Issue.record("not points"); return }235        #expect(pts == [Point2(1, 2), Point2(3, 4)] && !connected)236    }237238    @Test func parametersForSliders() throws {239        #expect(try PlotParser.parse("a*sin(b*x + c)").parameters == ["a", "b", "c"])240        #expect(try PlotParser.parse("y = m x + k").parameters == ["k", "m"])241        #expect(try PlotParser.parse("ax^2 + bx + c").parameters == ["a", "b", "c"])           // implicit products of single letters242        #expect(try PlotParser.parse("x^2/a^2 + y^2/b^2 = 1").parameters == ["a", "b"])243        #expect(try PlotParser.parse("(a cos(t), b sin(t))").parameters == ["a", "b"])244        #expect(try PlotParser.parse("r = a θ").parameters == ["a"])245        #expect(try PlotParser.parse("pi x + e").parameters.isEmpty)                            // constants are not parameters246        #expect(try PlotParser.parse("sin(x) + t").parameters.isEmpty)                          // x, y, t, θ never are247        #expect(try PlotParser.parse("sum(k x, k, 1, 3)").parameters.isEmpty)                   // bound variable248        // names known to the context are kept whole249        var context = EvalContext()250        context.variables["amp"] = Value(2.0)251        let item = try PlotParser.parse("amp sin(x)", context: context)252        #expect(item.parameters == ["amp"] && item.missingParameters(in: context).isEmpty)253        let g = try GraphEngine.geometry(for: item, viewport: .standard, context: context)254        #expect(g.polylines[0].points.allSatisfy { abs($0.y - 2 * sin($0.x)) < 1e-12 })255        // and with splitting off, an unknown multi-letter name is one parameter256        #expect(try PlotParser.parse("amp sin(x)", options: PlotParserOptions(splitUnknownIdentifiers: false)).parameters == ["amp"])257        // user functions from the context258        context.functions["sq"] = UserFunction(name: "sq", parameters: ["u"], body: try Parser.parse("u^2"))259        let h = try GraphEngine.geometry(for: PlotParser.parse("sq(x) - 1", context: context), viewport: .standard, context: context)260        #expect(h.polylines.allSatisfy { l in l.points.allSatisfy { $0.y >= 22.49 || abs($0.y - ($0.x * $0.x - 1)) < 1e-9 } })261    }262263    @Test func restrictions() throws {264        let p = try PlotParser.parse("(cos(t), sin(t)) for 0 <= t <= pi")265        #expect(p.parameterRange == 0...Double.pi)266        let g = try GraphEngine.geometry(for: p, viewport: Viewport(xMin: -2, xMax: 2, yMin: -2, yMax: 2))267        #expect(g.polylines.count == 1 && !g.polylines[0].isClosed && g.polylines[0].points.allSatisfy { $0.y >= -1e-12 })268        let q = try PlotParser.parse("r = θ {0 <= θ <= 4pi}")269        #expect(q.parameterRange == 0...(4 * Double.pi))270        let d = try PlotParser.parse("y = x^2 {-1 <= x <= 2}")271        #expect(d.domain == -1...2)272        let h = try GraphEngine.geometry(for: d, viewport: .standard)273        #expect(h.polylines.count == 1 && h.polylines[0].points.first!.x == -1 && h.polylines[0].points.last!.x == 2)274        #expect(throws: GraphError.self) { try PlotParser.parse("x^2 + y^2 = 1 for 0 <= t <= 1") }275        #expect(throws: GraphError.self) { try PlotParser.parse("(cos(t), sin(t)) for t > 0") }276    }277278    @Test func errors() {279        #expect(throws: CalcError.self) { try PlotParser.parse("") }280        #expect(throws: CalcError.self) { try PlotParser.parse("2 +* 3") }281        #expect(throws: CalcError.self) { try PlotParser.parse("y = ") }282        #expect(throws: GraphError.self) { try PlotParser.parse("(1, 2, 3)") }283        #expect(throws: GraphError.self) { try PlotParser.parse("y^2") }284        #expect(throws: GraphError.self) { try PlotParser.parse("[1, 2, 3]") }285        #expect(throws: GraphError.self) { try PlotParser.parse("k = 2x") }286        #expect(throws: GraphError.self) { try PlotParser.parse("x != y") }287        #expect(throws: GraphError.self) { try PlotParser.parse("(x, x^2)") }288        // unknown function: reported when compiling289        #expect(throws: CalcError.self) { try GraphEngine.geometry(for: PlotParser.parse("foo(x)", options: PlotParserOptions(splitUnknownIdentifiers: false)), viewport: .standard) }290    }291292    @Test func engineHandlesEveryKind() throws {293        let view = Viewport(xMin: -10, xMax: 10, yMin: -10, yMax: 10, width: 500, height: 500)294        let sideways = try GraphEngine.geometry(for: PlotParser.parse("x = y^2"), viewport: view)295        #expect(sideways.transposed && sideways.polylines.count == 1)296        #expect(sideways.polylines[0].points.allSatisfy { $0.x >= 29.99 || abs($0.x - $0.y * $0.y) < 1e-12 })     // the two ends are clip points297        let vertical = try GraphEngine.geometry(for: PlotParser.parse("x = 3"), viewport: view)298        #expect(vertical.polylines.count == 1 && vertical.polylines[0].points.allSatisfy { $0.x == 3 })299        let sidewaysPole = try GraphEngine.geometry(for: PlotParser.parse("x = 1/y"), viewport: view)300        #expect(sidewaysPole.polylines.count == 2 && sidewaysPole.discontinuities.map(\.kind) == [.pole])301        let hole = try GraphEngine.geometry(for: PlotParser.parse("sin(x)/x"), viewport: view)302        #expect(hole.holes.count == 1 && abs(hole.holes[0].y - 1) < 1e-9)303        var item = try PlotParser.parse("x^2")304        item.isVisible = false305        #expect(try GraphEngine.geometry(for: item, viewport: view).polylines.isEmpty)306        let points = try GraphEngine.geometry(for: PlotParser.parse("(1, 2), (3, 4)"), viewport: view)307        #expect(points.markers == [Point2(1, 2), Point2(3, 4)] && points.polylines.isEmpty)308        let series = try GraphEngine.geometry(for: .series([Point2(0, 0), Point2(1, 1), Point2(.nan, 0), Point2(2, 2), Point2(3, 1)]), viewport: view)309        #expect(series.polylines.count == 2 && series.markers.count == 4)310        #expect(try GraphEngine.geometry(for: PlotParser.parse("z = x y"), viewport: view).notices.count == 1)311        #expect(try GraphEngine.geometry(for: PlotParser.parse("a = 3"), viewport: view).polylines.isEmpty)312        #expect(sideways.itemID != vertical.itemID)313    }314315    @Test func concurrentGeometries() async throws {316        let items = try ["sin(x)", "1/x", "x^2 + y^2 = 25", "(cos(t), sin(t))", "q*x"].map { try PlotParser.parse($0) }317        let results = try await GraphEngine.geometries(for: items, viewport: .standard)318        #expect(results.count == 5)319        #expect((try? results[items[0].id]?.get())?.polylines.count == 1)320        #expect((try? results[items[1].id]?.get())?.polylines.count == 2)321        #expect((try? results[items[2].id]?.get())?.polylines.first?.isClosed == true)322        if case .failure(let e)? = results[items[4].id] { #expect(e == .unknownVariable("q")) } else { Issue.record("q*x should fail to compile") }323    }324}325326@Suite struct DataAndExport {327    @Test func boundsAndFit() {328        let pts = [Point2(1, 3), Point2(2, 5), Point2(3, 7), Point2(.nan, 1), Point2(4, 9)]329        let b = DataSeries.bounds(pts)!330        #expect(b.xMin == 1 && b.xMax == 4 && b.yMin == 3 && b.yMax == 9)331        let fit = DataSeries.linearFit(pts)!332        #expect(abs(fit.slope - 2) < 1e-14 && abs(fit.intercept - 1) < 1e-14 && abs(fit.rSquared - 1) < 1e-14 && fit.count == 4)333        #expect(abs(fit.y(at: 10) - 21) < 1e-12)334        // textbook example: (1,1), (2,2), (3,2): slope 1/2, intercept 2/3, r² = 3/4335        let f = DataSeries.linearFit([Point2(1, 1), Point2(2, 2), Point2(3, 2)])!336        #expect(abs(f.slope - 0.5) < 1e-14 && abs(f.intercept - 2.0 / 3) < 1e-14 && abs(f.rSquared - 0.75) < 1e-14)337        // large offsets keep their precision338        let years = (0..<10).map { Point2(2_000_000_000 + Double($0), 5 + 0.25 * Double($0)) }339        #expect(abs(DataSeries.linearFit(years)!.slope - 0.25) < 1e-12)340        #expect(DataSeries.linearFit([Point2(1, 1)]) == nil && DataSeries.linearFit([Point2(1, 1), Point2(1, 2)]) == nil)341        #expect(DataSeries.bounds([]) == nil)342        #expect(DataSeries.linearFit([Point2(0, 4), Point2(1, 4), Point2(2, 4)])!.rSquared == 1)343        let v = DataSeries.fit(pts, viewport: .standard)344        #expect(v.xMin < 1 && v.xMax > 4 && v.yMin < 3 && v.yMax > 9 && v.width == 800)345        let (a, c) = fit.segment(in: .standard)346        #expect(a == Point2(-10, -19) && c == Point2(10, 21))347    }348349    @Test func csv() {350        let lines = [Polyline(points: [Point2(0.1, 1.0 / 3), Point2(1, 2)]), Polyline(points: [Point2(3, 1e-300)])]351        let text = CSVExport.curve(lines)352        #expect(text == "x,y\n0.1,0.3333333333333333\n1.0,2.0\n\n3.0,1e-300\n")353        // full precision: every number reads back exactly354        let rows = text.split(separator: "\n").dropFirst().map { $0.split(separator: ",").map { Double($0)! } }355        #expect(rows[0] == [0.1, 1.0 / 3] && rows[2] == [3, 1e-300])356        #expect(CSVExport.curveWithSegments(lines) == "segment,x,y\n0,0.1,0.3333333333333333\n0,1.0,2.0\n1,3.0,1e-300\n")357        #expect(CSVExport.points([Point2(1, 2)], header: false) == "1.0,2.0\n")358        let sampled = CSVExport.curve(plot("1/x").polylines)359        #expect(sampled.components(separatedBy: "\n\n").count == 2)          // the two branches stay separate in the file360    }361}362
Files main
Menu

Theme