STEP-BY-STEP CODE · CONNECTIVITY

How we develop a calculation one part at a time.

By the end of this page, we will have learned the union–find algorithm and used it to study percolation and to count and measure precipitates. We build the Hoshen–Kopelman algorithm one part at a time. Each step introduces a small piece of code, explains its purpose and checks an expected result before we continue.

We start with a small grid that we can check by eye. We retain the complete code alongside the individual steps.

Python notebook · Educational notebook bundle

If you would like a similar tutorial in Julia or C, email me with the lesson title and your intended use. I can share a Google Colab notebook with step-by-step explanations and worked examples.

Email: saswata_at_msme.iith.ac.in (replace _at_ with @).

Install NumPy and Jupyter for the Python notebook, then run its cells in order.

The tutorial uses four-edge adjacency in 2D; the percolation and precipitate boards below let us switch corner contacts on and compare. Labels, occupancy values and cell counts are dimensionless. Physical area requires the grid spacing. The topology playground animates labeling and explains wrapping, holes and surfaces.

Which colored tiles belong to the same group?

We start with colored tiles. We choose one color, keep cells of that color and look for groups joined through shared edges. This is the connection rule for the labeling code; an L-shaped group counts, and no straight line of three is required.

Worked Python example for this board · Label the tiles yourself · What do joined edges change? · Use it for percolation · Count precipitates

Choose a color:

1

A board full of colored tiles

Which tiles can we reach without leaving this color?

2

Keep one color: make a mask

The picture becomes numbers: 1 for this color, 0 for the rest.

3

Two names meet

The algorithm records that the labels are connected. The earlier numbers in the grid remain provisional until the final pass.

4

One number for each connected group

ClusterCells

The tile shapes and colors are original schematic artwork. The faces are decoration; shared grid edges define connections, even where we leave a small gap between drawn tiles. The periodic switch joins the top to the bottom in the same column, and the left to the right in the same row. Corner contact alone is not a connection. The activity below lets us do the same labeling by hand, with hard edges and with joined edges.

Now you label the tiles

Tiles get names one at a time: left to right, then the next row. Each tile looks only up and left, because those tiles already have names. Tap a name. The board stays in view while the rules scroll past it, and each rule marks, on your board, the tile where it will matter. By the last board, we will have used an algorithm called union–find.

Tap a name to label each tile. This activity needs JavaScript.

1 · Provisional naming

Nobody up or left: a new name.
A neighbor has a name: copy it.

The first walk hands out names as it goes. A name is provisional: a tile named 2 may later turn out to belong with the tiles named 1. We do not go back to fix earlier tiles during this walk.

2 · Find: follow the arrows

Follow the arrows to the end. The name at the end is the root.

A name can carry an arrow to another name. When a neighbor's name has an arrow, we follow it, and keep following, until we reach a name with no arrow. That name is the root, and the root is what we copy. In the code this walk is find_label.

3 · Union: draw one arrow

Two roots meet: the bigger name points to the smaller.

When the tile above and the tile to the left have different roots, the tile we are naming joins two groups. We draw one arrow from the bigger root to the smaller one. Nothing else changes now; the arrow is a promise that the second walk keeps. In the code this is merge_labels.

4 · Joined edges

Fold the board: top meets bottom, left meets right.

For a periodic box we add one more round after the walk: each tile on the top edge is joined to the tile below it on the bottom edge, and each tile on the left edge to the tile on the right edge. A pair with different roots gets an arrow, exactly as in union. Choose the last board above to play this round.

5 · The second walk

Every old name follows its arrows once more.

The second walk visits each tile again and replaces its provisional name by the root. Afterwards every tile in a group carries the same name, and counting names counts groups. The arrows are no longer needed.

What do joined edges change?

1

Hard edges

I am at the top.

I am at the bottom. The edge stops us. We are strangers.

4 groups

2

Joined edges

Fold the board. Now the bottom row sits above me.

Same tiles, same count of tiles. Only the groups changed.

2 groups

3

We touch, but no loop

We touch across the edge. One small island.

But the gap stops us. We cannot walk all the way around.

4

We go all the way around

I walk down, cross the edge and come back to where I began.

Both of us are just “one group”. Labels cannot tell the difference.

Test a loop in the topology playground

How the code folds the board

A row of the board is an array of N cells. A neighbor index that runs past either end must come back in at the other end, and that is all "folding" means in code. One expression does it: (i + N) % N. Hover or tap an index below, including the two outside the array, to see where it lands.

