Algorithm Search⌘K

Data structureadvanced

Non-directional blocking graph

Also called NDBG, Wilson-Latombe blocking graph.

Wilson and Latombe's arrangement of directional blocking graphs over the sphere of translations, which finds a removable subassembly in polynomial time.

Time
O(n^2) worst
Space
O(n^2) extra
Where
n = the number of parts

The non-directional blocking graph (NDBG) of an assembly, due to Wilson and Latombe, answers one question for every direction at once: which sets of parts can move by a small translation in that direction while the other parts stay? For one direction dd, the directional blocking graph DBG(d)\mathrm{DBG}(d) has a node for each part and an arc i→ji \to j when part jj stops part ii from moving along dd. A set SS can move exactly when no arc leaves SS, so a removable set exists exactly when the graph is not strongly connected, and a sink component of its condensation is one. The graph changes only when dd crosses a great circle of the sphere of directions that is perpendicular to a contact plane. So the sphere falls into finitely many cells, with one graph per cell, and the NDBG is that list. For axis-aligned boxes there are 26 cells, and the whole structure costs O(n2)O(n^2).

In plain words

Push one part of a machine a tiny bit in some direction. Some other parts are in the way. Draw an arrow from the part you push to each part in the way. If you want to move a group of parts together, no arrow may go from the group to a part outside it.

Now look for parts that stop each other in a ring: A stops B, B stops C, C stops A. Such a ring can only move as one group. Squeeze each ring into one dot. The arrows between the dots never form a ring, so some dot has no arrow out. That group can move.

The arrows depend on the push direction. But they change only when the direction crosses a few special lines. So you only need to check one direction from each region between those lines.

The abstract type

The input is an assembly of nn rigid parts with disjoint interiors, which may touch. The structure is built for a stated model:

  • Motion model: one infinitesimal translation. A set SS moves by εd\varepsilon d for all small ε>0\varepsilon > 0. Rotations are not allowed, and a set that can make a small move may still collide later on its way out.
  • Hand model: two-handed. One hand moves SS as one rigid body, and the other hand holds the rest of the subassembly. The parts of SS do not move relative to each other, and SS does not need to be connected.

The operations are:

  • BUILD: the graph DBG(c)\mathrm{DBG}(c) for each cell cc of the sphere of directions,
  • CAN-MOVE(S,c)(S, c): can SS move along a direction of cell cc?
  • REMOVABLE(c,A)(c, A): a nonempty proper subset of a subassembly AA that can move along cell cc, or none,
  • SEPARATE(A)(A): a cell and a set that can move along it, or none if AA is locked.

Representation

For general polyhedra, a contact between two parts with a contact plane of normal ν\nu blocks the directions in a closed half sphere, and the border of that half sphere is the great circle perpendicular to ν\nu. The great circles of all contact planes cut the sphere into an arrangement of open cells of dimension 2, 1 and 0, as a line arrangement cuts the plane. Each cell keeps one graph. With rr different contact planes there are O(r2)O(r^2) cells.

For axis-aligned boxes, every contact plane is perpendicular to an axis, so the great circles are the three coordinate planes. They cut the sphere into 8 open triangles, 12 open arcs and 6 points, 26 cells in all. A cell is named by the sign vector s∈{−1,0,1}3∖{0}s \in \{-1, 0, 1\}^3 \setminus \{0\} of its directions. Each graph is a list of nn bit masks: bit jj of outc[i]out_c[i] is set when jj blocks ii along cell cc.

The test BLOCKED(a,b,s)(a, b, s) for two boxes looks at one axis at a time. On axis kk it is true when the open intervals of aa and bb overlap, or when the right end of aa touches the left end of bb and sk>0s_k > 0, or when the left end of aa touches the right end of bb and sk<0s_k < 0. Box bb blocks box aa when the test is true on all three axes. This rule also covers boxes that touch only along an edge or at a corner.

