Algorithm Search⌘K

Algorithmresearch

Motion space approach to assembly planning

Also called motion space assembly framework.

Halperin, Latombe and Wilson's framework that splits the space of subassembly motions into cells of constant blocking relations and searches it for separations.

Time
O(n^2 + n R) worst
Space
O(n^2 + R) extra
Where
R = the number of removable sets in the output over the six directions; n = the number of parts of the subassembly
Properties
deterministicexactrecursive
Origin
Dan Halperin, Jean Claude Latombe, Randall H. Wilson, 2000

The motion space approach of Halperin, Latombe and Wilson is a general method to find the subassemblies that can be taken out of an assembly. First choose a family of motions, such as all translations to infinity or all small rigid motions, and treat the family as a space. For each pair of parts, find the motions of that space along which one part hits the other. These sets cut the space into cells, and inside one cell the blocking graph, with an arc i→ji \to j when jj is in the way of ii, does not change. In each cell, a set of parts can move exactly when no arc leaves it, so the removable sets are the closed unions of the strongly connected components of the cell's graph. The non-directional blocking graph is the case of small translations. This page implements one core step: the removable subassemblies along the six axis directions, where each direction is its own cell.

In plain words

To take a machine apart, you must choose what to pull out and which way to pull it. There are many ways to pull. But two ways that are close together often hit the same parts. So group the ways to pull into regions where the same parts are in the way.

In one region, draw an arrow from each part to each part that stops it. A group of parts can come out when no arrow goes from the group to a part outside it. Parts that stop each other in a ring must come out together, so squeeze each ring into one dot. Then list every group of dots that no arrow leaves.

Do this for every region, and you know every group that can come out with that kind of pull.

The problem

The input is a subassembly AA of rigid parts and a motion space M\mathcal{M}. The output is every pair (m,S)(m, S) of a motion m∈Mm \in \mathcal{M}, given by its cell, and a nonempty proper subset S⊂AS \subset A that can move along mm while A∖SA \setminus S stays. The partitions of AA are the question of assembly partitioning. This page finds the separations of one subassembly, and the assembly sequence planning problem chains such separations into a whole plan, for example in an AND/OR graph.

The model of the implemented step is:

  • Motion model: one translation to infinity along an axis. The motion space is the finite set {+x,−x,+y,−y,+z,−z}\{+x, -x, +y, -y, +z, -z\}. Each direction is one cell.
  • Hand model: two-handed. SS moves as one rigid body and A∖SA \setminus S stays. Neither side needs to be connected.
  • Parts: axis-aligned boxes with disjoint interiors, which may touch.

The algorithm

The approach has five steps. The implemented one is step 4.

  1. Choose the motion space M\mathcal{M}.
  2. For each ordered pair of parts (i,j)(i, j), compute the set Bij⊆MB_{ij} \subseteq \mathcal{M} of motions along which part ii meets part jj. For translations to infinity, these are the directions dd for which the ray from the origin along dd meets the Minkowski difference of jj and ii.
  3. Compute the arrangement of the borders of all BijB_{ij}. In each cell, the blocking graph is constant.
  4. For each cell, build the blocking graph, compute its strongly connected components, and list the closed sets.
  5. Use the closed sets to answer a partitioning query, or to fill the hyperarcs of an AND/OR graph.

For the six axis directions, steps 1 to 3 are trivial, and step 4 is:

  1. REMOVABLE-SETS(A) ▷ A: a subassembly; M: the six axis directions
  2. 1for each direction d ∈ M do ▷ each direction is one cell
  3. 2for each ordered pair (i, j) of distinct parts of A do
  4. 3if j blocks i along d then add the arc i → j to G_d
  5. 4C_0, …, C_{k−1} ← the components of G_d in the order Tarjan's algorithm completes them
  6. 5succ[t] ← the parts outside C_t that an arc from C_t reaches, for each t
  7. EXTEND(0, ∅)
  8. EXTEND(t, chosen) ▷ chosen: a union of C_0, …, C_{t−1}
  9. 6if t < k then go to L8
  10. 7output chosen as a set that leaves along d, if chosen ≠ ∅ and chosen ≠ A; return
  11. 8EXTEND(t + 1, chosen) ▷ C_t stays
  12. 9if succ[t] ⊆ chosen then EXTEND(t + 1, chosen ∪ C_t) ▷ C_t moves

The blocking test. Box jj blocks box ii along +x+x when their open yy intervals overlap, their open zz intervals overlap, and jj lies at or beyond the right face of ii. The other directions are the same with other axes and signs.

