Algorithm Search⌘K

Algorithmcore

Friends-of-friends algorithm

Also called friends-of-friends halo finder.

Groups simulation particles into halos by linking every pair closer than a linking length and taking the connected components.

Time
Θ(N^2) worstO(N + P α(N)) expected average
Space
Θ(N) extra
Where
N = the number of particles; P = the number of pairs in neighboring grid cells
Properties
deterministic
Origin
John P. Huchra, Margaret J. Geller, Marc Davis, George Efstathiou, Carlos S. Frenk, Simon D. M. White, 1982

The friends-of-friends (FoF) algorithm finds groups of points that are linked by chains of close neighbors. Two points are friends when their distance is at most a linking length bb, and a group is a set of points in which any two are joined by a chain of friends: the groups are the connected components of the graph of friend pairs. In cosmology the points are the particles of a simulation, the groups with enough members are the dark matter halos, and bb is usually 0.20.2 times the mean distance between particles. The efficient method puts the points in a grid of cells of side bb, tests only pairs in neighboring cells, and merges the groups with a disjoint-set forest. FoF is the same clustering as single linkage cut at the height bb, and as DBSCAN with a minimum of one neighbor.

In plain words

Pick a distance. Any two points closer than that distance are friends. A friend of a friend is in the same group, and so is a friend of that one, and so on. A group is everything that you can reach by jumping from friend to friend.

To find the groups fast, draw a grid of boxes as wide as the distance. A friend of a point is always in the same box or in a box next to it, so only those boxes need to be checked. Each time two friends are found, their groups are joined. The groups do not have a fixed shape: a long thin chain of points is one group.

The problem

The input is NN points x1,…,xN∈RD\mathbf{x}_1, \ldots, \mathbf{x}_N \in \mathbb{R}^D, a linking length b>0b > 0 and a minimum size nmin⁡≥1n_{\min} \ge 1. Let FF be the graph with an edge between i≠ji \ne j when ∣xi−xj∣≤b|\mathbf{x}_i - \mathbf{x}_j| \le b. The output is the list of connected components of FF with at least nmin⁡n_{\min} points. In cosmology bb is given as a fraction of the mean distance ℓˉ=(V/N)1/3\bar{\ell} = (V / N)^{1/3} of NN particles in a volume VV, and halos need nmin⁡n_{\min} of about 20 or more particles.

The algorithm

  1. FOF(x, b, n_min)
  2. 1for i ← 1 to N do add i to the list of cell ⌊x_i / b⌋ of a hash grid
  3. 2for i ← 1 to N do MAKE-SET(i)
  4. 3for i ← 1 to N do
  5. 4for each offset o ∈ {-1, 0, 1}^D do
  6. 5for each j in the cell ⌊x_i / b⌋ + o with j > i do
  7. 6if |x_i - x_j| ≤ b then UNION(i, j)
  8. 7group the points by FIND(i)
  9. 8return the groups with at least n_min points
  10. FIND(i):
  11. 9while parent(i) ≠ i do parent(i) ← parent(parent(i)); i ← parent(i)
  12. UNION(i, j):
  13. 10link the root of the smaller set below the root of the larger one

Line L1 builds a spatial hash of the cells that hold points, so empty cells cost nothing. Lines L4 and L5 visit the 3D3^D cells around the cell of ii; the test j>ij > i makes each pair count once. Lines L9 and L10 are the disjoint-set forest with path halving and union by size.

Example

Take six points on a line: 00, 0.150.15, 0.30.3, 1.01.0, 1.11.1 and 2.52.5, with b=0.2b = 0.2. The cells of side 0.20.2 are 0,0,1,5,5,120, 0, 1, 5, 5, 12.

