Algorithm Search⌘K

Data structurecore

AND/OR graph of assembly plans

Also called Homem de Mello-Sanderson AND/OR graph.

Homem de Mello and Sanderson's graph whose nodes are subassemblies and whose hyperarcs are feasible splits, which holds all assembly sequences compactly.

Time
O(C n^2) worst
Space
O(N + C) extra
Where
C = the number of candidate splits tested (over all nodes); N = the number of connected sets of parts; n = the number of parts

The AND/OR graph of an assembly, due to Homem de Mello and Sanderson, stores every way to build a product in a structure much smaller than the list of those ways. Its nodes are subassemblies, and a hyperarc goes from a subassembly to the two smaller subassemblies of each feasible way to split it. An assembly plan is a solution tree of the graph: take the whole product, choose one hyperarc, and continue in the same way in both children. The number of plans can grow like n!n!, but the graph has at most one node for each connected set of parts, and it gives the plan count, the best plan for a cost, and all plans by a recursion over its nodes.

In plain words

Think about building a product backwards. Take the finished product and ask: in how many ways can I pull it into two pieces, each still in one piece itself, with one simple motion? Each answer is a fork in the road. Then ask the same question of each piece, and so on down to single parts.

Many different build orders share the same pieces. A plan that first makes the left half and a plan that first makes the right half both use the same "left half" piece. The AND/OR graph stores each piece once and keeps for it the list of its good splits. "OR" means you choose one split of a piece. "AND" means that after you choose it, you must build both halves.

To count all plans, count the plans of each piece once, from the small pieces up, and multiply along each split.

The abstract type

A product has parts P={1,…,n}P = \{1, \ldots, n\} and a liaison graph LL. The graph is built for a stated model:

  • Hand model: two-handed and monotone. Each step takes two finished subassemblies and joins them with one motion. A part never moves again relative to the other parts of its subassembly. Each subassembly, except perhaps the whole product, must be connected in LL. Linear sequences, which add one part at a time, are the special case where one side of every step is a single part.
  • Motion model on this page: one step translations. A split {S1,S2}\{S_1, S_2\} is feasible if one side can leave the other by one translation to infinity along a direction of a fixed set MM, here a subset of the six axis directions ±x,±y,±z\pm x, \pm y, \pm z. The parts are axis-aligned boxes. Other motion models change only the test FEASIBLE, not the structure.

The structure is a directed hypergraph G=(V,A)G = (V, A):

  • the nodes VV are the product PP and the connected subassemblies that can appear in a plan,
  • a hyperarc S→{S1,S2}S \to \{S_1, S_2\} is an admissible split of SS: S1S_1 and S2S_2 are connected and FEASIBLE(S1S_1, S2S_2) holds,
  • a plan (solution tree) below SS is SS itself if ∣S∣=1|S| = 1, and otherwise one hyperarc of SS with a plan below each side.

The operations are BUILD(PP), the hyperarcs of a node, PLANS(SS), the number of plans below SS, the plans themselves one by one, and the best plan for a cost on the hyperarcs. Every hyperarc goes to strictly smaller sets, so the graph is a directed acyclic graph of hyperarcs, and every recursion over it stops.

This page is the representation. The task of finding a sequence is the assembly sequence planning problem, and the question of one split is assembly partitioning.

Representation

A set of parts is a bit mask. The graph is a dictionary from a node to its list of hyperarcs, each a pair of masks (S1,S2)(S_1, S_2) where S1S_1 holds the lowest part of SS. For the motion test, each direction d∈Md \in M and each part ii has a mask stopd[i]stop_d[i] of the parts that block ii when it moves along dd. Then S1S_1 can leave S2S_2 along dd exactly when stopd[i]∩S2=∅stop_d[i] \cap S_2 = \emptyset for all i∈S1i \in S_1. For boxes and an axis direction, jj blocks ii along +x+x when their open yy and zz intervals overlap and bjb_j lies at or beyond the right face of bib_i.

