affine·mess Run live Notebook

Two shapes at the limit

Sixteen points in the plane with seven distances: a classification you can run

Theorem. Up to similarity, there are exactly two sets of 16 points in the plane that determine at most seven distinct distances.

Similarity means translation, rotation, reflection and scaling. The two sets, E₁ and E₂, are drawn below. Both are pieces of the triangular lattice, as Erdős and Fishburn conjectured in 1996 for every maximum set with seven or more distances [EF]. Seventeen points always determine at least eight distances (the corollary in §7), and six distances allow at most 13 points [W], so "at most seven" and "exactly seven" mean the same thing here: these are the two largest seven-distance sets.

The proof is computer-assisted, and this notebook is the proof: the text explains each idea, the code next to it carries it out in exact arithmetic, and the last section lists precisely what is taken from the literature and what is computed outside the notebook.

import time
from collections import Counter
from fractions import Fraction
from itertools import combinations, product
from pathlib import Path

import sympy as sp
from IPython.display import Code, Markdown, display

import fewdist as fd        # the mathematics (fewdist.py, next to this notebook)
import figures as fg        # drawing helpers (figures.py)

DATA = Path("data")
# True: solve the 228 systems of §4 again instead of loading the saved result (four minutes)
RECOMPUTE = False
started = time.time()
print("SymPy", sp.__version__)
SymPy 1.14.0
def norm(a, b):
    "Squared length of the lattice vector a + b·ω, where ω = e^{iπ/3}."
    return a*a + a*b + b*b

lattice_d2 = lambda p, q: norm(p[0] - q[0], p[1] - q[1])

# the 13 lattice points of norm 0, 1 or 3
star = [(a, b) for a, b in product(range(-2, 3), repeat=2) if norm(a, b) in (0, 1, 3)]
E1 = star + [(-2, 0), (-2, 2), (0, -2)]
E2 = star + [(-2, 0), (0, 2), (2, -2)]

for name, E in (("E1", E1), ("E2", E2)):
    census = Counter(lattice_d2(p, q) for p, q in combinations(E, 2))
    print(f"{name}: {len(E)} points; squared distance -> number of pairs:",
          dict(sorted(census.items())))

orange = {13: fg.ACCENT, 14: fg.ACCENT, 15: fg.ACCENT}
fg.figure([fg.panel(fg.lattice_xy(E), segments="shortest", title=name, box=300, marks=orange)
           for name, E in (("E₁", E1), ("E₂", E2))])
E1: 16 points; squared distance -> number of pairs: {1: 33, 3: 24, 4: 20, 7: 24, 9: 9, 12: 4, 13: 6}
E2: 16 points; squared distance -> number of pairs: {1: 33, 3: 24, 4: 18, 7: 24, 9: 9, 12: 6, 13: 6}
E₁E₂

Segments join points at the shortest distance. The 13 black points are common to both sets; the three orange points differ.

The plan

The difficulty is that a set of 16 points has 28 degrees of freedom up to similarity, and "seven distances" does not obviously pin anything down. The proof goes through a much more rigid object, a set of ten points with at most six distances.

Step Statement Where
1 Every 16-point set with at most seven distances contains ten points with at most six distances: a core. §5
2 A core has one of 228 distance patterns. §1, §3
3 Each of the 228 patterns is realised by finitely many point sets; all of them are computed exactly. §2, §4
4 Every way of adding six points to a core without exceeding seven distances is found. All results have squared distances proportional to 1, 3, 4, 7, 9, 12, 13. §6
5 Every 16-point set with these squared distances is E₁ or E₂. §7

§8 classifies the fifteen-point sets with the same tools, §9 checks the computation from the opposite direction, and §10 is the ledger of everything that is assumed.

Running the notebook. Run All takes about three and a half minutes. Three long computations are not repeated on every run. The exact solution of the 228 systems of equations in §4 (about four minutes on two cores) loads its saved result by default; set RECOMPUTE = True in the first code cell to redo it. The lists of patterns on six to ten points and their certificates are in the folder certificates; §3.5 says how to compute and check them again. The fifteen-point classification of §8 runs in full with fifteen/fifteen.py (16 minutes). Requirements: Python 3.10 or later and SymPy.

The code. The mathematics lives in fewdist.py, about a thousand lines (comments included) organised in the same order as this notebook; figures.py only draws. The notebook calls these functions and shows the most important ones in full.

1. Distance patterns

1.1 From a point set to a coloured graph

Take n points. Each of the C(n,2) pairs has a distance. Now forget the numbers and remember only which pairs are equally far apart. What is left is a colouring of the edges of the complete graph Kₙ: two edges get the same colour exactly when the two distances are equal. The colours have no names and no order; only the way they split the pairs into classes matters. We call this the distance pattern of the point set.

In the code a pattern is a tuple with one colour number per pair, the pairs listed in the order (0,1),(0,2),…,(0,n-1),(1,2),…, and the colours numbered in order of first appearance.

# lattice coordinates: two equilateral triangles glued along a side
rhombus = [(0, 0), (1, 0), (0, 1), (1, -1)]
p = fd.pattern_of(rhombus, lattice_d2)
print("pairs:  ", fd.pairs(4))
print("pattern:", p)

fg.figure([fg.panel(fg.lattice_xy(rhombus), title="four points", labels="0123"),
           fg.abstract_panel(p, 4, title="their pattern", labels="0123")],
          legend_entries=[(0, "length 1"), (1, "length √3")])
pairs:   ((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3))
pattern: (0, 0, 0, 0, 0, 1)
length 1length √3four points0123their pattern0123

Left: the point set. Right: the same information as a colouring of K₄. Here and below, the vertices of a pattern are drawn as empty circles: they are not points of the plane yet, and where they sit in the picture means nothing.

1.2 When are two patterns the same?

Numbering the points differently changes the tuple but not the pattern. Two patterns are equivalent if one becomes the other after renumbering the points (colour names never mattered). To compare patterns we compute a canonical form: a tuple that is the same for all equivalent patterns and different otherwise.

fd.canonical does this by individualise and refine, the idea behind the graph-isomorphism program nauty. Sort the points into classes according to what they see (how many edges of each kind, leading to which classes) and repeat until nothing changes. If a class still contains several points, try each of them as "the first" and refine again. Each branch ends with an ordering of the points; the smallest colour tuple over all these orderings is the canonical form. Nothing in the procedure depends on the original numbering.

shuffled = [rhombus[k] for k in (2, 0, 3, 1)]
q = fd.pattern_of(shuffled, lattice_d2)
print("same points, other numbering:", q)
print("canonical forms:", fd.canonical(p), fd.canonical(q),
      "-> equivalent:", fd.same_pattern(p, q))
same points, other numbering: (0, 1, 0, 0, 0, 0)
canonical forms: (0, 1, 1, 1, 1, 1) (0, 1, 1, 1, 1, 1) -> equivalent: True

1.3 How many patterns are there?

For three points there are three: equilateral, isosceles, scalene. For four points we can simply colour the six edges in all 203 ways (the number of partitions of a six-element set) and keep one representative of each class.

for n in (3, 4):
    pats = fd.all_patterns(n)
    by_colours = dict(sorted(Counter(max(p) + 1 for p in pats).items()))
    print(f"{n} points: {len(pats)} patterns;  number of colours -> patterns: {by_colours}")

four = fd.all_patterns(4)
# Drawn by number of colours, then by class sizes (largest class first).
sizes = lambda p: sorted(Counter(p).values(), reverse=True)
groups = {}
for p in sorted(four, key=lambda p: (max(p), [-s for s in sizes(p)], p)):
    groups.setdefault(max(p) + 1, []).append(p)
fg.grouped_figure([(f"{k} colour{'s' if k > 1 else ''}",
                    [fg.abstract_panel(p, 4, box=112, margin=20, radius=3.2, width=2.4) for p in ps])
                   for k, ps in groups.items()], columns=7)
3 points: 3 patterns;  number of colours -> patterns: {1: 1, 2: 1, 3: 1}
4 points: 25 patterns;  number of colours -> patterns: {1: 1, 2: 5, 3: 9, 4: 7, 5: 2, 6: 1}
1 colour2 colours3 colours4 colours5 colours6 colours

All 25 patterns on four points. Colours only separate classes; which colour is used for which class is arbitrary.

The numbers grow quickly. On five points there are already 1205 patterns with at most six colours (six is all we shall need):

t0 = time.time()
n_colourings, five = 0, set()
for c in fd.colourings(10, max_colours=6):       # the 10 pairs of five points, colours unnamed
    n_colourings += 1
    five.add(fd.canonical(c))
print(f"{n_colourings} colourings of K5 with at most six colours make {len(five)} patterns",
      f" ({time.time() - t0:.0f} s)")
109299 colourings of K5 with at most six colours make 1205 patterns  (7 s)

1.4 A pattern is not a shape

A pattern is combinatorial; a point set is geometric. Going back from a pattern to point sets, three things can happen.

  • No point set at all. The one-colour pattern on four points asks for four points that are pairwise equidistant. In the plane there are none.
  • Finitely many shapes. The pattern of the square (four equal sides, two equal diagonals) is realised only by squares. Such a pattern is called rigid. A rigid pattern can have more than one shape; we shall meet one with two in §2.2.
  • Infinitely many shapes. "Opposite sides equal, diagonals equal" describes all rectangles. Such a pattern is flexible.

Here "shape" means a point set up to similarity. The whole proof rests on one fact, established in §3 and §4: every pattern of ten points with at most six distances is rigid, and there are 228 of them.

2. From a pattern to its shapes

2.1 Squared lengths as unknowns

Give each colour an unknown: the squared length of its edges (squares, because then everything is polynomial). One colour serves as the unit and gets the value 1; the code uses the colour of the pair {0,1}. So a pattern with k colours has k-1 unknowns x₁,…,xₖ₋₁.

Which values of the unknowns come from actual points in the plane? Put p₀ at the origin and let vᵢ = pᵢ - p₀. Writing Dᵢⱼ=|pᵢ-pⱼ|² and expanding |vᵢ-vⱼ|² gives the dot products in terms of the distances alone:

⟨ vᵢ, vⱼ⟩ = 1/2 (D₀ᵢ+D₀ⱼ-Dᵢⱼ).

The matrix G=(⟨ vᵢ,vⱼ⟩)_i,j≥1 is the Gram matrix. If the points lie in a plane, any three of the vectors vᵢ are linearly dependent, so every 3×3 minor of G vanishes. These are polynomial equations in the unknowns. For four points there is exactly one, det G=0; it says that the tetrahedron p₀p₁p₂p₃ has volume zero.

Here is the pattern "equilateral triangle 0,1,2; point 3 as far from 2 as the side of the triangle; point 3 equally far from 0 and 1".

#        pairs: 01 02 03 12 13 23
kite = (0, 0, 1, 0, 1, 0)
xs, values = fd.length_symbols(kite)                 # one unknown x1; colour 0 is the unit
D = sp.Matrix(fd.distance_table(kite, values))
G = sp.Matrix(fd.gram2(fd.distance_table(kite, values))) / 2
display(Markdown("Squared distances $D$, Gram matrix $G$, and $\\det G$:"),
        D, G, sp.factor(G.det()))

Squared distances D, Gram matrix G, and det G:

Matrix([ [ 0, 1, 1, x1], [ 1, 0, 1, x1], [ 1, 1, 0, 1], [x1, x1, 1, 0]])
Matrix([ [ 1, 1/2, 1/2], [1/2, 1, x1/2], [1/2, x1/2, x1]])
-(x1**2 - 4*x1 + 1)/4

So x₁²-4x₁+1=0, that is x₁ = 2±√3. Both roots are genuine, and they give two different shapes with the same pattern: point 3 lies on the axis of the triangle at distance 1 from the corner 2, on one side of that corner or on the other.

The function fd.solve_lengths automates all of this (how is the subject of the next subsections), and realisation turns a solution into points.

solution, = fd.solve_lengths(kite)
print("lengths (unit, x1):", solution.lengths, "  where", solution.field)
print("real roots at which this is a planar point set:", solution.embeddings)

panels = []
for root in solution.embeddings:
    conf = solution.realisation(root)
    x1 = solution.field.approx(solution.lengths[1], root)
    panels.append(fg.panel(conf.xy(), title=f"x₁ = {x1:.4f}", labels="0123"))
fg.figure(panels, legend_entries=[(0, "the shorter length"), (1, "the longer length")])
lengths (unit, x1): (1, t)   where Q(t), t a root of t**2 - 4*t + 1
real roots at which this is a planar point set: [0, 1]
the shorter lengththe longer lengthx₁ = 0.26790123x₁ = 3.73210123

One rigid pattern, two shapes. On the left four pairs are at the longer distance, on the right only two.

2.2 Example: the four-point sets with two distances

There are five patterns with two colours on four points. Solving each one recovers a classical list: the six four-point sets with exactly two distances.

panels = []
for pattern in [p for p in four if max(p) == 1]:
    for sol in fd.solve_lengths(pattern):
        for root in sol.embeddings:
            conf = sol.realisation(root)
            values = [sol.field.approx(v, root) if sol.field else float(v) for v in sol.lengths]
            ratio = max(values) / min(values)
            panels.append(fg.panel(conf.xy(), box=170, margin=24,
                                   title=f"long² : short² = {ratio:.3f}"))
print(len(panels), "solutions")
fg.figure(panels, columns=4, legend_entries=[(0, "shorter"), (1, "longer")])
7 solutions
shorterlongerlong² : short² = 3.000long² : short² = 2.000long² : short² = 2.618long² : short² = 2.618long² : short² = 3.732long² : short² = 3.732long² : short² = 3.000

Seven solutions, six shapes: the two trapezoids are the same shape (four corners of a regular pentagon) with the points named differently.

The last remark matters later. Solutions are counted for a fixed numbering of the points and a fixed unit colour; shapes are counted up to similarity. Renaming points can turn one solution into another without changing the shape.

2.3 Solutions that are not point sets

The equations do not know that the points must be distinct, nor that different colours must have different lengths. The square pattern shows the problem in its simplest form.

#          pairs: 01 02 03 12 13 23       (0,1,2,3 in cyclic order; 02 and 13 are the diagonals)
square = (0, 1, 0, 0, 1, 0)
xs, eqs = fd.planarity_equations(square)
print("equation:", sp.factor(eqs[0]), "= 0")
equation: x1**2*(x1 - 2) = 0

The double root x₁=0 collapses each diagonal to a point. We want only solutions in which all lengths are non-zero and pairwise different. Let q be the product of all the unknowns and all differences of two lengths (here q=x₁(x₁-1)). The classical device is to add one more unknown w and the equation w q=1: a solution with q=0 cannot be extended to w, and a solution with q≠0 extends in exactly one way. This is known as the Rabinowitsch trick.

x1, w = xs[0], sp.Symbol("w")
sp.groebner([eqs[0], w * x1 * (x1 - 1) - 1], w, x1, order="lex").exprs
[2*w - 1, x1 - 2]

Only x₁=2 survives: the diagonal of the unit square. The call to groebner is explained next.

2.4 Many equations: what a Gröbner basis does for us

With ten points there are C(9,3)=84 equations of the simplest kind (the minors on rows and columns {i,j,k}, one for each quadruple 0,i,j,k of points) in up to five unknowns. We need all their solutions, with a guarantee that none is missed. Numerical root-finding cannot give that guarantee; elimination theory can.

A Gröbner basis of a system of polynomial equations is another system with exactly the same solutions (over the complex numbers), arranged so that questions about the solutions become mechanical. It plays the role that row-echelon form plays for linear systems, and like row reduction it is computed by exact rational arithmetic. We use three facts.

  1. The basis is {1} exactly when the system has no solution at all, real or complex.
  2. One can read off from the basis whether the number of solutions is finite.
  3. If it is finite, a basis for the lexicographic ordering is triangular: its last equation involves only the last unknown, the one before only the last two, and so on, so the solutions can be listed by back-substitution, all of them.

fd.solve_lengths(pattern) is this recipe: write down the minors, add w q=1, compute a Gröbner basis, check finiteness, list the solutions. It uses only some of the minors, which is harmless: fewer equations can only produce more candidates, and every candidate is tested in §2.6 by actually constructing the points.

2.5 Irrational lengths

The lengths are often irrational. Four vertices of a regular pentagon have three sides and three diagonals; the pattern leads to a quadratic equation.

#               pairs: 01 02 03 12 13 23    (0,1,2,3 consecutive vertices: 01, 12, 23 are sides)
trapezoid = (0, 1, 1, 0, 1, 0)
print("equation:", sp.factor(fd.planarity_equations(trapezoid)[1][0]), "= 0\n")
for sol in fd.solve_lengths(trapezoid):
    print("lengths", sol.lengths, "| field:", sol.field, "| valid real roots:", sol.embeddings)
equation: (x1 + 1)*(x1**2 - 3*x1 + 1) = 0

lengths (Fraction(1, 1), Fraction(-1, 1)) | field: None | valid real roots: []
lengths (1, t) | field: Q(t), t a root of t**2 - 3*t + 1 | valid real roots: [0, 1]

There are two things to see.

  • The rational solution x₁=-1 is discarded (no valid root): a squared length cannot be negative.
  • The other solution is written as x₁=t where t is "a root of t²-3t+1", without saying which. Computations with such a number are done with polynomials in t, reduced using t²=3t-1. This is exact, and it is how the code represents every irrational length: as an element of a number field ℚ(t).

Arithmetic in ℚ(t) decides whether two numbers are equal. It cannot decide whether a number is positive, because that depends on which root t is: here t≈0.38 or t≈2.62 (the squared golden ratio and its inverse). For signs the code keeps an interval with rational endpoints around each real root and shrinks it until the sign is certain.

K = next(sol.field for sol in fd.solve_lengths(trapezoid) if sol.field)
t = K.t
print("t*t        =", t * t)
print("1/t        =", 1 / t)
print("t + 1/t    =", t + 1 / t, "  (exactly 3)")
for root in range(K.real_roots):
    print(f"at root {root}: t ≈ {K.approx(t, root):.6f},  sign of t - 1:", K.sign(t - 1, root))
t*t        = 3*t - 1
1/t        = 3 - t
t + 1/t    = 3   (exactly 3)
at root 0: t ≈ 0.381966,  sign of t - 1: -1
at root 1: t ≈ 2.618034,  sign of t - 1: 1

The conjugation principle. A computation that uses only +,-,×,div and tests of equality gives the same result at every root of the polynomial, because it never asks which root is meant. Only tests of sign distinguish the roots.

We shall use this in §6: the search for extensions of a core uses only equality tests, so it has to be run once per number field, not once per root.

2.6 From lengths back to points

A solution of the equations is a list of squared lengths. To see that it is a point set we rebuild the points and check every distance. The function is short enough to read in full.

import inspect
show = lambda f: display(Code(inspect.getsource(f), language="python"))
show(fd.place)
def place(pattern, lengths):
    """Rebuild the points from the squared lengths, or return None if they do not fit in a
    plane.  Point 0 is the origin; two other points a, b with independent position vectors
    serve as basis; every point is then found from its dot products with those two; finally
    ALL squared distances are compared with the prescribed ones."""
    n = n_points(pattern)
    D = distance_table(pattern, list(lengths))
    G = [[(D[0][i] + D[0][j] - D[i][j]) / 2 for j in range(n)] for i in range(n)]
    basis = next(((a, b) for a, b in combinations(range(1, n), 2)
                  if G[a][a] * G[b][b] != G[a][b] * G[a][b]), None)
    if basis is None:
        return None                                 # all points on a line
    a, b = basis
    A, B, C = G[a][a], G[b][b], G[a][b]
    H = A * B - C * C
    pts = [((B * G[a][j] - C * G[b][j]) / H, (A * G[b][j] - C * G[a][j]) / H) for j in range(n)]
    conf = Configuration(pts, A, B, C)
    if any(conf.d2(pts[i], pts[j]) != D[i][j] for i, j in pairs(n)):
        return None
    return conf

The coordinates are taken in the basis formed by two of the position vectors, which need not be perpendicular; this keeps all coordinates in the same field as the lengths (no square roots are introduced). The squared length of the vector with coordinates (x,y) is then Ax²+2Cxy+By² with A=⟨ e₁,e₁⟩, B=⟨ e₂,e₂⟩, C=⟨ e₁,e₂⟩.

One last condition: the plane must be the Euclidean plane. That is the case when all squared lengths are positive and AB-C²>0 (Cauchy–Schwarz with strict inequality); LengthSolution.realisation(root) checks both with certified signs. If AB-C² were negative the "points" would live in a plane with an indefinite metric, and if the root were not real they would not be real points at all.

Summary of §2. For a pattern, fd.solve_lengths returns every assignment of non-zero, pairwise different squared lengths satisfying the planarity equations, or reports that there are infinitely many. For each one, realisation either returns exact coordinates of a planar point set with exactly that pattern, or None.

3. Which patterns can occur?

3.1 One point at a time

We want all patterns of ten points in the plane with at most six distances. Trying all colourings of the 45 pairs is hopeless. The way through is a simple observation:

If a pattern is realised by a point set, then each of its sub-patterns (delete some points) is realised too.

So the patterns can be found one point at a time. For n=4,5,…,10 we build a list Lₙ that contains the pattern of every set of n points in the plane with at most six distances. Given Lₙ₋₁, there are three steps.

  1. Call a pattern on n points with at most six colours a candidate if all its sub-patterns on n-1 points are in Lₙ₋₁. By the observation, the pattern of every point set is a candidate.
  2. List all candidates: take each pattern in Lₙ₋₁, add a new point, colour its n-1 new pairs in all possible ways (old colours or new ones, at most six in total), keep the colourings all of whose sub-patterns on n-1 points are in Lₙ₋₁, put them in canonical form and remove duplicates.
  3. Discard a candidate when it is proved that no set of points in the plane has this pattern. The candidates that are kept form Lₙ.

Step 3 is optional, in the sense that a list which is too long does no harm. But it is what keeps the lists within reach, and every candidate that is discarded needs a proof.

The scheme is due to Szöllősi and Östergård [SÖ], for exactly this problem. They discard a candidate when a Gröbner basis shows that its planarity equations have no solution with non-zero, pairwise different lengths, not even a complex one (§2.4, fact 1). Here every discarded candidate comes with something that is simpler to check: a certificate.

3.2 Certificates

Let points p₀,…,pₙ₋₁ have a pattern with colours 0,…,k-1. Write c(i,j) for the colour of a pair, and x_c for the squared distance of colour c; this time no colour is singled out as the unit. Any point p_b can play the role that p₀ played in §2.1: the numbers