pair tested distance friends? sets after the step
(0, 0.15) 0.15 yes {0, 0.15}, {0.3}, {1.0}, {1.1}, {2.5}
(0, 0.3) 0.3 no same
(0.15, 0.3) 0.15 yes {0, 0.15, 0.3}, {1.0}, {1.1}, {2.5}
(1.0, 1.1) 0.1 yes {0, 0.15, 0.3}, {1.0, 1.1}, {2.5}

The point 2.52.5 is in cell 12, and the cells 11 and 13 are empty, so it is tested against no other point. The groups are {0,0.15,0.3}\{0, 0.15, 0.3\}, {1.0,1.1}\{1.0, 1.1\} and {2.5}\{2.5\}; with nmin⁡=2n_{\min} = 2 the last one is dropped. The points 00 and 0.30.3 are 0.3>b0.3 > b apart but are in one group through 0.150.15: this chaining is the defining property of FoF.

Correctness

If two points are at distance at most bb, each coordinate differs by at most bb, so their cells differ by at most 1 in each coordinate (Lemma 1 of the proof file). So lines L3 to L6 call UNION for every friend pair, and for no other pair (Lemma 2). A disjoint-set forest that has seen all edges of a graph has the connected components as its sets (Lemma 3). So line L7 gives the components of the friendship graph, as the definition asks.

Proof: The grid search finds every friend pair, so the disjoint sets are the connected componentsfull

Let x1,…,xN∈RDx_1, \ldots, x_N \in \mathbb{R}^D and b>0b > 0. The friendship graph FF has the vertices 1,…,N1, \ldots, N and an edge {i,j}\{i, j\} when i≠ji \ne j and ∣xi−xj∣≤b|x_i - x_j| \le b. The output should be the connected components of FF (with at least nmin⁡n_{\min} vertices). The cell of a point is c(x)=(⌊x1/b⌋,…,⌊xD/b⌋)c(x) = (\lfloor x_1 / b \rfloor, \ldots, \lfloor x_D / b \rfloor).

Lemma 1 (friends are in neighboring cells). If ∣x−y∣≤b|x - y| \le b, then ∣c(x)k−c(y)k∣≤1|c(x)_k - c(y)_k| \le 1 for each coordinate kk.

Proof. ∣xk−yk∣≤∣x−y∣≤b|x_k - y_k| \le |x - y| \le b. For reals s,ts, t with ∣s−t∣≤1|s - t| \le 1, ⌊s⌋−⌊t⌋<s−(t−1)≤2\lfloor s \rfloor - \lfloor t \rfloor < s - (t - 1) \le 2, and the difference of the floors is an integer, so it is at most 1; by symmetry it is at least −1-1. Apply this with s=xk/bs = x_k / b and t=yk/bt = y_k / b. □\square

Lemma 2 (the loops union exactly the edges). Lines L3 to L6 call UNION(i,j)(i, j) for each edge {i,j}\{i, j\} of FF, with i<ji < j, and for no other pair.

Proof. Line L1 puts each point in the list of its cell. Take an edge with i<ji < j. By Lemma 1, c(xj)=c(xi)+oc(x_j) = c(x_i) + o for some o∈{−1,0,1}Do \in \{-1, 0, 1\}^D, so when the loop of line L3 is at ii, the loop of line L4 reaches the cell of jj and line L5 finds jj. Then j>ij > i and the distance test of line L6 is true. Conversely, line L6 calls UNION only when the distance is at most bb and j>ij > i, that is, for an edge. □\square

Lemma 3 (disjoint sets). After a sequence of UNION calls on the edges of a graph HH, two vertices are in the same set exactly when they are connected in HH.

Proof. Invariant: each set is connected in the graph of the edges seen so far, and the two ends of each edge seen so far are in one set. It holds at the start, when each set is one vertex (line L2) and no edge is seen. UNION(i,j)(i, j) for an edge merges the set of ii and the set of jj, which are joined by that edge, so the merged set is connected and the new edge has both ends in it; if the two ends were already in one set nothing changes. After all edges, the second part says that each path of HH stays in one set, so each connected component lies in one set, and the first part says that no set holds two components. Path halving (line L9) and union by size (line L10) change the shape of the trees, not the sets. □\square