Why the order of Tarjan's algorithm. Tarjan's algorithm completes a component only after every component that it reaches. So when EXTEND decides on CtC_t, it has already decided on every component that CtC_t points to, and the test of line L9 is final. Every path of calls ends in a valid set, and no call is wasted.

Example

Take the frame of the liaison graph page: base plate 0, left post 1, right post 2, block 3 on the base between the posts, top plate 4 on the posts. All parts have the same yy interval. The blocking graphs are:

direction arcs removable sets
+x+x 1→21 \to 2, 1→31 \to 3, 3→23 \to 2 14
−x-x 2→12 \to 1, 2→32 \to 3, 3→13 \to 1 14
+y+y, −y-y none 30 each
+z+z 0→1,2,3,40 \to 1, 2, 3, 4; 1→41 \to 4; 2→42 \to 4; 3→43 \to 4 8
−z-z 4→0,1,2,34 \to 0, 1, 2, 3; 1→01 \to 0; 2→02 \to 0; 3→03 \to 0 8

Along +z+z, a set that holds the base must hold all parts above it, so it is all of AA. A set without the base can leave exactly when it holds the top plate. Any subset of {1,2,3}\{1, 2, 3\} can go with it, which gives 23=82^3 = 8 sets. Along +x+x, the parts 0 and 4 have no arcs and are free to join any set, and the closed subsets of {1,2,3}\{1, 2, 3\} are ∅\emptyset, {2}\{2\}, {2,3}\{2, 3\} and {1,2,3}\{1, 2, 3\}. That gives 4⋅4=164 \cdot 4 = 16 closed sets, and 14 without ∅\emptyset and AA. Along ±y\pm y every one of the 25−2=302^5 - 2 = 30 sets can leave.

Read as splits, the four directions in the plane of the frame give 13 of the 15 splits of the frame into two sets. The two splits that are missing are {0,1,2,4}\{0, 1, 2, 4\} against {3}\{3\}, because the closed frame holds the block, and {0,3,4}\{0, 3, 4\} against {1,2}\{1, 2\}. In the second one, the two posts cannot move together along ±x\pm x because the block is between them, and the base and the top plate stop them along ±z\pm z. Of the 13 splits, 11 have two connected sides, and these are the 11 hyperarcs of the root in the AND/OR graph example. With the ±y\pm y directions, all 15 splits are possible.

Correctness

Box jj blocks box ii along an axis direction exactly when ii hits jj for some distance of travel, which follows from a test on one axis. A rigid set SS collides only when one of its parts hits a part outside it, so SS can leave exactly when no arc of GdG_d leaves SS. Such a closed set is a union of components. Because the components come in the order of Tarjan's algorithm, the test of line L9 is final when it is made, so the recursion outputs every closed set except ∅\emptyset and AA once, and nothing else. For boxes and an axis direction, an arc always goes to a part with a larger lower coordinate on that axis, so GdG_d has no cycle and each component is one part. The full proofs are in the correctness proof.

Proof: The core step lists, for each of the six axis directions, exactly the subsets of a subassembly that can leave the rest by one translationfull

This proof covers the one step of the motion space approach that the page implements: lines L1 to L9, for the motion space of the six axis translations to infinity. The parts are closed axis-aligned boxes with 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). A subassembly is a set AA of parts. A nonempty proper subset S⊂AS \subset A can leave along dd when, for every t>0t > 0, no part of SS moved by tdt d meets the interior of a part of A∖SA \setminus S. The hand model is two-handed: SS moves as one rigid body and A∖SA \setminus S stays.

The graph GdG_d of lines L2 and L3 has the parts of AA as nodes and an arc i→ji \to j when blocks(bi,bj,d)\mathrm{blocks}(b_i, b_j, d). For d=+ekd = +e_k the predicate is: on both axes m≠km \ne k the open intervals of bib_i and bjb_j overlap, and bj,k≥bi,k′b_{j,k} \ge b'_{i,k}. For d=−ekd = -e_k the last condition is bj,k′≤bi,kb'_{j,k} \le b_{i,k}.

Lemma 1 (the pair test). For two boxes aa, bb with disjoint interiors and d∈{±e1,±e2,±e3}d \in \{\pm e_1, \pm e_2, \pm e_3\}, there is a t>0t > 0 for which a+tda + t d meets the interior of bb if and only if blocks(a,b,d)\mathrm{blocks}(a, b, d).

