Algorithm Search⌘K

Techniquecore

Least-squares reference feature

Also called Gaussian association, Gaussian reference element.

Fits the ideal feature that minimizes the sum of squared deviations, an option in standards beside the minimum zone. It is simpler, and its zone is never narrower than the minimum zone.

A least-squares reference feature is the ideal line, plane, circle, sphere or cylinder that minimizes the sum of the squared orthogonal deviations of the measured points from it. In metrology this is the Gaussian association. Coordinate measuring machine software uses it to report the position, orientation and size of a feature, to set up datums, and to report a form error as the width of the zone between the largest and the smallest deviation from the fitted feature. That width is never smaller than the minimum zone form error, because the least-squares feature is one of the features over which the minimum zone is taken. The minimum zone is the definition of a form tolerance, the problem is form error evaluation, and its methods are minimum zone flatness, which is exact, and minimum zone cylindricity, which finds a local minimum only. This page is the least-squares alternative and how to compute it.

In plain words

We have points measured on a face that should be flat. We want one plane that represents the face. For any plane, each point is a little above or below it. Square those distances and add them up. The best plane makes that sum as small as possible. It passes through the center of mass of the points and lies along the directions in which the points spread most.

The plane is stable: moving one point a little moves the plane a little. It is also cheap to compute. Its disadvantage is that it does not give the thinnest pair of parallel planes around the points. If we put two planes parallel to it through the highest and lowest points, the gap is a correct but sometimes pessimistic flatness value. Lines and circles work the same way.

When it applies

  • A feature of known type is measured by many points, and a smooth, repeatable reference is wanted: the center of a bore, the axis of a shaft, the normal of a face, a datum plane.
  • The noise in the points is random and of similar size in all directions. Then the least-squares feature is the maximum likelihood estimate of the ideal feature.
  • A form value is wanted fast, and an upper bound is acceptable, or the drawing asks for the Gaussian association.

It does not apply when the tolerance must be checked against the minimum zone without a margin, and it is a poor choice when the data have outliers.

The template

  1. Choose the feature and its deviation. The parameters θ\theta of the ideal feature and the signed orthogonal deviation ei(θ)e_i(\theta) of each point: u⋅xi−du \cdot x_i - d for a plane with unit normal uu, ∣xi−c∣−r\lvert x_i - c \rvert - r for a circle or a sphere, the distance to the axis minus rr for a cylinder.
  2. Minimize S(θ)=∑iei(θ)2S(\theta) = \sum_i e_i(\theta)^2.
  3. Report the feature θLS\theta_{\mathrm{LS}}, the root mean square deviation S/n\sqrt{S/n}, and the least-squares zone, the region between the levels min⁡iei\min_i e_i and max⁡iei\max_i e_i, of width WLS=max⁡iei(θLS)−min⁡iei(θLS)W_{\mathrm{LS}} = \max_i e_i(\theta_{\mathrm{LS}}) - \min_i e_i(\theta_{\mathrm{LS}}).

The zone is never narrower than the minimum zone. For each θ\theta the zone between the extreme deviations holds all points and has the shape of the tolerance zone, so its width is at least the minimum over θ\theta, which is the minimum zone form error EE. In particular WLS≥EW_{\mathrm{LS}} \ge E. Equality holds when θLS\theta_{\mathrm{LS}} also minimizes the zone width, for example on noise-free points, where both are 00.

Plane: the smallest eigenvector. Let xˉ\bar x be the centroid and C=∑i(xi−xˉ)(xi−xˉ)TC = \sum_i (x_i - \bar x)(x_i - \bar x)^{\mathsf T} the scatter matrix. For a fixed unit normal uu, S=∑i(u⋅xi−d)2S = \sum_i (u \cdot x_i - d)^2 is a quadratic in dd with derivative −2∑i(u⋅xi−d)-2 \sum_i (u \cdot x_i - d), so the best offset is d=u⋅xˉd = u \cdot \bar x: the plane passes through the centroid. Then S(u)=∑i(u⋅(xi−xˉ))2=uTCuS(u) = \sum_i (u \cdot (x_i - \bar x))^2 = u^{\mathsf T} C u. Over unit vectors this is the Rayleigh quotient of CC, whose minimum is the smallest eigenvalue λ1\lambda_1, attained at its eigenvector. So the least-squares plane passes through the centroid with the normal of the smallest eigenvector of CC, and S=λ1S = \lambda_1. This is Pearson's result of 1901, and it is the same computation as principal component analysis.