Theorem. The output of line L8 is the set of connected components of FF with at least nmin⁡n_{\min} vertices.

Proof. By Lemma 2 the unions are exactly the edges of FF, and by Lemma 3 the sets are the components of FF. Line L7 groups the vertices by the root of their set, and line L8 keeps the groups that are large enough. □\square

Cost. Let PP be the number of pairs (i,j)(i, j) that line L5 visits, the pairs in neighboring cells. With a hash grid that has O(1)O(1) expected time per access, lines L1 to L6 cost O(3DN+P)O(3^D N + P) expected time, and the disjoint-set operations cost O((N+P) α(N))O((N + P)\, \alpha(N)), where α\alpha is the inverse Ackermann function. Points in a cell of side bb are at distance at most bDb \sqrt{D}, so if at most qq points lie in any cell, P≤3DqNP \le 3^D q N. In the worst case all points share one cell and P=Θ(N2)P = \Theta(N^2). □\square

Complexity

In the word RAM model, with a hash table of O(1)O(1) expected time per access:

  • Line L1 costs O(N)O(N) expected time, and the table has at most NN cells.
  • Lines L3 to L6 cost O(3DN+P)O(3^D N + P), where PP is the number of pairs in neighboring cells, plus O(P)O(P) disjoint-set operations of O(α(N))O(\alpha(N)) amortized time each.
  • For points with a bounded number qq per cell, P≤3DqNP \le 3^D q N, so the total is O(Nα(N))O(N \alpha(N)), close to linear. In a simulation, the dense centers of halos have many points per cell, and PP grows with their density.
  • In the worst case all points lie in one cell, and P=N(N−1)/2P = N(N-1)/2. A k-d tree search does not improve this bound, because the friendship graph itself can have Θ(N2)\Theta(N^2) edges.
  • The extra space is Θ(N)\Theta(N) for the grid and the forest.

Properties

  • Unique result. The groups depend only on the points and bb, not on the order of the points or of the unions (the components of a graph are unique).
  • No shape. Groups follow any shape of the density, such as filaments, so two halos joined by a thin bridge of particles become one group.
  • Density threshold (heuristic). A group of FoF with linking length bb is bounded, roughly, by a surface of constant density proportional to b−3b^{-3}; for b=0.2ℓˉb = 0.2 \bar{\ell} the groups have a mean density of very roughly a hundred or two hundred times the mean density.
  • Monotone in bb. A larger bb only merges groups; the groups for all bb form the tree of single-linkage clustering.

Variants and improvements

  • Periodic boxes. Cosmological simulations are periodic: take the cell offsets and the distances modulo the box size (periodic boundary conditions).
  • Subhalo finders. FoF finds the halos; methods such as SUBFIND then split each halo into bound substructures by density and by energy.
  • Phase-space FoF. Link points that are close in both position and velocity, with two linking lengths.
  • Parallel FoF. Each processor finds the groups of its domain, and groups that cross the boundaries are merged by a second union pass over the pairs that cross.
  • Tree or sorting instead of a grid. A k-d tree with a range search of radius bb gives the same pairs and works well for very uneven densities.
  • Other uses. The same algorithm finds clusters of atoms in molecular dynamics and groups of galaxies in surveys (Huchra and Geller 1982), where the linking length must change with the distance from the observer.

When to use it

Use FoF to find halos or groups when a single density scale defines them and the groups may have any shape. It is fast, has one parameter and gives a unique answer, so it is the first step of most halo catalogs. Use DBSCAN when single noise points must not bridge clusters, and a spherical overdensity or a subhalo finder when the mass inside a radius is needed.