N = len(row)                 # 6 cells, indices 0 to 5
left  = (i - 1 + N) % N      # i = 0 gives 5: the last cell
right = (i + 1) % N          # i = 5 gives 0: the first cell

Python's % already returns a nonnegative result for a negative i, so (i - 1) % N works there. C and C++ do not: -1 % 6 is -1, which is why we add N before taking the remainder. Step 6 of the code below joins the two edges explicitly after the scan instead of folding every lookup; both are the same fold, applied once or applied everywhere.

What you just learned has a name

1

Find

Which group am I in? I follow the arrows.

The arrows stop at me. I am the root.

Find: follow arrows to the root

2

Union

We touch, so our groups become one.

One arrow is enough. Nobody else must change now.

Union: point one root at the other

3

You have learned union–find

Find and union: that is the union–find algorithm. You have just used it, by hand.

Hoshen–Kopelman is union–find on a grid: one walk to name tiles and draw arrows, a second walk to fix old names.

In the code: find_label is find, merge_labels is union. See them in Python.

Now use it: can water cross the board?

Fill each site at random with probability \(p\). Union–find names the groups. If one group touches both the top and the bottom, water can cross. This is percolation.

Where does crossing begin?

Move \(p\) to your guess. Then test many boards at each \(p\).

The numbers in this chart
pBoards that crossNeighbors

Should we join top and bottom here?

No. Then top and bottom are one edge, and “crossing” means nothing. For a periodic box, we test for a loop instead.

Try it in Python

After the function in the Python steps below:

rng = np.random.default_rng(1)
mask = rng.random((64, 64)) < 0.6
labels, sizes = hoshen_kopelman(mask)
crossing = (set(labels[0]) & set(labels[-1])) - {0}
print(len(sizes), "groups; crossing groups:", crossing)

Use it again: how many precipitates, and how big?

In a microstructure, each connected group of tiles is one precipitate in the matrix. Its label gives the count. Its number of tiles gives its size. Together, the sizes give a distribution.

0 groups

The numbers in this histogram
Size in tilesGroups

For crossing we kept hard edges. Why join them here?

A periodic box has no real edge. A precipitate cut by the box is still one precipitate.

What if two precipitates touch?

Then the labels see one group. Labels count connections, not how a group formed.

The round shapes here are drawn, not simulated. For a real field, we first choose a composition threshold, and the count and sizes can depend on it. In two dimensions, tiles × cell area gives the area; in three dimensions, tiles × cell volume gives the volume. One small box holds few precipitates, so a distribution needs a large enough box or several boxes.

Try it in Python

Here c is a composition field and dx is the grid spacing:

mask = c >= 0.5
labels, sizes = hoshen_kopelman(mask, periodic=True)
print("Precipitates:", len(sizes))
counts, edges = np.histogram(sizes, bins=10)
areas = np.array(sizes) * dx**2
radii = np.sqrt(areas / np.pi)

Worked Python: label this same tile board

We choose color A, turn the board into a binary mask, and call the hoshen_kopelman function developed in the steps below. In the runnable notebook, this example comes after the function definition. The faces are decoration; only the chosen color and shared grid edges enter the calculation.

Follow the function from its first step · See how we join the periodic edges

import numpy as np

board = np.array([
    ['A', 'B', 'A', 'C', 'C', 'B'],
    ['A', 'A', 'A', 'C', 'B', 'B'],
    ['B', 'C', 'A', 'A', 'C', 'A'],
    ['B', 'C', 'C', 'A', 'C', 'A'],
    ['A', 'A', 'B', 'B', 'C', 'C'],
    ['A', 'C', 'A', 'B', 'A', 'A']
])
color = "A"
mask = board == color

bounded_labels, bounded_sizes = hoshen_kopelman(mask, periodic=False)
periodic_labels, periodic_sizes = hoshen_kopelman(mask, periodic=True)

print("Mask for color", color)
print(mask.astype(int))
print("Bounded labels:")
print(bounded_labels)
print("Bounded cluster sizes:", bounded_sizes)
print("Periodic labels:")
print(periodic_labels)
print("Periodic cluster sizes:", periodic_sizes)

assert np.array_equal(bounded_labels > 0, mask)
assert np.array_equal(periodic_labels > 0, mask)
assert sum(bounded_sizes) == sum(periodic_sizes) == int(mask.sum())
if color == "A":
    assert bounded_sizes == [8, 2, 3, 1, 2]
    assert periodic_sizes == [14, 2]
Labels and group sizes for color A
Mask for color A
[[1 0 1 0 0 0]
 [1 1 1 0 0 0]
 [0 0 1 1 0 1]
 [0 0 0 1 0 1]
 [1 1 0 0 0 0]
 [1 0 1 0 1 1]]