Line: the largest eigenvector. For a line through xˉ\bar x with unit direction uu, the squared distance of xix_i is ∣xi−xˉ∣2−(u⋅(xi−xˉ))2\lvert x_i - \bar x \rvert^2 - (u \cdot (x_i - \bar x))^2. The first term does not depend on uu, so the best uu maximizes uTCuu^{\mathsf T} C u and is the largest eigenvector; the best line passes through the centroid by the same argument as for the plane, applied in the plane normal to uu. In two dimensions the angle has the closed form 12atan2⁡(2Sxy,Sxx−Syy)\tfrac12 \operatorname{atan2}(2 S_{xy}, S_{xx} - S_{yy}).

Circle, sphere and cylinder: iterate. There is no closed form. The code starts from the linear fit of Kåsa, which minimizes the algebraic residuals of x2+y2+Dx+Ey+G=0x^2 + y^2 + D x + E y + G = 0 by a 3×33 \times 3 linear system, and improves it with Levenberg-Marquardt steps on the orthogonal residuals ∣xi−c∣−r\lvert x_i - c \rvert - r, keeping a step only if it lowers SS. At a minimum the derivative in rr gives ∑iei=0\sum_i e_i = 0: the fitted radius is the mean distance from the center. The details and the bias of the algebraic start are on circle fitting and geometric primitive fitting.

Classic examples

Straightness. The points (0,0),(1,0),(2,0),(3,0),(4,1)(0,0), (1,0), (2,0), (3,0), (4,1) have the centroid (2,0.2)(2, 0.2) and Sxx=10S_{xx} = 10, Sxy=2S_{xy} = 2, Syy=0.8S_{yy} = 0.8. The least-squares line has slope about 0.2080.208, and the strip between the extreme deviations from it has the width 0.77540.7754. The minimum zone strip, through (0,0)(0,0) and (4,1)(4,1) and the parallel line through (3,0)(3,0), has the width 3/17≈0.72763/\sqrt{17} \approx 0.7276. The least-squares value overstates straightness by about 77 percent here.

Flatness of a plate. For a nearly flat plate the least-squares plane and the minimum zone planes are nearly parallel, and the least-squares zone is often close to the minimum zone. How close depends on the data; the tests on this page check only that it is never smaller.

Datum planes and axes. A primary datum plane is often taken as a least-squares plane of the datum face, or as a constrained fit of it, and an axis as the axis of a least-squares cylinder. The datum reference frame page describes how datums are built from them.

Center of a bore. The least-squares circle of points on a hole gives the center used for position tolerances. Its zone gives a roundness upper bound, compared with the exact minimum width annulus.

Variations

  • Vertical regression minimizes ∑i(zi−axi−byi−c)2\sum_i (z_i - a x_i - b y_i - c)^2. It is a linear least-squares problem, but it is not invariant under rotation and is biased when xx and yy carry errors too; see errors-in-variables regression. For a tilted surface it gives a different plane from the orthogonal fit.
  • Minimum zone (Chebyshev) association minimizes the largest deviation instead of the sum of squares, and gives the form error itself.
  • Minimum circumscribed and maximum inscribed features fit the smallest circle or cylinder around the points, or the largest inside them, as for a shaft or a hole that must mate.
  • Weighted and robust fits reduce the effect of outliers or of points with larger uncertainty.
  • Constrained fits force parallel axes, equal radii or a fixed direction across several features; see constrained primitive fitting.
  • Algebraic fits such as the algebraic distance fit and the Taubin fit are faster and noniterative, but they do not minimize the orthogonal deviations and they are biased.