Pitfalls

  • Bridging. One chain of points can link two large groups. A larger nmin⁡n_{\min} does not help; DBSCAN with a minimum of several neighbors, or a split by density, does.
  • Linking length in the wrong units. b=0.2b = 0.2 means 0.2ℓˉ0.2 \bar{\ell}, not 0.20.2 length units.
  • Cell side smaller than bb. Then friends can be two or more cells apart, and searching only the neighboring cells misses them. The cell side must be at least bb.
  • Rounding at the threshold. A pair at distance exactly bb on paper can be just above bb after rounding; the result can change at such pairs.
  • Recursive search. A depth-first search of the friend graph with recursion can run out of stack on large groups. Use the disjoint-set forest or an explicit queue.

Implementations

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.

friends_of_friends_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/friends-of-friends-algorithm/. The authors are listed in prov/HXVJ9V.jsonl.
"""Friends-of-friends groups of points.

Two points are friends when their distance is at most the linking length b.
A group is a connected component of the friendship graph. Points are put in a
hash grid of cells of side b, so each friend of a point lies in the same cell
or in one of the 3^dim - 1 neighboring cells, and the components are built
with a disjoint-set forest (union by size, path halving).

Positions are tuples of any dimension. Expected time O(N + P) for P pairs at
distance at most about 2 b, when the grid lookups are O(1).
"""

import math
from itertools import product
from typing import Sequence

Vec = Sequence[float]


def _find(parent: list[int], i: int) -> int:
    while parent[i] != i:  # @line L9
        parent[i] = parent[parent[i]]
        i = parent[i]
    return i


def _union(parent: list[int], size: list[int], i: int, j: int) -> None:
    ri, rj = _find(parent, i), _find(parent, j)
    if ri == rj:
        return
    if size[ri] < size[rj]:  # @line L10
        ri, rj = rj, ri
    parent[rj] = ri
    size[ri] += size[rj]


def friends_of_friends(x: Sequence[Vec], b: float, min_size: int = 1) -> list[list[int]]:
    """Groups of point indices, each sorted, ordered by their smallest index."""
    if b <= 0:
        raise ValueError("the linking length must be positive")
    n = len(x)
    if n == 0:
        return []
    dim = len(x[0])
    grid: dict[tuple[int, ...], list[int]] = {}
    for i, p in enumerate(x):  # @line L1
        grid.setdefault(tuple(math.floor(c / b) for c in p), []).append(i)
    parent = list(range(n))  # @line L2
    size = [1] * n
    b2 = b * b
    offsets = list(product((-1, 0, 1), repeat=dim))
    for i, p in enumerate(x):  # @line L3
        cell = tuple(math.floor(c / b) for c in p)
        for off in offsets:  # @line L4
            for j in grid.get(tuple(c + o for c, o in zip(cell, off)), ()):  # @line L5
                if j > i and sum((p[k] - x[j][k]) ** 2 for k in range(dim)) <= b2:  # @line L6
                    _union(parent, size, i, j)
    groups: dict[int, list[int]] = {}
    for i in range(n):  # @line L7
        groups.setdefault(_find(parent, i), []).append(i)
    return sorted((g for g in groups.values() if len(g) >= min_size), key=lambda g: g[0])  # @line L8
test_friends_of_friends_algorithm.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/friends-of-friends-algorithm/. The authors are listed in prov/HXVJ9V.jsonl.
import math
import random
from collections import deque

import pytest

from friends_of_friends_algorithm import friends_of_friends


def brute(x, b, min_size=1):
    """Reference: test all pairs, then breadth-first search for the components."""
    n = len(x)
    adj = [[j for j in range(n) if j != i and math.dist(x[i], x[j]) <= b] for i in range(n)]
    seen, out = [False] * n, []
    for s in range(n):
        if seen[s]:
            continue
        seen[s], comp, q = True, [], deque([s])
        while q:
            u = q.popleft()
            comp.append(u)
            for v in adj[u]:
                if not seen[v]:
                    seen[v] = True
                    q.append(v)
        if len(comp) >= min_size:
            out.append(sorted(comp))
    return sorted(out, key=lambda g: g[0])