Bounded labels:
[[1 0 1 0 0 0]
 [1 1 1 0 0 0]
 [0 0 1 1 0 2]
 [0 0 0 1 0 2]
 [3 3 0 0 0 0]
 [3 0 4 0 5 5]]
Bounded cluster sizes: [8, 2, 3, 1, 2]
Periodic labels:
[[1 0 1 0 0 0]
 [1 1 1 0 0 0]
 [0 0 1 1 0 2]
 [0 0 0 1 0 2]
 [1 1 0 0 0 0]
 [1 0 1 0 1 1]]
Periodic cluster sizes: [14, 2]

The periodic connection changes which cells belong together, but does not add or remove any of the 16 A cells. For B and C on this particular board, the component counts happen to stay unchanged when we join the edges. Periodicity does not automatically merge every group.

The same steps with numbers: grid, parent list and code

Why one cluster can initially receive two labels

We begin with five occupied cells. The first row has two separated cells, but the next row joins them. All five cells belong to one cluster. A cluster is a set of occupied cells connected through shared edges; touching at a corner alone does not connect them.

Occupied cells       After the first pass       Final cluster labels
1  0  1              1  0  2                     1  0  1
1  1  1              1  1  1                     1  1  1
0  0  0              0  0  0                     0  0  0

We scan from left to right, then move to the next row. The cell at the upper right receives label 2 because its connection to label 1 has not yet been visited. When the two arms meet, we record that label 2 belongs to the same cluster as label 1. We do not rewrite every earlier cell at that moment.

The parent list records links between labels

parent[k] stores the next label to follow from label k. These are integer label numbers, not memory addresses. For example, the list [0, 1, 1, 2] gives the following sequence:

label 3             label 2             label 1
   3  ───────────────►  2  ───────────────►  1
parent[3] = 2       parent[2] = 1       parent[1] = 1
                                        stop here

Label 1 is the root, also called the representative: it points to itself. The function find_label follows these links and returns that root. Label 0 is reserved for background. This three-label sequence illustrates lookup; the five-cell example needs only labels 1 and 2.

To merge two labels, we first find both roots. If they differ, merge_labels makes the larger root point to the smaller root. For the two arms, this gives parent[2] = 1. If both labels already lead to the same root, no new link is needed.

Pass 1: assign labels and record connections

scan_grid visits every cell once. At an occupied cell, we inspect the cells above and to the left because they have already been visited. The four-edge connection rule still includes all four directions: connections to the right and below are considered when those cells are visited.

Already visited neighborsOur next operation
Neither is occupiedWe create a new label that points to itself.
One is occupiedWe follow its label to the root and use that root.
Both are occupiedWe find both roots. If they differ, we merge them; otherwise they already identify one cluster.

Pass 2: resolve the provisional labels

finish_labels scans the grid again. For each occupied cell, we find its root and assign a final cluster number. Surviving roots receive consecutive numbers starting at 1. This replaces provisional grid labels; the code does not perform path compression on the parent list. We then count the cells in each final cluster.

Hoshen–Kopelman, one operation at a time

We show the grid, parent links and the code used at the current step together. Cell coordinates are (row, column), starting at 0, as in the Python code. A dot is an occupied cell awaiting a label; 0 is background.

Scan a cellFind its rootMerge if neededResolve labels

The first three operations belong to pass 1. Pass 2 resolves the grid labels. A new label needs no lookup, and labels with the same root need no new merge.

Grid state

Solid outline: current cell. Dashed outline: an already visited neighbor. Cell colors indicate labels, not composition.

Parent links

Active algorithm block

These excerpts show the caller and helper used at this step. Blue lines mark the current operation. The complete runnable functions appear below.

Compare provisional and final labels
Provisional labels
Final labels

This example uses nonperiodic boundaries. Periodic connections are introduced later in the code lesson. The ring has one cluster and one enclosed hole; these label counts do not measure holes.

The same sequence in code

The functions below follow the operations shown above: look up a root, merge roots, scan the grid, then resolve the labels. We retain the small checks after each function.

Step 1: Our small test grid

We begin with a small array that we can inspect by eye. A value of 1 identifies an occupied cell; 0 identifies background. Rows run downward and columns run to the right. These values and the labels are dimensionless. We count connections through shared edges, so corner contact alone does not connect two cells.

Python

import numpy as np

mask = np.array([[1, 0, 1],
                 [1, 1, 1],
                 [0, 0, 0]], dtype=bool)