Operations

  1. BUILD(P) ▷ P: all parts; M: the motion set
  2. 1arcs ← empty map; push P on a stack; until the stack is empty, pop S and DECOMPOSE(S)
  3. DECOMPOSE(S)
  4. 2if S is a node already then return
  5. 3make S a node with no hyperarcs
  6. 4if |S| = 1 then return
  7. 5v ← the lowest part of S
  8. 6for each connected S1 with v ∈ S1 ⊊ S do ▷ GROW of the liaison graph, inside S
  9. 7S2 ← S \ S1
  10. 8if S2 is connected and FEASIBLE(S1, S2) then
  11. 9add the hyperarc S → {S1, S2}; push S1 and S2
  12. FEASIBLE(S1, S2)
  13. 10for each d in M: if no part of S1 is blocked along d by a part of S2, or no part of S2 is blocked along d by a part of S1, then return true
  14. 11return false
  15. PLANS(S) ▷ memoized
  16. 12if |S| = 1 then return 1
  17. 13return the sum over the hyperarcs S → {S1, S2} of PLANS(S1) · PLANS(S2)

Splits once. Every split has exactly one side that holds the lowest part vv of SS, so line L6 meets each split exactly once. The enumeration is the GROW scheme of the liaison graph, restricted to SS.

Memoization. Line L2 makes the graph share subassemblies. A set such as {0,1,3}\{0, 1, 3\} can come from many larger sets, but it is expanded once. PLANS uses the same idea, as in memoization.

Best plan. Replace sum by minimum and product by sum in line L13, add a cost c(S→{S1,S2})c(S \to \{S_1, S_2\}) for each hyperarc, and the recursion returns the cost of the cheapest plan: BEST(S)=min⁡(c+BEST(S1)+BEST(S2))\mathrm{BEST}(S) = \min (c + \mathrm{BEST}(S_1) + \mathrm{BEST}(S_2)).

Example

Take the frame of the liaison graph page: base plate 0, left post 1, right post 2, block 3 between the posts on the base, top plate 4 on the posts, with liaisons {0,1},{0,2},{0,3},{1,3},{2,3},{1,4},{2,4}\{0,1\}, \{0,2\}, \{0,3\}, \{1,3\}, \{2,3\}, \{1,4\}, \{2,4\}. The frame is a planar product, so let the parts move in its plane only: M={+x,−x,+z,−z}M = \{+x, -x, +z, -z\}.

The blocking relation along +z+z is: the top plate blocks every part below it (1, 2, 3, and also 0), and the base plate blocks nothing. Along +x+x the right post blocks the left post and the block, and the block blocks the left post. So the block is caught in the closed frame: the posts stop it along ±x\pm x, the top plate along +z+z and the base plate along −z-z. The split {{0,1,2,4},{3}}\{\{0, 1, 2, 4\}, \{3\}\} is not feasible, and the frame without its block, {0,1,2,4}\{0, 1, 2, 4\}, is not a node. The block must be in place before the top plate closes the frame.

The root has 12 splits into two connected sets, and 11 of them are feasible. The table gives each hyperarc with the plan counts of its two sides:

hyperarc of the root plans of the sides product
{0}\{0\}, {1,2,3,4}\{1,2,3,4\} 1, 10 10
{0,1}\{0,1\}, {2,3,4}\{2,3,4\} 1, 2 2
{0,1,2,3}\{0,1,2,3\}, {4}\{4\} 12, 1 12
{0,1,3}\{0,1,3\}, {2,4}\{2,4\} 3, 1 3
{0,1,3,4}\{0,1,3,4\}, {2}\{2\} 8, 1 8
{0,1,4}\{0,1,4\}, {2,3}\{2,3\} 2, 1 2
{0,2}\{0,2\}, {1,3,4}\{1,3,4\} 1, 2 2
{0,2,3}\{0,2,3\}, {1,4}\{1,4\} 3, 1 3
{0,2,3,4}\{0,2,3,4\}, {1}\{1\} 8, 1 8
{0,2,4}\{0,2,4\}, {1,3}\{1,3\} 2, 1 2
{0,3}\{0,3\}, {1,2,4}\{1,2,4\} 1, 2 2