def clustered(n, dim, seed):
    rng = random.Random(seed)
    centers = [tuple(rng.uniform(-5, 5) for _ in range(dim)) for _ in range(6)]
    pts = []
    for _ in range(n):
        if rng.random() < 0.3:
            pts.append(tuple(rng.uniform(-6, 6) for _ in range(dim)))
        else:
            c = rng.choice(centers)
            pts.append(tuple(c[k] + rng.gauss(0, 0.4) for k in range(dim)))
    return pts


def test_hand_example_on_a_line():
    x = [(0.0,), (0.15,), (0.3,), (1.0,), (1.1,), (2.5,)]
    assert friends_of_friends(x, 0.2) == [[0, 1, 2], [3, 4], [5]]
    assert friends_of_friends(x, 0.2, min_size=2) == [[0, 1, 2], [3, 4]]
    assert friends_of_friends(x, 0.12) == [[0], [1], [2], [3, 4], [5]]
    assert friends_of_friends(x, 1.5) == [[0, 1, 2, 3, 4, 5]]


@pytest.mark.parametrize("dim", [1, 2, 3])
@pytest.mark.parametrize("b", [0.2, 0.5, 1.0])
def test_against_brute_force(dim, b):
    x = clustered(250, dim, 10 * dim + int(10 * b))
    assert friends_of_friends(x, b) == brute(x, b)
    assert friends_of_friends(x, b, min_size=5) == brute(x, b, min_size=5)


def test_negative_coordinates_and_cell_boundaries():
    # Friends that sit in neighboring grid cells, including across zero.
    x = [(-0.05, 0.0), (0.05, 0.0), (0.95, 1.0), (1.05, 1.0), (-1.0, -1.0)]
    assert friends_of_friends(x, 0.2) == brute(x, 0.2) == [[0, 1], [2, 3], [4]]


def test_permutation_gives_same_partition():
    x = clustered(200, 3, 4)
    perm = list(range(200))
    random.Random(1).shuffle(perm)
    y = [x[p] for p in perm]
    a = {frozenset(g) for g in friends_of_friends(x, 0.5)}
    b = {frozenset(perm[i] for i in g) for g in friends_of_friends(y, 0.5)}
    assert a == b


def test_chaining_links_far_points():
    # Ten points 0.1 apart form one group with b = 0.1 even though the ends are 0.9 apart.
    x = [(0.1 * i + 1e-12 * i, 0.0) for i in range(10)]
    assert friends_of_friends(x, 0.1 + 1e-9) == [list(range(10))]


def test_bad_linking_length():
    with pytest.raises(ValueError):
        friends_of_friends([(0.0,)], 0.0)

History

Huchra and Geller (1982) found groups of galaxies in a redshift survey by linking galaxies that are close in the sky and in redshift. Davis, Efstathiou, Frenk and White (1985) used the same linking on the particles of their simulations of cold dark matter, and the method has been the standard first halo finder of cosmological simulations since then. The linking length of 0.20.2 of the mean separation became the common choice in later work.

References

  1. John P. Huchra and Margaret J. Geller, Groups of galaxies. I. Nearby groups, Astrophysical Journal 257, 1982, 423-437, the linking of galaxies into groups
  2. Marc Davis, George Efstathiou, Carlos S. Frenk and Simon D. M. White, The evolution of large-scale structure in a universe dominated by cold dark matter, Astrophysical Journal 292, 1985, 371-394, the friends-of-friends groups of the simulation particles
  3. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein, Introduction to Algorithms, 4th edition, MIT Press, 2022, Chapter 19 (data structures for disjoint sets)

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 proofH1 sketch
  • a full proof of time.average
  • a full proof of time.worst
  • a full proof of space.extra
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
  • a scene preset for the example