Algorithm Search⌘K

Data structurecore

Liaison graph

Also called contact graph of an assembly, assembly connection graph.

An undirected graph with a node per part and an edge per contact or fastening, the input of most assembly sequence generators.

Time
O(n log n + K) worst
Space
Θ(n + m) extra
Where
K = the number of pairs of parts whose closed x intervals meet; m = the number of liaisons; n = the number of parts

The liaison graph of an assembly has one node for each part and one edge, called a liaison, for each pair of parts that touch or that a fastener joins. Each liaison can carry data: the kind of joint, the contact normal, the contact area. Assembly sequence methods use it in three ways: a liaison is the unit of work that a sequence orders, a set of parts counts as a subassembly only if it is connected in the graph, and the liaisons that cross a split are the joints that the split must make or break. This page builds the graph from a model of axis-aligned boxes and gives the operations that the assembly planners call.

In plain words

Draw a dot for each part of a product. When two parts touch, or a screw or a weld holds them together, draw a line between their dots. That picture is the liaison graph.

The picture answers simple questions fast. Which parts touch this part? Do these four parts hold together as one piece, or do they fall into two piles? If I lift these parts off the rest, which joints do I break? A planner asks these questions thousands of times, so it is worth building the picture once.

To build it from a CAD model, do not test every pair of parts. Sort the parts from left to right, and compare each part only with the earlier parts that reach far enough to the right to touch it. Parts far apart are never compared.

The abstract type

An assembly is a set of parts P={1,…,n}P = \{1, \ldots, n\}. The liaison graph is an undirected graph L=(P,E)L = (P, E) with a label on each edge. On this page a part is a closed axis-aligned box bib_i, and the interiors of the boxes are pairwise disjoint. A contact liaison joins ii and jj when bi∩bjb_i \cap b_j has positive area in a plane, that is, the two parts share a patch of a face. Its label is (k,s,A)(k, s, A): the contact normal from ii to jj is s eks\,e_k with s=±1s = \pm 1 and eke_k a unit vector along the axis kk, and AA is the area of the patch. Boxes that touch only along an edge or at a corner do not give a liaison. A fastener liaison is added by hand, because a bolt or a weld is not in the geometry of the two parts.

The graph has no motion model and no hand model of its own. It is the same for every planner. The planners add them: the blocking graphs add the motions, and the AND/OR graph adds the two-handed hand model.

The operations are:

  • BUILD(b1,…,bn)\mathrm{BUILD}(b_1, \ldots, b_n): the graph of all contact liaisons.
  • ADD(i,j,label)\mathrm{ADD}(i, j, label): add a fastener liaison.
  • NEIGHBOURS(i)\mathrm{NEIGHBOURS}(i): the parts that share a liaison with ii.
  • IS-CONNECTED(S)\mathrm{IS\text{-}CONNECTED}(S): true if the induced subgraph L[S]L[S] is connected. Most planners accept a set SS as a subassembly only if this holds.
  • CUT(S)\mathrm{CUT}(S): the liaisons with one end in SS and one end outside, the joints made when SS is joined to the rest.
  • CONNECTED-SUBSETS()\mathrm{CONNECTED\text{-}SUBSETS}(): every connected nonempty set of parts, each once. Their number NN bounds the size of the AND/OR graph of all plans.

Representation

The code keeps, for each part ii, a bit mask adj[i]adj[i] of its neighbours, and a dictionary from the pair (i,j)(i, j) with i<ji < j to the label. A set of parts is a bit mask too, so the neighbourhood N(S)N(S) of a set (the parts outside SS with a neighbour in SS) is the union of adj[i]adj[i] over i∈Si \in S, without SS. For a product of a few dozen parts, a mask fits in one or two machine words. For large products, adjacency lists with a hash set of edges give the same operations, with a breadth first search for IS-CONNECTED.