Pitfalls

  • Reporting the zone width as the form error. The least-squares zone width is an upper bound. A part can fail a tolerance by the least-squares value and pass it by the minimum zone. The converse cannot happen.
  • Reporting the RMS deviation as the form error. The root mean square deviation is smaller than the zone width and is not a tolerance value.
  • Non-unique fits. If the scatter matrix has a repeated smallest eigenvalue, every normal in its eigenspace is optimal. For the four vertices of a regular tetrahedron the scatter matrix is a multiple of the identity, so every plane through the centroid is a least-squares plane. Their zones range from 11 to 2/32/\sqrt 3 for a tetrahedron of edge 2\sqrt 2.
  • Short arcs. A circle fitted to a short arc has a poorly determined radius and center, and the algebraic start is biased toward a smaller radius; see circle fitting.
  • Cancellation. Compute the scatter matrix from centered coordinates, and compute a distance to a line from the perpendicular component, not as the difference of two large squares.
  • Outliers. One wrong point moves the fit and widens the zone. Filter the data, or use a robust fit, before the evaluation.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

least_squares_reference_feature.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-squares-reference-feature/. The authors are listed in prov/5ETC50.jsonl.

"""Least-squares (Gaussian) reference features: line, plane and circle.

Each fit minimizes the sum of the squared orthogonal deviations of the points
from the ideal feature. The deviations from the fitted feature give the
least-squares zone, whose width max(e) - min(e) is an upper bound of the
minimum zone form error.
"""

import math


def _centroid(points):
    n = len(points)
    d = len(points[0])
    return tuple(sum(p[k] for p in points) / n for k in range(d))


def _covariance(points, c):
    d = len(c)
    m = [[0.0] * d for _ in range(d)]
    for p in points:
        q = [p[k] - c[k] for k in range(d)]
        for i in range(d):
            for j in range(d):
                m[i][j] += q[i] * q[j]
    return m


def jacobi_eigen(a, sweeps=60):
    """Eigenvalues and unit eigenvectors (columns) of a small symmetric matrix."""
    n = len(a)
    a = [row[:] for row in a]
    v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(a[i][i] ** 2 for i in range(n)) + 1e-300
        if off <= 1e-30 * scale:
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                s = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - s * akq
                    a[k][q] = s * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - s * aqk
                    a[q][k] = s * apk + c * aqk
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - s * vkq
                    v[k][q] = s * vkp + c * vkq
    vals = [a[i][i] for i in range(n)]
    vecs = [tuple(v[k][i] for k in range(n)) for i in range(n)]
    order = sorted(range(n), key=lambda i: vals[i])
    return [vals[i] for i in order], [vecs[i] for i in order]


def zone_width(deviations):
    """Width of the zone between the extreme deviations."""
    return max(deviations) - min(deviations)


def ls_plane(points):
    """Least-squares plane of 3D points.

    Returns (centroid, unit normal, deviations, sum of squares). The normal is
    the eigenvector of the smallest eigenvalue of the scatter matrix, and the
    sum of squares equals that eigenvalue.
    """
    c = _centroid(points)
    vals, vecs = jacobi_eigen(_covariance(points, c))
    n = vecs[0]
    dev = [sum(n[k] * (p[k] - c[k]) for k in range(3)) for p in points]
    return c, n, dev, sum(e * e for e in dev)


def ls_line(points):
    """Least-squares line of 2D or 3D points.

    Returns (centroid, unit direction, distances). The direction is the
    eigenvector of the largest eigenvalue of the scatter matrix. In 2D the
    deviations are signed; in 3D they are distances to the line.
    """
    c = _centroid(points)
    d = len(c)
    vals, vecs = jacobi_eigen(_covariance(points, c))
    u = vecs[-1]
    if d == 2:
        nrm = (-u[1], u[0])
        dev = [nrm[0] * (p[0] - c[0]) + nrm[1] * (p[1] - c[1]) for p in points]
        return c, u, dev
    dev = []
    for p in points:
        q = [p[k] - c[k] for k in range(d)]
        h = sum(q[k] * u[k] for k in range(d))
        dev.append(math.sqrt(sum((q[k] - h * u[k]) ** 2 for k in range(d))))
    return c, u, dev