Proof. Take d=+ekd = +e_k. The motion does not change the intervals on the axes m≠km \ne k, so these must overlap, as the predicate asks. On axis kk, the interval (ak+t,ak′+t)(a_k + t, a'_k + t) meets (bk,bk′)(b_k, b'_k) when bk−ak′<t<bk′−akb_k - a'_k < t < b'_k - a_k. Some t>0t > 0 satisfies this exactly when bk′>akb'_k > a_k, because bk′−ak>bk−ak′b'_k - a_k > b_k - a'_k always holds. The intervals on the other two axes overlap and the interiors are disjoint, so the intervals on axis kk do not overlap: either bk≥ak′b_k \ge a'_k or bk′≤akb'_k \le a_k. Of these, bk′>akb'_k > a_k holds exactly in the first case, which is the predicate. The case d=−ekd = -e_k is the mirror image. □\square

Lemma 2 (a set leaves when no arc leaves it). SS can leave along dd if and only if GdG_d has no arc from a part of SS to a part of A∖SA \setminus S.

Proof. The parts of SS keep their relative positions and the parts of A∖SA \setminus S do not move, so a collision at some tt is a pair i∈Si \in S, j∈A∖Sj \in A \setminus S with bi+tdb_i + t d meeting the interior of bjb_j. By Lemma 1 such a tt exists for the pair exactly when i→ji \to j is an arc. □\square

Call a set closed when no arc of GdG_d leaves it. A closed set is a union of strongly connected components: if i∈Si \in S and jj is in the component of ii, a path goes from ii to jj, and none of its arcs leaves SS.

Lemma 3 (the order of the components). Let C0,…,Ck−1C_0, \ldots, C_{k-1} be the components in the order that Tarjan's algorithm completes them on line L4. If an arc goes from CtC_t to CuC_u with u≠tu \ne t, then u<tu < t.

Proof. Tarjan's algorithm completes a component only after every other component that it can reach, which is the standard reverse topological order of the condensation. □\square

Lemma 4 (the enumeration). The calls of lines L6 to L9 output every closed set other than ∅\emptyset and AA exactly once, and nothing else.

Proof. Line L5 sets succ[t]succ[t] to the parts of AA outside CtC_t that an arc from CtC_t reaches. By Lemma 3, succ[t]⊆C0∪⋯∪Ct−1succ[t] \subseteq C_0 \cup \cdots \cup C_{t-1}. A call EXTEND(t,chosen)\mathrm{EXTEND}(t, chosen) has decided, for each u<tu < t, whether Cu⊆chosenC_u \subseteq chosen, and chosenchosen is the union of the chosen components. Line L8 leaves CtC_t out, and line L9 puts it in when succ[t]⊆chosensucc[t] \subseteq chosen.

Only closed sets. By induction on tt, chosenchosen is closed at each call: a component put in at line L9 has all its targets in chosenchosen already, and the targets of earlier components do not change.

All closed sets. Let SS be closed. Then SS is a union of components, and for each Ct⊆SC_t \subseteq S, succ[t]⊆S∩(C0∪⋯∪Ct−1)succ[t] \subseteq S \cap (C_0 \cup \cdots \cup C_{t-1}). So the path of calls that puts in exactly the components of SS passes the test of line L9 at each step, and it reaches t=kt = k with chosen=Schosen = S.

Once. Two different paths differ in the first component on which they decide differently. The components are disjoint and nonempty, so the two outputs differ.

Line L7 drops ∅\emptyset and AA. □\square

Theorem 1 (the core step). For each d∈Md \in M, removable_sets(A)[d](A)[d] is the list of the nonempty proper subsets of AA that can leave the rest of AA along dd, each once.

Proof. Line L1 visits each direction. Lines L2 and L3 build GdG_d on AA, and by Lemma 2 the sets that can leave are the closed sets other than ∅\emptyset and AA. Lemma 4 lists them. □\square

Corollary 1 (separations). A split {S,A∖S}\{S, A \setminus S\} of AA can be done by one axis translation of one side, under the motions MM, exactly when SS or A∖SA \setminus S is in one of the lists. So the splits that an AND/OR graph needs for the node AA are read from the lists, without a test of each of the 2∣A∣−1−12^{|A| - 1} - 1 splits.

Lemma 5 (no cycles along an axis). For boxes, GdG_d has no cycle for each axis direction dd. So every component is one part, and when ∣A∣≥2|A| \ge 2, one part of AA can always leave along dd.