So PLANS(root) =54= 54. Inside {1,2,3,4}\{1, 2, 3, 4\}, without the base plate, the block can drop out along −z-z, so the split {{1,2,4},{3}}\{\{1,2,4\}, \{3\}\} is feasible there. The graph has 26 nodes (all 27 connected sets but {0,1,2,4}\{0,1,2,4\}) and 58 hyperarcs. Of the 54 plans, 32 are linear, and each linear plan gives two part orders, because the first two parts can come in either order. So 64 of the 120 orders of the five parts are feasible linear sequences.

If all six directions are allowed, every connected set of the frame can slide out along +y+y, because all parts have the same yy interval. Then all 27 connected sets are nodes, all 65 splits into two connected sets are hyperarcs, and there are 64 plans.

Correctness

Each split of a node has exactly one side that holds its lowest part, and the GROW scheme lists each connected set with that part once. So each node gets exactly one hyperarc for each admissible split. By induction on the size of a node, the solution trees below it are in one to one correspondence with the plans for it: the root hyperarc of a plan is a hyperarc of the graph, and the two subtrees are plans for its two sides. So the graph holds every monotone two-handed plan under the model once and nothing else, and the recursion of line L13 counts them. Every node other than the product is a side of an admissible split, so it is connected, and the graph has at most NN nodes when the product is connected. The full proofs are in the correctness proof.

Proof: The AND/OR graph holds every monotone two-handed plan once, and its nodes are connected subassembliesfull

We use the pseudocode of the page. The product has parts P={1,…,n}P = \{1, \ldots, n\} with n≥1n \ge 1, a liaison graph LL, and a test FEASIBLE on splits. A split of a set SS is an unordered pair {S1,S2}\{S_1, S_2\} of nonempty sets with S1∪S2=SS_1 \cup S_2 = S and S1∩S2=∅S_1 \cap S_2 = \emptyset. A split is admissible when S1S_1 and S2S_2 are connected in LL and FEASIBLE(S1S_1, S2S_2) holds. Under the motion model of the page, FEASIBLE holds when one side can leave the other by one translation to infinity along a direction of MM; the proofs below use only that FEASIBLE is a fixed test on the pair, symmetric in its two arguments.

A plan for a set SS is a full binary tree whose leaves are the parts of SS, with unordered children, such that for every internal node vv with children v1v_1 and v2v_2, the split {leaves(v1),leaves(v2)}\{\mathrm{leaves}(v_1), \mathrm{leaves}(v_2)\} of leaves(v)\mathrm{leaves}(v) is admissible. This is the monotone two-handed model: each step joins two subassemblies that are already finished, and no part moves again inside its subassembly. A solution tree below a node SS of the graph is SS itself when ∣S∣=1|S| = 1, and otherwise a choice of one hyperarc S→{S1,S2}S \to \{S_1, S_2\} together with a solution tree below S1S_1 and one below S2S_2.

Lemma 1 (each admissible split is one hyperarc). When line L3 makes a node SS with ∣S∣≥2|S| \ge 2, lines L5 to L9 add exactly one hyperarc for each admissible split of SS, and no other hyperarc.

Proof. Let vv be the lowest part of SS. Every split {S1,S2}\{S_1, S_2\} of SS has exactly one side that contains vv. Name it S1S_1. Then S1S_1 is a connected set with v∈S1⊊Sv \in S_1 \subsetneq S. Line L6 runs GROW of the liaison graph from {v}\{v\} inside SS, which lists every connected set that contains vv and lies inside SS exactly once (the proof is on the liaison graph page). So the split comes up exactly once, line L7 forms its other side, and line L8 adds it exactly when S2S_2 is connected and FEASIBLE holds, that is, exactly when the split is admissible. □\square

Lemma 2 (nodes). Every set that DECOMPOSE turns into a node is PP or a connected set. Every side of every hyperarc becomes a node.

Proof. The stack starts with PP. A set is pushed on line L9 only as a side of an admissible split, and such a side is connected. Line L2 makes each popped set a node once. □\square

Theorem 1 (plans are solution trees). For each node SS, the map that sends a solution tree below SS to the binary tree of its chosen splits is a bijection onto the plans for SS.