def _solve3(m, b):
    m = [row[:] + [b[i]] for i, row in enumerate(m)]
    for col in range(3):
        piv = max(range(col, 3), key=lambda r: abs(m[r][col]))
        if abs(m[piv][col]) < 1e-300:
            raise ValueError("singular system")
        m[col], m[piv] = m[piv], m[col]
        for r in range(3):
            if r != col:
                f = m[r][col] / m[col][col]
                for k in range(col, 4):
                    m[r][k] -= f * m[col][k]
    return [m[i][3] / m[i][i] for i in range(3)]


def kasa_start(points):
    """Linear algebraic circle used as the start: x^2 + y^2 + D x + E y + G = 0."""
    ata = [[0.0] * 3 for _ in range(3)]
    atb = [0.0] * 3
    for x, y in points:
        row = (x, y, 1.0)
        rhs = -(x * x + y * y)
        for i in range(3):
            atb[i] += row[i] * rhs
            for j in range(3):
                ata[i][j] += row[i] * row[j]
    d, e, g = _solve3(ata, atb)
    a, b = -d / 2.0, -e / 2.0
    return (a, b), math.sqrt(max(0.0, a * a + b * b - g))


def _circle_cost(points, a, b, r):
    return sum((math.hypot(x - a, y - b) - r) ** 2 for x, y in points)


def ls_circle(points, max_iter=200, tol=1e-15):
    """Least-squares (geometric) circle of 2D points.

    Starts from the Kasa circle and takes Levenberg-Marquardt steps on the
    orthogonal residuals |x_i - c| - r. Returns (center, radius, deviations,
    sum of squares). The cost never increases from one accepted step to the
    next.
    """
    (a, b), r = kasa_start(points)
    cost = _circle_cost(points, a, b, r)
    mu = 1e-3
    for _ in range(max_iter):
        jtj = [[0.0] * 3 for _ in range(3)]
        jtr = [0.0] * 3
        for x, y in points:
            dist = math.hypot(x - a, y - b)
            if dist == 0.0:
                continue
            row = (-(x - a) / dist, -(y - b) / dist, -1.0)
            res = dist - r
            for i in range(3):
                jtr[i] += row[i] * res
                for j in range(3):
                    jtj[i][j] += row[i] * row[j]
        improved = False
        for _ in range(30):
            m = [[jtj[i][j] + (mu * (1.0 + jtj[i][i]) if i == j else 0.0) for j in range(3)] for i in range(3)]
            step = _solve3(m, [-v for v in jtr])
            na, nb, nr = a + step[0], b + step[1], r + step[2]
            ncost = _circle_cost(points, na, nb, nr)
            if ncost < cost:
                gain = cost - ncost
                a, b, r, cost = na, nb, nr, ncost
                mu = max(mu / 10.0, 1e-12)
                improved = True
                break
            mu *= 10.0
        if not improved or gain <= tol * max(cost, 1e-300):
            break
    dev = [math.hypot(x - a, y - b) - r for x, y in points]
    return (a, b), r, dev, cost


if __name__ == "__main__":
    pts = [(0, 0), (1, 0), (2, 0), (3, 0), (4, 1)]
    c, u, dev = ls_line(pts)
    print("line", c, u, zone_width(dev))
    arc = [(math.cos(t), math.sin(t)) for t in (0.0, 0.2, 0.4, 0.6)]
    print("circle", ls_circle(arc)[:2])
test_least_squares_reference_feature.py 220 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-squares-reference-feature/. The authors are listed in prov/5ETC50.jsonl.

import math
import random
import unittest
from fractions import Fraction
from itertools import combinations

from least_squares_reference_feature import (
    kasa_start,
    ls_circle,
    ls_line,
    ls_plane,
    zone_width,
)


def unit(v):
    n = math.sqrt(sum(x * x for x in v))
    return tuple(x / n for x in v)