assert mask.shape == (3, 3)
assert mask.sum() == 5
print(mask.astype(int))

Step 2: Finding the root of a label

The first row appears to contain two separate clusters. Later cells connect them. We therefore need a way to record that two labels belong to the same cluster. In the parent list, parent[k] gives the next label to follow. A label that points to itself is the representative. Label 0 is reserved for background. We first test lookup without scanning a grid.

Python

def find_label(parent, label):
    while parent[label] != label:
        label = parent[label]
    return label

parent = [0, 1, 1, 2]
assert find_label(parent, 3) == 1
assert find_label(parent, 1) == 1
print("Label 3 belongs to the cluster represented by label 1.")

Step 3: Merging two labels

We find the representatives before merging labels. Otherwise we could link the wrong entries or form a cycle in the parent list. We make the larger representative point to the smaller one. This gives predictable labels in the worked example. We do not need a more elaborate data structure for this small lesson.

Python

def merge_labels(parent, first, second):
    first_root = find_label(parent, first)
    second_root = find_label(parent, second)
    root = min(first_root, second_root)
    parent[max(first_root, second_root)] = root
    return root

parent = [0, 1, 2, 3]
merge_labels(parent, 2, 3)
merge_labels(parent, 1, 3)
assert [find_label(parent, k) for k in (1, 2, 3)] == [1, 1, 1]
print("Three labels now identify one cluster.")

Step 4: The first grid scan

We visit rows from top to bottom, and cells within each row from left to right. Only the upper and left neighbors have already been visited. If both are background, we create a label. If one is occupied, we use its label. If both are occupied, we merge their labels. Each shared-edge connection is considered when its later cell is visited. The returned labels are provisional: some different numbers may already refer to the same cluster.

Python

def scan_grid(mask):
    rows, columns = mask.shape
    labels = np.zeros(mask.shape, dtype=int)
    parent = [0]
    for row in range(rows):
        for column in range(columns):
            if not mask[row, column]:
                continue
            above = labels[row - 1, column] if row > 0 else 0
            left = labels[row, column - 1] if column > 0 else 0
            if above == 0 and left == 0:
                new_label = len(parent)
                parent.append(new_label)
                labels[row, column] = new_label
            elif above == 0:
                labels[row, column] = find_label(parent, left)
            elif left == 0:
                labels[row, column] = find_label(parent, above)
            else:
                labels[row, column] = merge_labels(parent, above, left)
    return labels, parent

labels, parent = scan_grid(mask)
assert labels[0, 0] != labels[0, 2]
assert find_label(parent, labels[0, 0]) == find_label(parent, labels[0, 2])
print("Provisional labels:")
print(labels)

Step 5: The final labels and cluster sizes

We now replace each occupied cell label by its representative. We renumber the surviving representatives from 1 upward. The size of a cluster is the number of cells with its final label. For a uniform two-dimensional grid, its area is this count multiplied by the cell area. A count has no units; an area has the units of the squared grid spacing. The largest-cluster fraction is the largest count divided by the occupied-cell count, not the total grid-cell count.

Python

def finish_labels(labels, parent):
    final = np.zeros(labels.shape, dtype=int)
    numbers = {}
    for row in range(labels.shape[0]):
        for column in range(labels.shape[1]):
            label = labels[row, column]
            if label == 0:
                continue
            root = find_label(parent, label)
            if root not in numbers:
                numbers[root] = len(numbers) + 1
            final[row, column] = numbers[root]
    sizes = [int(np.count_nonzero(final == k))
             for k in range(1, len(numbers) + 1)]
    return final, sizes

final, sizes = finish_labels(labels, parent)
assert sizes == [5]
assert np.array_equal(final > 0, mask)
print("Final labels:")
print(final)
print("Cluster sizes:", sizes)

Step 6: Add periodic connections as a separate step

We keep the bounded scan unchanged. For periodic data we then connect occupied cells at matching positions on opposite edges. The top cell in a column is adjacent to the bottom cell in that same column. The left and right cells in a row are adjacent in the same way. We merge these labels before producing the final counts. The two-cell example has two bounded clusters and one periodic cluster. It is a small island crossing the displayed seam; it does not form a loop around the whole domain.

Python

def join_periodic_edges(labels, parent):
    rows, columns = labels.shape
    for column in range(columns):
        top = labels[0, column]
        bottom = labels[rows - 1, column]
        if top and bottom:
            merge_labels(parent, top, bottom)
    for row in range(rows):
        left = labels[row, 0]
        right = labels[row, columns - 1]
        if left and right:
            merge_labels(parent, left, right)