Operations

  1. BUILD(parts) ▷ 26 cells for boxes
  2. 1for each cell s ∈ {−1, 0, 1}³ \ {0} do
  3. 2for each ordered pair (i, j) of distinct parts do
  4. 3if BLOCKED(part i, part j, s) then
  5. 4add the arc i → j to DBG(s)
  6. CAN-MOVE(S, s, A) ▷ S ⊆ A, the parts of the subassembly
  7. 5return no arc of DBG(s) goes from a part of S to a part of A \ S
  8. REMOVABLE(s, A)
  9. 6run Tarjan's algorithm on DBG(s) restricted to A
  10. 7C ← the first strongly connected component that it completes
  11. 8if C = A then return none ▷ A is strongly connected along s
  12. 9return C ▷ C has no arc out
  13. SEPARATE(A)
  14. 10for each cell s: if REMOVABLE(s, A) is a set C, then return (s, C); return none

The first component. Tarjan's algorithm completes a component only after every component that it can reach. So the first completed one is a sink of the condensation graph, and it has no arc out. No second pass over the condensation is needed.

Subassemblies. The graph of a subassembly AA is the graph of the product restricted to AA, because blocking is a relation between two parts. So BUILD runs once, and REMOVABLE works for every node of an AND/OR graph.

All removable sets. A set can move along ss exactly when it is a union of components that is closed under the arcs of the condensation. All such sets can be listed from the condensation, which is how the motion space approach uses the graphs.

Example

Take three boxes that fill six of the eight unit cells of a 2×2×22 \times 2 \times 2 cube:

part corners shape
a (1,1,0)(1,1,0) to (2,2,2)(2,2,2) a column along zz
b (0,0,0)(0,0,0) to (2,1,1)(2,1,1) a bar along xx
c (0,0,1)(0,0,1) to (1,2,2)(1,2,2) a bar along yy

Move along a direction of the cell s=(+,−,+)s = (+, -, +), for example (1,−1,1)(1, -1, 1). Part a moves toward −y-y and its face y=1y = 1 lies on the face y=1y = 1 of b, so b blocks a. Part b moves toward +z+z and its top face lies on the bottom face of c, so c blocks b. Part c moves toward +x+x and its face x=1x = 1 lies on the face x=1x = 1 of a, so a blocks c. The graph is the cycle a→b→c→aa \to b \to c \to a, it is strongly connected, and no part and no pair can move along this cell. By the reverse rule, the cell (−,+,−)(-, +, -) has the reverse cycle. In the other 24 cells the graph has no cycle and some part can move: for example, along +x+x the only arc is c→ac \to a, and Tarjan's algorithm completes {a}\{a\} first. The 26 cells give 26 different graphs.

The frame of the liaison graph page shows the limit of the model. Its block sits on the base between two posts, with a gap of one unit below the top plate. Along +z+z the block can make a small move, so its set is free in DBG(+z)\mathrm{DBG}(+z). A translation to infinity along +z+z is still blocked by the top plate. The frame has only 9 different graphs, because all its parts have the same yy interval and so the sign of sys_y does not change any arc.

Correctness

For two boxes and a direction dd, the moved box a+εda + \varepsilon d meets the interior of bb for all small ε\varepsilon exactly when BLOCKED(a,b,sign(d))(a, b, \mathrm{sign}(d)) holds, and for no small ε\varepsilon otherwise. This follows from a check of one axis at a time. So the graph is constant on each cell. A rigid set SS collides only when one of its parts meets a part outside it, so SS can move exactly when no arc leaves it. If the graph restricted to AA is strongly connected, every proper subset has an arc out along a path to a part outside it. If it is not, the first component that Tarjan's algorithm completes has no arc out. Every direction lies in one of the 26 cells, so SEPARATE answers for all directions. The full proofs are in the correctness proof, which also shows that the six axis cells of a box product never have a cycle.

Proof: A set of parts can make a small translation exactly when no arc of the blocking graph leaves it, and the first strongly connected component that Tarjan's algorithm completes is such a setfull