def smallest_eigenvalue_3x3(m):
    """Closed form of the smallest eigenvalue of a symmetric 3x3 matrix
    (the trigonometric solution of the characteristic cubic)."""
    p1 = m[0][1] ** 2 + m[0][2] ** 2 + m[1][2] ** 2
    q = (m[0][0] + m[1][1] + m[2][2]) / 3.0
    p2 = sum((m[i][i] - q) ** 2 for i in range(3)) + 2 * p1
    p = math.sqrt(p2 / 6.0)
    b = [[(m[i][j] - (q if i == j else 0.0)) / p for j in range(3)] for i in range(3)]
    detb = (
        b[0][0] * (b[1][1] * b[2][2] - b[1][2] * b[2][1])
        - b[0][1] * (b[1][0] * b[2][2] - b[1][2] * b[2][0])
        + b[0][2] * (b[1][0] * b[2][1] - b[1][1] * b[2][0])
    )
    r = max(-1.0, min(1.0, detb / 2.0))
    phi = math.acos(r) / 3.0
    return q + 2 * p * math.cos(phi + 2 * math.pi / 3)


def plane_cost(points, n):
    c = [sum(p[k] for p in points) / len(points) for k in range(3)]
    return sum(sum(n[k] * (p[k] - c[k]) for k in range(3)) ** 2 for p in points)


def circle_cost(points, a, b, r):
    return sum((math.hypot(x - a, y - b) - r) ** 2 for x, y in points)


def brute_flatness2(points):
    def sub(a, b):
        return tuple(x - y for x, y in zip(a, b))

    def cross(a, b):
        return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])

    best = None
    cands = [cross(sub(b, a), sub(c, a)) for a, b, c in combinations(points, 3)]
    segs = list(combinations(points, 2))
    cands += [cross(sub(b, a), sub(d, c)) for (a, b), (c, d) in combinations(segs, 2)]
    for n in cands:
        if n == (0, 0, 0):
            continue
        v = [sum(x * y for x, y in zip(n, p)) for p in points]
        w2 = Fraction((max(v) - min(v)) ** 2, sum(x * x for x in n))
        best = w2 if best is None or w2 < best else best
    return best


def brute_roundness(points):
    """Minimum width annulus: the best center is equidistant from two pairs of
    points (a vertex of the nearest or farthest point Voronoi diagram, or a
    crossing of their edges), so it is a crossing of two bisectors."""
    best = math.inf
    pairs = list(combinations(points, 2))
    for (p, q), (r, s) in combinations(pairs, 2):
        # Bisector of p, q: 2 (q - p) . c = |q|^2 - |p|^2.
        a1, b1 = 2 * (q[0] - p[0]), 2 * (q[1] - p[1])
        c1 = q[0] ** 2 + q[1] ** 2 - p[0] ** 2 - p[1] ** 2
        a2, b2 = 2 * (s[0] - r[0]), 2 * (s[1] - r[1])
        c2 = s[0] ** 2 + s[1] ** 2 - r[0] ** 2 - r[1] ** 2
        det = a1 * b2 - a2 * b1
        if det == 0:
            continue
        cx = Fraction(c1 * b2 - c2 * b1, det)
        cy = Fraction(a1 * c2 - a2 * c1, det)
        d = [math.hypot(x - cx, y - cy) for x, y in points]
        best = min(best, max(d) - min(d))
    return best