Operations

  1. BUILD(b[1..n]) ▷ closed boxes with disjoint interiors
  2. 1order ← the parts sorted by lo_x; active ← empty list
  3. 2for each part i in order do
  4. 3remove from active every j with hi_x(b_j) < lo_x(b_i)
  5. 4for each j in active do c ← CONTACT(b_i, b_j)
  6. 5if c ≠ nil then add the liaison {i, j} with label c
  7. 6append i to active
  8. CONTACT(a, b) ▷ w_m: overlap width of a and b on axis m
  9. 7for each axis k do
  10. 8if hi_k(a) = lo_k(b) then s ← +1 else if hi_k(b) = lo_k(a) then s ← -1 else skip k
  11. 9if w_m > 0 for both other axes m then return (k, s, the product of the two w_m)
  12. 10return nil
  13. IS-CONNECTED(S) ▷ S: a bit mask of parts
  14. 11R ← {the lowest part of S}; repeat R' ← R; R ← R ∪ (N(R) ∩ S) until R = R'
  15. 12return R = S
  16. CUT(S)
  17. 13return the liaisons {i, j} with i in S and j not in S
  18. GROW(S, B) ▷ S connected, B: banned parts
  19. 14output S
  20. 15C ← N(S) \ B
  21. 16for each w in C, in increasing order do
  22. 17GROW(S ∪ {w}, B); B ← B ∪ {w}
  23. CONNECTED-SUBSETS()
  24. 18B ← ∅
  25. 19for each part v in increasing order do
  26. 20GROW({v}, B); B ← B ∪ {v}

Build. This is the sort step of a sweep along xx, as in the rectangle intersection sweep. Two parts in contact have closed xx intervals that meet. So when part ii comes, the only earlier parts that can touch it are the ones whose interval has not ended before lox(bi)lo_x(b_i). Line L3 drops the others, and they can never come back, because later parts start even further right. Each pair that survives gets the exact test CONTACT. With integer or rational coordinates, the test is exact.

Contact. Disjoint interiors force at least one axis with overlap width at most 0. The patch has positive area exactly when one axis has width 0, where one box ends and the other starts, and the two other widths are positive.

Connected subsets. GROW never lists a set twice: the first branch that takes candidate ww covers every larger set that contains ww, so the later branches ban ww. A set is listed by the call for its lowest part.

Example

Take a frame of five boxes, with corners (x0,y0,z0)(x_0, y_0, z_0) and (x1,y1,z1)(x_1, y_1, z_1):

part name corners
0 base plate (0,0,0)(0, 0, 0), (4,2,1)(4, 2, 1)
1 left post (0,0,1)(0, 0, 1), (1,2,3)(1, 2, 3)
2 right post (3,0,1)(3, 0, 1), (4,2,3)(4, 2, 3)
3 block (1,0,1)(1, 0, 1), (3,2,2)(3, 2, 2)
4 top plate (0,0,3)(0, 0, 3), (4,2,4)(4, 2, 4)

The posts and the block stand on the base plate. The block sits between the posts, and the top plate rests on the posts, with an empty gap of height 1 above the block.

BUILD sorts by loxlo_x and gets the order 0,1,4,3,20, 1, 4, 3, 2. Part 0 finds an empty list. Part 1 is compared with 0. Part 4 is compared with 0 and 1. Part 3 is compared with 0, 1 and 4. When part 2 comes, with lox=3lo_x = 3, line L3 drops part 1, whose interval ends at x=1x = 1, and part 2 is compared with 0, 4 and 3. That is 9 calls of CONTACT, out of the 10 pairs. The pair {1,2}\{1, 2\} is never tested. Seven calls find a contact:

liaison axis sign area
{0,1}\{0, 1\} zz +1+1 2
{0,2}\{0, 2\} zz +1+1 2
{0,3}\{0, 3\} zz +1+1 4
{1,3}\{1, 3\} xx +1+1 2
{2,3}\{2, 3\} xx −1-1 2
{1,4}\{1, 4\} zz +1+1 2
{2,4}\{2, 4\} zz +1+1 2

For {2,3}\{2, 3\} the normal from part 2 to part 3 points along −x-x, because the block lies to the left of the right post. The pairs {0,4}\{0, 4\} and {3,4}\{3, 4\} do not touch: the top plate is 2 above the base and 1 above the block.

CUT({3}\{3\}) gives {0,3}\{0, 3\}, {1,3}\{1, 3\} and {2,3}\{2, 3\}: inserting the block makes three joints at once. IS-CONNECTED is false for the three pairs without a liaison, {1,2}\{1, 2\}, {0,4}\{0, 4\} and {3,4}\{3, 4\}, and true for every set of four parts, because no single part holds the frame together. CONNECTED-SUBSETS lists N=27N = 27 sets: 5 single parts, 7 pairs, 9 triples, 5 sets of four and the whole frame. Of the 25−1=312^5 - 1 = 31 nonempty sets, only the three pairs above and the triple {0,3,4}\{0, 3, 4\} are not connected.

Correctness