def hoshen_kopelman(mask, periodic=False):
    mask = np.asarray(mask, dtype=bool)
    if mask.ndim != 2 or min(mask.shape) == 0:
        raise ValueError("Use a nonempty two-dimensional grid.")
    labels, parent = scan_grid(mask)
    if periodic:
        join_periodic_edges(labels, parent)
    return finish_labels(labels, parent)

seam = np.zeros((5, 5), dtype=bool)
seam[0, 2] = seam[-1, 2] = True
assert hoshen_kopelman(seam)[1] == [1, 1]
assert hoshen_kopelman(seam, periodic=True)[1] == [2]
print("Seam island: 2 bounded clusters; 1 periodic cluster.")

Step 7: Our checks on small grids

We test an empty grid, a filled grid, a corner contact and a ring. A ring and a filled square each have one connected component. Cluster labeling cannot distinguish their hole counts. We also test a rectangular grid so that accidentally exchanging the row and column dimensions cannot remain hidden.

Python

assert hoshen_kopelman(np.zeros((3, 5), bool))[1] == []
assert hoshen_kopelman(np.ones((3, 5), bool))[1] == [15]
assert hoshen_kopelman(np.eye(3, dtype=bool))[1] == [1, 1, 1]
ring = np.ones((5, 5), dtype=bool)
ring[1:4, 1:4] = False
assert hoshen_kopelman(ring)[1] == [16]
rectangle = np.zeros((3, 5), dtype=bool)
rectangle[1, 0] = rectangle[1, -1] = True
assert hoshen_kopelman(rectangle)[1] == [1, 1]
assert hoshen_kopelman(rectangle, periodic=True)[1] == [2]
print("All small-grid checks passed.")

Step 8: Thresholds and the two phases

The composition c and threshold are dimensionless here. We define the high-composition phase using c >= 0.5 and the other phase using c < 0.5. We measure each separately. The occupied fraction uses all grid cells in its denominator. For an absent phase we report a largest-cluster fraction of zero by convention. In a real simulation we would load the saved field instead of this small example. We do not infer winding, holes or numerical convergence from these counts.

Python

composition = np.array([[0.8, 0.2, 0.7],
                        [0.9, 0.6, 0.8],
                        [0.1, 0.2, 0.1]])
for name, phase in [("High composition", composition >= 0.5),
                    ("Low composition", composition < 0.5)]:
    labels, sizes = hoshen_kopelman(phase, periodic=True)
    occupied = int(phase.sum())
    largest_fraction = max(sizes) / occupied if occupied else 0.0
    assert sum(sizes) == occupied
    print(name, "occupied fraction:", occupied / phase.size,
          "clusters:", len(sizes), "largest-cluster fraction:", largest_fraction)

The same labeling in a library

For real data we do not write this ourselves. skimage.measure.label and scipy.ndimage.label label connected components in two or three dimensions with the same union–find idea, and skimage.segmentation.flood_fill floods one group from a seed point instead. None of them folds the edges of a periodic box; Step 6 above shows the extra merge we add ourselves.

from skimage.measure import label
labels = label(mask, connectivity=1)   # edges only; connectivity=2 counts corners in 2D

from scipy import ndimage
labels, count = ndimage.label(mask)    # 4 neighbors in 2D and 6 in 3D by default

What the algorithm establishes

Hoshen–Kopelman assigns the same final label to cells connected by the specified neighbor rule. It gives component counts and sizes. A periodic edge connection does not, by itself, prove a loop around the domain. A ring and a filled square can each have one component but different hole counts. We use separate winding and topology measurements for those questions.

The same labels in three dimensions

Real microstructures are three-dimensional, and the labeling barely changes: each voxel looks at six face neighbors instead of four edge neighbors, and the parent list is the same. The structure below is a smoothed random field cut at its median, generated in the browser each time. It is schematic, not a phase-field result, but its connectivity is real: we label it with the six-neighbor rule and color the group that reaches from the bottom face to the top face orange. Drag to rotate it.

Loading the 3D view…

Only the outer voxels of each group are drawn, which is why the picture looks like a surface. The view uses the three.js library (r160, MIT license) from cdnjs, loaded when this section scrolls into view.

References and source credits

The algorithm is due to Hoshen and Kopelman (1976). Tobin Fricke explains the union–find formulation and provides a C implementation. The code above is a new small teaching implementation. Older C files used in our analysis retain their existing credits, including Prof. T. A. Abinandanan, my PhD advisor (Abi in the original source comments); Fricke’s separate source retains his copyright and GPL notice. I retain the original credits on historical source files.