class TestPlane(unittest.TestCase):
    def test_noise_free_plane(self):
        rng = random.Random(1)
        for _ in range(50):
            n = unit((rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1)))
            off = rng.uniform(-5, 5)
            pts = []
            for _ in range(rng.randint(3, 30)):
                p = [rng.uniform(-10, 10) for _ in range(3)]
                t = sum(n[k] * p[k] for k in range(3)) - off
                pts.append(tuple(p[k] - t * n[k] for k in range(3)))
            if len(pts) == 3:
                pts.append(tuple((pts[0][k] + pts[1][k]) / 2 for k in range(3)))
            c, m, dev, ss = ls_plane(pts)
            self.assertAlmostEqual(abs(sum(m[k] * n[k] for k in range(3))), 1.0, places=9)
            self.assertLess(max(abs(e) for e in dev), 1e-9)

    def test_smallest_eigenvalue_closed_form(self):
        rng = random.Random(2)
        for _ in range(50):
            pts = [tuple(rng.gauss(0, s) for s in (3.0, 2.0, 0.3)) for _ in range(40)]
            c, n, dev, ss = ls_plane(pts)
            cov = [[sum((p[i] - c[i]) * (p[j] - c[j]) for p in pts) for j in range(3)] for i in range(3)]
            self.assertAlmostEqual(ss, smallest_eigenvalue_3x3(cov), delta=1e-9 * (1 + ss))
            # No other normal does better.
            for _ in range(20):
                other = unit(tuple(n[k] + rng.gauss(0, 0.05) for k in range(3)))
                self.assertGreaterEqual(plane_cost(pts, other), ss - 1e-9)

    def test_zone_never_narrower_than_minimum_zone(self):
        rng = random.Random(3)
        for _ in range(40):
            pts = [(rng.randint(-5, 5), rng.randint(-5, 5), rng.randint(-1, 1)) for _ in range(8)]
            w2 = brute_flatness2(pts)
            if w2 is None:
                continue
            c, n, dev, ss = ls_plane([tuple(map(float, p)) for p in pts])
            self.assertGreaterEqual(zone_width(dev), math.sqrt(w2) - 1e-9)


class TestLine(unittest.TestCase):
    def test_closed_form_angle(self):
        rng = random.Random(4)
        for _ in range(50):
            pts = [(rng.gauss(0, 3), rng.gauss(0, 1)) for _ in range(20)]
            c, u, dev = ls_line(pts)
            sxx = sum((x - c[0]) ** 2 for x, y in pts)
            syy = sum((y - c[1]) ** 2 for x, y in pts)
            sxy = sum((x - c[0]) * (y - c[1]) for x, y in pts)
            th = 0.5 * math.atan2(2 * sxy, sxx - syy)
            self.assertAlmostEqual(abs(u[0] * math.cos(th) + u[1] * math.sin(th)), 1.0, places=9)

    def test_page_example(self):
        pts = [(0, 0), (1, 0), (2, 0), (3, 0), (4, 1)]
        c, u, dev = ls_line(pts)
        self.assertAlmostEqual(zone_width(dev), 0.7754, places=4)
        self.assertAlmostEqual(u[1] / u[0], 0.2080, places=4)
        self.assertGreater(zone_width(dev), 3 / math.sqrt(17))

    def test_line_in_space(self):
        pts = [(1 + 2 * t, -1 + t, 3 - 2 * t) for t in (-2, -0.5, 0, 1.5, 4)]
        c, u, dev = ls_line(pts)
        self.assertLess(max(dev), 1e-9)
        self.assertAlmostEqual(abs(u[0] * 2 + u[1] - u[2] * 2) / 3, 1.0, places=9)