CONTACT is correct because the intersection of two boxes is a box whose sides are the three overlap widths, so it is a planar patch of positive area exactly when one width is 0 and the two others are positive. The sweep tests every pair in contact: such a pair has meeting xx intervals, and since the parts come in order of loxlo_x, the earlier part is still in the active list when the later one comes. IS-CONNECTED grows the component of one part inside SS. GROW outputs each connected set that contains its first argument and avoids the banned set exactly once, by induction on the number of free parts: a larger set is produced only in the branch of the first candidate it contains. The full proofs are in the correctness proof.

Proof: The sweep finds every contact liaison, and GROW lists every connected subassembly oncefull

We use the pseudocode of the page. The parts are closed axis-aligned boxes b1,…,bnb_1, \ldots, b_n whose interiors are pairwise disjoint. For a box bb and an axis k∈{x,y,z}k \in \{x, y, z\}, write [lok(b),hik(b)][lo_k(b), hi_k(b)] for its interval on that axis. For two boxes aa and bb, the overlap width on axis kk is wk=min⁡(hik(a),hik(b))−max⁡(lok(a),lok(b))w_k = \min(hi_k(a), hi_k(b)) - \max(lo_k(a), lo_k(b)).

Lemma 1 (contact test). Let aa and bb be closed boxes with disjoint interiors. The set a∩ba \cap b has positive area in a plane exactly when there is one axis kk with hik(a)=lok(b)hi_k(a) = lo_k(b) or hik(b)=lok(a)hi_k(b) = lo_k(a), and wm>0w_m > 0 for the two other axes mm. In that case a∩ba \cap b lies in the plane normal to eke_k, its area is the product of the two widths wmw_m, and the outward normal of aa on it is +ek+e_k in the first case and −ek-e_k in the second. CONTACT on line L4 returns exactly this.

Proof. The intersection of two boxes is the product of the three intervals of length max⁡(wk,0)\max(w_k, 0). The interiors meet exactly when wk>0w_k > 0 on all three axes, so by the hypothesis some wk≤0w_k \le 0. If some wk<0w_k < 0, the intersection is empty. If two widths are 0, the intersection lies in a line and has no area. So a∩ba \cap b has positive area in a plane exactly when one width is 0 and the two others are positive. A width of 0 on axis kk, with lok<hiklo_k < hi_k for both boxes, means that one interval ends where the other starts, which is hik(a)=lok(b)hi_k(a) = lo_k(b) or hik(b)=lok(a)hi_k(b) = lo_k(a), and only one of the two can hold. In the first case bb lies on the side of aa where the kk coordinate grows, so the outward normal of aa on the patch is +ek+e_k. The patch is a rectangle with sides wmw_m for the two other axes. □\square

Lemma 2 (the sweep sees every contact pair). Lines L1 to L6 call CONTACT on every pair {i,j}\{i, j\} for which CONTACT can return a contact.

Proof. If bib_i and bjb_j are in contact, their intersection is not empty, so their closed xx intervals meet: lox(bi)≤hix(bj)lo_x(b_i) \le hi_x(b_j) and lox(bj)≤hix(bi)lo_x(b_j) \le hi_x(b_i). Say that jj comes before ii in the order of line L1, so lox(bj)≤lox(bi)lo_x(b_j) \le lo_x(b_i). Line L6 puts jj in the active list when jj is processed. Line L3 removes jj only at a step i′i' with hix(bj)<lox(bi′)hi_x(b_j) < lo_x(b_{i'}). Every step i′i' from jj up to and including ii has lox(bi′)≤lox(bi)≤hix(bj)lo_x(b_{i'}) \le lo_x(b_i) \le hi_x(b_j), because the order is sorted. So jj is still active at step ii, and line L4 tests the pair. □\square

Theorem 1 (BUILD). BUILD returns the graph whose edges are exactly the pairs of parts that share a face patch of positive area, each labelled with its axis, the sign of the normal from the smaller index to the larger, and the area.

Proof. Line L4 calls CONTACT only on pairs of distinct parts, each pair at most once, because jj is active only for the steps after its own. By Lemma 1, an edge is added only for a real contact, with the stated label. By Lemma 2, no contact is missed. □\square

Lemma 3 (IS-CONNECTED). IS-CONNECTED(SS) returns true exactly when SS is not empty and the subgraph induced by SS is connected. It does at most ∣S∣|S| rounds.

Proof. Let vv be the lowest part of SS. After round rr, the set RR is the set of parts of SS that a path inside SS of at most rr edges joins to vv: this holds for r=0r = 0, and line L11 adds exactly the parts of SS one edge away from RR. The loop stops when a round adds nothing, so RR is then closed under steps inside SS, and RR is the component of vv in the induced subgraph. The answer R=SR = S is true exactly when this component is all of SS. Each round that goes on adds a part, so there are at most ∣S∣|S| rounds. □\square