Proof. By induction on ∣S∣|S|. If ∣S∣=1|S| = 1 both sides have exactly one element, the leaf. Let ∣S∣≥2|S| \ge 2. A solution tree below SS chooses a hyperarc S→{S1,S2}S \to \{S_1, S_2\}, whose split is admissible by Lemma 1, and solution trees below S1S_1 and S2S_2, which are nodes by Lemma 2. By induction these map to plans for S1S_1 and S2S_2, so the whole maps to a plan for SS. Conversely, take a plan for SS. Its root split is admissible, so by Lemma 1 it is exactly one hyperarc of SS. Its two subtrees are plans for S1S_1 and S2S_2, which by induction come from exactly one solution tree each. So each plan comes from exactly one solution tree. □\square

In words: the graph holds every monotone two-handed plan in which each intermediate subassembly is connected and each joining step passes FEASIBLE, it holds each such plan once, and it holds nothing else.

Corollary 1 (counting by recursion). For a node SS, the number of plans for SS is PLANS(S)\mathrm{PLANS}(S) of lines L12 and L13: 1 if ∣S∣=1|S| = 1, and otherwise the sum over the hyperarcs S→{S1,S2}S \to \{S_1, S_2\} of PLANS(S1)⋅PLANS(S2)\mathrm{PLANS}(S_1) \cdot \mathrm{PLANS}(S_2).

Proof. By Theorem 1 we count solution trees. A solution tree below SS is a hyperarc together with an independent choice of a solution tree below each side, and different hyperarcs give different trees. □\square

Theorem 2 (size). Let NN be the number of connected nonempty sets of parts. The graph has at most NN nodes when PP is connected, and at most N+1N + 1 otherwise. Each node SS has at most c(S)−1c(S) - 1 hyperarcs, where c(S)c(S) is the number of connected sets inside SS that contain the lowest part of SS.

Proof. The first claim is Lemma 2. For the second, Lemma 1 maps each hyperarc of SS to its side S1S_1, a connected set inside SS that contains the lowest part, with S1≠SS_1 \ne S, and the map is one to one. □\square

The bounds are reached. If all parts touch each other and every split is feasible, then every one of the 2n−12^n - 1 nonempty sets is a node, the number of hyperarcs is ∑k(nk)(2k−1−1)=(3n−2n+1+1)/2\sum_k \binom{n}{k}(2^{k-1} - 1) = (3^n - 2^{n+1} + 1)/2, and the number of plans is (2n−3)!!=1⋅3⋅5⋯(2n−3)(2n - 3)!! = 1 \cdot 3 \cdot 5 \cdots (2n - 3), because a plan for nn parts comes from a plan for n−1n - 1 parts in exactly 2n−32n - 3 ways, by putting the new leaf above one of the 2n−32n - 3 nodes of the smaller tree. So the number of plans grows like n!n! times an exponential, while the graph has fewer than 3n3^n nodes and hyperarcs together.

For a chain of nn parts in which each split of a contiguous block is feasible, the connected sets are the n(n+1)/2n(n+1)/2 contiguous blocks, a block of kk parts has k−1k - 1 hyperarcs, so there are ∑k(n−k+1)(k−1)=(n+13)\sum_k (n - k + 1)(k - 1) = \binom{n+1}{3} hyperarcs, and the plans are the binary bracketings of nn symbols, counted by the Catalan number Cn−1C_{n-1}.

Termination and cost. Each set is expanded at most once by line L2, and there are at most N+1N + 1 sets, so DECOMPOSE stops. Expanding SS lists c(S)c(S) sets on line L6 and runs line L8 on each. With bit masks of the blocking sets, the connectivity test costs O(∣S∣2)O(|S|^2) word operations and FEASIBLE costs O(∣M∣⋅∣S∣)O(|M| \cdot |S|), so the build costs O(∑Sc(S) (∣S∣2+∣M∣ ∣S∣))O\big(\sum_S c(S)\,(|S|^2 + |M|\,|S|)\big) over the nodes SS. PLANS visits each node and each hyperarc once with memoization, with arithmetic on integers of at most O(nlog⁡n)O(n \log n) bits.

Complexity