Proof. An arc i→ji \to j along +ek+e_k needs bj,k≥bi,k′>bi,kb_{j,k} \ge b'_{i,k} > b_{i,k}, so the lower coordinate on axis kk grows strictly along a path. A graph with no cycle has a node with no arc out, and that node is a closed set. □\square

So for the axis motion space and boxes, line L4 only orders the parts. The step is written with components because the same lines apply to every cell of a motion space, and in other motion spaces, such as oblique translations or small motions, the graph of a cell can have cycles.

Termination and cost. Let k=∣A∣k = |A| and let RdR_d be the number of sets output for dd. Lines L2 and L3 cost O(k2)O(k^2), and Tarjan's algorithm and line L5 cost O(k2)O(k^2). In the recursion of lines L6 to L9, each call has a child at line L8, so every path of calls goes down to a leaf at depth kk. There are Rd+2R_d + 2 leaves at most, so there are at most k(Rd+2)+1k (R_d + 2) + 1 calls. The step stops, and costs O(k2+kRd)O(k^2 + k R_d) for each direction.

Complexity

For a subassembly of nn parts, lines L2 and L3 test n(n−1)n(n-1) pairs in O(1)O(1) time each, and Tarjan's algorithm and line L5 take O(n2)O(n^2) time. Each call of EXTEND has a child at line L8, so the recursion tree has at most n(Rd+2)+1n (R_d + 2) + 1 calls for RdR_d output sets. Over the six directions the step costs O(n2+nR)O(n^2 + n R) time, which is O(n)O(n) for each output set after the graphs are built. The output can be exponential: along ±y\pm y the frame has 2n−22^n - 2 removable sets.

For general motion spaces, the cost of the whole approach is the cost of the arrangement of step 3 times the cost of step 4 per cell. The number of cells depends on the motion space and the shapes. For small translations of polyhedra it is quadratic in the number of contact planes, as on the NDBG page. For larger motion spaces the arrangement grows much faster, and assembly partitioning with general motions is NP-complete.

Properties

  • Exact for its motion space. The lists hold every removable set for the chosen motions, and only those. A set that needs a motion outside the space, such as a turn or two steps of translation, is not found.
  • Not connected by default. A removable set or its complement can be disconnected. A planner that needs connected subassemblies filters the output.
  • Output sensitive. After the graphs are built, each removable set costs O(n)O(n).
  • Shared work. The pair tests of step 2 depend only on the two parts, so the graphs of a subassembly are the graphs of the product restricted to it.

Variants and improvements

  • Small translations. The motion space is the sphere of directions with small motions. Step 3 gives the arrangement of great circles of the non-directional blocking graph.
  • Translations to infinity in any direction. The blocking sets are the directions that meet the Minkowski differences of pairs of parts, and step 3 is an arrangement of curves on the sphere. The axis directions of this page are 6 of its points.
  • Small rigid motions. Translations and rotations together give a 6-dimensional motion space. The blocking sets come from linear constraints at each contact.
  • One part at a time. A linear planner keeps only the sets of one part, which are the sinks of the condensation, as the De Fazio and Whitney method needs.
  • Disassembly. For disassembly sequence planning, the same lists give the first step of each plan, and the rest follows by recursion on both sides.

When to use it

Use the approach when the motions of a product fit a family with a clear geometry: translations along a few fixed axes, as for many boxed or machined products, or small motions to test for local locks. The axis case of this page is cheap and exact, and it fills an AND/OR graph without a test of every split. When parts need long paths with turns, use a motion planner on the few candidates that the approach leaves.

Pitfalls

  • The motion space must be stated. The same product can be separable under one space and locked under another. In the frame, the block is free along ±y\pm y and caught in the plane.
  • Infinitesimal is not extended. A set that can make a small move may still hit a part on its way out. Do not mix the graphs of the two spaces.
  • Lists can be huge. For a product whose parts are free along one direction, every subset is removable. Ask for the sinks only, or for one set, when the full list is not needed.
  • Touching at the end. A part that ends exactly at the face of another part along the direction of motion is blocked by it. A test with a strict inequality there misses contacts.
  • Cells of lower dimension. In a continuous motion space, the borders of the cells are cells too, and their graphs can have fewer arcs. A method that samples only open cells misses them.

Implementations