We use the pseudocode and the model of the page. The parts are closed axis-aligned boxes with pairwise disjoint interiors. A box aa has corners (a1,a2,a3)(a_1, a_2, a_3) and (a1′,a2′,a3′)(a'_1, a'_2, a'_3) with ak<ak′a_k < a'_k. A direction is a nonzero vector d∈R3d \in \mathbb{R}^3, and its cell is its sign vector s=sign(d)∈{−1,0,1}3∖{0}s = \mathrm{sign}(d) \in \{-1, 0, 1\}^3 \setminus \{0\}. A set SS of parts can move along dd when there is ε0>0\varepsilon_0 > 0 such that, for every ε∈(0,ε0]\varepsilon \in (0, \varepsilon_0], the boxes of SS moved by εd\varepsilon d meet the interior of no part outside SS. This is the infinitesimal translation model. The hand model is two-handed: one hand moves SS as one rigid body and the other holds the rest.

The predicate of line L3, BLOCKED(a,b,s)\mathrm{BLOCKED}(a, b, s), is true when, for each axis kk, one of three conditions holds: ak<bk′a_k < b'_k and bk<ak′b_k < a'_k; or ak′=bka'_k = b_k and sk>0s_k > 0; or ak=bk′a_k = b'_k and sk<0s_k < 0. The graph DBG(s)\mathrm{DBG}(s) has an arc i→ji \to j when BLOCKED(bi,bj,s)\mathrm{BLOCKED}(b_i, b_j, s).

Lemma 1 (the axis test). Let aa and bb be two boxes with disjoint interiors and let dd be a direction with cell ss. Then a+εda + \varepsilon d meets the interior of bb for every small enough ε>0\varepsilon > 0 if BLOCKED(a,b,s)\mathrm{BLOCKED}(a, b, s), and for no small enough ε>0\varepsilon > 0 otherwise.

Proof. Two open boxes meet exactly when their open intervals meet on each of the three axes. On axis kk, the moved interval is (ak+εdk,ak′+εdk)(a_k + \varepsilon d_k, a'_k + \varepsilon d_k), and it meets (bk,bk′)(b_k, b'_k) exactly when ak+εdk<bk′a_k + \varepsilon d_k < b'_k and bk<ak′+εdkb_k < a'_k + \varepsilon d_k. Look at the cases.

  • If ak<bk′a_k < b'_k and bk<ak′b_k < a'_k, both strict inequalities stay true for small ε\varepsilon.
  • If ak′=bka'_k = b_k, the second inequality reads 0<εdk0 < \varepsilon d_k, which holds exactly when sk>0s_k > 0. The first holds, because ak<ak′=bk<bk′a_k < a'_k = b_k < b'_k.
  • If ak=bk′a_k = b'_k, the first inequality reads εdk<0\varepsilon d_k < 0, which holds exactly when sk<0s_k < 0, and the second holds for the same reason.
  • Otherwise ak′<bka'_k < b_k or bk′<akb'_k < a_k, and a gap of positive length stays open for small ε\varepsilon.

In each case the answer is the same for all small ε\varepsilon, and it is the condition of BLOCKED on axis kk. Take the smallest of the three thresholds. □\square

Corollary 1 (cells). DBG(d)\mathrm{DBG}(d) depends only on the cell of dd. So the 26 graphs of line L1 are all the directional blocking graphs of the product.

Lemma 2 (a set moves when no arc leaves it). A set SS can move along dd if and only if DBG(s)\mathrm{DBG}(s) has no arc from a part of SS to a part outside SS.

Proof. The parts of SS move together, so two parts of SS never collide, and the parts outside SS do not move, so they never collide with each other. A collision is a pair i∈Si \in S, j∉Sj \notin S with bi+εdb_i + \varepsilon d meeting the interior of bjb_j. By Lemma 1, for each such pair there is a threshold below which this happens for all ε\varepsilon when i→ji \to j is an arc, and for no ε\varepsilon when it is not. There are finitely many pairs, so below the smallest threshold, SS collides exactly when an arc leaves SS. □\square

So line L5 is correct. A set with no arc out is a union of strongly connected components: if i∈Si \in S and jj is in the component of ii, there is a path from ii to jj, and no arc of it can leave SS.

Lemma 3 (the first component is a sink). In Tarjan's algorithm on a graph GG, a component is completed only after every other component that it can reach. So the first completed component CC has no arc to a part outside CC.

Proof. This is the standard property of Tarjan's algorithm: the components come out in reverse topological order of the condensation of GG. If CC had an arc to a part ww of another component C′C', then C′C' is reachable from CC and would be completed before CC, which contradicts that CC is first. □\square

Theorem 1 (the SCC test). Let AA be a set of at least one part. REMOVABLE(s,A)(s, A) returns a nonempty proper subset of AA that can move along any dd of cell ss, with the other parts of AA fixed, if one exists, and returns none otherwise.

Proof. Lines L6 and L7 run on the graph induced on AA, which is DBG(s)\mathrm{DBG}(s) of the subassembly AA, because blocking is a relation between two parts. If line L9 returns CC, then CC is a component, so it is nonempty, it is not AA by line L8, and no arc leaves it by Lemma 3. By Lemma 2 it can move. If line L8 returns none, then AA is one strongly connected component. Take any nonempty proper S⊂AS \subset A and parts i∈Si \in S, j∈A∖Sj \in A \setminus S. There is a path from ii to jj in the induced graph, and one of its arcs leaves SS, so SS cannot move by Lemma 2. □\square

Theorem 2 (one translation in any direction). SEPARATE(A)(A) returns a cell and a set that can move along it if some nonempty proper subset of AA can move along some direction, and none if AA is locked for every small translation.

Proof. Every direction lies in exactly one of the 26 cells, and by Corollary 1 the cell decides the graph. Line L10 tries every cell, and Theorem 1 answers each one. □\square

Lemma 4 (reverse cells). DBG(−s)\mathrm{DBG}(-s) is DBG(s)\mathrm{DBG}(s) with every arc reversed.

Proof. a+εda + \varepsilon d meets the interior of bb exactly when b−εdb - \varepsilon d meets the interior of aa, because both say that the open boxes overlap after a relative motion of εd\varepsilon d. Apply Lemma 1 on both sides. □\square

Lemma 5 (axis cells have no cycle). For s=±eks = \pm e_k, DBG(s)\mathrm{DBG}(s) has no cycle. So some single part of any product can move along each of the six axis directions.

Proof. Take s=+e1s = +e_1. An arc i→ji \to j needs open overlap on axes 2 and 3, where ss is 0. The interiors are disjoint, so the intervals on axis 1 do not overlap, and the arc needs bi,1′=bj,1b'_{i,1} = b_{j,1}. Then bj,1>bi,1b_{j,1} > b_{i,1}, and the lower xx coordinate grows strictly along each path. The other axis cells are the same. A graph with no cycle has only single parts as components, and the first one is a sink. □\square

The off-axis cells can have cycles. Three boxes in a 2×2×22 \times 2 \times 2 cube give a cycle of length 3 in the cell (+,−,+)(+, -, +), as the example of the page shows.

Termination and cost. Line L1 runs 26 times, and lines L2 to L4 test each ordered pair once, in O(1)O(1) time, so BUILD costs O(n2)O(n^2). Tarjan's algorithm visits each part and each arc once, so line L6 costs O(n+e)O(n + e) with e≤n(n−1)e \le n(n-1) arcs, and SEPARATE costs O(n2)O(n^2) for one subassembly.

Scope. The proofs are about small motions. A set that can make a small move may still collide later on its way out: in the frame of the page, the block can move up a little, but the top plate stops it before it leaves. The test for one translation to infinity uses other blocking graphs, and the same SCC argument holds for them, because Lemma 2 and Theorem 1 use only that a collision of a rigid set is a collision of one pair.

Complexity

For boxes, BUILD tests 26⋅n(n−1)26 \cdot n(n-1) ordered pairs in O(1)O(1) time each, which is O(n2)O(n^2) time, and stores 26 graphs of nn masks of nn bits, which is O(n2)O(n^2) space. Tarjan's algorithm costs O(n+e)O(n + e) for ee arcs, so SEPARATE costs O(n2)O(n^2) for one subassembly. For polyhedra with rr contact planes, the arrangement has O(r2)O(r^2) cells and each graph costs O(n2)O(n^2) pairs of parts plus the contact tests, so the structure is polynomial in the size of the input. This is the main result of Wilson and Latombe: with one small translation, a removable subassembly is found in polynomial time, even though there are 2n−22^n - 2 candidate sets.

The hardness results mark the edge of that result. If the moving set may follow any collision free path and not only one translation, deciding whether a proper subassembly can be removed is NP-complete for polygons in the plane (Kavraki, Latombe and Wilson, 1993). If both sides of a partition must be connected, partitioning a planar assembly is NP-complete (Kavraki and Kolountzakis, 1995). The assembly partitioning page gives the details.

Variants

  • One translation to infinity. A set that can leave along dd is the same test with a different arc rule: jj blocks ii when the swept volume of ii along dd meets jj. For boxes and the six axis directions this is a test of one axis at a time, and the graph along an axis has no cycle. The motion space approach uses these graphs.
  • Small rigid motions. Wilson and Latombe also built the graph for small motions with rotation. The space of motions is then 6-dimensional, and the cells come from an arrangement of hyperplanes in it.
  • The motion space. Halperin, Latombe and Wilson put the NDBG into a general frame: cut a space of motions into cells where the blocking graph does not change, then run the strong connectivity test in each cell.
  • Connected sides. A planner that wants connected subassemblies must search among the closed unions of components for one whose sides are connected. This is the step that the hardness result of Kavraki and Kolountzakis is about.

When to use it

Use the NDBG to answer the question of one partition for a polyhedral product, or to fill the hyperarcs of an AND/OR graph or the answers of the De Fazio and Whitney method from geometry. It is the right tool when parts touch along faces and the main question is which way each part can start to move. Use extended blocking graphs, or a motion planner, when a part must travel far through a cluttered product.

Pitfalls

  • Small motion is not removal. A set that is free in a cell may still hit another part farther along. The frame block can move up a little but cannot leave along +z+z. Use the infinitesimal graph to find candidates and confirm each one with a test of the full path.
  • Edge and corner contacts. Two boxes that touch only along an edge can block each other in the off-axis cells. A test that looks only at face contacts misses those arcs.
  • The 1-cells and 0-cells. A direction such as +x+x lies on the border of four triangle cells, and its graph has only arcs that each of them also has, often fewer. Checking only the open triangles can miss a set that moves along an axis.
  • Floating point. The cell of a direction is decided by exact equalities between coordinates. Use exact numbers, or snap contacts with a stated tolerance.
  • A disconnected answer. The removable set may not be connected, and its complement may not be connected either. If the plan needs connected subassemblies, check that after the SCC test.

Implementations

The Python module builds the 26 graphs for boxes with integer or Fraction corners as bit masks, and gives CAN-MOVE, Tarjan's algorithm, REMOVABLE and SEPARATE. A shared helper holds the box predicates. The tests compare the test BLOCKED with a real small step, on random products with face, edge and corner contacts and on random directions of each cell. They compare CAN-MOVE and REMOVABLE with a step of every subset of up to 6 parts in every cell, and SEPARATE with every subassembly. They also check the reverse cell rule, the invariance under a scale of the coordinates, and the example.

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
non_directional_blocking_graph.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/non-directional-blocking-graph/. The authors are listed in prov/RMGX71.jsonl.
"""The non-directional blocking graph of a product of axis-aligned boxes.

Motion model: one infinitesimal translation. A set S of parts moves as one
rigid body by e d for a small e > 0, and the other parts stay. Hand model:
two-handed, one hand holds S and the other holds the rest.

The contact normals of boxes are the six axis directions, so their great
circles are the three coordinate planes. They cut the sphere of directions
into 26 cells: 8 open triangles, 12 open arcs and 6 points. A cell is named
by the sign vector of its directions, in {-1, 0, 1}^3 without (0, 0, 0). The
directional blocking graph DBG(s) is the same for all directions of a cell,
and the NDBG is the list of the 26 graphs.

A graph is a list out with one bit mask per part: bit j of out[i] is set
when part j blocks part i, that is, i cannot move along s without j.
"""

from assembly_boxes import members

CELLS = tuple((sx, sy, sz) for sx in (-1, 0, 1) for sy in (-1, 0, 1) for sz in (-1, 0, 1)
              if (sx, sy, sz) != (0, 0, 0))


def cell_of(d):
    """The cell of a nonzero direction vector d: its sign vector."""
    return tuple((x > 0) - (x < 0) for x in d)


def blocked(a, b, s):
    """True if box b blocks a small translation of box a along cell s.

    a + e d meets the open box b for all small e > 0 exactly when, on each
    axis, the open intervals already overlap, or they touch and d moves a
    into b on that axis.
    """
    for k in range(3):
        if a[k] < b[k + 3] and b[k] < a[k + 3]:
            continue
        if a[k + 3] == b[k] and s[k] > 0:
            continue
        if a[k] == b[k + 3] and s[k] < 0:
            continue
        return False
    return True


def build(boxes):
    """The NDBG: a dict from each of the 26 cells to its blocking graph."""
    n = len(boxes)
    ndbg = {}
    for s in CELLS:  # @line L1
        out = [0] * n
        for i in range(n):  # @line L2
            for j in range(n):
                if i != j and blocked(boxes[i], boxes[j], s):  # @line L3
                    out[i] |= 1 << j  # @line L4
        ndbg[s] = out
    return ndbg


def can_move(out, s_mask, within):
    """True if the parts s_mask can move with no part of within \\ s_mask."""
    rest = within & ~s_mask
    return all(out[i] & rest == 0 for i in members(s_mask))  # @line L5


def tarjan_sccs(out, within):
    """The strongly connected components of the graph induced on within,
    as bit masks, in the order Tarjan's algorithm completes them. A component
    is completed after every component that it can reach, so the first one
    has no arc to another component."""
    index, low, on_stack = {}, {}, set()
    stack, comps = [], []
    counter = 0
    for root in members(within):
        if root in index:
            continue
        index[root] = low[root] = counter
        counter += 1
        stack.append(root)
        on_stack.add(root)
        work = [(root, iter(members(out[root] & within)))]
        while work:
            v, it = work[-1]
            pushed = False
            for w in it:
                if w not in index:
                    index[w] = low[w] = counter
                    counter += 1
                    stack.append(w)
                    on_stack.add(w)
                    work.append((w, iter(members(out[w] & within))))
                    pushed = True
                    break
                if w in on_stack:
                    low[v] = min(low[v], index[w])
            if pushed:
                continue
            work.pop()
            if work:
                u = work[-1][0]
                low[u] = min(low[u], low[v])
            if low[v] == index[v]:
                comp = 0
                while True:
                    w = stack.pop()
                    on_stack.discard(w)
                    comp |= 1 << w
                    if w == v:
                        break
                comps.append(comp)
    return comps


def removable(out, within):
    """A nonempty proper subset of within that can move, or None."""
    comps = tarjan_sccs(out, within)  # @line L6
    first = comps[0]  # @line L7
    if first == within:  # @line L8
        return None
    return first  # @line L9


def separate(ndbg, within):
    """A cell and a set of parts that can move along it, or None if the
    subassembly within is locked for every small translation."""
    for s in CELLS:  # @line L10
        c = removable(ndbg[s], within)
        if c is not None:
            return s, c
    return None
test_non_directional_blocking_graph.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/non-directional-blocking-graph/. The authors are listed in prov/RMGX71.jsonl.

import random
from fractions import Fraction

from assembly_boxes import (
    free_by_sampling, interiors_overlap, is_valid_assembly, random_boxes, translate)
from non_directional_blocking_graph import (
    CELLS, blocked, build, can_move, cell_of, removable, separate, tarjan_sccs)

# ---- independent reference: move the parts a small step and look ----


def step(d):
    """A step length for direction d that is small enough for integer corners:
    each coordinate moves by at most 1/2, so a gap of at least 1 stays open
    and an overlap of at least 1 stays closed."""
    return Fraction(1, 2 * max(abs(x) for x in d))


def moves_freely(boxes, s_mask, d):
    """Does the set s_mask move by a small step along d with no collision?"""
    t = step(d)
    n = len(boxes)
    moved = [translate(boxes[i], d, t) for i in range(n) if s_mask >> i & 1]
    rest = [boxes[j] for j in range(n) if not s_mask >> j & 1]
    return not any(interiors_overlap(a, b) for a in moved for b in rest)


def directions_in(rng, s, count):
    """Random integer direction vectors whose sign vector is s."""
    out = [s]
    for _ in range(count):
        out.append(tuple(x * rng.randint(1, 3) for x in s))
    return out


def scenes(rng, count, n_max):
    """Random products, some with parts that touch only at an edge or a corner."""
    out = []
    for _ in range(count):
        n = rng.randint(2, n_max)
        out.append(random_boxes(rng, n, size=3, max_side=2, connected=rng.random() < 0.7))
    out.append([(0, 0, 0, 1, 1, 1), (1, 1, 1, 2, 2, 2)])            # corner contact
    out.append([(0, 0, 0, 1, 1, 1), (1, 1, 0, 2, 2, 1)])            # edge contact
    out.append([(0, 0, 0, 1, 1, 1), (1, 0, 0, 2, 1, 1), (0, 1, 0, 2, 2, 1)])
    return out


# ---- tests ----


def test_blocking_matches_a_small_motion():
    rng = random.Random(31)
    for boxes in scenes(rng, 60, 4):
        assert is_valid_assembly(boxes)
        for s in CELLS:
            for d in directions_in(rng, s, 2):
                assert cell_of(d) == s
                for i, a in enumerate(boxes):
                    for j, b in enumerate(boxes):
                        if i != j:
                            moved = translate(a, d, step(d))
                            assert blocked(a, b, s) == interiors_overlap(moved, b)


def test_reverse_cell_is_reverse_graph():
    rng = random.Random(32)
    for boxes in scenes(rng, 30, 5):
        g = build(boxes)
        n = len(boxes)
        for s in CELLS:
            minus = tuple(-x for x in s)
            for i in range(n):
                for j in range(n):
                    assert (g[s][i] >> j & 1) == (g[minus][j] >> i & 1)


def test_can_move_and_scc_against_all_subsets():
    rng = random.Random(33)
    for boxes in scenes(rng, 40, 6):
        n = len(boxes)
        g = build(boxes)
        full = (1 << n) - 1
        for s in CELLS:
            out = g[s]
            movable = []
            for mask in range(1, full):
                ok = moves_freely(boxes, mask, s)
                assert can_move(out, mask, full) == ok
                if ok:
                    movable.append(mask)
            c = removable(out, full)
            if movable:
                assert c is not None and c in movable
            else:
                assert c is None
            # every movable set is a union of strongly connected components
            comps = tarjan_sccs(out, full)
            assert sum(comps) == full
            for m in movable:
                assert all(m & k in (0, k) for k in comps)


def test_subassemblies():
    rng = random.Random(34)
    for boxes in scenes(rng, 20, 6):
        n = len(boxes)
        g = build(boxes)
        for within in range(1, 1 << n):
            sub = [boxes[i] for i in range(n) if within >> i & 1]
            index = [i for i in range(n) if within >> i & 1]
            found = separate(g, within)
            any_free = any(
                moves_freely(sub, m, s) for s in CELLS for m in range(1, (1 << len(sub)) - 1))
            assert (found is not None) == any_free
            if found is not None:
                s, c = found
                local = sum(1 << index.index(i) for i in range(n) if c >> i & 1)
                assert moves_freely(sub, local, s)


def test_fraction_coordinates():
    rng = random.Random(35)
    for _ in range(20):
        boxes = random_boxes(rng, 4, size=3, max_side=2, connected=True)
        scaled = [tuple(Fraction(c, 7) for c in b) for b in boxes]
        assert build(scaled) == build(boxes)


def test_example_three_bars():
    bars = [
        (1, 1, 0, 2, 2, 2),   # 0 a: a column along z
        (0, 0, 0, 2, 1, 1),   # 1 b: a bar along x
        (0, 0, 1, 1, 2, 2),   # 2 c: a bar along y
    ]
    g = build(bars)
    assert len({tuple(out) for out in g.values()}) == 26
    # along (+, -, +): a is blocked by b, b by c and c by a
    assert g[(1, -1, 1)] == [1 << 1, 1 << 2, 1 << 0]
    locked = sorted(s for s in CELLS if removable(g[s], 7) is None)
    assert locked == [(-1, 1, -1), (1, -1, 1)]
    # along each axis cell the graph has no cycle, so a part can move
    for s in CELLS:
        if sum(map(abs, s)) == 1:
            assert all(bin(c).count("1") == 1 for c in tarjan_sccs(g[s], 7))


def test_example_frame():
    frame = [
        (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
    ]
    g = build(frame)
    full = 31
    assert len({tuple(out) for out in g.values()}) == 9
    # along +x the left post is blocked by the block, the block by the right post
    assert g[(1, 0, 0)][1] == 1 << 3 and g[(1, 0, 0)][3] == 1 << 2
    # a small step up is free for the block, because it does not touch the top
    # plate; a translation to infinity along +z is not
    assert can_move(g[(0, 0, 1)], 1 << 3, full)
    assert not moves_far(frame, 3, (0, 0, 1))
    assert separate(g, full) is not None


def moves_far(boxes, i, d):
    return free_by_sampling([boxes[i]], [b for j, b in enumerate(boxes) if j != i], d)

History

Wilson and Latombe introduced the non-directional blocking graph in 1994. Their result changed the view of assembly partitioning: before it, planners tested cuts of the liaison graph one by one, which takes exponential time in the worst case. Wilson, Kavraki, Latombe and Lozano-Pérez used blocking graphs to generate two-handed sequences in 1995. Halperin, Latombe and Wilson generalized the idea to the motion space approach in 2000.

References

  1. Randall H. Wilson and Jean-Claude Latombe, Geometric reasoning about mechanical assembly, Artificial Intelligence 71(2), 371 to 396 (1994), the directional blocking graph, the non-directional blocking graph over the arrangement of great circles on the sphere of directions, and the strong connectivity test for a removable subassembly
  2. Randall H. Wilson, Lydia E. Kavraki, Jean-Claude Latombe and Tomás Lozano-Pérez, Two-handed assembly sequencing, International Journal of Robotics Research 14(4) (1995), blocking graphs for one translation to infinity and their use to generate partitionings
  3. Dan Halperin, Jean-Claude Latombe and Randall H. Wilson, A general framework for assembly planning, the motion space approach, Algorithmica 26(3-4), 577 to 601 (2000), the blocking graph of each cell of a motion space, of which the NDBG is the case of small translations
  4. Lydia E. Kavraki, Jean-Claude Latombe and Randall H. Wilson, On the complexity of assembly partitioning, Information Processing Letters 48(5), 229 to 235 (1993), the NP-completeness of assembly partitioning when the motion is not restricted to one translation
  5. Lydia E. Kavraki and Mihail N. Kolountzakis, Partitioning a planar assembly into two connected parts is NP-complete, Information Processing Letters 55(3), 159 to 165 (1995), the hardness of partitioning when both subassemblies must be connected

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/RMGX71/text.yaml