Let c(S)c(S) be the number of connected sets inside SS that hold the lowest part of SS. BUILD lists c(S)c(S) candidates for each node and tests each one in O(n2)O(n^2) word operations with bit masks, so it costs O(C n2)O(C\, n^2) for nn parts and a fixed motion set, where C=∑Sc(S)C = \sum_S c(S) is the number of candidate splits. The graph has at most NN nodes and at most ∑S(c(S)−1)\sum_S (c(S) - 1) hyperarcs. PLANS visits each node and hyperarc once.

product nodes hyperarcs plans
chain of nn parts, all splits feasible n(n+1)/2n(n+1)/2 (n+13)\binom{n+1}{3} Catalan Cn−1C_{n-1}
all pairs in contact, all splits feasible 2n−12^n - 1 (3n−2n+1+1)/2(3^n - 2^{n+1} + 1)/2 (2n−3)!!(2n-3)!!
the frame, M={±x,±z}M = \{\pm x, \pm z\} 26 58 54

For n=10n = 10 parts that all touch, there are (2n−3)!!=34,459,425(2n-3)!! = 34{,}459{,}425 plans but only 1023 nodes and 28,501 hyperarcs. The Catalan numbers of the chain grow like 4n4^n, and the chain has only O(n3)O(n^3) hyperarcs. The graph is still exponential in the worst case, because the number of connected sets is. It can also hold nodes with no plan below them, when a subassembly can be reached but not built, so a product with no plan at all can still have a large graph.

Variants

  • Directed graph of assembly states. For linear plans, a node can be a set of placed parts and an arc can add one part. De Fazio and Whitney draw the same states as sets of made liaisons in the diagram of liaison sequences. The AND/OR graph holds the two-handed plans as well.
  • Other motion models. FEASIBLE can test a single translation in any direction (with the non-directional blocking graph), a sequence of translations, or a general motion found by a motion planner. The structure does not change. The motion space approach gives the feasible splits for a whole family of motions.
  • Stability and tools. Real planners add tests to line L8: is each subassembly stable under gravity, can a gripper hold it, can a tool reach the joint. Each test removes hyperarcs.
  • Lazy search. Instead of building the whole graph, a best first search from the root expands only the nodes that the cheapest partial plans reach. This is the AO* idea for AND/OR graphs.
  • Disassembly. Read from the root down, a solution tree is a disassembly plan. A plan that takes out only one part uses only the path of nodes that hold that part.

When to use it

Use the AND/OR graph when the planner needs all plans of a product with up to a few tens of parts: to count them, to pick the cheapest one under a cost such as the number of tool changes or reorientations, or to keep alternatives for a line balancing step. If one plan is enough, a direct assembly partitioning search down one branch is cheaper. If only linear sequences are allowed, the precedence relations of De Fazio and Whitney are a more compact description when they exist.

Pitfalls

  • Connected sets are an assumption. Requiring each subassembly to be connected in the liaison graph is a model choice for stability. It removes plans in which a robot holds two loose parts together. State it.
  • Exponential size. The number of connected sets grows exponentially for products with a central part, such as a base plate that touches all others. The graph is compact compared with the list of plans, not small.
  • Same node from many parents. Without line L2, the same subassembly is expanded once for each parent, and the work grows like the number of plans.
  • Counting orders versus plans. A linear plan matches two part orders, because the first two parts are joined in one step. A two-handed plan matches several orders of its steps. State which one a count means.
  • Planar products and the third axis. A product drawn in a plane, with all parts of the same depth, can come apart along the depth axis in any order. The frame example has 64 plans with all six directions and 54 when motion is kept in the plane.

Implementations

The Python module builds the graph from a list of boxes with integer or Fraction corners and a set of axis directions, or from an abstract liaison graph and any feasibility test. It counts plans and linear plans by memoized recursion and lists the plans. A shared helper holds the box predicates. The tests compare the set of plans with all full binary trees on the parts, each checked on the geometry with a sampled sweep test, for up to 5 parts and a few products of 6 parts; compare twice the number of linear plans with a check of all n!n! orders; check that every node is a connected set; and check the chain and complete graph counts.

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.

