Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXGraph/Tests/ORIXGraphTests/ExplicitSamplerTests.swift3// Description: Proves the cardinal rule for explicit functions: no segment across a pole, a jump or an undefined region; exact domain boundaries; sub-pixel accuracy.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXExpression10@testable import ORIXGraph1112/// Checks shared by every function of the catalogue.13private func verify(_ expression: String, _ viewport: Viewport = .standard, polylines expected: Int, breaks: [Double] = [],14 sourceLocation: SourceLocation = #_sourceLocation) -> ExplicitPlot {15 let f = fn(expression)16 let p = Sampler.sampleExplicit(f, viewport: viewport)17 #expect(p.polylines.count == expected, "\(expression): polyline count", sourceLocation: sourceLocation)18 #expect(hiddenBreaks(p, f, viewport) == 0, "\(expression): a segment hides a discontinuity", sourceLocation: sourceLocation)19 #expect(!spans(p, breaks), "\(expression): a segment spans a known discontinuity", sourceLocation: sourceLocation)20 #expect(bounded(p, viewport), "\(expression): unbounded coordinates", sourceLocation: sourceLocation)21 #expect(uncovered(p, f, viewport) < 0.002, "\(expression): visible part of the curve is missing", sourceLocation: sourceLocation)22 #expect(maxScreenError(p, f, viewport) < 0.5, "\(expression): polyline further than half a pixel from the curve", sourceLocation: sourceLocation)23 #expect(p.isComplete, sourceLocation: sourceLocation)24 return p25}2627private func locations(_ p: ExplicitPlot, _ kind: Discontinuity.Kind) -> [Double] { p.discontinuities.filter { $0.kind == kind }.map(\.x) }2829private func matches(_ found: [Double], _ expected: [Double], tolerance: Double = 1e-9) -> Bool {30 found.count == expected.count && zip(found.sorted(), expected.sorted()).allSatisfy { abs($0 - $1) <= tolerance * max(1, abs($1)) }31}3233@Suite struct PolesAndJumps {34 let v = Viewport.standard // [-10, 10] × [-7.5, 7.5], 800 × 6003536 @Test func reciprocal() {37 let p = verify("1/x", polylines: 2, breaks: [0])38 #expect(matches(locations(p, .pole), [0]))39 #expect(p.discontinuities.count == 1)40 #expect(p.discontinuities[0].leftLimit == .infinite(positive: false))41 #expect(p.discontinuities[0].rightLimit == .infinite(positive: true))42 // The two branches leave through the bottom and through the top of the clip range, right at the asymptote.43 let clipLo = v.yMin - v.ySpan, clipHi = v.yMax + v.ySpan44 #expect(p.polylines[0].points.last!.y == clipLo)45 #expect(p.polylines[1].points.first!.y == clipHi)46 #expect(abs(p.polylines[0].points.last!.x) < 0.1 && abs(p.polylines[1].points.first!.x) < 0.1)47 }4849 @Test func reciprocalWhenTheGridMissesThePole() {50 // 0 is not a grid abscissa here: the pole has to be found between two finite samples of opposite sign.51 let view = Viewport(xMin: -3, xMax: 7.123, yMin: -5, yMax: 5, width: 777, height: 500)52 let p = verify("1/x", view, polylines: 2, breaks: [0])53 #expect(matches(locations(p, .pole), [0], tolerance: 1e-12))54 let q = verify("1/(x-1/3)", view, polylines: 2, breaks: [1.0 / 3])55 #expect(matches(locations(q, .pole), [1.0 / 3], tolerance: 1e-12))56 }5758 @Test func tangent() {59 let poles = [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5].map { $0 * Double.pi }60 let p = verify("tan(x)", polylines: 7, breaks: poles)61 #expect(matches(locations(p, .pole), poles, tolerance: 1e-12))62 #expect(p.discontinuities.count == 6)63 }6465 @Test func tangentOverTwentyPeriods() {66 let view = Viewport(xMin: 0, xMax: 20 * .pi, yMin: -5, yMax: 5, width: 800, height: 600)67 let poles = (0..<20).map { (Double($0) + 0.5) * Double.pi }68 let p = verify("tan(x)", view, polylines: 21, breaks: poles)69 #expect(matches(locations(p, .pole), poles, tolerance: 1e-12))70 // Every branch is increasing: a vertical connector would show up as a decreasing step.71 for line in p.polylines { #expect(zip(line.points, line.points.dropFirst()).allSatisfy { $1.y >= $0.y }) }72 }7374 @Test func evenOrderPole() {75 let p = verify("1/(x-1)^2", polylines: 2, breaks: [1])76 #expect(matches(locations(p, .pole), [1]))77 #expect(p.discontinuities[0].leftLimit == .infinite(positive: true) && p.discontinuities[0].rightLimit == .infinite(positive: true))78 // Off the grid: both neighbouring samples are huge and positive, nothing changes sign.79 let view = Viewport(xMin: -3, xMax: 7.123, yMin: -5, yMax: 5, width: 777, height: 500)80 let q = verify("1/(x-1/3)^2", view, polylines: 2, breaks: [1.0 / 3])81 #expect(matches(locations(q, .pole), [1.0 / 3], tolerance: 1e-9))82 // A tall but finite spike is not a pole and is not broken.83 let spike = verify("1/((x-1/3)^2+0.0001)", view, polylines: 2) // leaves the clip range and comes back84 #expect(spike.discontinuities.isEmpty)85 }8687 @Test func cosecant() {88 let poles = (-3...3).map { Double($0) * Double.pi }89 let p = verify("1/sin(x)", polylines: 8, breaks: poles)90 #expect(matches(locations(p, .pole), poles, tolerance: 1e-12))91 }9293 @Test func floorFunction() {94 let jumps = (-9...10).map(Double.init)95 let p = verify("floor(x)", polylines: 21, breaks: jumps)96 #expect(locations(p, .jump) == jumps) // exactly on the integers97 #expect(p.discontinuities.count == 20)98 // every piece is horizontal99 for line in p.polylines { #expect(Set(line.points.map(\.y)).count == 1) }100 let d = p.discontinuities[3]101 #expect(d.leftLimit == .finite(d.x - 1) && d.rightLimit == .finite(d.x))102 }103104 @Test func signFunction() {105 let p = verify("sign(x)", polylines: 3, breaks: [])106 #expect(locations(p, .jump) == [0])107 #expect(p.discontinuities.count == 1)108 #expect(p.discontinuities[0].leftLimit == .finite(-1) && p.discontinuities[0].rightLimit == .finite(1))109 // sign(0) = 0 is an isolated point of the graph110 #expect(p.polylines[1].points == [Point2(0, 0)])111 #expect(p.polylines[0].points.allSatisfy { $0.y == -1 && $0.x < 0 })112 #expect(p.polylines[2].points.allSatisfy { $0.y == 1 && $0.x > 0 })113 }114115 @Test func absOverX() {116 let p = verify("abs(x)/x", polylines: 2, breaks: [0])117 #expect(locations(p, .jump) == [0])118 #expect(p.polylines[0].points.allSatisfy { $0.y == -1 } && p.polylines[1].points.allSatisfy { $0.y == 1 })119 }120121 @Test func jumpOffTheGrid() {122 let view = Viewport(xMin: -3, xMax: 7.123, yMin: -5, yMax: 5, width: 777, height: 500)123 let p = verify("floor(x)", view, polylines: 11, breaks: (-2...7).map(Double.init))124 #expect(locations(p, .jump) == (-2...7).map(Double.init))125 let q = verify("piecewise(x < pi, 1, 2 + x/10)", view, polylines: 2, breaks: [.pi])126 #expect(matches(locations(q, .jump), [.pi], tolerance: 1e-14))127 }128}129130@Suite struct DomainsAndHoles {131 let v = Viewport.standard132133 @Test func squareRootStartsExactlyAtZero() {134 let p = verify("sqrt(x)", polylines: 1)135 #expect(p.polylines[0].points.first == Point2(0, 0))136 #expect(p.discontinuities.count == 1)137 let d = p.discontinuities[0]138 #expect(d.kind == .undefinedInterval && d.openStart && d.x == -10 && abs(d.xEnd) < 1e-18)139 #expect(d.rightLimit == .finite(0))140 }141142 @Test func squareRootBoundaryOffTheGrid() {143 let view = Viewport(xMin: -3, xMax: 7.123, yMin: -5, yMax: 5, width: 777, height: 500)144 let p = verify("sqrt(x - 1/3)", view, polylines: 1)145 #expect(abs(p.polylines[0].points.first!.x - 1.0 / 3) < 1e-15)146 #expect(abs(p.discontinuities[0].xEnd - 1.0 / 3) < 1e-15)147 let q = verify("sqrt(2 - x)", view, polylines: 1)148 #expect(abs(q.polylines[0].points.last!.x - 2) < 1e-15)149 #expect(q.discontinuities[0].kind == .undefinedInterval && q.discontinuities[0].openEnd && abs(q.discontinuities[0].x - 2) < 1e-15)150 }151152 @Test func logarithmLeavesThroughTheBottom() {153 let p = verify("ln(x)", polylines: 1)154 let d = p.discontinuities[0]155 #expect(d.kind == .undefinedInterval && abs(d.xEnd) < 1e-18)156 #expect(d.rightLimit == .infinite(positive: false))157 // The curve is extended down to the clip boundary instead of stopping at the last finite sample.158 let first = p.polylines[0].points.first!159 #expect(first.y == v.yMin - v.ySpan)160 #expect(first.x >= 0 && first.x < v.unitsPerPixelX)161 // and it is increasing all the way162 #expect(zip(p.polylines[0].points, p.polylines[0].points.dropFirst()).allSatisfy { $1.y >= $0.y })163 }164165 @Test func cubeRootIsOnePiece() {166 let p = verify("x^(1/3)", polylines: 1)167 #expect(p.discontinuities.isEmpty)168 #expect(p.polylines[0].points.first!.x == -10 && p.polylines[0].points.last!.x == 10)169 }170171 @Test func sincHasAHole() {172 let p = verify("sin(x)/x", polylines: 1)173 #expect(p.discontinuities.count == 1)174 #expect(p.discontinuities[0].kind == .removable && p.discontinuities[0].x == 0)175 #expect(p.holes.count == 1 && abs(p.holes[0].y - 1) < 1e-9 && p.holes[0].x == 0)176 }177178 @Test func rationalHole() {179 let p = verify("(x^2-1)/(x-1)", polylines: 1)180 #expect(p.discontinuities.map(\.kind) == [.removable])181 #expect(p.discontinuities[0].x == 1)182 #expect(abs(p.holes[0].y - 2) < 1e-6)183 // Drawn through: the polyline covers both sides of x = 1.184 #expect(p.polylines[0].points.first!.x == -10 && p.polylines[0].points.last!.x > 5)185 }186187 @Test func piecewiseWithAGap() {188 let p = verify("piecewise(x < 1, x, x > 2, x - 1)", polylines: 2)189 #expect(p.discontinuities.count == 1)190 let d = p.discontinuities[0]191 #expect(d.kind == .undefinedInterval && abs(d.x - 1) < 1e-9 && abs(d.xEnd - 2) < 1e-9)192 #expect(abs(p.polylines[0].points.last!.x - 1) < 1e-9 && abs(p.polylines[1].points.first!.x - 2) < 1e-9)193 }194195 @Test func semicircle() {196 let p = verify("sqrt(1-x^2)", polylines: 1)197 #expect(p.polylines[0].points.first == Point2(-1, 0) && p.polylines[0].points.last == Point2(1, 0))198 #expect(p.discontinuities.count == 2)199 #expect(abs(p.discontinuities[0].xEnd + 1) < 1e-15 && abs(p.discontinuities[1].x - 1) < 1e-15)200 // The steep ends are resolved: every vertex is on the circle.201 #expect(p.polylines[0].points.allSatisfy { abs($0.x * $0.x + $0.y * $0.y - 1) < 1e-12 })202 }203204 @Test func exponentialIsClipped() {205 let p = verify("exp(x)", polylines: 1)206 let top = v.yMax + v.ySpan207 #expect(p.polylines[0].points.last!.y == top)208 #expect(abs(p.polylines[0].points.last!.x - log(top)) < 0.01)209 #expect(p.polylines[0].points.allSatisfy { $0.y <= top })210 #expect(p.discontinuities.isEmpty)211 // exp(1000) overflows to +inf: still one bounded polyline.212 let far = Viewport(xMin: 0, xMax: 2000, yMin: -1, yMax: 10, width: 800, height: 600)213 let q = plot("exp(x)", far)214 #expect(q.polylines.count == 1 && bounded(q, far) && q.discontinuities.isEmpty)215 }216217 @Test func clampModeKeepsOnePolyline() {218 var o = SamplerOptions()219 o.clipMode = .clamp220 let p = plot("x^3", .standard, o)221 #expect(p.polylines.count == 1)222 #expect(p.polylines[0].points.allSatisfy { abs($0.y) <= 22.5 })223 #expect(p.polylines[0].points.first!.x == -10 && p.polylines[0].points.last!.x == 10)224 }225226 @Test func isolatedDefinedRegionNarrowerThanAColumnBetweenSamples() {227 // defined only on [0.5001, 0.5124]: half a pixel wide, found by the mid-column probe228 let p = plot("piecewise(x > 0.5001 and x < 0.5124, 2)")229 #expect(p.polylines.count == 1)230 #expect(abs(p.polylines[0].points.first!.x - 0.5001) < 1e-9 && abs(p.polylines[0].points.last!.x - 0.5124) < 1e-9)231 }232}233234@Suite struct Oscillation {235 @Test func sineOfReciprocal() {236 let view = Viewport(xMin: -1, xMax: 1, yMin: -1.5, yMax: 1.5, width: 800, height: 600)237 let f = fn("sin(1/x)")238 let p = Sampler.sampleExplicit(f, viewport: view)239 #expect(p.isAliased && p.bands.count == 1)240 let band = p.bands[0]241 // The band is centred on 0, covers the oscillation range and the lines take over where the curve is resolvable.242 #expect(band.columns.first!.x0 < -0.01 && band.columns.last!.x1 > 0.01)243 #expect(band.columns.first!.x0 > -0.2 && band.columns.last!.x1 < 0.2)244 #expect(band.columns.allSatisfy { $0.yMin >= -1 && $0.yMax <= 1 && $0.yMax > $0.yMin })245 let inner = band.columns.filter { abs($0.x0) < 0.005 }246 #expect(inner.allSatisfy { $0.yMin < -0.9 && $0.yMax > 0.9 })247 #expect(p.discontinuities.contains { $0.kind == .essential && $0.x == 0 })248 #expect(p.polylines.count == 2)249 #expect(hiddenBreaks(p, f, view) == 0)250 #expect(maxScreenError(p, f, view) < 0.5)251 #expect(uncovered(p, f, view) < 0.002)252 #expect(p.notices.contains { $0.kind == .aliased })253 // no polyline enters the band254 #expect(p.polylines[0].points.last!.x <= band.columns.first!.x0 && p.polylines[1].points.first!.x >= band.columns.last!.x1)255 }256257 @Test func fasterThanThePixelsGivesABandNotAMoire() {258 // 1000 rad per unit = 25 rad per column: on this grid the samples of sin(1000x) fall on a slow, smooth, completely259 // wrong sine (the classic alias). The sampler must not draw it.260 let f = fn("sin(1000x)")261 let p = Sampler.sampleExplicit(f, viewport: .standard)262 #expect(p.bands.count == 1 && p.polylines.isEmpty)263 #expect(p.bands[0].columns.count == 800)264 #expect(p.bands[0].columns.allSatisfy { $0.yMin < -0.9 && $0.yMax > 0.9 && $0.yMin >= -1 && $0.yMax <= 1 })265 #expect(p.bands[0].polygon.count == 3200)266 // The same with frequencies that are exact multiples of the sampling frequency.267 for k in [1, 2, 3, 7] {268 let g = fn("sin(\(k * 80) * pi * x)") // k periods per column, zero at every grid abscissa269 let q = Sampler.sampleExplicit(g, viewport: .standard)270 #expect(q.polylines.reduce(0) { $0 + $1.points.count } < 50, "k = \(k)")271 #expect(q.bands.reduce(0) { $0 + $1.columns.count } > 780, "k = \(k)")272 }273 }274275 @Test func resolvableHighFrequencyStaysALine() {276 // sin(100x): 2.5 pixels per period at this zoom; a line is still the truth, refined to the cap.277 let f = fn("sin(100x)")278 let p = Sampler.sampleExplicit(f, viewport: .standard)279 #expect(p.bands.isEmpty && p.polylines.count == 1)280 #expect(maxScreenError(p, f, .standard) < 0.5)281 #expect(p.pointCount < 15000)282 }283284 @Test func amplitudeModulatedAliasing() {285 let p = plot("x * sin(3000x)")286 let columns = p.bands.flatMap(\.columns)287 #expect(columns.count > 700)288 // the envelope follows |x|289 for c in columns where abs(c.x0) > 1 {290 let a = max(abs(c.x0), abs(c.x1))291 #expect(c.yMax <= a + 1e-9 && c.yMin >= -a - 1e-9)292 #expect(c.yMax > 0.8 * min(abs(c.x0), 7) && c.yMin < -0.8 * min(abs(c.x0), 7))293 }294 }295}296297@Suite struct Accuracy {298 @Test(arguments: ["sin(x)", "x^2", "x^3 - 3x", "exp(x)", "exp(-x^2)", "5 exp(-x^2/2)", "cos(3x) + x/2", "x^5/100 - x^3/3 + x", "abs(x) - 2", "sqrt(abs(x))", "atan(5x)", "7 sin(x)"])299 func smoothFunctionsWithinHalfAPixel(_ expression: String) {300 let f = fn(expression)301 let p = Sampler.sampleExplicit(f, viewport: .standard)302 #expect(maxScreenError(p, f, .standard) < 0.5)303 #expect(uncovered(p, f, .standard) == 0)304 #expect(hiddenBreaks(p, f, .standard) == 0)305 #expect(p.discontinuities.isEmpty)306 // budget: about one point per pixel column, more only where the curve bends307 #expect(p.pointCount <= 2500, "\(expression): \(p.pointCount) points")308 #expect(p.evaluations <= 8000, "\(expression): \(p.evaluations) evaluations")309 }310311 @Test func steepLineIsNotMistakenForAJump() {312 let f = fn("1000x")313 let p = Sampler.sampleExplicit(f, viewport: .standard)314 #expect(p.polylines.count == 1 && p.discontinuities.isEmpty)315 let g = fn("atan(1000x)")316 let q = Sampler.sampleExplicit(g, viewport: .standard)317 #expect(q.polylines.count == 1 && q.discontinuities.isEmpty)318 #expect(maxScreenError(q, g, .standard) < 0.5)319 let h = fn("tanh(1e6 x)") // a smooth step far narrower than the refinement cap: still continuous320 let r = Sampler.sampleExplicit(h, viewport: .standard)321 #expect(r.polylines.count == 1 && r.discontinuities.isEmpty)322 }323324 @Test func parameterUpdateRescalesTheCurve() throws {325 let item = try PlotParser.parse("a*sin(x)")326 #expect(item.parameters == ["a"])327 var context = EvalContext()328 #expect(item.missingParameters(in: context) == ["a"])329 #expect(throws: CalcError.unknownVariable("a")) { try GraphEngine.geometry(for: item, viewport: .standard, context: context) }330 context.variables["a"] = Value(1.0)331 let one = try GraphEngine.geometry(for: item, viewport: .standard, context: context)332 context.variables["a"] = Value(3.0)333 let three = try GraphEngine.geometry(for: item, viewport: .standard, context: context)334 #expect(one.polylines.count == 1 && three.polylines.count == 1)335 #expect(one.polylines[0].points.allSatisfy { abs($0.y - sin($0.x)) < 1e-12 })336 #expect(three.polylines[0].points.allSatisfy { abs($0.y - 3 * sin($0.x)) < 1e-12 })337 #expect(abs(three.polylines[0].points.map(\.y).max()! - 3) < 1e-3)338 #expect(abs(one.polylines[0].points.map(\.y).max()! - 1) < 1e-3)339 }340341 @Test func degreeModeReachesTheSampler() throws {342 var context = EvalContext()343 context.angleMode = .degrees344 let item = try PlotParser.parse("sin(x)")345 let view = Viewport(xMin: 0, xMax: 360, yMin: -1.5, yMax: 1.5)346 let g = try GraphEngine.geometry(for: item, viewport: view, context: context)347 #expect(g.polylines.count == 1)348 #expect(g.polylines[0].points.allSatisfy { abs($0.y - sin($0.x * .pi / 180)) < 1e-12 })349 }350}351352@Suite struct ExtremeRanges {353 @Test func sineFarFromTheOrigin() {354 let view = Viewport(xMin: 1e9, xMax: 1e9 + 10, yMin: -1.5, yMax: 1.5, width: 800, height: 600)355 let f = fn("sin(x)")356 let p = Sampler.sampleExplicit(f, viewport: view)357 #expect(p.polylines.count == 1 && p.discontinuities.isEmpty && p.bands.isEmpty)358 #expect(maxScreenError(p, f, view) < 0.5)359 #expect(p.pointCount >= 800 && p.pointCount < 2500)360 // screen mapping keeps its precision: consecutive vertices are distinct and ordered on screen361 let xs = p.polylines[0].points.map { view.screenX($0.x) }362 #expect(zip(xs, xs.dropFirst()).allSatisfy { $1 > $0 })363 #expect(xs.first == 0 && xs.last == 800)364 #expect(abs(view.functionX(view.screenX(1e9 + 3.25)) - (1e9 + 3.25)) < 1e-6)365 }366367 @Test func parabolaAtNanoScale() {368 let view = Viewport(xMin: -1e-9, xMax: 1e-9, yMin: -1e-19, yMax: 1e-18, width: 800, height: 600)369 let f = fn("x^2")370 let p = Sampler.sampleExplicit(f, viewport: view)371 #expect(p.polylines.count == 1 && p.discontinuities.isEmpty)372 #expect(maxScreenError(p, f, view) < 0.5)373 #expect(uncovered(p, f, view) == 0)374 }375376 @Test func hugeAndTinyWindows() {377 for (span, centre) in [(1e-12, 0.0), (1e12, 0.0), (1e-6, 1e6), (1e200, 0.0), (1e-200, 0.0), (2.0, 1e15)] {378 let view = Viewport(xMin: centre - span / 2, xMax: centre + span / 2, yMin: -2, yMax: 2)379 let width = view.xSpan // the last window is widened to what doubles can resolve380 let p = Sampler.sampleExplicit({ x in cos((x - centre) / width * 12) }, viewport: view)381 #expect(p.polylines.count == 1, "span \(span) centre \(centre)")382 #expect(p.pointCount >= 800)383 #expect(p.polylines[0].points.allSatisfy { $0.x.isFinite && $0.y.isFinite })384 }385 // A window at the resolution limit of doubles still terminates and returns something sane.386 let limit = Viewport(xMin: 1e15, xMax: 1e15 + 1, yMin: -2, yMax: 2)387 #expect(limit.xSpan >= 512)388 #expect(Sampler.sampleExplicit(fn("sin(x)"), viewport: limit).isComplete)389 }390391 @Test func cancellationStopsEarly() async {392 let task = Task { () -> ExplicitPlot in393 withUnsafeCurrentTask { $0?.cancel() }394 return Sampler.sampleExplicit(fn("sin(x)"), viewport: .standard)395 }396 let p = await task.value397 #expect(!p.isComplete && p.pointCount <= 2)398 #expect(p.notices.contains { $0.kind == .incomplete })399 let item = try! PlotParser.parse("sin(x)")400 let failing = Task { () -> Bool in401 withUnsafeCurrentTask { $0?.cancel() }402 do { _ = try await GraphEngine.geometryAsync(for: item, viewport: .standard); return false }403 catch is CancellationError { return true }404 catch { return false }405 }406 #expect(await failing.value)407 }408409 @Test func evaluationBudgetIsHonoured() {410 var o = SamplerOptions()411 o.maxEvaluations = 500412 let p = plot("sin(x)", .standard, o)413 #expect(!p.isComplete && p.evaluations < 600 && p.polylines.count == 1)414 #expect(p.polylines[0].points.last!.x < 0)415 }416}417418@Suite struct AwkwardFunctions {419 /// Functions chosen to break samplers: nested poles, poles next to jumps, undefined everywhere, essential singularities,420 /// overflow, many domain gaps. For each: terminates within budget, bounded coordinates, nothing visible missing,421 /// and no segment across a discontinuity.422 @Test(arguments: ["0/0 + x", "gamma(x)", "ln(sin(x))", "sqrt(sin(100x))", "1/(x - floor(x))", "tan(1/x)", "x mod 1", "exp(1/x)", "asin(x)", "x!",423 "1/x^0.1", "ln(abs(x))", "1e300*x", "x*1e-300", "1/(x^2 - 2)", "sec(x)", "cot(x)", "atan(1/x)", "sqrt(x^2 - 1)/x",424 "floor(sin(50x))", "sin(x^3)", "x sin(1/x)", "exp(x^2)", "tan(tan(x))", "1/sin(1/x)", "sign(sin(30x))",425 "piecewise(x < 0, 1/x, x < 1, 0/0, ln(x - 1))", "sin(1e6 x)/1e3", "x + sin(5000x)/50", "abs(tan(x))", "1/abs(x)", "frac(1/x)"])426 func staysHonest(_ expression: String) {427 let f = fn(expression)428 let p = Sampler.sampleExplicit(f, viewport: .standard)429 #expect(p.isComplete && p.evaluations < 200_000, "\(expression): \(p.evaluations) evaluations")430 #expect(bounded(p, .standard))431 #expect(hiddenBreaks(p, f, .standard) == 0)432 #expect(uncovered(p, f, .standard) < 0.01)433 #expect(maxScreenError(p, f, .standard) < 0.5)434 #expect(p.bands.allSatisfy { b in b.columns.allSatisfy { $0.yMin <= $0.yMax && $0.x0 < $0.x1 } })435 // discontinuities are sorted and lie in the window436 #expect(zip(p.discontinuities, p.discontinuities.dropFirst()).allSatisfy { $0.x <= $1.x })437 #expect(p.discontinuities.allSatisfy { $0.x >= -10 && $0.xEnd <= 10 })438 }439440 @Test func knownStructures() {441 #expect(plot("0/0 + x").polylines.isEmpty)442 let reciprocalGamma = plot("gamma(x)")443 #expect(reciprocalGamma.poles.count == 10 || reciprocalGamma.poles.count == 11) // 0, −1, …, −9 (and −10 on the edge)444 #expect(plot("1/(x^2 - 2)").poles.map { abs($0) }.allSatisfy { abs($0 - 2.0.squareRoot()) < 1e-12 })445 let jump = plot("atan(1/x)")446 #expect(jump.polylines.count == 2 && jump.discontinuities.count == 1 && jump.discontinuities[0].kind == .jump)447 #expect(abs(jump.discontinuities[0].leftLimit.value! + .pi / 2) < 1e-6 && abs(jump.discontinuities[0].rightLimit.value! - .pi / 2) < 1e-6)448 let oneSided = plot("exp(1/x)") // → 0 from the left, → +∞ from the right449 #expect(oneSided.polylines.count == 2 && oneSided.discontinuities.map(\.kind) == [.pole])450 #expect(oneSided.discontinuities[0].rightLimit == .infinite(positive: true) && abs(oneSided.discontinuities[0].leftLimit.value ?? 1) < 1e-6)451 let logarithmic = plot("ln(abs(x))") // a logarithmic singularity is an asymptote too452 #expect(logarithmic.polylines.count == 2 && logarithmic.discontinuities.map(\.kind) == [.pole])453 #expect(logarithmic.polylines[0].points.last!.y == -22.5 && logarithmic.polylines[1].points.first!.y == -22.5)454 }455}456