Gᵢⱼ=x_c(b,i)+x_c(b,j)-x_c(i,j) (i≠ j), Gᵢᵢ=2 x_c(b,i) (i,j≠ b)

are twice the dot products of the vectors pᵢ-p_b and pⱼ-p_b, so G is twice a Gram matrix and each of its 3×3 minors vanishes. A minor is a polynomial of degree 3 in x₀,…,xₖ₋₁.

Definition. A certificate for a pattern is an identity between polynomials

d·prod_cx_c^ e_c prod_a<b(x_a-x_b)^ e_ab = Σᵢ Aᵢ Mᵢ ,
where d is a non-zero integer, the exponents are non-negative integers, each Mᵢ is a 3×3 minor of one of the matrices G of the pattern, and each Aᵢ is a polynomial with integer coefficients.

Lemma (certificates). A pattern that has a certificate is not the pattern of any set of points in the plane.

Proof. Suppose it were, and put the squared distances of the points in place of the x_c. Every minor Mᵢ becomes zero, so the right side is zero. The left side is not: d≠0, every x_c is positive because the points are distinct, and x_a≠ x_b because different colours stand for different distances. ∎

Two examples: the one-coloured pattern on four points (four points pairwise at the same distance), whose certificate is a single minor, and a pattern on five points whose certificate combines three minors. M_b(rows;columns) stands for the minor of the matrix G with base point b.

import sys
sys.path.insert(0, "certificates")
import check                    # certificates/check.py: the program that checks certificates

CERT = Path("certificates")
x = sp.symbols("x0:6")          # x[c] stands for the squared length of colour c

def minor(pattern, base, rows, cols):
    "The minor of G on these rows and columns, for the base point `base`."
    c = fd.colour_matrix(pattern)
    d = lambda i, j: 0 if i == j else x[c[i][j]]
    entry = lambda r, s: d(base, rows[r]) + d(base, cols[s]) - d(rows[r], cols[s])
    return sp.Matrix(3, 3, entry).det()

def both_sides(cert):
    "The two sides of a certificate as SymPy expressions, and its right side in words."
    left = sp.Integer(cert["scale"])
    for factor, exponent in cert["product"]:
        form = x[factor[0]] if len(factor) == 1 else x[factor[0]] - x[factor[1]]
        left *= form ** exponent
    right, words = 0, []
    for base, rows, cols, multiplier in cert["terms"]:
        A = sum(coefficient * sp.prod([v ** e for v, e in zip(x, exponents)])
                for coefficient, exponents in multiplier)
        right += A * minor(cert["pattern"], base, rows, cols)
        words.append(f"({A})·M{base}({''.join(map(str, rows))};{''.join(map(str, cols))})")
    return left, right, " + ".join(words)

level5 = check.read(CERT / "level5.jsonl")
for cert in level5[:2]:
    left, right, words = both_sides(cert)
    print(f"{cert['n']} points, pattern {tuple(cert['pattern'])}")
    print(f"    {left}  =  {words}")
    print("    the two sides, expanded, are equal:", sp.expand(left - right) == 0)
4 points, pattern (0, 0, 0, 0, 0, 0)
    4*x0**3  =  (1)·M0(123;123)
    the two sides, expanded, are equal: True