class TestCircle(unittest.TestCase):
    def test_noise_free_circles_and_arcs(self):
        rng = random.Random(5)
        for _ in range(60):
            a, b, r = rng.uniform(-5, 5), rng.uniform(-5, 5), rng.uniform(0.5, 10)
            t0, span = rng.uniform(0, 2 * math.pi), rng.choice([0.3, 1.0, 3.0, 2 * math.pi])
            pts = [(a + r * math.cos(t0 + span * i / 9), b + r * math.sin(t0 + span * i / 9)) for i in range(10)]
            (ka, kb), kr = kasa_start(pts)
            (ca, cb), cr, dev, ss = ls_circle(pts)
            for got in ((ka, kb, kr), (ca, cb, cr)):
                self.assertAlmostEqual(got[0], a, delta=1e-6 * (1 + r))
                self.assertAlmostEqual(got[1], b, delta=1e-6 * (1 + r))
                self.assertAlmostEqual(got[2], r, delta=1e-6 * (1 + r))

    def test_noisy_arc_is_a_minimum(self):
        rng = random.Random(6)
        for _ in range(30):
            pts = []
            for i in range(30):
                t = 0.8 * i / 29
                rho = 1 + rng.gauss(0, 0.01)
                pts.append((rho * math.cos(t), rho * math.sin(t)))
            (ka, kb), kr = kasa_start(pts)
            (a, b), r, dev, ss = ls_circle(pts)
            self.assertLessEqual(ss, circle_cost(pts, ka, kb, kr) + 1e-15)
            for _ in range(20):
                da, db, dr = (rng.gauss(0, 1e-3) for _ in range(3))
                self.assertGreaterEqual(circle_cost(pts, a + da, b + db, r + dr), ss - 1e-12)
            # At a minimum the mean deviation is zero (the derivative in r).
            self.assertAlmostEqual(sum(dev), 0.0, delta=1e-8)

    def test_short_arc_example(self):
        # The example of the circle fitting page: seven points every 10
        # degrees on a 60 degree arc of the unit circle, moved radially by
        # -0.02 and +0.02 in turn.
        pts = []
        for k in range(7):
            t = math.radians(10 * k)
            rho = 1 + (0.02 if k % 2 else -0.02)
            pts.append((rho * math.cos(t), rho * math.sin(t)))
        (ka, kb), kr = kasa_start(pts)
        (a, b), r, dev, ss = ls_circle(pts)
        self.assertAlmostEqual(kr, 0.8141, places=4)
        self.assertAlmostEqual(r, 0.8909, places=4)
        self.assertLess(ss, circle_cost(pts, ka, kb, kr))
        self.assertLess(ss, circle_cost(pts, 0.0, 0.0, 1.0))

    def test_zone_never_narrower_than_minimum_zone(self):
        rng = random.Random(7)
        for _ in range(30):
            pts = []
            for i in range(7):
                t = 2 * math.pi * i / 7
                rho = 20 + rng.randint(-2, 2)
                pts.append((round(rho * math.cos(t)), round(rho * math.sin(t))))
            pts = list(dict.fromkeys(pts))
            (a, b), r, dev, ss = ls_circle([tuple(map(float, p)) for p in pts])
            self.assertGreaterEqual(zone_width(dev), brute_roundness(pts) - 1e-9)


if __name__ == "__main__":
    unittest.main()

Exercises

  1. Show that the least-squares line of points in the plane passes through the centroid, and derive the closed form of its angle from the 2×22 \times 2 scatter matrix.
  2. For the straightness example above, find the extreme deviations from the least-squares line and check the value 0.77540.7754.
  3. Give four points in a plane whose least-squares line is not unique. What do the least-squares zones of the different optimal lines measure?
  4. Prove that the least-squares radius of a circle with a fixed center is the mean distance of the points from the center.
  5. Give a set of five points in the plane whose least-squares straightness equals its minimum zone straightness, though the points are not collinear. Then move one point so that the two values differ.

References

  1. Karl Pearson, On lines and planes of closest fit to systems of points in space, The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science, Series 6, 2(11), 1901, 559 to 572, the line and the plane of least summed squared perpendicular distances through the centroid, along the principal axes of the ellipsoid of the data
  2. Craig M. Shakarji, Least-squares fitting algorithms of the NIST algorithm testing system, Journal of Research of the National Institute of Standards and Technology 103(6), 1998, 633 to 641, the orthogonal least-squares fits of lines, planes, circles, spheres, cylinders, cones and tori used to test coordinate measuring machine software
  3. Nikolai Chernov, Circular and Linear Regression, Fitting Circles and Lines by Least Squares, CRC Press, Monographs on Statistics and Applied Probability 117, 2010, Chapter 2 (fitting lines), Chapter 4 (geometric circle fits by Gauss-Newton and Levenberg-Marquardt) and Chapter 5 (algebraic circle fits used as starting points)
  4. István Kåsa, A circle fitting procedure and its error analysis, IEEE Transactions on Instrumentation and Measurement IM-25(1), 1976, 8 to 14, the linear circle fit used here as the start of the geometric circle fit
  5. Jorge Nocedal and Stephen J. Wright, Numerical Optimization, second edition, Springer, 2006, Chapter 10, nonlinear least squares (Gauss-Newton and Levenberg-Marquardt)
  6. ISO 1101:2017, Geometrical product specifications (GPS), Geometrical tolerancing, Tolerances of form, orientation, location and run-out, fourth edition, the standard as a whole (form tolerance zones, against which the least-squares zone is an upper bound); no clause is quoted

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples