Testing iOS polyline simplification: endpoints and error bounds

Testing iOS polyline simplification: endpoints and error bounds

Testing iOS polyline simplification: endpoints and error bounds

When simplifying movement tracks before a release, tests need to assert more than “the point count went down.” A reversal can be reduced to a straight line, duplicate coordinates can cause division by zero, and deviations too small to notice on a map can still exceed the product’s tolerance. Running Swift assertions against the same fixed fixtures on cloud Macs gives multiple regression nodes a consistent basis for their results.

The checks below validate the geometric contract of Douglas–Peucker polyline simplification without a map UI or a running simulator. The example handles open polylines; closed geofences, road matching, and geographic distance calculations are outside the guarantees of this algorithm.

Define coordinate and error units first

Normalize all input to coordinates in meters within a single planar coordinate system, and express the error tolerance in meters as well. Do not feed latitude and longitude directly into the algorithm: the same difference in longitude represents different distances at different latitudes. For real tracks, first choose a projection appropriate to the area covered. Tracks spanning large areas also require a separate assessment of projection error.

Define the following behavior so development and testing share the same expectations:

Measure distance to the finite line segment, not the infinite line through it. For a track that doubles back, using distance to the line can incorrectly assign zero error to a point beyond an endpoint.

Return indices to preserve links to the original samples

Save this as polyline-check.swift. The implementation returns original indices, allowing callers to retain timestamps and speed fields without looking up samples by floating-point coordinates. Absolute coordinate values are limited to one billion meters to bound the range of squared calculations; this is not a guarantee of geographic accuracy.

import Foundation

struct Point {
    let x: Double
    let y: Double
}

func distanceSquared(_ p: Point, _ a: Point, _ b: Point) -> Double {
    let dx = b.x - a.x
    let dy = b.y - a.y
    let lengthSquared = dx * dx + dy * dy
    let t = lengthSquared == 0
        ? 0
        : max(0, min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy)
                         / lengthSquared))
    let ex = p.x - (a.x + t * dx)
    let ey = p.y - (a.y + t * dy)
    return ex * ex + ey * ey
}

func simplify(_ points: [Point], epsilon: Double) throws -> [Int] {
    enum InputError: Error { case invalid }
    guard epsilon.isFinite, epsilon >= 0, epsilon <= 1e9,
          points.allSatisfy({
              $0.x.isFinite && $0.y.isFinite &&
              abs($0.x) <= 1e9 && abs($0.y) <= 1e9
          }) else {
        throw InputError.invalid
    }
    guard points.count > 2 else { return Array(points.indices) }

    var kept: Set<Int> = [0, points.count - 1]
    var pending = [(0, points.count - 1)]
    let limit = epsilon * epsilon

    while let (start, end) = pending.popLast() {
        guard end - start > 1 else { continue }
        var maximum = limit
        var split: Int?
        for i in (start + 1)..<end {
            let value = distanceSquared(points[i], points[start], points[end])
            if value > maximum {
                maximum = value
                split = i
            }
        }
        if let split {
            kept.insert(split)
            pending.append((start, split))
            pending.append((split, end))
        }
    }
    return kept.sorted()
}

func verify(_ points: [Point], epsilon: Double) throws -> [Int] {
    let indices = try simplify(points, epsilon: epsilon)
    if points.isEmpty {
        precondition(indices.isEmpty)
        return indices
    }
    precondition(indices.first == 0 && indices.last == points.count - 1)
    for (start, end) in zip(indices, indices.dropFirst()) {
        precondition(start < end)
        for i in start...end {
            let value = distanceSquared(points[i], points[start], points[end])
            precondition(value <= epsilon * epsilon + 1e-12)
        }
    }
    return indices
}

let bend = [
    Point(x: 0, y: 0),
    Point(x: 1, y: 1),
    Point(x: 2, y: 0)
]
let boundary = try verify(bend, epsilon: 1)
precondition(boundary == [0, 2])
let retained = try verify(bend, epsilon: 0.5)
precondition(retained == [0, 1, 2])
let reversal = [
    Point(x: 0, y: 0),
    Point(x: 2, y: 0),
    Point(x: 1, y: 0)
]
let reversedIndices = try verify(reversal, epsilon: 0)
precondition(reversedIndices == [0, 1, 2])
let duplicates = Array(repeating: Point(x: 3, y: 4), count: 4)
let duplicateIndices = try verify(duplicates, epsilon: 0)
precondition(duplicateIndices == [0, 3])
do {
    _ = try simplify([Point(x: .nan, y: 0)], epsilon: 1)
    preconditionFailure("Expected invalid input")
} catch {}

Run xcrun swift polyline-check.swift. Normal completion means these assertions passed; either a compilation error or a failed assertion should fail the task. Do not run the acceptance script with an unsafe optimization mode that removes runtime checks.

Cover degenerate inputs and threshold boundaries

Add separate fixtures for an empty array, a single point, two points, and an array of identical points. Check the output indices, not just the coordinates. Two identical coordinates can represent samples taken at different times; comparing only sets of coordinates can hide the replacement of the first or last sample.

Test the same bend with three thresholds: slightly below, exactly equal to, and slightly above its actual distance. Equality at the threshold is part of the product contract, not something to leave to whichever side a particular floating-point calculation happens to land on. The integer-coordinate fixture above is suitable for testing the equality rule. For real projected data, use fixtures well away from the threshold to check overall behavior.

Confirm that negative values, infinities, NaN values, and inputs outside the allowed range all throw errors. The script demonstrates only the NaN case; add the remaining cases individually in the same way. Do not silently filter out invalid points and then return a “successful” track.

Check error bounds instead of freezing every output

verify divides the original polyline into subchains using adjacent retained indices, then checks the distance from every vertex in each subchain to its corresponding output segment. This is stricter than finding the nearest arbitrary output segment for each point: that approach can let another segment after a reversal cover for the current interval.

Because the example shares its distance function, this basic operation also needs independent validation. At a minimum, calculate expected results by hand for perpendicular distance, a projection outside the segment, and a zero-length segment, then turn them into separate assertions. If the verifier and the algorithm under test use the same incorrect formula, both can pass together.

The small margin added to squared distance is only for numerical comparisons in tests; it must not automatically become a product tolerance. For production fixtures, define absolute and relative tolerances appropriate to the coordinate scale, and record their units.

Add the geometric contract to regression batches

For every run, save the commit identifier, Swift toolchain version, input fixtures, thresholds, and output indices. When running across multiple nodes in parallel, partition the work by fixture ID and use the same input file on every node. When aggregating results, preserve the exit codes of failed processes.

Use the fixed fixtures to block merges first, then measure runtime and memory usage on long tracks. An iterative stack avoids recursion-depth issues, but this implementation can still require quadratic work in the worst case. Validate the maximum input point count against actual hardware and task budgets rather than extrapolating from short fixtures.

Finally, sign off on “geometric error passed” separately from “the route is correct for the product.” Simplification does not guarantee that topology, road association, dwell time, or enclosed area remains unchanged. Products that depend on those properties should allow simplified results into a release only after separate checks pass.

Frequently asked questions

Can I pass latitude and longitude directly?

No. The example expects planar coordinates in meters. Choose a projection appropriate for the covered area first; differences in degrees are not meter distances.

Does passing the error bound preserve route semantics?

No. The check measures original vertices against their corresponding simplified segments. Road matching, topology, and enclosed area need separate tests.

Rent a dedicated Mac for your release window

Choose a model, location, and rental term, then distribute independent regression tests across multiple physical Mac minis. Each node has its own rental term and stops when it expires unless renewed.

Choose a model and rental term

Set your regression budget, then provision a node

Choose a daily, weekly, monthly, or quarterly term. Before stopping a node, export build artifacts, test reports, and logs.