and_or_graph_of_assembly_plans.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/and-or-graph-of-assembly-plans/. The authors are listed in prov/XTSFWX.jsonl.
"""The AND/OR graph of all monotone two-handed assembly plans.

A node is a connected subassembly (a bit mask of parts). A hyperarc joins a
node S to the two nodes S1 and S2 of a feasible split of S. A plan is a
solution tree: the root, and for each node of the tree with two or more
parts, one of its hyperarcs.

The default model: parts are axis-aligned boxes, a subassembly counts only
if its parts are connected in the liaison graph, and a split is feasible if
one side can leave the other by one translation to infinity along one of
the six axis directions.
"""

from assembly_boxes import AXES6, blocks, face_contact


def low_bit(mask):
    return mask & -mask


class AndOrGraph:
    def __init__(self, n, adj, feasible):
        """n parts, adj[i] the bit mask of the liaison neighbours of i, and
        feasible(s1, s2) the test of a split into two connected sets."""
        self.n = n
        self.adj = adj
        self.feasible = feasible
        self.root = (1 << n) - 1
        self.arcs = {}              # node -> list of (s1, s2), lowest part in s1
        self._plans = {}
        if n > 0:
            self._decompose(self.root)  # @line L1

    # ---- liaison graph queries ----

    def neighbourhood(self, mask):
        out = 0
        m = mask
        while m:
            b = low_bit(m)
            out |= self.adj[b.bit_length() - 1]
            m ^= b
        return out & ~mask

    def connected(self, mask):
        if mask == 0:
            return False
        reach = low_bit(mask)
        while True:
            grow = (reach | self.neighbourhood(reach)) & mask
            if grow == reach:
                return reach == mask
            reach = grow

    def _connected_containing(self, v, within):
        """Each connected set S1 with v in S1 inside within, once."""
        out = []

        def grow(s, banned):
            out.append(s)
            cand = self.neighbourhood(s) & within & ~banned
            while cand:
                w = low_bit(cand)
                grow(s | w, banned)
                banned |= w
                cand ^= w

        grow(v, ~within)
        return out

    # ---- construction ----

    def _decompose(self, root):
        stack = [root]
        while stack:
            s = stack.pop()
            if s in self.arcs:  # @line L2
                continue
            self.arcs[s] = []  # @line L3
            if s & (s - 1) == 0:  # @line L4
                continue
            v = low_bit(s)  # @line L5
            for s1 in self._connected_containing(v, s):  # @line L6
                if s1 == s:
                    continue
                s2 = s & ~s1  # @line L7
                if self.connected(s2) and self.feasible(s1, s2):  # @line L8
                    self.arcs[s].append((s1, s2))  # @line L9
                    stack.append(s1)
                    stack.append(s2)

    # ---- queries ----

    def nodes(self):
        return sorted(self.arcs)

    def hyperarc_count(self):
        return sum(len(a) for a in self.arcs.values())

    def count_plans(self, s=None):
        """The number of solution trees below s, by memoized recursion."""
        if s is None:
            s = self.root
        if s in self._plans:
            return self._plans[s]
        if s & (s - 1) == 0:  # @line L12
            return 1
        total = 0
        for s1, s2 in self.arcs[s]:  # @line L13
            total += self.count_plans(s1) * self.count_plans(s2)
        self._plans[s] = total
        return total

    def count_linear_plans(self, s=None, memo=None):
        """Solution trees in which every split takes off one single part."""
        if s is None:
            s = self.root
        if memo is None:
            memo = {}
        if s & (s - 1) == 0:
            return 1
        if s in memo:
            return memo[s]
        total = 0
        for s1, s2 in self.arcs[s]:
            if s1 & (s1 - 1) == 0 or s2 & (s2 - 1) == 0:
                total += (self.count_linear_plans(s1, memo)
                          * self.count_linear_plans(s2, memo))
        memo[s] = total
        return total

    def plans(self, s=None):
        """Yield each plan as a nested pair of frozensets of parts."""
        if s is None:
            s = self.root
        if s & (s - 1) == 0:
            yield s.bit_length() - 1
            return
        for s1, s2 in self.arcs[s]:
            for t1 in self.plans(s1):
                for t2 in self.plans(s2):
                    yield frozenset((t1, t2))

    def solvable_nodes(self):
        """The nodes with at least one plan below them."""
        return [s for s in self.nodes() if self.count_plans(s) > 0]