The Python module computes the blocking graphs along the six axis directions for boxes with integer or Fraction corners, lists the removable sets of a subassembly for each direction, and turns them into splits. A shared helper holds the box predicates. The tests compare the lists with a test of every subset of every subassembly of up to 5 parts, and of the whole product for 6 parts, each subset swept out along the direction at small steps. They also compare the enumeration of closed sets with all subsets on random directed graphs with cycles, and check the splits, the absence of cycles along an axis, a scale of the coordinates, and the frame.

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
motion_space_assembly_planning.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/motion-space-assembly-planning/. The authors are listed in prov/TCQ1T4.jsonl.
"""One core step of the motion space approach, for one family of motions.

The framework of Halperin, Latombe and Wilson cuts a space of motions into
cells on which the blocking graph does not change, and reads the removable
subassemblies of each cell from the strongly connected components of its
graph. This module does that step for the motion space of the six axis
translations to infinity, where each of the six directions is its own cell:

    for each direction d, list every nonempty proper subset S of a
    subassembly A that can leave A \\ S by one translation along d.

Motion model: one translation to infinity along +x, -x, +y, -y, +z or -z.
Hand model: two-handed; S moves as one rigid body and A \\ S stays.
"""

from assembly_boxes import AXES6, blocks, members


def blocking_graph(boxes, d, within):
    """Bit j of out[i] is set when part j blocks part i along d, inside within."""
    out = [0] * len(boxes)
    for i in members(within):  # @line L2
        for j in members(within):
            if i != j and blocks(boxes[i], boxes[j], d):
                out[i] |= 1 << j  # @line L3
    return out


def tarjan_sccs(out, within):
    """Strongly connected components of the graph induced on within, as bit
    masks, in completion order: each one after every component it reaches."""
    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 closed_sets(out, within):
    """Every nonempty proper subset of within with no arc to the rest of within."""
    comps = tarjan_sccs(out, within)  # @line L4
    k = len(comps)
    succ = []
    for c in comps:  # @line L5
        m = 0
        for i in members(c):
            m |= out[i]
        succ.append(m & within & ~c)
    result = []

    def extend(t, chosen):  # @line L6
        if t == k:  # @line L7
            if chosen and chosen != within:
                result.append(chosen)
            return
        extend(t + 1, chosen)  # @line L8
        if succ[t] & ~chosen == 0:  # @line L9
            extend(t + 1, chosen | comps[t])

    extend(0, 0)
    return result


def removable_sets(boxes, within, motions=AXES6):
    """A dict from each direction d to the sorted list of the subsets of
    within that can leave the rest of within along d."""
    found = {}
    for d in motions:  # @line L1
        out = blocking_graph(boxes, d, within)
        found[d] = sorted(closed_sets(out, within))
    return found


def separations(boxes, within, motions=AXES6):
    """The splits {S, within \\ S} of within for which one side can leave the
    other along some direction, each as (S1, S2) with S1 holding the lowest
    part of within."""
    low = within & -within
    splits = set()
    for sets in removable_sets(boxes, within, motions).values():
        for s in sets:
            other = within & ~s
            splits.add((s, other) if s & low else (other, s))
    return sorted(splits)
test_motion_space_assembly_planning.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/motion-space-assembly-planning/. The authors are listed in prov/TCQ1T4.jsonl.

import random
from fractions import Fraction

from assembly_boxes import AXES6, free_by_sampling, members, random_boxes
from motion_space_assembly_planning import (
    blocking_graph, closed_sets, removable_sets, separations, tarjan_sccs)

# ---- independent reference: try every subset and sweep it out ----


def brute_removable(boxes, within, d):
    out = []
    for s in range(1, within):
        if s & ~within or s == within:
            continue
        movers = [boxes[i] for i in members(s)]
        others = [boxes[i] for i in members(within & ~s)]
        if free_by_sampling(movers, others, d):
            out.append(s)
    return out


def brute_closed(out, within):
    return [s for s in range(1, within)
            if not s & ~within and s != within
            and all(out[i] & within & ~s == 0 for i in members(s))]


# ---- tests ----


def test_against_all_subsets_up_to_five_parts():
    rng = random.Random(41)
    for _ in range(8):
        n = rng.randint(2, 5)
        boxes = random_boxes(rng, n, size=3, max_side=2, connected=rng.random() < 0.8)
        for within in range(1, 1 << n):
            got = removable_sets(boxes, within)
            for d in AXES6:
                assert got[d] == brute_removable(boxes, within, d)