Lemma 4 (one call of GROW). Let SS be connected, let BB be a set disjoint from SS, and call a set TT reachable from (S,B)(S, B) when TT is connected, S⊆TS \subseteq T and T∩B=∅T \cap B = \emptyset. The call GROW(SS, BB) outputs every reachable set exactly once, and nothing else.

Proof. By induction on the number of parts outside S∪BS \cup B. Line L14 outputs SS, which is reachable. Let w1,…,wkw_1, \ldots, w_k be the candidates of line L15, which are the parts outside SS and BB with a neighbour in SS. The call for wiw_i on line L17 has the first set S+wiS + w_i, which is connected because wiw_i has a neighbour in SS, and the banned set Bi=B∪{w1,…,wi−1}B_i = B \cup \{w_1, \ldots, w_{i-1}\}, which is disjoint from S+wiS + w_i. It has one more part in its first set, so by induction it outputs exactly the sets reachable from (S+wi,Bi)(S + w_i, B_i), each once.

Take a reachable T≠ST \ne S. A path inside TT joins a part of T∖ST \setminus S to SS, so some part of T∖ST \setminus S has a neighbour in SS. That part is not in BB, so it is a candidate. Let wiw_i be the first candidate in TT. Then TT is reachable from (S+wi,Bi)(S + w_i, B_i), and from no (S+wi′,Bi′)(S + w_{i'}, B_{i'}) with i′≠ii' \ne i: if i′<ii' < i then wi′∉Tw_{i'} \notin T, and if i′>ii' > i then wi∈Bi′∩Tw_i \in B_{i'} \cap T. So TT is output exactly once, in the call for wiw_i. The set SS itself is output only on line L14, because every set that a child call outputs contains a candidate. Every output set is reachable from (S,B)(S, B), because a set reachable from (S+wi,Bi)(S + w_i, B_i) is reachable from (S,B)(S, B). □\square

Theorem 2 (CONNECTED-SUBSETS). Lines L18 to L20 output every connected nonempty set of parts exactly once.

Proof. The loop calls GROW({v}\{v\}, {u:u<v}\{u : u < v\}) for each part vv. By Lemma 4 this outputs exactly the connected sets whose lowest part is vv. Each connected nonempty set has one lowest part. □\square

Termination and cost. The sweep makes nn steps over a list of at most nn parts. In GROW, every call outputs one set, and by Theorem 2 there are exactly NN calls in total, where NN is the number of connected sets. One call does O(∣S∣)O(|S|) word operations on bit masks to form its candidates on line L15, plus constant work for each child call. So the enumeration costs O(Nn)O(N n) word operations when nn is at most the word length.

Complexity

operation worst-case time
BUILD O(nlog⁡n+K)O(n \log n + K), KK the pairs of parts whose closed xx intervals meet
ADD O(1)O(1) expected (dictionary)
NEIGHBOURS(ii) O(n/w)O(n / w) word operations to scan the mask, O(deg⁡i)O(\deg i) with lists
IS-CONNECTED(SS) $O(
CUT(SS) O(m)O(m)
CONNECTED-SUBSETS O(Nn)O(N n) word operations, NN the number of connected sets

Here ww is the word length, and the mask bounds assume n≤wn \le w. Space is Θ(n+m)\Theta(n + m). The sweep does KK calls of CONTACT, and K≥mK \ge m. Both can be Θ(n2)\Theta(n^2): lay n/2n/2 long bars along xx side by side, and n/2n/2 long bars along yy on top of them, and every bar of the lower layer touches every bar of the upper layer, so m=n2/4m = n^2/4. With an interval tree on the yy intervals of the active parts, the sweep can skip pairs whose yy intervals do not meet, but it still pays for each liaison it reports.

NN can be small or large. A chain of nn parts has n(n+1)/2n(n+1)/2 connected sets, a star with one central part has 2n−1+n−12^{n-1} + n - 1, and a product where every part touches every other has 2n−12^n - 1. The frame above has 27 of 31.

Variants

  • Contact types. Real liaison graphs label each liaison with its kind: plane contact, cylindrical fit, thread, snap fit, weld, glue. A cylindrical fit allows motion only along its axis, and the planners turn this into motion constraints.
  • Contact normals for planning. The normals on the labels are the raw data of the infinitesimal blocking graph: a part with a plane contact of normal nn against another part cannot move along any direction dd with d⋅n>0d \cdot n > 0.
  • Liaison diagram with numbered liaisons. The question methods of Bourjault and of De Fazio and Whitney number the liaisons 1,…,m1, \ldots, m and describe a state of the assembly by the set of liaisons made. A state is then a set of edges, not a set of parts.
  • Graph of connections. Homem de Mello and Sanderson describe an assembly by a relational model and its graph of connections, which is the same graph with contacts and attachments as two kinds of edge.
  • Polyhedral parts. For general solids the contact test is a face to face test on the boundary representations, with a tolerance. The sweep stays the same, with bounding boxes in place of the parts.

When to use it

Use the liaison graph as the first structure of any assembly planner. It decides which subsets are physical subassemblies, it is the vocabulary of the question methods, and its connected sets index the nodes of the AND/OR graph. It is also the base of design reviews that count joints, such as design for assembly. It is not a model of motion: two parts can be free of contact and still block each other, as the top plate blocks the block in the example. For motion, build the blocking graphs.

Pitfalls

  • Contact is not blocking. The top plate and the block do not touch, yet the plate stops the block from moving up. A planner that uses only liaisons to test motions accepts wrong sequences.
  • Edge contacts. Two boxes that share only an edge have no liaison here, but under an infinitesimal motion along a diagonal they still collide. The blocking tests must use the geometry, not the liaison list.
  • Tolerances. Real CAD faces that should touch often have a gap or an overlap of 10−610^{-6}. With floating point coordinates, a contact test needs a tolerance and a rule for what it means. The code here uses exact coordinates, so the question does not come up.
  • Fasteners are not in the geometry. When the CAD model leaves out a bolt, a rivet or a weld, nothing in the geometry joins the parts it holds. Add such liaisons by hand.
  • Parts versus liaisons. A state can be a set of parts or a set of liaisons. When all liaisons inside a set of parts must be made together (the usual monotone model), the two are the same thing for a connected set of two or more parts. When a part can be placed with one liaison made and another left open, they differ.
  • Exponential lists. CONNECTED-SUBSETS is output sensitive, not polynomial. A product with one central part, such as a base plate that holds all others, has more than 2n−12^{n-1} connected sets.

Implementations

The Python module builds the graph of a list of boxes with integer or Fraction corners by the sweep, keeps neighbours as bit masks, and gives NEIGHBOURS, CUT, IS-CONNECTED and CONNECTED-SUBSETS by the GROW scheme. A shared helper holds the box predicates and a generator of random assemblies. The tests compare the sweep with the pairwise test on every pair for random assemblies of up to 30 boxes, compare each contact area and normal with a count of unit faces on a voxel grid, compare the connected sets and IS-CONNECTED with a check of all 2n2^n subsets for up to 9 parts, and check the counts for chains, stars and complete graphs.

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.

assembly_boxes.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the ma4 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Axis-aligned boxes for the assembly planning pages.

A box is a tuple (x0, y0, z0, x1, y1, z1) with x0 < x1, y0 < y1 and z0 < z1.
Coordinates are int or Fraction, so every test here is exact. A part is a
closed box, and two parts of an assembly may touch but their interiors must
be disjoint.
"""

from fractions import Fraction

AXES6 = ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1))

AXIS_NAMES = {
    (1, 0, 0): "+x", (-1, 0, 0): "-x",
    (0, 1, 0): "+y", (0, -1, 0): "-y",
    (0, 0, 1): "+z", (0, 0, -1): "-z",
}


def check_box(b):
    if len(b) != 6 or not all(b[k] < b[k + 3] for k in range(3)):
        raise ValueError("a box is (x0, y0, z0, x1, y1, z1) with x0 < x1, y0 < y1, z0 < z1")


def interiors_overlap(a, b):
    """True if the open boxes a and b meet, that is, the parts collide."""
    return all(a[k] < b[k + 3] and b[k] < a[k + 3] for k in range(3))


def is_valid_assembly(boxes):
    for b in boxes:
        check_box(b)
    n = len(boxes)
    return all(not interiors_overlap(boxes[i], boxes[j])
               for i in range(n) for j in range(i + 1, n))


def face_contact(a, b):
    """Return (k, s, area) if a and b share a planar patch of positive area.

    The contact normal from a to b is s times the unit vector e_k. Boxes that
    touch only along an edge or at a corner give None.
    """
    for k in range(3):
        if a[k + 3] == b[k]:
            s = 1
        elif b[k + 3] == a[k]:
            s = -1
        else:
            continue
        area = 1
        for m in range(3):
            if m == k:
                continue
            w = min(a[m + 3], b[m + 3]) - max(a[m], b[m])
            if w <= 0:
                area = 0
                break
            area *= w
        if area > 0:
            return (k, s, area)
    return None


def translate(b, d, t):
    """The box b moved by t times the vector d."""
    return tuple(b[k] + t * d[k % 3] for k in range(6))


def blocks(a, b, d):
    """True if box b blocks box a when a translates to infinity along d.

    d is one of AXES6. This is the extended translation model: a moves by
    t d for all t > 0, and b blocks it if a + t d meets the interior of b
    for some t > 0.
    """
    k = 0 if d[0] else (1 if d[1] else 2)
    for m in range(3):
        if m != k and not (a[m] < b[m + 3] and b[m] < a[m + 3]):
            return False
    if d[k] > 0:
        return b[k] >= a[k + 3]
    return b[k + 3] <= a[k]


def free_by_sampling(movers, others, d):
    """Reference test: do the boxes movers leave along d without a collision?

    Only for integer corners. Each collision of two boxes happens for t in an
    open interval with integer ends, so the half integers t = 1/2, 1, 3/2, ...
    up to the size of the scene meet every such interval.
    """
    span = 0
    for b in list(movers) + list(others):
        span = max(span, max(abs(c) for c in b))
    for step in range(1, 4 * span + 3):
        t = Fraction(step, 2)
        for a in movers:
            moved = translate(a, d, t)
            if any(interiors_overlap(moved, b) for b in others):
                return False
    return True


def members(mask):
    """The indices of the set bits of mask, in increasing order."""
    out = []
    i = 0
    while mask:
        if mask & 1:
            out.append(i)
        mask >>= 1
        i += 1
    return out


def random_boxes(rng, n, size=4, max_side=2, connected=True, tries=400):
    """n boxes with integer corners in [0, size]^3 and disjoint interiors.

    With connected=True, each new box shares a face patch with an earlier
    box, so the contact graph is connected. The result depends only on rng.
    """
    while True:
        boxes = []
        for _ in range(tries):
            lo = []
            hi = []
            for _k in range(3):
                side = rng.randint(1, max_side)
                x0 = rng.randint(0, size - side)
                lo.append(x0)
                hi.append(x0 + side)
            b = tuple(lo + hi)
            if any(interiors_overlap(b, c) for c in boxes):
                continue
            if connected and boxes and not any(face_contact(b, c) for c in boxes):
                continue
            boxes.append(b)
            if len(boxes) == n:
                return boxes
liaison_graph.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/liaison-graph/. The authors are listed in prov/RHWBG9.jsonl.
"""The liaison graph of an assembly of axis-aligned boxes.

A node is a part. A liaison joins two parts that share a face patch of
positive area (a contact), or two parts that the designer joins on purpose
(a fastener). A set of parts is stored as a bit mask.
"""


def contact(a, b):
    """Return (k, s, area) if boxes a and b share a planar patch of positive area.

    The boxes are (x0, y0, z0, x1, y1, z1) with disjoint interiors. The
    contact normal from a to b is s times e_k.
    """
    for k in range(3):  # @line L7
        if a[k + 3] == b[k]:  # @line L8
            s = 1
        elif b[k + 3] == a[k]:
            s = -1
        else:
            continue
        area = 1
        for m in range(3):  # @line L9
            if m == k:
                continue
            w = min(a[m + 3], b[m + 3]) - max(a[m], b[m])
            if w <= 0:
                area = 0
                break
            area *= w
        if area > 0:
            return (k, s, area)
    return None  # @line L10


class LiaisonGraph:
    def __init__(self, n):
        self.n = n
        self.adj = [0] * n          # adj[i]: bit mask of the neighbours of i
        self.label = {}             # (i, j) with i < j -> data of the liaison

    def add_liaison(self, i, j, data):
        if i == j:
            raise ValueError("a liaison joins two different parts")
        if i > j:
            i, j = j, i
        self.adj[i] |= 1 << j
        self.adj[j] |= 1 << i
        self.label[(i, j)] = data

    def neighbours(self, i):
        return [j for j in range(self.n) if self.adj[i] >> j & 1]

    def liaisons(self):
        return sorted(self.label)

    def neighbourhood(self, mask):
        """N(S): the parts outside mask that share a liaison with a part of mask."""
        out = 0
        m = mask
        while m:
            low = m & -m
            out |= self.adj[low.bit_length() - 1]
            m ^= low
        return out & ~mask

    def cut(self, mask):
        """The liaisons with exactly one end in mask."""
        return [(i, j) for (i, j) in self.liaisons()
                if (mask >> i & 1) != (mask >> j & 1)]  # @line L13

    def is_connected(self, mask):
        """True if mask is nonempty and its parts form one connected piece."""
        if mask == 0:
            return False
        reach = mask & -mask  # @line L11
        while True:
            grow = (reach | self.neighbourhood(reach)) & mask
            if grow == reach:
                return reach == mask  # @line L12
            reach = grow

    def connected_subsets(self, within=None):
        """Each connected subset of within (default: all parts) once."""
        full = (1 << self.n) - 1 if within is None else within
        out = []

        def grow(s, banned):
            out.append(s)  # @line L14
            cand = self.neighbourhood(s) & full & ~banned  # @line L15
            while cand:  # @line L16
                w = cand & -cand
                grow(s | w, banned)  # @line L17
                banned |= w
                cand ^= w

        banned = ~full  # @line L18
        m = full
        while m:  # @line L19
            v = m & -m
            grow(v, banned)  # @line L20
            banned |= v
            m ^= v
        return out


def build(boxes):
    """The contact liaisons of a list of boxes, found by a sweep along x."""
    g = LiaisonGraph(len(boxes))
    order = sorted(range(len(boxes)), key=lambda i: boxes[i][0])  # @line L1
    active = []
    for i in order:  # @line L2
        x0 = boxes[i][0]
        active = [j for j in active if boxes[j][3] >= x0]  # @line L3
        for j in active:  # @line L4
            a, b = (j, i) if j < i else (i, j)
            c = contact(boxes[a], boxes[b])
            if c is not None:  # @line L5
                g.add_liaison(a, b, ("contact",) + c)
        active.append(i)  # @line L6
    return g
test_liaison_graph.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/liaison-graph/. The authors are listed in prov/RHWBG9.jsonl.

import random
from fractions import Fraction

from assembly_boxes import face_contact, random_boxes, is_valid_assembly
from liaison_graph import LiaisonGraph, build

# ---- independent references ----


def all_pairs(boxes):
    """The pairwise test on every pair, with no sweep."""
    out = {}
    for i in range(len(boxes)):
        for j in range(i + 1, len(boxes)):
            c = face_contact(boxes[i], boxes[j])
            if c is not None:
                out[(i, j)] = ("contact",) + c
    return out


def voxel_faces(boxes, size):
    """Count unit faces between different boxes on a voxel grid."""
    owner = {}
    for idx, b in enumerate(boxes):
        for x in range(b[0], b[3]):
            for y in range(b[1], b[4]):
                for z in range(b[2], b[5]):
                    owner[(x, y, z)] = idx
    out = {}
    for (x, y, z), a in owner.items():
        for k in range(3):
            q = [x, y, z]
            q[k] += 1
            b = owner.get(tuple(q))
            if b is None or b == a:
                continue
            i, j, s = (a, b, 1) if a < b else (b, a, -1)
            key = (i, j)
            prev = out.get(key, ("contact", k, s, 0))
            assert prev[1] == k and prev[2] == s
            out[key] = ("contact", k, s, prev[3] + 1)
    return out


def connected_by_bfs(n, pairs, mask):
    parts = [i for i in range(n) if mask >> i & 1]
    if not parts:
        return False
    seen = {parts[0]}
    stack = [parts[0]]
    while stack:
        u = stack.pop()
        for (i, j) in pairs:
            for a, b in ((i, j), (j, i)):
                if a == u and mask >> b & 1 and b not in seen:
                    seen.add(b)
                    stack.append(b)
    return len(seen) == len(parts)


EXAMPLE = [
    (0, 0, 0, 4, 2, 1),   # 0 base plate
    (0, 0, 1, 1, 2, 3),   # 1 left post
    (3, 0, 1, 4, 2, 3),   # 2 right post
    (1, 0, 1, 3, 2, 2),   # 3 block
    (0, 0, 3, 4, 2, 4),   # 4 top plate
]

# ---- tests ----


def test_example():
    g = build(EXAMPLE)
    assert g.liaisons() == [(0, 1), (0, 2), (0, 3), (1, 3), (1, 4), (2, 3), (2, 4)]
    assert g.label[(0, 3)] == ("contact", 2, 1, 4)
    assert g.label[(1, 3)] == ("contact", 0, 1, 2)
    assert g.neighbours(3) == [0, 1, 2]
    assert g.cut(0b01000) == [(0, 3), (1, 3), (2, 3)]
    assert g.is_connected(0b11110)
    assert not g.is_connected(0b11000)
    assert len(g.connected_subsets()) == 27
    assert g.label[(2, 3)] == ("contact", 0, -1, 2)


def test_sweep_matches_all_pairs():
    rng = random.Random(1)
    for trial in range(300):
        n = rng.randint(1, 30)
        boxes = random_boxes(rng, n, size=8, max_side=3, connected=trial % 2 == 0)
        assert is_valid_assembly(boxes)
        g = build(boxes)
        assert g.label == all_pairs(boxes)


def test_contacts_match_voxel_faces():
    rng = random.Random(2)
    for _ in range(200):
        n = rng.randint(2, 12)
        boxes = random_boxes(rng, n, size=5, max_side=3, connected=False)
        assert build(boxes).label == voxel_faces(boxes, 5)


def test_edge_and_corner_touch_are_not_liaisons():
    a = (0, 0, 0, 1, 1, 1)
    edge = (1, 1, 0, 2, 2, 1)
    corner = (1, 1, 1, 2, 2, 2)
    face = (1, 0, 0, 2, 1, 1)
    g = build([a, edge, corner, face])
    assert (0, 1) not in g.label and (0, 2) not in g.label
    assert g.label[(0, 3)] == ("contact", 0, 1, 1)


def test_fraction_coordinates():
    h = Fraction(1, 2)
    boxes = [(0, 0, 0, h, 1, 1), (h, Fraction(1, 3), 0, 1, 1, 1)]
    g = build(boxes)
    assert g.label[(0, 1)] == ("contact", 0, 1, Fraction(2, 3))


def test_connected_subsets_against_all_subsets():
    rng = random.Random(3)
    for _ in range(150):
        n = rng.randint(1, 9)
        boxes = random_boxes(rng, n, size=5, max_side=2, connected=rng.random() < 0.7)
        g = build(boxes)
        pairs = g.liaisons()
        brute = sorted(m for m in range(1, 1 << n) if connected_by_bfs(n, pairs, m))
        got = g.connected_subsets()
        assert len(got) == len(set(got))
        assert sorted(got) == brute
        for m in range(1 << n):
            assert g.is_connected(m) == connected_by_bfs(n, pairs, m)


def test_counts_on_simple_graphs():
    for n in range(1, 9):
        chain = LiaisonGraph(n)
        for i in range(n - 1):
            chain.add_liaison(i, i + 1, ("fastener",))
        assert len(chain.connected_subsets()) == n * (n + 1) // 2
        star = LiaisonGraph(n)
        for i in range(1, n):
            star.add_liaison(0, i, ("fastener",))
        assert len(star.connected_subsets()) == 2 ** (n - 1) + n - 1
        full = LiaisonGraph(n)
        for i in range(n):
            for j in range(i + 1, n):
                full.add_liaison(i, j, ("fastener",))
        assert len(full.connected_subsets()) == 2 ** n - 1


def test_fastener_liaison():
    g = build([(0, 0, 0, 1, 1, 1), (2, 0, 0, 3, 1, 1)])
    assert g.liaisons() == []
    g.add_liaison(1, 0, ("fastener", "bolt"))
    assert g.liaisons() == [(0, 1)] and g.is_connected(0b11)

History

Bourjault introduced the graph of liaisons in his 1984 thesis at Besançon as the base of an automatic method for generating assembly sequences: the method asks the engineer questions about the liaisons. De Fazio and Whitney (1987) kept the liaison diagram and cut down the number of questions. Homem de Mello and Sanderson (1986 and 1990) built their AND/OR graph of plans on a relational model whose graph of connections is the same object. Whitney's book (2004) uses the liaison diagram as the start of assembly sequence analysis.

References

  1. Alain Bourjault, Contribution à une approche méthodologique de l'assemblage automatisé: élaboration automatique des séquences opératoires, Thèse d'État, Université de Franche-Comté, Besançon, 1984, the graph of liaisons of a product and the questions asked on its liaisons
  2. Thomas L. De Fazio and Daniel E. Whitney, Simplified generation of all mechanical assembly sequences, IEEE Journal of Robotics and Automation 3(6), 640 to 658 (1987), the liaison diagram of a product and the numbering of its liaisons
  3. Luiz S. Homem de Mello and Arthur C. Sanderson, AND/OR graph representation of assembly plans, IEEE Transactions on Robotics and Automation 6(2), 188 to 199 (1990), the relational model of an assembly and its graph of connections
  4. Daniel E. Whitney, Mechanical Assemblies: Their Design, Manufacture, and Role in Product Development, Oxford University Press, 2004, the chapter on assembly sequence analysis (the liaison diagram)

Where this leads

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.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)
WritingW4 complete
  • a review of the text: no review record reviews/RHWBG9/text.yaml