def from_boxes(boxes, motions=AXES6):
    """The AND/OR graph of a product of boxes under one-step translations."""
    n = len(boxes)
    adj = [0] * n
    for i in range(n):
        for j in range(i + 1, n):
            if face_contact(boxes[i], boxes[j]) is not None:
                adj[i] |= 1 << j
                adj[j] |= 1 << i
    # stop[d][i]: the parts that block part i when it moves along d
    stop = {d: [sum(1 << j for j in range(n) if j != i and blocks(boxes[i], boxes[j], d))
                for i in range(n)] for d in motions}

    def free(s1, s2, d):
        m = s1
        while m:
            b = low_bit(m)
            if stop[d][b.bit_length() - 1] & s2:
                return False
            m ^= b
        return True

    def feasible(s1, s2):
        for d in motions:
            if free(s1, s2, d) or free(s2, s1, d):  # @line L10
                return True
        return False  # @line L11

    return AndOrGraph(n, adj, feasible)
assembly_boxes.py 142 lines
# 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
test_and_or_graph_of_assembly_plans.py 181 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/and-or-graph-of-assembly-plans/. The authors are listed in prov/XTSFWX.jsonl.

import itertools
import random
from math import comb

from assembly_boxes import AXES6, face_contact, free_by_sampling, random_boxes
from and_or_graph_of_assembly_plans import AndOrGraph, from_boxes

# ---- independent references: every binary tree, checked on the geometry ----


def all_trees(parts):
    """Every full binary tree with the given leaves, children unordered."""
    if len(parts) == 1:
        yield parts[0]
        return
    first, rest = parts[0], parts[1:]
    for r in range(len(rest)):
        for left_rest in itertools.combinations(rest, r):
            left = (first,) + left_rest
            right = tuple(p for p in rest if p not in left_rest)
            for t1 in all_trees(left):
                for t2 in all_trees(right):
                    yield frozenset((t1, t2))


def leaves(t):
    if isinstance(t, int):
        return {t}
    a, b = tuple(t)
    return leaves(a) | leaves(b)


def connected(boxes, parts):
    parts = list(parts)
    seen = {parts[0]}
    stack = [parts[0]]
    while stack:
        u = stack.pop()
        for v in parts:
            if v not in seen and face_contact(boxes[u], boxes[v]) is not None:
                seen.add(v)
                stack.append(v)
    return len(seen) == len(parts)


def split_ok(boxes, p1, p2, motions):
    if not (connected(boxes, p1) and connected(boxes, p2)):
        return False
    b1 = [boxes[i] for i in p1]
    b2 = [boxes[i] for i in p2]
    return any(free_by_sampling(b1, b2, d) or free_by_sampling(b2, b1, d) for d in motions)


def tree_ok(boxes, t, motions, cache):
    if isinstance(t, int):
        return True
    a, b = tuple(t)
    la, lb = frozenset(leaves(a)), frozenset(leaves(b))
    key = frozenset((la, lb))
    if key not in cache:
        cache[key] = split_ok(boxes, la, lb, motions)
    return cache[key] and tree_ok(boxes, a, motions, cache) and tree_ok(boxes, b, motions, cache)


def brute_plans(boxes, motions):
    cache = {}
    return {t for t in all_trees(tuple(range(len(boxes)))) if tree_ok(boxes, t, motions, cache)}


def brute_linear_orders(boxes, motions):
    count = 0
    cache = {}
    for order in itertools.permutations(range(len(boxes))):
        ok = True
        for k in range(1, len(order)):
            key = (frozenset(order[:k]), order[k])
            if key not in cache:
                cache[key] = split_ok(boxes, order[:k], (order[k],), motions)
            if not cache[key]:
                ok = False
                break
        count += ok
    return count