def test_against_all_subsets_six_parts():
    rng = random.Random(42)
    for _ in range(4):
        boxes = random_boxes(rng, 6, size=3, max_side=2, connected=True)
        full = 63
        got = removable_sets(boxes, full)
        for d in AXES6:
            assert got[d] == brute_removable(boxes, full, d)


def test_closed_sets_with_cycles():
    rng = random.Random(43)
    for _ in range(300):
        n = rng.randint(1, 7)
        out = [0] * n
        for i in range(n):
            for j in range(n):
                if i != j and rng.random() < 0.3:
                    out[i] |= 1 << j
        full = (1 << n) - 1
        got = closed_sets(out, full)
        assert len(got) == len(set(got))
        assert sorted(got) == brute_closed(out, full)
        within = rng.randint(1, full)
        assert sorted(closed_sets(out, within)) == brute_closed(out, within)


def test_axis_graphs_have_no_cycle():
    rng = random.Random(44)
    for _ in range(40):
        n = rng.randint(2, 6)
        boxes = random_boxes(rng, n, size=3, max_side=3, connected=True)
        full = (1 << n) - 1
        for d in AXES6:
            comps = tarjan_sccs(blocking_graph(boxes, d, full), full)
            assert all(bin(c).count("1") == 1 for c in comps)
            # so a single part can always leave along d
            assert any(bin(s).count("1") == 1 for s in removable_sets(boxes, full, [d])[d])


def test_separations():
    rng = random.Random(45)
    for _ in range(15):
        n = rng.randint(2, 5)
        boxes = random_boxes(rng, n, size=3, max_side=2, connected=True)
        full = (1 << n) - 1
        motions = tuple(rng.sample(AXES6, rng.randint(1, 3)))
        want = set()
        for s in range(1, full):
            if s & 1:
                a = [boxes[i] for i in members(s)]
                b = [boxes[i] for i in members(full & ~s)]
                if any(free_by_sampling(a, b, d) or free_by_sampling(b, a, d) for d in motions):
                    want.add((s, full & ~s))
        assert set(separations(boxes, full, motions)) == want


def test_fraction_coordinates():
    rng = random.Random(46)
    for _ in range(10):
        boxes = random_boxes(rng, 5, size=3, max_side=2, connected=True)
        scaled = [tuple(Fraction(c, 3) for c in b) for b in boxes]
        assert removable_sets(scaled, 31) == removable_sets(boxes, 31)


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
    ]
    got = removable_sets(frame, 31)
    counts = {d: len(v) for d, v in got.items()}
    assert counts == EXAMPLE_COUNTS
    # along +z only sets that hold the top plate can leave
    assert all(s >> 4 & 1 for s in got[(0, 0, 1)])
    # in the plane of the frame, the block alone never leaves the closed frame
    plane = ((1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1))
    assert all(s != 1 << 3 for d in plane for s in got[d])
    assert 1 << 3 in got[(0, 1, 0)]
    # 13 of the 15 splits can be done in the plane, 11 with both sides connected
    splits = separations(frame, 31, plane)
    assert len(splits) == 13
    assert len(separations(frame, 31)) == 15
    disconnected = {(0b00111, 0b11000), (0b10001, 0b01110)}
    assert disconnected <= set(splits)


EXAMPLE_COUNTS = {(1, 0, 0): 14, (-1, 0, 0): 14, (0, 1, 0): 30, (0, -1, 0): 30,
                  (0, 0, 1): 8, (0, 0, -1): 8}

History

Wilson and Latombe introduced the non-directional blocking graph for small translations in 1994. Wilson, Kavraki, Latombe and Lozano-Pérez used blocking graphs of translations to generate two-handed sequences in 1995. Halperin, Latombe and Wilson published the motion space approach in Algorithmica in 2000. It showed that these methods, and others for richer motions, follow one scheme: cut the motion space into cells of constant blocking graph and use strong connectivity in each cell.

References

  1. 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 motion space, the partition into regions of constant blocking graph, and the computation of removable subassemblies from the strongly connected components in each region
  2. Randall H. Wilson and Jean-Claude Latombe, Geometric reasoning about mechanical assembly, Artificial Intelligence 71(2), 371 to 396 (1994), the non-directional blocking graph, the first case of the approach
  3. 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), the generation of two-handed sequences from blocking graphs of translations
  4. Jean-Claude Latombe, Robot Motion Planning, Kluwer Academic Publishers (1991), configuration space and the decomposition of a space into cells of constant behavior

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)
WritingW2 basic
  • a scene preset for the example