5 points, pattern (0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
    18*x0**3  =  (13)·M0(123;123) + (-3)·M1(234;234) + (-22)·M0(123;124)
    the two sides, expanded, are equal: True

Expanding the two sides is all it takes to check a certificate. For the half a million certificates used below this is done without SymPy, by the function check of certificates/check.py. Every discarded candidate depends on it, so here it is in full. A polynomial is stored as a dictionary that maps exponents to integer coefficients.

show(check.check)
def check(cert):
    """True if the certificate is valid; an AssertionError if it is not."""
    n, pattern = cert["n"], cert["pattern"]
    pairs = list(combinations(range(n), 2))
    assert len(pattern) == len(pairs) and all(isinstance(c, int) for c in pattern)
    k = max(pattern) + 1
    assert set(pattern) == set(range(k))
    colour = {}
    for (i, j), c in zip(pairs, pattern):
        colour[i, j] = colour[j, i] = c

    def var(c):                               # the polynomial x_c
        return {tuple(int(i == c) for i in range(k)): 1}

    def entry(b, i, j):                       # G_ij for the base point b, a linear form
        if i == j:
            return add(var(colour[b, i]), var(colour[b, i]))
        return add(add(var(colour[b, i]), var(colour[b, j])), var(colour[i, j]), -1)

    def minor(b, rows, cols):                 # 3x3 determinant, expanded along the first row
        m = [[entry(b, i, j) for j in cols] for i in rows]

        def det2(c1, c2):                     # rows 1 and 2, columns c1 and c2
            return add(multiply(m[1][c1], m[2][c2]), multiply(m[1][c2], m[2][c1]), -1)

        out = multiply(m[0][0], det2(1, 2))
        out = add(out, multiply(m[0][1], det2(0, 2)), -1)
        return add(out, multiply(m[0][2], det2(0, 1)))

    # left side: scale * product of factors
    assert isinstance(cert["scale"], int) and cert["scale"] != 0
    left = {(0,) * k: cert["scale"]}
    for factor, exponent in cert["product"]:
        assert isinstance(exponent, int) and exponent >= 1 and len(factor) in (1, 2)
        assert all(isinstance(c, int) and 0 <= c < k for c in factor)
        if len(factor) == 1:
            form = var(factor[0])                              # x_c
        else:
            assert factor[0] != factor[1]
            form = add(var(factor[0]), var(factor[1]), -1)     # x_a - x_b
        for _ in range(exponent):
            left = multiply(left, form)

    # right side: sum of multiplier * minor
    right = {}
    for b, rows, cols, multiplier in cert["terms"]:
        assert isinstance(b, int) and 0 <= b < n
        for triple in (rows, cols):
            assert len(set(triple)) == 3 and b not in triple
            assert all(isinstance(i, int) and 0 <= i < n for i in triple)
        a = {}
        for coefficient, exponents in multiplier:
            assert isinstance(coefficient, int) and len(exponents) == k
            assert all(isinstance(e, int) and e >= 0 for e in exponents)
            a = add(a, {tuple(exponents): coefficient})
        right = add(right, multiply(a, minor(b, rows, cols)))

    assert left == right, "the identity does not hold"
    return True

3.3 Four and five points, live

The file certificates/level5.jsonl holds 272 certificates: one for a pattern on four points and 271 for patterns on five points. The next cell checks them all and carries out the three steps for n=4 and n=5. (At four points there is no list below, so every pattern is a candidate.) fd.add_a_point is step 2 in its plainest form: it tries every colouring of the new pairs.

for cert in level5:
    check.check(cert)                       # raises an error if an identity does not hold
discarded = {fd.canonical(tuple(cert["pattern"])) for cert in level5}
by_colours = lambda pats: dict(sorted(Counter(max(p) + 1 for p in pats).items()))

L4 = [p for p in four if p not in discarded]
print(f"4 points: {len(four)} candidates;  with a certificate:",
      f"{[p for p in four if p in discarded]};  kept: {len(L4)}")

t0 = time.time()
raw5 = fd.add_a_point(L4, allowed=L4)
L5 = [p for p in raw5 if p not in discarded]
print(f"5 points: {len(raw5)} candidates  ({time.time() - t0:.1f} s);",
      f" with a certificate: {len(raw5) - len(L5)};  kept: {len(L5)}")
print("number of colours -> candidates:", by_colours(raw5))
print("number of colours -> kept:      ", by_colours(L5))

assert len(discarded) == len(level5) and discarded <= set(four) | set(raw5)
assert set(L5) == {fd.canonical(p) for p in fd.load_patterns(CERT / "L5.json")}
4 points: 25 candidates;  with a certificate: [(0, 0, 0, 0, 0, 0)];  kept: 24
5 points: 1193 candidates  (1.0 s);  with a certificate: 271;  kept: 922
number of colours -> candidates: {2: 13, 3: 120, 4: 369, 5: 442, 6: 249}
number of colours -> kept:       {2: 1, 3: 20, 4: 248, 5: 409, 6: 244}

At four points only the one-colour pattern is discarded. At five points the candidates are therefore the patterns without a one-coloured K₄, 1193 of the 1205 found in §1.3, and 271 of them have a certificate.

For comparison, here is the test of [SÖ] on the same candidates: is there an assignment of non-zero, pairwise different squared lengths, possibly complex, for which the Gram matrix has rank at most 2? fd.complex_realisable answers it with a Gröbner basis (§2.4, fact 1). With five or six colours the solution sets are large (five points with six different distances form a two-parameter family) and SymPy's Gröbner bases become slow, so the comparison is made on the candidates with at most four colours.

t0 = time.time()
assert [p for p in four if fd.complex_realisable(p)] == L4
tested = [p for p in raw5 if max(p) + 1 <= 4]
passed = [p for p in tested if fd.complex_realisable(p)]
print(f"five-point candidates with at most four colours: {len(tested)};",
      f"pass the Gröbner-basis test: {len(passed)}  ({time.time() - t0:.0f} s)")
print("the ones that pass are exactly the ones without a certificate:",
      passed == [p for p in tested if p not in discarded])
assert passed == [p for p in tested if p not in discarded]
five-point candidates with at most four colours: 502; pass the Gröbner-basis test: 269  (32 s)
the ones that pass are exactly the ones without a certificate: True

The two methods agree, on these 502 candidates and on the 25 patterns at four points: a candidate has a certificate exactly when its equations have no admissible solution at all.

3.4 Listing the candidates, faster

Trying every colouring of the new pairs is fine at five points. At seven points it would mean up to 6⁶ colourings for each of 20,229 patterns. certificates/generate.py does step 2 with one improvement: it colours the new pairs one at a time, and gives up on a partial colouring as soon as a sub-pattern that is already complete is not in its list.

This loses nothing, because the lists are closed under taking sub-patterns: a pattern in Lₙ is a candidate, so its sub-patterns on n-1 points are in Lₙ₋₁, theirs are in Lₙ₋₂, and so on. Hence every sub-pattern on s points of a candidate is in L_s. Here is the function that adds a point.

import generate                 # certificates/generate.py
show(generate.extensions)
def extensions(Q, tables, kept_below=None):
    """All candidates obtained from the kept pattern Q on m points by adding the point m.
    tables[s]: labelled table of the kept patterns on s points (s = 4, 5, 6);
    kept_below: canonical forms of the kept patterns on m points (needed only if m > 6)."""
    m = n_points(Q)
    old = [[None] * m for _ in range(m)]                # old[a][b]: colour of the old pair
    for (a, b), c in zip(pairs(m), Q):
        old[a][b] = old[b][a] = c
    new = [None] * m                                    # new[a]: colour of the pair (a, m)
    top = min(m, max(TABLE_SIZES))                      # largest size tested by table lookup
    found = []

    def sub_code(points):                 # the sub-pattern on these old points and the new one
        names, value = {}, 0
        for i, a in enumerate(points):
            for b in points[i + 1:]:
                value = value * MAX_COLOURS + names.setdefault(old[a][b], len(names))
            value = value * MAX_COLOURS + names.setdefault(new[a], len(names))
        return value

    def whole():                                        # the pattern on all m + 1 points
        return tuple(new[a] if b == m else old[a][b] for a, b in pairs(m + 1))

    def without(d):                                     # the sub-pattern without old point d
        rest = [v for v in range(m) if v != d] + [m]
        return tuple(new[a] if b == m else old[a][b] for a, b in combinations(rest, 2))

    def colour_pair(j, used):             # colour the pair (j, m); `used` colours so far
        if j == m:
            if m == top or all(canonical(without(d)) in kept_below for d in range(m)):
                found.append(whole())
            return
        size = min(j + 2, top)            # the sub-patterns completed now have this many points
        completed = [T + (j,) for T in combinations(range(j), size - 2)]
        if size < 4:                      # no list below four points: nothing to test yet
            completed = []
        for c in range(min(used + 1, MAX_COLOURS)):
            new[j] = c
            if all(in_table(tables[size], sub_code(points)) for points in completed):
                colour_pair(j + 1, max(used, c + 1))
        new[j] = None

    colour_pair(0, max(Q) + 1)
    return found

tables[s] holds, for s=4,5,6, every colouring of the pairs of s numbered points that is a pattern of L_s after renumbering, so that the test is a lookup.

No candidate is missed. Let P be a candidate and v one of its points. P without v is in Lₙ₋₁, so after renumbering the points it is one of the patterns Q the function is called with; and the colours of the pairs at v form one of the colourings that are tried, once the colours that do not occur in Q are named in the order in which they appear. At five points the function finds the same 1193 candidates as the plain enumeration:

t0 = time.time()
again = generate.candidates(5, log=lambda *message: None)
print(f"generate.py, five points: {len(again)} candidates; the same as above:",
      again == set(raw5), f" ({time.time() - t0:.1f} s)")
assert again == set(raw5)
generate.py, five points: 1193 candidates; the same as above: True  (1.0 s)

3.5 Six to ten points

From six points on the lists are too long for a notebook that should run in a few minutes: there are 537,230 candidates on six points. This part was computed once, and the result is in the folder certificates, next to this notebook:

  • the lists L₅,…,L₁₀ (L5.json to L10.json);
  • a certificate for every candidate that was discarded: 517,001 on six points and 10,065 on seven. These two files are large (1.2 GB of text). They are attached to the release g7-certificates-v1 of the repository planar-distance-sets; a random sample of each is included here.

The next cell prints the numbers and checks what can be checked in a few seconds:

  • the lists have the stated sizes, and they are closed under taking sub-patterns, as §3.4 requires;
  • the 228 patterns of data/L10.json, whose numbering the rest of this notebook uses, are the patterns of L₁₀;
  • the sampled certificates are valid, and belong to patterns that are not in L₆ or L₇.
import json
summary = json.loads((CERT / "summary.json").read_text())["levels"]
ns = range(4, 11)
L = {n: [fd.canonical(p) for p in fd.load_patterns(CERT / f"L{n}.json")] for n in ns if n > 4}
L[4] = L4

def row(label, value):
    return f"| {label} | " + " | ".join(f"{value(n):,}" for n in ns) + " |"

display(Markdown("\n".join([
    "| points | " + " | ".join(map(str, ns)) + " |",
    "|---|" + "---:|" * len(ns),
    row("candidates", lambda n: summary[str(n)]["candidates"]),
    row("discarded, each with a certificate", lambda n: summary[str(n)]["certificates"]),
    row("kept: the list $L_n$", lambda n: len(L[n])),
    row("… with five colours or fewer", lambda n: sum(max(p) + 1 <= 5 for p in L[n])),
    row("… with six colours", lambda n: sum(max(p) + 1 == 6 for p in L[n])),
])))

t0 = time.time()
kept = {n: set(L[n]) for n in ns}
for n in ns:
    level = summary[str(n)]
    assert len(kept[n]) == len(L[n]) == level["kept"]
    assert level["candidates"] == level["certificates"] + level["kept"]
assert (len(four), len(raw5), kept[5]) == (summary["4"]["candidates"],
                                           summary["5"]["candidates"], set(L5))
for n in range(5, 11):
    assert all(fd.canonical(fd.subpattern(p, [v for v in range(n) if v != drop])) in kept[n - 1]
               for p in L[n] for drop in range(n))
print(f"the lists are closed under taking sub-patterns  ({time.time() - t0:.0f} s)")

patterns = fd.load_patterns(DATA / "L10.json")
assert len(patterns) == 228 and {fd.canonical(p) for p in patterns} == kept[10]
print("the 228 patterns of data/L10.json are the list for ten points")
print("number of colours -> patterns:", by_colours(patterns))

for n in (6, 7):
    sample = check.read(CERT / f"level{n}_sample.jsonl.gz")
    assert all(check.check(cert) for cert in sample)
    assert not any(fd.canonical(tuple(cert["pattern"])) in kept[n] for cert in sample)
    print(f"{n} points: {len(sample)} sampled certificates are valid,",
          f"for patterns that are not in the list")
points 4 5 6 7 8 9 10
candidates 25 1,193 537,230 14,732 1,565 635 228
discarded, each with a certificate 1 271 517,001 10,065 0 0 0
kept: the list Lₙ 24 922 20,229 4,667 1,565 635 228
… with five colours or fewer 23 678 1,620 398 157 57 19
… with six colours 1 244 18,609 4,269 1,408 578 209
the lists are closed under taking sub-patterns  (14 s)
the 228 patterns of data/L10.json are the list for ten points
number of colours -> patterns: {5: 19, 6: 209}
6 points: 400 sampled certificates are valid, for patterns that are not in the list
7 points: 200 sampled certificates are valid, for patterns that are not in the list

The shape of the table tells the story. Few points with six colours are almost unconstrained, so the number of patterns explodes at six points. From seven points on the constraints win. From eight points on no candidate has a certificate, so nothing is discarded, and the lists shrink to 228 patterns at ten points. Every number in the first and third rows agrees with Table 9 of [SÖ].

Two things in this section are not computed again when the notebook runs. Both can be: download the two files of the release into the folder certificates and run the following commands there.

  • The candidates at six to ten points. python generate.py N --jobs 2 lists the candidates on N points from the list for N-1 points, and checks that each one is in the list for N points or has a certificate. The five levels take about 13 minutes on two cores. The candidates had first been listed by a different program, which shares no code with this one and takes its canonical forms from the library nauty (tools/fixed-distances/g7fin/gen in the repository); the two agree. At six points, where 98% of the discarded candidates are, the plain enumeration fd.add_a_point gives the same 537,230 as well.
  • The certificates at six and seven points. python check.py level6.jsonl.gz level7.jsonl.gz checks all 527,066 of them in about 45 minutes (--jobs K uses K cores).

How the certificates were found is described in certificates/README.md (by linear algebra: for each candidate, a search for a product of factors x_c and x_a-x_b among the combinations of minors). It plays no role in the proof. A certificate is checked, not trusted.

3.6 Why the list is complete

Proposition A. Every set of ten points in the plane with at most six distances has one of the 228 patterns in data/L10.json.

Proof. We show for n=4,…,10 that the pattern of every set X of n points with at most six distances is in Lₙ. For n=4, the list L₄ contains every pattern on four points except the one-coloured one, which has a certificate. Let n≥5. Each subset of n-1 points of X has at most six distances, so its pattern is in Lₙ₋₁ by induction; that is, the pattern of X is a candidate. Every candidate is in Lₙ or has a certificate (§3.3 for five points, §3.5 for six to ten), and by the lemma a pattern with a certificate is not the pattern of X. ∎

Note what the argument rests on: that the candidates are listed completely, which is a finite enumeration, and that each certificate is a true identity, which is a matter of multiplying polynomials. It does not use the Gröbner bases of §2.4, and it takes nothing from the literature.

4. Every ten-point core, exactly

4.1 Solving the 228 systems

For each pattern we now find all solutions of its length equations (§2.4). This is the longest computation of the proof, about four minutes on two cores, so its result (the output of fd.solve_many) is saved in data/solutions.json. The next cell solves six of the patterns again as a spot check and then loads the file; with RECOMPUTE = True it solves all 228.

t0 = time.time()
if RECOMPUTE:
    solutions = fd.solve_many(patterns)
    fd.save_solutions(DATA / "solutions.json", solutions)
    print(f"solved all 228 patterns in {time.time() - t0:.0f} s")
else:
    solutions = fd.load_solutions(DATA / "solutions.json", patterns)
    as_text = lambda sols: sorted(repr(s.lengths) for s in sols)
    for i in (0, 12, 13, 62, 142, 200):
        assert as_text(fd.solve_lengths(patterns[i])) == as_text(solutions[i]), i
    print("loaded the saved solutions; six patterns solved again and compared",
          f" ({time.time() - t0:.0f} s)")
loaded the saved solutions; six patterns solved again and compared  (6 s)

Pattern 12 shows why the device of §2.3 is needed. Its equations alone have infinitely many solutions, a whole curve of them on which several lengths are zero. Only after excluding collapsed solutions does a single one remain.

xs, eqs = fd.planarity_equations(patterns[12])
G = sp.groebner(eqs, *xs, order="grevlex", domain=sp.QQ)
print(f"pattern 12: {len(eqs)} equations in {len(xs)} unknowns")
print("finitely many solutions before excluding collapses?", G.is_zero_dimensional)
print("two members of the Gröbner basis:",
      [sp.factor(g) for g in G.exprs if len(sp.Poly(g, *xs).terms()) == 2][:2])
print("solutions with non-zero, pairwise different lengths:",
      [tuple(map(str, s.lengths)) for s in solutions[12]])
pattern 12: 44 equations in 5 unknowns
finitely many solutions before excluding collapses? False
two members of the Gröbner basis: [x1*(13*x1 - 3)/13, x1*(13*x2 - 7)/13]
solutions with non-zero, pairwise different lengths: [('1', '3/13', '7/13', '1/13', '9/13', '4/13')]

4.2 Every solution is a point set

Loading a file proves nothing by itself, so the next cell checks the saved solutions directly. For each solution and each root of its number field it requires that the root is real, that all squared lengths are positive and pairwise different, that the points can be rebuilt in a Euclidean plane, and that all 45 distances come out right (this is inside realisation, via place). This is exact and takes a second.

cores = []                            # (pattern number, solution, root), one per realisation
for i, sols in enumerate(solutions):
    assert sols, f"pattern {i} has no solution"
    for sol in sols:
        degree = sol.field.deg if sol.field else 1
        assert (sol.field.real_roots if sol.field else 1) == degree   # all roots are real
        assert len(set(sol.lengths)) == max(patterns[i]) + 1          # lengths all different
        for root in range(degree):
            conf = sol.realisation(root)                              # None if not a point set
            assert conf is not None
            assert fd.pattern_of(conf.points, conf.d2) == fd.rename(patterns[i])
            cores.append((i, sol, root))

tally = lambda counter: dict(sorted(counter.items()))
per_pattern = Counter(i for i, _, _ in cores)
degrees = Counter((sol.field.deg if sol.field else 1) for sols in solutions for sol in sols)
print(len(cores), "solutions in all; every one is a planar point set with exactly its pattern")
print("solutions per pattern -> number of patterns:", tally(Counter(per_pattern.values())))
print("degree of the number field -> number of fields:", tally(degrees))
282 solutions in all; every one is a planar point set with exactly its pattern
solutions per pattern -> number of patterns: {1: 199, 2: 20, 3: 1, 4: 3, 5: 2, 6: 3}
degree of the number field -> number of fields: {1: 199, 2: 22, 3: 1, 4: 2, 5: 2, 6: 3}

Proposition B. Each of the 228 patterns is realised in the plane, in only finitely many ways: there are 282 solutions in all (for the fixed numbering of points and unit colour), and every one of them is a genuine planar point set.

The first half is the converse of Proposition A: the list has no superfluous entry. The second half says that every ten-point set with at most six distances is similar to one of 282 explicitly known point sets. (As in §2.2, several solutions can be the same shape.)

Two things are perhaps unexpected. All 228 patterns are rigid, although nothing in §3 required it. And every solution of the equations is real and Euclidean; no candidate had to be thrown away. For 199 patterns the solution is unique and rational. The other 29 have irrational lengths: in ℚ(√3) or ℚ(√5) for 21 of them, and in fields of degree 3 to 6 for the remaining eight, among them the fields of the regular 9-, 11- and 13-gons.

4.3 Solutions and shapes

As in §2.2, different solutions can be the same shape. Two realisations are similar exactly when, after dividing all lengths by the shortest one, the two tables of distances agree up to renumbering the points. fd.shape_key computes a key that decides this: the list of length ratios in increasing order, each identified as a real number independently of how it is written (by its minimal polynomial and the position of the number among that polynomial's real roots), together with the canonical form of the pattern in which every colour is named by the rank of its length.

shapes = {}
for i, sol, root in cores:
    shapes.setdefault(fd.shape_key(sol, root), []).append(i)

assert all(len(set(ids)) == 1 for ids in shapes.values())    # similar sets share their pattern
print(len(shapes), "shapes;  number of distances -> shapes:",
      tally(Counter(max(patterns[ids[0]]) + 1 for ids in shapes.values())))
print("shapes per pattern -> number of patterns:",
      tally(Counter(Counter(ids[0] for ids in shapes.values()).values())))
257 shapes;  number of distances -> shapes: {5: 19, 6: 238}
shapes per pattern -> number of patterns: {1: 214, 2: 9, 4: 2, 5: 1, 6: 2}

Corollary. Up to similarity there are exactly 257 sets of ten points in the plane with at most six distances: 19 with five distances and 238 with six.

Most patterns have a single shape. Fourteen have several; these are patterns with many symmetries, such as ten corners of a regular 13-gon, where the same combinatorial pattern fits chords of different lengths.

4.4 A gallery

One realisation of each of the 228 patterns, in the order of the file.

gallery = []
for i, sols in enumerate(solutions):
    sol = sols[0]
    conf = sol.realisation(sol.embeddings[0])
    colour = fg.INK if sol.field is None else fg.ACCENT
    gallery.append(fg.panel(conf.xy(), segments="shortest", title=str(i), title_size=8.5,
                            box=74, margin=12, radius=2.3, width=1.1, fill=colour))
fg.figure(gallery, columns=12, gap=4)
0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227

One realisation of each pattern, with its number in the file. Segments join points at the shortest distance. Black: all ratios of squared lengths are rational (199 patterns). Orange: irrational lengths (29 patterns).

5. Ten points are enough

Now the geometric step: why does a 16-point set with seven distances contain a ten-point set with six? The idea goes back to Erdős and Fishburn: remove points until the largest distance disappears.

5.1 The diameter graph

Let X be a finite set of points in the plane and D its largest distance. Join two points of X when they are at distance D. The result is the diameter graph; let X_D be the set of points that lie on at least one of its edges, and m=|X_D|.

If I⊆ X_D contains no edge of the diameter graph (an independent set), then A = I∪(X∖ X_D) contains no pair at distance D. So if X has at most seven distances, A has at most six, and |A| = |X| - m + |I|. We want |A|≥ 10, so we need m to be small and I to be large.

The picture shows the diameter graphs of E₁ and E₂ and, for each, an independent set I (the grey points are the ones removed).

def diameter_graph(points, d2):
    D = max(d2(p, q) for p, q in combinations(points, 2))
    return [(i, j) for i, j in combinations(range(len(points)), 2)
            if d2(points[i], points[j]) == D]

def independent_set(edges):
    "Greedy: keep an endpoint of smallest degree, delete it and its neighbours, repeat."
    nbrs = {}
    for i, j in edges:
        nbrs.setdefault(i, set()).add(j)
        nbrs.setdefault(j, set()).add(i)
    kept = []
    while nbrs:
        v = min(nbrs, key=lambda u: (len(nbrs[u]), u))
        kept.append(v)
        for u in [*nbrs[v], v]:
            for z in nbrs.pop(u):
                if z in nbrs:
                    nbrs[z].discard(u)
    return kept

panels = []
for name, E in (("E₁", E1), ("E₂", E2)):
    edges = diameter_graph(E, lattice_d2)
    ends = sorted({v for e in edges for v in e})
    keep = independent_set(edges)
    removed = [v for v in ends if v not in keep]
    A = [E[v] for v in range(16) if v not in removed]
    assert len({lattice_d2(p, q) for p, q in combinations(A, 2)}) <= 6 and len(A) >= 10
    note = f"m = {len(ends)};  {len(removed)} removed;  {len(A)} left"
    panels.append(fg.panel(fg.lattice_xy(E), segments=edges, colour_of=lambda i, j: 1,
                           box=300, width=1.6, title=name, marks={v: fg.FAINT for v in removed},
                           subtitle=note))
fg.figure(panels, legend_entries=[(1, "pairs at the largest distance, √13")])
pairs at the largest distance, √13E₁m = 7; 3 removed; 13 leftE₂m = 9; 3 removed; 13 left

The diameter graphs of E₁ and E₂. Removing the grey points leaves no pair at the largest distance.

5.2 Three facts about diameter graphs

These are classical; (i) and (ii) take a few lines each, and (iii) is proved in [W, Lemmas 3–5 and 9].

(i) Every point of X_D is a corner of the convex hull of X. If |p-q|=D, all of X lies in the disc of radius D about q and p is on its boundary circle; a point of a disc that lies on the boundary circle is not between two other points of the disc.

(ii) Any two edges of the diameter graph meet (in a common endpoint or in a crossing). If pq and rs were disjoint segments of length D, one of the distances between their endpoints would exceed D. (Hopf and Pannwitz, 1934.)

(iii) The diameter graph has no cycle of even length and at most one cycle. If it is not a single cycle through all m points of X_D, it has an independent set of size at least ⌈ m/2⌉. If it is a single cycle, m is odd and taking every other point gives (m-1)/2.

5.3 At most 13 points lie on diameters

Lemma C. If X has 16 points and at most seven distances, then m≤13.

The proof is short, and it uses a classical theorem about convex polygons:

Theorem (Altman 1963; Fishburn 1995). A convex polygon with h corners determines at least ⌊ h/2⌋ distances. If it determines exactly ⌊ h/2⌋, it is a regular h-gon when h is odd, and a regular h-gon or a regular (h+1)-gon with one corner removed when h≥ 8 is even.

Proof of Lemma C. Let h be the number of corners of the convex hull of X. By (i), m≤ h, and by the theorem ⌊ h/2⌋≤7, so h≤15. Suppose h≥14. Then the corners already determine seven distances, so they form a regular 15-gon R₁₅, a regular 14-gon R₁₄, or R₁₅ minus a corner; scale the circumradius to 1. All seven distances of X are chord lengths of this polygon. X has a point q that is not a corner; it lies in the polygon, so r=|q|<1.

q is not the centre: its distance to the corners would be 1, and a chord 2sin(π j/n) equals 1 only if n=6j; but n is 14 or 15.

q is not another point: a circle about q is not the circumcircle, so it passes through at most two corners. Then the h distances from q to the corners take each value at most twice, hence at least h/2 values. For h=15 that is eight values, too many. For h=14 each of the seven chord lengths occurs exactly twice, so the squared distances from q to the corners add up to twice the sum S of the seven squared chord lengths. On the other hand Σ_v|q-v|²=14(1+r²)-2 q·Σ_v v. For R₁₄: Σ_v v=0 and S=16, so 14(1+r²)=32 and r²=9/7>1. For R₁₅ minus the corner v₀: Σ_v v=-v₀ and S=15, so 7r²+q· v₀=8; but q· v₀≤ r<1 gives 7r²+q· v₀<8. Both are impossible, so h≤13. ∎

The two sums S follow from 4sin²θ=2-2cos2θ; the next cell confirms them.

import math
for n in (14, 15):
    S = sum((2 * math.sin(math.pi * j / n)) ** 2 for j in range(1, 8))
    print(f"regular {n}-gon, circumradius 1: the seven squared chord lengths add up to",
          f"{S:.12f}")
regular 14-gon, circumradius 1: the seven squared chord lengths add up to 16.000000000000
regular 15-gon, circumradius 1: the seven squared chord lengths add up to 15.000000000000

5.4 Thirteen points on a cycle

Fact (iii) gives a small independent set in one case only: when the diameter graph is a single cycle through m=13 points. Then the 13 points are very special.

Lemma D. Thirteen points whose diameter graph is a single 13-cycle and which determine at most seven distances are the corners of a regular 13-gon.

Proof. Scale the diameter to 1. By fact (i) the points are corners of their convex hull; number them p₀,…,p₁₂ counterclockwise, indices modulo 13. Seen from any corner p_y, the other corners p_y+1,…,p_y+12 appear in counterclockwise order within an angle less than π.

1. The diameters. Let pₓp_y be a diameter. Removing pₓ,p_y from the cycle leaves a path through the other eleven points, and by fact (ii) each of its edges crosses the segment pₓp_y. So the path alternates between the two sides of the line pₓp_y, which contain 6 and 5 of its points. Hence y-xequiv±6, and each p_y is joined exactly to p_y+6 and p_y+7=p_y-6.

2. Monotone chains. For 1≤ k≤5: |p_y-p_y+k|<|p_y-p_y+k+1|. Indeed p_y+k+7 is at distance 1 from p_y+k and from p_y+k+1, so it lies on the perpendicular bisector of that side; this line cuts the polygon between the midpoint of the side and p_y+k+7, and p_y lies on the side of p_y+k. So from every corner the six distances |p_y-p_y+k|, k=1,…,6, increase, the last being 1. With six distances in all, the chords of each step k (pairs {p_y,p_y+k}) all have the same length. With seven, delta₁<…<delta₇=1, a chord of step k is deltaₖ or deltaₖ₊₁: the chords of each step take at most two values.

3. Apex angles. Let gamma_y be the angle at p_y of the isosceles triangle p_yp_y+6p_y+7 (legs 1, base a side, so gamma_y<π/3). With complex numbers and w_y=p_y+6-p_y we have p_y+7-p_y=e^igamma_yw_y=-w_y+7. From this:

  • the side pⱼpⱼ₊₁ (the base of the triangle at pⱼ₊₇) has length s(gammaⱼ₊₇), where s(t)=2sin(t/2);
  • the exterior angle at pⱼ is varepsilonⱼ=gammaⱼ+1/2(gammaⱼ₊₆+gammaⱼ₊₇); summing, Σgamma_y=π.

If all sides are equal, all gamma_y and all exterior angles are equal, and the polygon is regular. Otherwise there are seven distances, and the gamma_y take two values alpha<beta; since they add up to π, alpha<π/13<beta. Read them in the cyclic order gamma₀,gamma₇,gamma₁₄,… (gamma_y is followed by gamma_y+7).

4. Two chord formulas. For two consecutive terms (A,B)=(gammaₓ₊₁₂,gammaₓ₊₆) and three consecutive terms (A,B,C)=(gammaⱼ₊₆,gammaⱼ,gammaⱼ₊₇),

|pₓ-pₓ₊₅|²=f(A,B)=1-8sintfrac A2sintfrac B2costfracA+B2, |pⱼ₋₁-pⱼ₊₁|²=F(A,B,C)=s(A)²+s(C)²+2s(A)s(C)cos(B+tfracA+C2).

The first is |1-e^-iA+e^-i(A+B)|² (three unit diameters in a row); the second is the law of cosines for two consecutive sides.

5. Not both alphaalpha and betabeta. If both pairs occur as consecutive terms, then f(alpha,alpha)>f(alpha,beta)>f(beta,beta): by sinfrac x2cosfraca+x2=frac12(sin(x+frac a2)-sinfrac a2) the two differences are 4sinfracalpha2(sin(beta+fracalpha2)-sinfrac3alpha2) and 4sinfracbeta2(sinfrac3beta2-sin(alpha+fracbeta2)), both positive because 2alpha+beta<π and alpha+2beta<π here. Three values for the chords of step 5: impossible. As 13 is odd, exactly one of alphaalpha, betabeta occurs.

6. The chords of step 2. F(A,B,A)=4s(A)²cos²fracA+B2, and F increases in A and in C as long as A+C<π and B+fracA+C2≤fracπ2 (the derivative is at least s(C)(2cosfrac C2-2sinfrac A2)).

  • No betabeta: then alphabetaalpha and alphaalphabeta occur, and alphaalphaalpha or betaalphabeta (not every run of alpha's has length 2, as 13 is not a multiple of 3); and F(alpha,beta,alpha)<F(alpha,alpha,alpha)<F(alpha,alpha,beta)<F(beta,alpha,beta).
  • No alphaalpha: then betaalphabeta and betabetaalpha occur, and betabetabeta or alphabetaalpha; and F(alpha,beta,alpha)<F(beta,beta,alpha)<F(beta,beta,beta)<F(beta,alpha,beta).

Either way the chords of step 2 take three values, which is impossible. So all sides are equal, and the polygon is regular. ∎

The paper (paper/seven-distances.pdf, Lemma 11) checks the side conditions of each inequality in detail. The next cell confirms the four identities used above symbolically.

A, B, C, a, x = sp.symbols("A B C a x", real=True)
s = lambda t: 2 * sp.sin(t / 2)
z = 1 - sp.exp(-sp.I * A) + sp.exp(-sp.I * (A + B))          # three unit diameters in a row
f = 1 - 8 * sp.sin(A / 2) * sp.sin(B / 2) * sp.cos((A + B) / 2)
F = s(A)**2 + s(C)**2 + 2 * s(A) * s(C) * sp.cos(B + (A + C) / 2)
eps = B + (A + C) / 2
identities = {
    "|1 - e^(-iA) + e^(-i(A+B))|^2 = f(A, B)": sp.expand(z * sp.conjugate(z)) - f,
    "F(A, B, A) = 4 s(A)^2 cos^2((A+B)/2)": F.subs(C, A) - 4 * s(A)**2 * sp.cos((A + B) / 2)**2,
    "dF/dC = 2cos(C/2)(s(C) + s(A)cos e) - s(A)s(C)sin e": sp.diff(F, C)
        - (2 * sp.cos(C / 2) * (s(C) + s(A) * sp.cos(eps)) - s(A) * s(C) * sp.sin(eps)),
    "sin(x/2)cos((a+x)/2) = (sin(x + a/2) - sin(a/2))/2": sp.sin(x / 2) * sp.cos((a + x) / 2)
        - (sp.sin(x + a / 2) - sp.sin(a / 2)) / 2,
}
for name, difference in identities.items():
    print(name, "  holds:", sp.simplify(difference.rewrite(sp.exp)) == 0)
|1 - e^(-iA) + e^(-i(A+B))|^2 = f(A, B)   holds: True
F(A, B, A) = 4 s(A)^2 cos^2((A+B)/2)   holds: True
dF/dC = 2cos(C/2)(s(C) + s(A)cos e) - s(A)s(C)sin e   holds: True
sin(x/2)cos((a+x)/2) = (sin(x + a/2) - sin(a/2))/2   holds: True

5.5 The reduction

Proposition E. Every set X of 16 points in the plane with at most seven distances contains ten points with at most six distances.

Proof. By Lemma C, m≤13.

case independent set I | A| = 16-m+| I|
diameter graph is not a single cycle through X_D | I|≥⌈ m/2⌉ ≥ 16-⌊ m/2⌋≥ 16-6=10
a single cycle, m≤ 11 (then m is odd) | I|=(m-1)/2 =16-(m+1)/2≥ 16-6=10
a single cycle, m=13 — see below

In the first two cases A=I∪(X∖ X_D) has no pair at the largest distance, hence at most six distances, and at least ten points. In the last case X_D is a 13-point set with at most seven distances whose diameter graph is a 13-cycle, so by Lemma D it is a regular 13-gon. A regular 13-gon has only six distances, so any ten of its corners will do. ∎

We call such a ten-point subset a core of X. By Propositions A and B, a core is similar to one of the 282 point sets of §4. Nothing else about the core will be used; in particular not that it avoids the largest distance.

6. Growing a core

Fix one of the 282 point sets as the core K, with its set Δ of five or six squared distances. We look for all ways to add six points so that the 16 points have at most seven distances. At most b = 7-|Δ| new distances may appear in total, so b is 1 or 2; call it the budget.

6.1 Where can a new point be?

Let y be a point to be added, and look at its ten distances to the points of K. At most b different new values occur among them.

  • Some value occurs three times. Then y is equidistant from three points of K, so it is the centre of the circle through them (and they are not collinear).
  • Every value occurs at most twice. Then at most 2b of the ten distances are new, so at least 10-2b of them are old (they lie in Δ). It will turn out that no core has more than five collinear points, and 10-2b≥6; so among the points of K at old distance from y there are three non-collinear ones, u,v,w, with squared distances r,s,t∈Δ to y.

In both cases y is determined by three non-collinear points of K and three numbers. Subtracting |y-u|²=r from |y-v|²=s cancels the quadratic term and leaves a linear equation,

2 ⟨ y, v-u⟩ = |v|²-|u|²+r-s,

and the same with w,t. Two independent linear equations determine y. (For the circle centre take r=s=t.) So the candidates are:

  • the circle centres of all non-collinear triples of K, and
  • for suitable triples (u,v,w) and all (r,s,t)∈Δ³, the solution y of the two linear equations.

Suitable means: a family of non-collinear triples such that any 10-2b points of K contain one of them. All 120 triples would do; a handful suffices, and fd.anchor_triples chooses them greedily. Each candidate is then tested directly: compute its ten distances to K and keep it if at most b new values occur.

show(fd.candidate_points)
def candidate_points(conf, budget, exhaustive=False):
    """Every point of the plane that can be added to `conf` creating at most `budget` new
    squared distances *to the points of conf*.  Returns {point: set of new distances}.

    Why the list is complete (n = number of points of conf, at most 5 of them collinear is
    checked by anchor_triples):  look at the n distances from a new point y.
      * If some value occurs three times, y is the circumcentre of three points of conf.
      * Otherwise each new value occurs at most twice, so at least n - 2*budget distances
        are old; any n - 2*budget points of conf contain an anchor triple T, and y is
        determined by its (old) distances to T.
    exhaustive=True uses all non-collinear triples instead of the anchor triples (slower;
    the result must be the same, which is a test of the argument)."""
    old = conf.distances()
    lengths = sorted(old, key=repr)
    pts, n = conf.points, len(conf.points)
    seen, good = set(pts), {}
    all_triples = [T for T in combinations(range(n), 3)
                   if not conf.collinear(*(pts[i] for i in T))]
    anchors = all_triples if exhaustive else anchor_triples(conf, n - 2 * budget)

    def consider(y):
        if y in seen:
            return
        seen.add(y)
        new = set()
        for p in pts:
            d = conf.d2(y, p)
            if d not in old:
                new.add(d)
                if len(new) > budget:
                    return
        good[y] = frozenset(new)

    zero = lengths[0] - lengths[0]
    for T in all_triples:                      # circumcentres
        consider(_locate(conf, T, zero, zero, zero))
    for T in anchors:                          # points at old distances from an anchor triple
        for r, s, t in product(lengths, repeat=3):
            consider(_locate(conf, T, r, s, t))
    return good

An example: the first pattern in the list. Its unique realisation has six distances, so the budget is 1.

i, sol, root = cores[0]
K0 = sol.realisation(root)
budget = 7 - len(K0.distances())
candidates, subsets = fd.grow(K0, budget)
print(f"core 0: {len(K0.distances())} distances, budget {budget};",
      "anchor triples:", fd.anchor_triples(K0, 10 - 2 * budget))
print(f"{len(candidates)} candidate points;  number of added points -> number of ways:",
      dict(sorted(Counter(map(len, subsets)).items())))
# using all 120 triples instead of the anchor triples gives the same candidates
assert set(candidates) == set(fd.candidate_points(K0, budget, exhaustive=True))

six = [s for s in subsets if len(s) == 6]
rings = [(x, y, "ring") for x, y in K0.xy(candidates)]
dots = [(x, y, "dot") for x, y in K0.xy([candidates[j] for j in six[0]])]
fg.figure([fg.panel(K0.xy(), segments="shortest", box=300, extra=rings,
                    title="the core and its candidate points"),
           fg.panel(K0.xy(), segments="shortest", box=300, extra=dots,
                    title=f"one of the {len(six)} ways to reach 16 points")])
core 0: 6 distances, budget 1; anchor triples: [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
9 candidate points;  number of added points -> number of ways: {0: 1, 1: 9, 2: 33, 3: 63, 4: 66, 5: 36, 6: 8}
the core and its candidate pointsone of the 8 ways to reach 16 points

Black: the ten points of the core. Rings: the only positions where a point can be added. Orange dots: six of them that fit together.

6.2 Which candidates fit together?

Candidates were tested one at a time against the core. A set of candidates must also get along with each other: the distances between added points count, and all new values together must stay within the budget. fd.grow runs a depth-first search that adds candidates one by one and keeps track of the set of new values; as soon as it has more than b elements, the branch is abandoned (adding more points can only add more values). This enumerates all admissible sets of added points, of every size.

6.3 All cores

By the conjugation principle of §2.5 the search gives the same result at all roots of a number field, because it only ever asks whether two numbers are equal. So it is run once for each of the 229 solutions-with-field and its result is counted once for each of the real roots. This takes under a minute.

t0 = time.time()
E_PALETTE = [1, 3, 4, 7, 9, 12, 13]
largest, completions, max_collinear, proportional = Counter(), Counter(), 0, set()

for i, sols in enumerate(solutions):
    for sol in sols:
        K = fd.place(sol.pattern, sol.lengths)     # exact coordinates, valid at every root
        on_a_line = max(sum(K.collinear(p, q, r) for r in K.points)
                        for p, q in combinations(K.points, 2))
        max_collinear = max(max_collinear, on_a_line)
        budget = 7 - len(K.distances())
        candidates, subsets = fd.grow(K, budget)   # fails if 10 - 2·budget points are on a line
        n_roots = len(sol.embeddings)
        largest[10 + max(map(len, subsets))] += n_roots
        for s in subsets:
            if len(s) == 6:
                completions[i] += n_roots
                full = K.with_points(candidates[j] for j in s)
                proportional.add(fd.proportional(full.distances(), E_PALETTE))

print(f"all cores extended in {time.time() - t0:.0f} s")
print("at most", max_collinear, "points of a core are collinear")
print("largest number of points reached -> number of cores:", tally(largest))
print(len(completions), "patterns have a core that reaches 16 points;",
      sum(completions.values()), "ways in all")
print("every 16-point result has squared distances proportional to 1, 3, 4, 7, 9, 12, 13:",
      proportional == {True})
assert max(largest) == 16 and sum(largest.values()) == len(cores) and proportional == {True}
all cores extended in 44 s
at most 5 points of a core are collinear
largest number of points reached -> number of cores: {10: 11, 11: 10, 12: 18, 13: 28, 14: 18, 15: 12, 16: 185}
185 patterns have a core that reaches 16 points; 826 ways in all
every 16-point result has squared distances proportional to 1, 3, 4, 7, 9, 12, 13: True

Proposition F. No core can be extended to 17 points with at most seven distances. A core can be extended to 16 points only if it has one of 185 patterns, and then the seven squared distances of the 16-point set are proportional to 1,3,4,7,9,12,13.

Two remarks. The 826 ways are counted with the core fixed; one 16-point set contains many cores, so this is not a count of shapes. And the first sentence gives the bound g(7)≤16: a 17-point set with at most seven distances would contain a 16-point one, hence a core (Proposition E), and that core would have a seven-point extension. The end of §7 checks the same bound in a second, more direct way.

7. Sixteen points with squared distances 1, 3, 4, 7, 9, 12, 13

What remains is a finite problem of a simpler kind: find all 16-point sets whose squared distances all lie in the list P={1,3,4,7,9,12,13} (after scaling). The method of §6.1 works again, with a triangle in place of the core.

Such a set is not collinear (16 points on a line have 15 different distances from an endpoint), so it contains a genuine triangle. Its squared sides a≤ b≤ c belong to P. Place the triangle; every other point of the set has squared distances (r,s,t)∈ P³ to its corners, and by the two linear equations of §6.1 that determines the point. So for each of the possible triangles there are at most 7³ candidate points, and we need 13 of them that are pairwise at distances in P. Each set found is identified by the canonical form of its full table of distances, which decides congruence.

The search knows nothing about lattices.

t0 = time.time()
found = fd.sets_with_distances(E_PALETTE, 16)
print(f"{len(found)} sets up to congruence  ({time.time() - t0:.0f} s)")

def lattice_set(E):
    "Lattice points as an exact Configuration: basis 1, ω with <1,1> = <ω,ω> = 1, <1,ω> = 1/2."
    return fd.Configuration([(Fraction(a), Fraction(b)) for a, b in E],
                            Fraction(1), Fraction(1), Fraction(1, 2))

names = {fd.congruence_key(lattice_set(E))[1]: name for name, E in (("E₁", E1), ("E₂", E2))}
assert set(found) == set(names) and len(names) == 2
fg.figure([fg.panel(conf.xy(), segments="shortest", box=300,
                    title=f"found by the search: congruent to {names[key]}")
           for key, conf in sorted(found.items(), key=lambda item: names[item[0]])])
2 sets up to congruence  (2 s)
found by the search: congruent to E₁found by the search: congruent to E₂

The two sets as the search produced them, in the coordinates of the triangle it started from.

E₁ and E₂ are not similar to each other: they have the same seven distances, but the squared distance 4 occurs 20 times in E₁ and 18 times in E₂ (first cell). This completes the proof.

Theorem. A set of 16 points in the plane with at most seven distinct distances is similar to E₁ or to E₂.

Proof. Let X be such a set. By Proposition E it contains a core; by Propositions A and B the core is similar to one of the 282 point sets of §4; X is that core with six points added, so by Proposition F its squared distances are proportional to 1,3,4,7,9,12,13; and by the computation above X is then similar to E₁ or E₂. ∎

Seventeen points

The theorem also says what happens one point further.

Corollary. Seventeen points in the plane determine at least eight distinct distances.

Proof. Let X be a set of 17 points with at most seven distances, and y one of its points. By the theorem the other 16 points form a copy of E₁ or E₂; apply the similarity, so that X=Eₖ∪{y}. Now Eₖ has seven distances already, so y may not bring a new one: its squared distances to all 16 points lie in P.

Write y=a+b ω with real a,b. The lattice points 0, 1 and ω belong to both sets; let r,s,t∈ P be the squared distances from y to them. Subtracting, as in §6.1, leaves the two linear equations 2a+b=1+r-s and a+2b=1+r-t, so

a=1/3 (1+r-2s+t), b=1/3 (1+r+s-2t).

So y is one of at most 7³=343 points, and the next cell tries each of them against each of the two sets. None is at an admissible distance from all 16 points. ∎

P = set(E_PALETTE)
for name, E in (("E1", E1), ("E2", E2)):
    assert {(0, 0), (1, 0), (0, 1)} <= set(E)
    fits = {}                      # position -> number of points of E at an admissible distance
    for r, s, t in product(P, repeat=3):                # squared distances from y to 0, 1 and ω
        a, b = Fraction(1 + r - 2*s + t, 3), Fraction(1 + r + s - 2*t, 3)
        fits[a, b] = sum(norm(a - p, b - q) in P for p, q in E)
    near = sorted(f"({a}, {b})" for (a, b), n in fits.items() if n == 15 and (a, b) not in E)
    print(f"{name}: {len(fits)} positions;  at an admissible distance from all 16 points:",
          sum(n == 16 for n in fits.values()))
    print(f"    from 15 of them: the 16 points of {name} themselves, and", ", ".join(near))
    assert max(fits.values()) == 15 and sum(n == 15 for n in fits.values()) == 16 + 3
E1: 265 positions;  at an admissible distance from all 16 points: 0
    from 15 of them: the 16 points of E1 themselves, and (0, 2), (2, -2), (2, 0)
E2: 265 positions;  at an admissible distance from all 16 points: 0
    from 15 of them: the 16 points of E2 themselves, and (-2, 2), (0, -2), (2, 0)

So E₁ and E₂ are the largest sets with seven distances. The second line of the output shows how narrowly a 17th point fails. Apart from the points of Eₖ themselves (at distance 0 from one point), three positions are at an admissible distance from 15 of the 16 points: the three corners of the hexagon { |z|²=4 } of lattice points that are not in Eₖ. Each is at squared distance 16 from the opposite corner, and both sets contain exactly one corner of each opposite pair.

This is the bound g(7)≤16 for the second time: Proposition F gave it before the two sets were known.

8. Fifteen points

The same tools settle the next row of the table: fifteen points with seven distances. Here is the answer.

Theorem. Up to similarity there are exactly sixteen sets of fifteen points in the plane with at most seven distances: the regular 15-gon; the fourteen sets obtained by deleting one point from E₁ or from E₂ (one of them arises from both); and one more piece of the triangular lattice, F below, which is not contained in any sixteen-point set with seven distances.

8.1 Nine points suffice

The diameter-graph argument of §5 works with fifteen points too, but it only guarantees nine points without the largest distance.

Lemma G. Every set X of 15 points with at most seven distances is the regular 15-gon or contains nine points with at most six distances.

Proof. The argument of Lemma C shows more than was stated there: a set with at most seven distances whose convex hull has 14 or more corners consists of those corners alone, and is R₁₅, R₁₄ or R₁₅ minus a corner. So if X is not R₁₅, its hull has at most 13 corners and m≤13. As in Proposition E, an independent set gives |A| = 15-m+|I|: at least 15-⌊ m/2⌋≥9 if the diameter graph is not a single cycle, 15-(m+1)/2≥9 for a single cycle with m≤11, and for a 13-cycle Lemma D makes X_D a regular 13-gon, any nine of whose corners have six distances. ∎

The regular 15-gon is a genuine exception: no nine of its corners avoid any one of its seven distances.

# the chord of step k joins corners i and i + k of the regular 15-gon (k = 1, ..., 7)
def avoids(S, k):
    return all((b - a) % 15 not in (k, 15 - k) for a, b in combinations(S, 2))

nine = [S for S in combinations(range(15), 9) if any(avoids(S, k) for k in range(1, 8))]
print("sets of nine corners of the regular 15-gon with at most six distances:", len(nine))
sets of nine corners of the regular 15-gon with at most six distances: 0

8.2 The nine-point sets

By Proposition A (its induction covers n=9), a nine-point set with at most six distances has one of the 635 patterns of L₉ (certificates/L9.json). They were solved like the 228 patterns of §4; the result is saved in fifteen/solutions9.json, and the next cell checks it: every saved solution is rebuilt as a point set (or found to have no real realisation). Two patterns behave differently: their equations have a whole curve of solutions. fifteen.family checks that the Gröbner basis of such a pattern is linear equations plus one conic, and that its parametrisation of the conic solves them.

sys.path.insert(0, "fifteen")
import fifteen as ft                          # fifteen/fifteen.py

t0 = time.time()
L9 = ft.load_L9()
sol9 = ft.solve_all(L9, Path("fifteen") / "solutions9.json")
flexible = [i for i, x in enumerate(sol9) if x is None]
realised = sum(len(sol.embeddings) for x in sol9 if x for sol in x)
print(f"{len(L9)} patterns: {len(L9) - len(flexible)} with finitely many solutions, which give",
      f"{realised} point sets  ({time.time() - t0:.0f} s)")
for i in flexible:
    lengths, note = ft.family(L9[i], i)
    print(f"pattern {i} is flexible; squared lengths", ", ".join(map(str, lengths)))
    print("    the parametrisation covers", note)
635 patterns: 633 with finitely many solutions, which give 811 point sets  (3 s)
pattern 124 is flexible; squared lengths 1, (s**2 + 6*s + 21)/(s**2 + 3), (s**2 + 6*s + 9)/(s**2 + 3), 12/(s**2 + 3), (s**2 + 12*s + 39)/(s**2 + 3)
    the parametrisation covers every solution except x3 = 0 (a zero length), the limit s -> infinity
pattern 520 is flexible; squared lengths 1, (s**2 - 2*s + 1)/4, (s**2 + 2*s + 1)/4, (s**2 + 3)/4, (3*s**2 + 1)/4, s**2
    the parametrisation covers every solution (s = +-sqrt(x5) covers both branches)

8.3 Adding six points

Each nine-point set K is extended by six points, with budget 7-|Δ(K)|, exactly as in §6; ft.extend returns the shapes of all fifteen-point sets found. Two details differ from §6.

  • Three nine-point sets have only four distances (budget 3) and contain collinear triples, so a point added at old distances to three collinear points is not determined by them. The other six points are then at new distances, three values each taken twice, and the point lies on perpendicular bisectors of pairs; ft.candidate_points handles this case.
  • For the two families K(s) the parameter is kept symbolic: no candidate point works for every s, and the values of s at which one can work are roots of finitely many polynomials (344 irreducible ones with real roots). At each root, K(s₀) is extended like a rigid set.

The complete run, python fifteen/fifteen.py --jobs 2, takes about 16 minutes and writes fifteen/result.json. The next cell repeats it for a random sample of 60 nine-point sets and the three with four distances.

import random

palette = tuple(("Q", Fraction(v)) for v in E_PALETTE)
tasks = [(i, k) for i, x in enumerate(sol9) if x for k in range(len(x))]
four = [(i, 0) for i, x in enumerate(sol9) if x and max(L9[i]) + 1 == 4]
random.seed(15)
t0 = time.time()
found15 = set()
for i, k in random.sample(tasks, 60) + four:
    shapes15, _ = ft.extend(sol9[i][k])
    found15 |= set(shapes15)
print(f"{len(found15)} fifteen-point shapes from {60 + len(four)} nine-point sets",
      f"({time.time() - t0:.0f} s); squared distances proportional to {E_PALETTE}:",
      all(key[0] == palette for key in found15))
15 fifteen-point shapes from 64 nine-point sets (16 s); squared distances proportional to [1, 3, 4, 7, 9, 12, 13]: True

8.4 Fifteen points with squared distances 1, 3, 4, 7, 9, 12, 13

As in §7, every fifteen-point set found has squared distances proportional to 1,3,4,7,9,12,13, and the search of §7 lists all fifteen-point sets with these squared distances. It finds fifteen. Fourteen are E₁ or E₂ minus a point; the last one is new.

t0 = time.time()
found = fd.sets_with_distances(E_PALETTE, 15)
minus = {}
for name, E in (("E1", E1), ("E2", E2)):
    for p in E:
        key = fd.congruence_key(lattice_set([q for q in E if q != p]))[1]
        minus.setdefault(key, set()).add(name)
result = json.load(open(Path("fifteen") / "result.json"))
print(f"{len(found)} fifteen-point sets with these squared distances",
      f"({time.time() - t0:.0f} s);",
      f"{len(minus)} of them are E1 or E2 minus a point,",
      f"{sum(len(v) == 2 for v in minus.values())} of these in both ways")
assert set(minus) <= set(found) and len(found) == len(result["sets"]) == 15
assert {fd.canonical(k[1], named=True) for k in found15} <= set(found)

F = [(0, 0), (1, 0), (0, 1), (1, -1), (-1, 1), (0, -1), (-1, 0), (1, 1), (2, -1), (-1, 2),
     (1, -2), (2, 0), (0, 2), (-2, 2), (2, 1)]
assert fd.congruence_key(lattice_set(F))[1] in set(found) - set(minus)
print("the remaining one is F; squared distance -> number of pairs:",
      dict(sorted(Counter(lattice_d2(p, q) for p, q in combinations(F, 2)).items())))

gallery15 = [fg.panel(fg.polygon_xy(15), segments="shortest", title="R₁₅", box=150,
                      margin=18, radius=2.8, width=1.3)]
for key, names in sorted(minus.items(), key=lambda kv: sorted(kv[1])):
    E, name = (E1, "E₁") if "E1" in names else (E2, "E₂")
    q = next(q for q in E
             if fd.congruence_key(lattice_set([z for z in E if z != q]))[1] == key)
    gallery15.append(fg.panel(fg.lattice_xy([z for z in E if z != q]), segments="shortest",
                              title=f"{name} − {q}", box=150, margin=18, radius=2.8, width=1.3))
gallery15.append(fg.panel(fg.lattice_xy(F), segments="shortest", title="F", box=150, margin=18,
                          radius=2.8, width=1.3, fill=fg.ACCENT))
fg.figure(gallery15, columns=6)
15 fifteen-point sets with these squared distances (8 s); 14 of them are E1 or E2 minus a point, 1 of these in both ways
the remaining one is F; squared distance -> number of pairs: {1: 30, 3: 21, 4: 18, 7: 21, 9: 6, 12: 3, 13: 6}
R₁₅E₁ − (-2, 1)E₁ − (-1, 0)E₁ − (-1, 1)E₁ − (-1, 2)E₁ − (0, 0)E₁ − (0, 1)E₁ − (1, 0)E₁ − (1, 1)E₁ − (-2, 2)E₁ − (-2, 0)E₂ − (-2, 1)E₂ − (-1, 0)E₂ − (-1, 1)E₂ − (0, 0)F

The sixteen fifteen-point sets with seven distances. Segments join points at the shortest distance; the title says which point of E₁ or E₂ was deleted (in triangular coordinates). F, in orange, is the one that is not part of a sixteen-point set.

8.5 A second route

All fifteen of these sets contain a ten-point core (only R₁₅ does not), so the extension search of §6, asked for five added points instead of six, must find exactly them. It does. This takes about a minute and uses none of the nine-point machinery.

t0 = time.time()
from_cores = set()
for i, sols in enumerate(solutions):
    for sol in sols:
        K = fd.place(sol.pattern, sol.lengths)
        cands, comps = ft.completions(K, 7 - len(K.distances()), need=5)
        for root in sol.embeddings:
            for c in comps:
                key = ft.shape_key(K.with_points(cands[j] for j in c), root, sol.field)
                from_cores.add(key)
print(f"fifteen-point sets containing a core: {len(from_cores)} ({time.time() - t0:.0f} s);",
      "the same fifteen:", {fd.canonical(k[1], named=True) for k in from_cores} == set(found))
fifteen-point sets containing a core: 15 (48 s); the same fifteen: True

This proves the theorem, given the full run of fifteen/fifteen.py (the nine-point sets not in the sample, and the two families). The paper (paper/seven-distances.pdf, section 8) has the details.

9. A check from the other direction

The proof is complete, but a long computation deserves a test that could fail. Here is one that uses none of the machinery of §6.

Take E₁ and E₂ themselves and list all their ten-point subsets with at most six distances. Each is a core, so its pattern must be among the 228; and the number of ways that core extends to 16 points can be predicted: by the theorem every extension is a copy of E₁ or E₂ around the core, so

#{extensions of K} = Σ_k=1,2 frac#{subsets of Eₖ congruent to K}·#{symmetries of K}#{symmetries of Eₖ} .

If the search of §6 had missed a candidate point or a completion anywhere, or if a pattern were missing from the list, the prediction and the count of §6.3 would disagree.

index = {fd.canonical(p): i for i, p in enumerate(patterns)}

def table_of(points):
    "The squared distances of lattice points, each replaced by its rank among the values."
    values = sorted({lattice_d2(p, q) for p, q in combinations(points, 2)})
    return tuple(values.index(lattice_d2(p, q)) for p, q in combinations(points, 2)), values

classes = {}              # one entry per shape of ten-point subset with at most six distances
for k, E in enumerate((E1, E2)):
    for S in combinations(E, 10):
        ranks, values = table_of(S)
        if len(values) <= 6:
            ratios = tuple(Fraction(v, values[0]) for v in values)
            key = (ratios, fd.canonical(ranks, named=True))               # decides similarity
            if key not in classes:
                classes[key] = {"count": [0, 0], "pattern": index[fd.canonical(ranks)],
                                "symmetries": fd.symmetry_count(ranks, named=True)}
            classes[key]["count"][k] += 1

symmetries = [fd.symmetry_count(table_of(E)[0], named=True) for E in (E1, E2)]
predicted = Counter()
for c in classes.values():
    predicted[c["pattern"]] += sum(Fraction(c["count"][k] * c["symmetries"], symmetries[k])
                                   for k in (0, 1))

print("symmetries of E1, E2:", symmetries)
print(f"ten-point subsets of E1 or E2 with at most six distances: {len(classes)} shapes,",
      len(predicted), "different patterns")
print("predicted number of extensions, summed over all cores:", sum(predicted.values()))
print("prediction equals the count of §6.3 for every pattern:",
      dict(predicted) == dict(completions))
assert dict(predicted) == dict(completions)
symmetries of E1, E2: [2, 6]
ten-point subsets of E1 or E2 with at most six distances: 185 shapes, 185 different patterns
predicted number of extensions, summed over all cores: 826
prediction equals the count of §6.3 for every pattern: True

The 185 patterns and the 826 extensions of §6.3 are reproduced exactly, pattern by pattern.

10. What the proof assumes

Everything in the following list is used without being re-proved, or without being computed again, when this notebook runs. Nothing else is.

Statement Source Used in
1 A convex polygon with h corners has at least ⌊ h/2⌋ distances, and the polygons attaining the bound are as stated in §5.3. Altman 1963; Fishburn 1995; see [EF, Lemma 2] Lemma C
2 Facts (ii) and (iii) on diameter graphs. Hopf–Pannwitz 1934; [W, Lemmas 3–5, 9] Proposition E
3 The candidates on six to ten points are listed completely, and the 527,066 certificates on six and seven points are true identities. computations outside the notebook, which can be run again: certificates/generate.py (13 minutes) and certificates/check.py (45 minutes) Proposition A
4 SymPy's Gröbner-basis routines are correct. — §4.1 (that no solution of a pattern is missed)

Comments.

  • On 3. Nothing here is taken from the literature. The notebook itself carries out four and five points and checks samples of the rest (§3.3, §3.5). The candidates were listed by two programs that share no code, and by a third at six points, where 98% of the discarded candidates are. A certificate is an identity between polynomials with integer coefficients, checked by the short function shown in §3.2. All counts agree with [SÖ, Table 9], which is where the number 228 first appeared.
  • On 4. That the 282 solutions are point sets with the right patterns is checked directly in §4.2 and does not depend on SymPy's Gröbner bases. What does depend on them is that there are no further solutions. This was cross-checked outside the notebook with a different implementation (FLINT), using the planarity equations of all 210 quadruples of points: the solution sets agree for all 228 patterns.
  • Exact arithmetic. All computations are in rational numbers or number fields; signs of irrational numbers are certified by interval arithmetic with rational endpoints. No floating-point number takes part in a decision (floating point is used for drawing only).
  • The paper. The same proof is written up in paper/seven-distances.pdf (published as Hexagon 2610.00534v2), with Lemma D as its Lemma 11. Lemma C and facts (i), (ii) and the computations are as here; the only results quoted from the literature are items 1 and 2.
  • Earlier computations. The classification was first obtained with certified numerical root isolation and 100-digit arithmetic (tools/fixed-distances/g7count in the affinemess-applets repository), then by an exact computation of which this notebook is a rewrite. All three agree on every count: 228 patterns, 282 solutions, 257 shapes, 185 patterns with extendable cores, 826 extensions, two sets.

References

  • [EF] P. Erdős and P. Fishburn, Maximum planar sets that determine k distances, Discrete Mathematics 160 (1996), 115–125.
  • [SÖ] F. Szöllősi and P. R. J. Östergård, Constructions of maximum few-distance sets in Euclidean spaces, Electronic Journal of Combinatorics 27(1) (2020), #P1.23.
  • [W] X. Wei, A proof of Erdős–Fishburn's conjecture for g(6) = 13, Electronic Journal of Combinatorics 19(4) (2012), #P38.
  • E. Altman, On a problem of P. Erdős, American Mathematical Monthly 70 (1963), 148–157.
  • P. Fishburn, Convex polygons with few intervertex distances, Computational Geometry 5 (1995), 65–93.

Words used in this notebook

word meaning
pattern a colouring of the pairs of n points, up to renumbering the points and renaming the colours (§1)
rigid / flexible a pattern with finitely / infinitely many shapes (§1.4)
solution an assignment of squared lengths to the colours of a pattern, satisfying the planarity equations, for a fixed numbering and unit (§2)
shape a point set up to similarity
core ten points with at most six distances inside a 16-point set (§5.5)
budget the number of new distances that may still appear when points are added to a core (§6)
print(f"notebook ran in {time.time() - started:.0f} s")
notebook ran in 201 s