def mask(parts):
    return sum(1 << p for p in 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_plans_match_all_binary_trees():
    rng = random.Random(11)
    for trial in range(80):
        n = rng.randint(1, 5)
        boxes = random_boxes(rng, n, size=3, max_side=3, connected=rng.random() < 0.8)
        if trial % 3 == 0:
            motions = AXES6
        else:
            motions = tuple(rng.sample(AXES6, rng.randint(1, 3)))
        g = from_boxes(boxes, motions)
        brute = brute_plans(boxes, motions)
        assert set(g.plans()) == brute
        assert g.count_plans() == len(brute)


def test_six_parts():
    rng = random.Random(12)
    for _ in range(4):
        boxes = random_boxes(rng, 6, size=3, max_side=2, connected=True)
        motions = (AXES6[4], AXES6[1])
        g = from_boxes(boxes, motions)
        assert g.count_plans() == len(brute_plans(boxes, motions))


def test_linear_plans_against_all_orders():
    rng = random.Random(13)
    for trial in range(60):
        n = rng.randint(2, 5)
        boxes = random_boxes(rng, n, size=3, max_side=3, connected=rng.random() < 0.8)
        motions = AXES6 if trial % 2 else tuple(rng.sample(AXES6, 2))
        g = from_boxes(boxes, motions)
        assert 2 * g.count_linear_plans() == brute_linear_orders(boxes, motions)


def test_nodes_are_connected_and_bounded():
    rng = random.Random(14)
    for _ in range(60):
        n = rng.randint(1, 7)
        boxes = random_boxes(rng, n, size=4, max_side=2, connected=True)
        g = from_boxes(boxes)
        conn = [m for m in range(1, 1 << n)
                if connected(boxes, [i for i in range(n) if m >> i & 1])]
        assert set(g.nodes()) <= set(conn)
        assert len(g.nodes()) <= len(conn)
        for s, arcs in g.arcs.items():
            for s1, s2 in arcs:
                assert s1 | s2 == s and s1 & s2 == 0


def test_chain_counts():
    for n in range(1, 9):
        boxes = [(i, 0, 0, i + 1, 1, 1) for i in range(n)]
        g = from_boxes(boxes)
        assert len(g.nodes()) == n * (n + 1) // 2
        assert g.hyperarc_count() == comb(n + 1, 3)
        assert g.count_plans() == comb(2 * n - 2, n - 1) // n   # Catalan number C(n-1)
        assert g.count_linear_plans() == (2 ** (n - 2) if n >= 2 else 1)


def test_complete_and_free():
    for n in range(1, 9):
        full = (1 << n) - 1
        adj = [full & ~(1 << i) for i in range(n)]
        g = AndOrGraph(n, adj, lambda s1, s2: True)
        double_factorial = 1
        for k in range(1, 2 * n - 2, 2):
            double_factorial *= k
        assert g.count_plans() == double_factorial
        assert len(g.nodes()) == 2 ** n - 1
        assert g.hyperarc_count() == (3 ** n - 2 ** (n + 1) + 1) // 2


def test_example_frame():
    g = from_boxes(EXAMPLE)
    assert len(g.nodes()) == 27
    assert g.count_plans() == len(brute_plans(EXAMPLE, AXES6))
    up = from_boxes(EXAMPLE, ((0, 0, 1),))
    assert up.count_plans() == len(brute_plans(EXAMPLE, ((0, 0, 1),)))

History

Homem de Mello and Sanderson presented the AND/OR graph of assembly plans at AAAI in 1986 and in the IEEE Transactions on Robotics and Automation in 1990. In 1991 they gave the decomposition algorithm with a proof that it is correct and complete. De Fazio and Whitney (1987) gave the diagram of liaison states for linear sequences at the same time. Wilson, Kavraki, Latombe and Lozano-Pérez (1995) studied the two-handed monotone model for translations and showed how to generate the feasible partitions directly from the geometry, instead of testing each cut of the liaison graph.

References

  1. 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 AND/OR graph of an assembly, its solution trees as assembly plans, and the decomposition by cut-sets of the graph of connections
  2. Luiz S. Homem de Mello and Arthur C. Sanderson, A correct and complete algorithm for the generation of mechanical assembly sequences, IEEE Transactions on Robotics and Automation 7(2), 228 to 240 (1991), the decomposition algorithm and its proof of correctness and completeness
  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 monotone two-handed model and the generation of partitionings by translations
  4. 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 diagram of assembly states, an equivalent representation of the same sequences

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