Algorithm Search⌘K

Algorithmadvanced

De Fazio-Whitney precedence method

Also called Bourjault method, liaison precedence method.

Generates all assembly sequences from precedence relations among liaisons, found by two questions per liaison, after Bourjault and De Fazio and Whitney.

Time
O(N m l^2) worst
Space
O(N l + m l^2) extra
Where
N = the number of connected sets of parts; l = the number of liaisons; m = the number of motion directions; n = the number of parts
Properties
deterministicexactiterative
Origin
Thomas L. De Fazio, Daniel E. Whitney, 1987

The De Fazio and Whitney method lists every linear assembly sequence of a product from a short set of answers. It works on the liaison graph: one node for each part and one liaison for each contact. For each liaison ii it asks two questions. Which liaisons must be made before ii? Which liaisons must not be made yet when ii is made? Each answer is a logical condition on the set of liaisons made so far. A state is a set of made liaisons, and a step is allowed when the conditions of every liaison it makes pass. The method then draws the diagram of all states and allowed steps and reads each sequence as a path through it. The answers come from an engineer or, on this page, from the geometry of boxes that move by translations along fixed directions. Under that model the paths are exactly the feasible orders, up to the order of the first two parts.

In plain words

Think of a product as a set of joints. Each joint is a place where two parts touch. To plan how to build it, ask two questions about each joint. What must be done before this joint? What must not be done yet when this joint is made?

The answers are rules such as "the block must go on the base before the top plate closes the frame". With the rules, a program can try all orders of the joints. It starts with no joint, adds a part at each step, and keeps a step only if the rules allow it. All the orders that it keeps form a small map of states. Each road through the map from start to end is one way to build the product.

With two questions per joint, an engineer can answer them by hand for a small product.

The problem

The input is a product with parts PP, ∣P∣=n|P| = n, its liaison graph with liaisons l1,…,lll_1, \ldots, l_l, and a motion set MM. The output is every feasible linear sequence. This page solves assembly sequence planning in one restricted model. The problem page also covers two-handed plans, other motions and costs, and this method gives only the linear sequences under a fixed oracle for the questions.

The model is:

  • Hand model: linear and monotone. Each step adds one part to the parts already placed, and a placed part never moves again. The first step joins two parts.
  • Connected steps. The new part shares a liaison with a placed part, and the step makes all its liaisons with the placed parts at the same time.
  • Motion model: one translation. The parts are axis-aligned boxes. A part comes in from infinity by one translation along −d-d, for some d∈Md \in M, where MM is a subset of the six axis directions. This is possible exactly when the part could leave the placed parts along dd.

For a part vv and d∈Md \in M, B(v,d)B(v, d) is the set of parts that block vv when it moves along dd. A box ww blocks vv along +x+x when their open yy and zz intervals overlap and ww lies at or to the right of the right face of vv, and the same holds for the other directions.

The algorithm

The answers are monotone logical formulas over the liaisons. For a part ww, present(w)=⋁i∋wli\mathrm{present}(w) = \bigvee_{i \ni w} l_i says that ww is placed, which is true as soon as two or more parts are placed. A part vv is stuck when each direction has a placed blocker: stuck(v)=⋀d∈M⋁w∈B(v,d)present(w)\mathrm{stuck}(v) = \bigwedge_{d \in M} \bigvee_{w \in B(v, d)} \mathrm{present}(w).

  1. DFW(P, liaisons, M) ▷ ask the questions, then draw the diagram
  2. 1for each liaison i = {u, v} do
  3. 2pre_i ← false if u and v interlock alone along every d ∈ M, else true ▷ Q1
  4. 3post_i ← (present(u) ∧ stuck(v)) ∨ (present(v) ∧ stuck(u)) ▷ Q2
  5. 4for each liaison i = {u, v}: if pre_i(∅) and not post_i(∅) then make {i} a start state, with parts {u, v}
  6. 5while a state X with parts Q is not expanded do
  7. 6for each part p ∉ Q with a liaison to Q do
  8. 7Δ ← the liaisons between p and Q
  9. 8if pre_i(X) and not post_i(X) for every i ∈ Δ then
  10. 9add the arc X → X ∪ Δ, with parts Q ∪ {p}
  11. 10return the number of paths from the start states to the full state ▷ PATHS, memoized

The two questions. Q1, on line L2, asks which liaisons must be made before lil_i. Blocking only gets worse when parts are added, so in this model no liaison must come first, and the only answer other than "none" is that the two parts of lil_i cannot be joined at all. Q2, on line L3, asks which liaisons must not be made yet: the step is wrong when one end of lil_i is already placed and the other end is stuck.

A step makes several liaisons. When the block comes in between two posts on a base, it makes three liaisons in one step. Line L7 makes them all, and line L8 checks the answers of each.

Counting. The diagram is a directed acyclic graph, because each arc adds a part. Line L10 counts its paths from each node to the full state with memoization, so it visits each state and arc once. A list of all sequences is a walk of all those paths.

Example

Take the frame of the liaison graph page. Part 0 is the base plate, 1 and 2 are the left and right posts, 3 is a block between the posts on the base, and 4 is a top plate on the posts. The liaisons, numbered as pairs in order, are:

liaison l1l_1 l2l_2 l3l_3 l4l_4 l5l_5 l6l_6 l7l_7
parts 0, 1 0, 2 0, 3 1, 3 1, 4 2, 3 2, 4

Let the parts move in the plane of the frame only: M={+x,−x,+z,−z}M = \{+x, -x, +z, -z\}. No two parts interlock alone, so every prei\mathrm{pre}_i is true. The block is stuck when the posts, the top plate and the base are all placed: the posts stop it along ±x\pm x, the top plate along +z+z, and the base along −z-z. No other part is ever stuck, because each one can leave the frame along −x-x, +x+x, −z-z or +z+z. So

  • post1,post2,post5,post7\mathrm{post}_1, \mathrm{post}_2, \mathrm{post}_5, \mathrm{post}_7 are false,
  • post3=post4=post6=present(0)∧present(1)∧present(2)∧present(4)\mathrm{post}_3 = \mathrm{post}_4 = \mathrm{post}_6 = \mathrm{present}(0) \wedge \mathrm{present}(1) \wedge \mathrm{present}(2) \wedge \mathrm{present}(4), with present(4)=l5∨l7\mathrm{present}(4) = l_5 \vee l_7 and so on.

In words: the block must be in before the frame closes around it. The diagram has 7 start states, one for each liaison, 22 states and 42 arcs. The state {l1,l2,l5,l7}\{l_1, l_2, l_5, l_7\} is the closed frame without the block, and it has no arc out. There are 32 paths. Each path is two orders of the parts, because the first two parts can come in either order, so 64 of the 120 orders of the parts are feasible. Of the 120 orders, 80 add a part that touches a placed part at each step, and the 16 that put the block after the closed frame are removed by the answers.

Correctness

The proof uses the model above. If QQ is the connected set of placed parts and ∣Q∣≥2|Q| \ge 2, then present(w)\mathrm{present}(w) is true on the state E(Q)E(Q) exactly when w∈Qw \in Q, so the state names its parts and stuck(v)\mathrm{stuck}(v) is true exactly when vv cannot come in. For a new part pp with a liaison {p,u}\{p, u\} to QQ, the term present(p)∧stuck(u)\mathrm{present}(p) \wedge \mathrm{stuck}(u) is false and posti=stuck(p)\mathrm{post}_i = \mathrm{stuck}(p), so line L8 passes exactly when pp can come in. The first step passes exactly when prei\mathrm{pre}_i is true, that is, when one of the two parts can come in next to the other. Every state is the set of liaisons inside a connected set of parts, and the full state is reached only when all parts are placed. So the paths of the diagram are exactly the images of the feasible orders, and two feasible orders have the same image exactly when they differ in their first two parts. The full proofs are in the correctness proof.

Proof: Under the stated model, the precedence relations select exactly the feasible assembly ordersfull

We use the pseudocode and the model of the page. The product has parts PP, ∣P∣=n≥2|P| = n \ge 2, and a connected liaison graph LL with liaison set EE. For a set QQ of parts, E(Q)E(Q) is the set of liaisons with both ends in QQ. The motion set is MM. For a part vv and a direction d∈Md \in M, B(v,d)B(v, d) is the set of parts that block vv when vv translates to infinity along dd. The test for one step is

f(Q,p)  ⟺  there is d∈M with Q∩B(v,d)=∅ for v=p,f(Q, p) \iff \text{there is } d \in M \text{ with } Q \cap B(v, d) = \emptyset \text{ for } v = p,

that is, part pp can come into the placed set QQ by one translation along −d-d, since the motion that takes it out along dd meets nothing. A feasible order is an order p1,…,pnp_1, \ldots, p_n of PP such that for each k≥2k \ge 2, part pkp_k shares a liaison with one of p1,…,pk−1p_1, \ldots, p_{k-1} and f({p1,…,pk−1},pk)f(\{p_1, \ldots, p_{k-1}\}, p_k) holds. Its image is the sequence of states E(Q2),E(Q3),…,E(Qn)E(Q_2), E(Q_3), \ldots, E(Q_n) with Qk={p1,…,pk}Q_k = \{p_1, \ldots, p_k\}.

The answers are the formulas of lines L1 to L3. For a part ww, present(w)\mathrm{present}(w) is the disjunction of the liaisons at ww. For a part vv, stuck(v)=⋀d∈M⋁w∈B(v,d)present(w)\mathrm{stuck}(v) = \bigwedge_{d \in M} \bigvee_{w \in B(v, d)} \mathrm{present}(w), where an empty disjunction is false. For a liaison i={u,v}i = \{u, v\}:

  • prei\mathrm{pre}_i is false if f({u},v)f(\{u\}, v) and f({v},u)f(\{v\}, u) are both false, and true otherwise;
  • posti=(present(u)∧stuck(v))∨(present(v)∧stuck(u))\mathrm{post}_i = (\mathrm{present}(u) \wedge \mathrm{stuck}(v)) \vee (\mathrm{present}(v) \wedge \mathrm{stuck}(u)).

A step from a state XX that makes the set of liaisons Δ\Delta passes when prei(X)\mathrm{pre}_i(X) is true and posti(X)\mathrm{post}_i(X) is false for every i∈Δi \in \Delta.

Lemma 1 (monotone blocking). If Q′⊆QQ' \subseteq Q and f(Q,p)f(Q, p), then f(Q′,p)f(Q', p).

Proof. If Q∩B(p,d)=∅Q \cap B(p, d) = \emptyset then Q′∩B(p,d)=∅Q' \cap B(p, d) = \emptyset. □\square

Lemma 2 (a state names its parts). Let QQ be connected in LL with ∣Q∣≥2|Q| \ge 2, and let X=E(Q)X = E(Q). For every part ww, present(w)\mathrm{present}(w) is true on XX exactly when w∈Qw \in Q. So QQ is the set of ends of the liaisons in XX, and stuck(v)\mathrm{stuck}(v) is true on XX exactly when f(Q,v)f(Q, v) is false. On the empty state, every present(w)\mathrm{present}(w) is false.

Proof. If w∈Qw \in Q, then ww has a neighbour in QQ because QQ is connected and has a second part, so a liaison at ww lies in XX. If w∉Qw \notin Q, no liaison at ww lies in E(Q)E(Q). Then stuck(v)\mathrm{stuck}(v) on XX says that for each d∈Md \in M some w∈B(v,d)w \in B(v, d) lies in QQ, which is the negation of f(Q,v)f(Q, v). □\square

Lemma 3 (a later step passes exactly when it is feasible). Let QQ be connected with ∣Q∣≥2|Q| \ge 2, let p∉Qp \notin Q share a liaison with QQ, and let X=E(Q)X = E(Q) and Δ=E(Q∪{p})∖X\Delta = E(Q \cup \{p\}) \setminus X, the liaisons between pp and QQ. The step from XX that makes Δ\Delta passes if and only if f(Q,p)f(Q, p).

Proof. Δ\Delta is not empty. Take i={p,u}∈Δi = \{p, u\} \in \Delta, so u∈Qu \in Q. By Lemma 2, present(u)\mathrm{present}(u) is true and present(p)\mathrm{present}(p) is false on XX, so posti(X)=stuck(p)(X)=¬f(Q,p)\mathrm{post}_i(X) = \mathrm{stuck}(p)(X) = \neg f(Q, p). If f(Q,p)f(Q, p) holds, then f({u},p)f(\{u\}, p) holds by Lemma 1, so prei\mathrm{pre}_i is true, and posti(X)\mathrm{post}_i(X) is false: every liaison of Δ\Delta passes. If f(Q,p)f(Q, p) fails, then posti(X)\mathrm{post}_i(X) is true for any i∈Δi \in \Delta, and the step does not pass. □\square

Lemma 4 (the first step). The start state {i}\{i\} for i={u,v}i = \{u, v\} is made on line L4 if and only if f({u},v)f(\{u\}, v) or f({v},u)f(\{v\}, u).

Proof. The step from the empty state makes Δ=E({u,v})={i}\Delta = E(\{u, v\}) = \{i\}. On the empty state posti\mathrm{post}_i is false by Lemma 2, so the step passes exactly when prei\mathrm{pre}_i is true. □\square

Lemma 5 (prefixes are connected). In an order where each new part shares a liaison with an earlier part, every prefix QkQ_k is connected. Conversely, in the diagram every state is E(Q)E(Q) for a connected QQ with ∣Q∣≥2|Q| \ge 2, and the full state EE is E(Q)E(Q) only for Q=PQ = P.

Proof. The first claim is by induction on kk. For the second, the start states are E({u,v})E(\{u, v\}) for a liaison {u,v}\{u, v\}, and line L6 adds only a part with a liaison to QQ. If Q≠PQ \ne P, some liaison of the connected graph LL leaves QQ and is not in E(Q)E(Q), so E(Q)≠EE(Q) \ne E. □\square

Theorem 1 (exact selection). The paths of the diagram from a start state to the full state are exactly the images of the feasible orders.

Proof. Take a feasible order. Its first two parts share a liaison ii, and f({p1},p2)f(\{p_1\}, p_2) holds, so {i}\{i\} is a start state by Lemma 4. For k≥2k \ge 2, QkQ_k is connected by Lemma 5, pk+1p_{k+1} shares a liaison with it, and f(Qk,pk+1)f(Q_k, p_{k+1}) holds, so line L6 tries p=pk+1p = p_{k+1} and by Lemma 3 line L9 adds the arc from E(Qk)E(Q_k) to E(Qk+1)E(Q_{k+1}). The last state is E(P)=EE(P) = E. So the image is a path.

Conversely, take a path X2,…,XmX_2, \ldots, X_m from a start state X2={i}X_2 = \{i\}, i={u,v}i = \{u, v\}, to EE. By Lemma 5, Xk=E(Qk)X_k = E(Q_k) with Q2={u,v}Q_2 = \{u, v\}, each arc adds one part, and Qm=PQ_m = P, so m=nm = n. By Lemma 4 one of f({u},v)f(\{u\}, v) and f({v},u)f(\{v\}, u) holds: let p1,p2p_1, p_2 be u,vu, v in an order for which it holds. For k≥3k \ge 3 let pkp_k be the part of Qk∖Qk−1Q_k \setminus Q_{k-1}. It shares a liaison with Qk−1Q_{k-1}, because line L6 chose it so, and f(Qk−1,pk)f(Q_{k-1}, p_k) holds by Lemma 3, because the arc passed. So p1,…,pnp_1, \ldots, p_n is a feasible order with this image. □\square

Corollary 1 (counting). Two feasible orders have the same image exactly when they differ only in the order of their first two parts. So the number of feasible orders is the sum over the sequences of the number (1 or 2) of feasible orders of their first two parts. When MM is closed under d↦−dd \mapsto -d and the parts are boxes, both orders of the first two parts are feasible, and the number of feasible orders is twice the number of sequences.

Proof. By Lemma 2 the image fixes Q2,…,QnQ_2, \ldots, Q_n, hence p3,…,pnp_3, \ldots, p_n and the set {p1,p2}\{p_1, p_2\}. For the last claim: if f({u},v)f(\{u\}, v) fails, then u∈B(v,d)u \in B(v, d) for every d∈Md \in M, so u∈B(v,d)u \in B(v, d) and u∈B(v,−d)u \in B(v, -d) for one dd, which would put uu on both sides of vv along the axis of dd. □\square

Termination. The states are sets E(Q)E(Q) for distinct connected sets QQ, so there are at most NN of them, NN the number of connected sets, and each is expanded once. The path count of line L10 recurses only to larger states, so it stops, and with memoization it visits each state and arc once.

Scope. The proof uses one property of the answers: on the states that can occur, prei∧¬posti\mathrm{pre}_i \wedge \neg \mathrm{post}_i for the liaisons of a step says exactly whether the new part can come in. Lemma 1, which says that blocking only gets worse when parts are added, is what makes the answer to Q1 trivial in this model. A condition that gets easier as parts are added, such as a part that needs another part below it as a support, goes into Q1 instead. It can be written in the same way, but on the empty state it cannot tell which of the first two parts came first, so the first step must then be checked on the parts.

Complexity

The answers have size O(ml)O(m l) each, because stuck(v)\mathrm{stuck}(v) has at most mm terms of at most 2l2l variables. A state is the set of liaisons inside a connected set QQ of at least two parts, so there are at most NN states. At each state, line L6 tries at most nn parts, and lines L7 and L8 evaluate the answers of at most 2l2l liaisons in all, so a state costs O(ml2)O(m l^2) and the whole diagram costs O(Nml2)O(N m l^2). The diagram holds at most NN states of O(l)O(l) liaisons and at most NnN n arcs, so with the answers the space is O(Nl+ml2)O(N l + m l^2). The method asks 2l2l questions, which is the reason for the method. The diagram is still exponential in the worst case: when one base part touches all others, N≥2n−1N \ge 2^{n-1}.

Properties

  • Exact under its model. The paths are the feasible linear sequences, no more and no fewer, when the answers are the geometric ones of line L2 and L3. Answers from a person are only as good as the person.
  • Monotone answers. Each answer is a formula with "and" and "or" and no "not". So a step that passes in a state still passes in a smaller state with the same new part.
  • Linear only. The method cannot show a plan that builds two subassemblies and then joins them.
  • One state, many orders. A state does not record the order in which its parts came in, so all orders that reach the same set of parts share one node.

Variants and improvements

  • The earlier questions of Bourjault. Bourjault's 1984 thesis asked yes or no questions about one liaison against others. The number of questions grows faster than the number of liaisons. De Fazio and Whitney put each answer into one logical condition, which gives 2l2l questions.
  • Precedence relations as a partial order. When each answer is a conjunction of single liaisons, the relations are a partial order on the liaisons, and the sequences are its linear extensions. Their number is a count of linear extensions, and one sequence is a topological sort. The frame has a disjunction in its answers, so it is not of this kind.
  • Pruning the diagram. A planner can also remove states that are bad for other reasons, such as an unstable subassembly or a state that needs a hard reorientation, and then pick paths by cost.
  • Two-handed plans. The AND/OR graph of assembly plans holds the plans that join subassemblies. Homem de Mello and Sanderson compared the diagram of liaison states, the AND/OR graph and precedence relations as ways to hold the same sequences.
  • Automatic answers. The non-directional blocking graph answers the geometric part of Q2 for all translation directions at once, and so removes the person from the loop.

When to use it

Use it for products of up to a few tens of parts when an engineer must review the rules, because two questions per liaison are short to ask and to check. Use it when only linear sequences are allowed, as on many assembly lines with one fixture. When the parts are given as geometry, compute the answers as on this page instead of asking a person. Use the AND/OR graph when two-handed plans count, and a search of one branch when one plan is enough.

Pitfalls

  • Answers by hand can be wrong. A missed blocker lets through a sequence that cannot be built. A blocker that does not exist removes a good sequence. Check the answers against the geometry when there is geometry.
  • The empty state cannot tell which part came first. On the first step, a condition on the liaisons sees neither part. If one of the first two parts must come first, for example because it is a fixture, that fact cannot be written as an answer. Check the first step on the parts.
  • One liaison at a time is wrong. A step can make several liaisons. If the diagram adds one liaison per arc, it creates states with parts that touch but are not joined, which the model does not have.
  • A product in pieces. If the liaison graph is not connected, no sequence exists under the connected model. The program must say so. It must not stop at a state that has all liaisons but not all parts.
  • All six directions. With all six axis directions, a box is never stuck among five or fewer other boxes, because each other box blocks it along at most one direction. For small box products, only the connection rule then removes orders. The example keeps motion in the plane for that reason.

Implementations

The Python module computes the answers to both questions from a list of boxes with integer or Fraction corners and a set of axis directions, as formulas that can be printed. It then draws the diagram, counts its paths and lists the sequences. A shared helper holds the box predicates. The tests check every order of up to 6 parts, with each step tested by moving the new part along each direction and sampling its positions, and compare the feasible orders with the paths of the diagram. They also check the frame, the dead state of the closed frame, and the fact that with all six directions every order with connected steps is feasible.

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
de_fazio_whitney_precedence_method.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/de-fazio-whitney-precedence-method/. The authors are listed in prov/RRPKFP.jsonl.
"""The De Fazio-Whitney question method for linear assembly sequences.

For each liaison i = {u, v} the method asks two questions:
  Q1: which liaisons must be done before liaison i can be done?  -> pre[i]
  Q2: which liaisons must not be done yet when liaison i is done? -> post[i]
Each answer is a monotone logical formula over the liaisons. A state is the
set of liaisons made so far. A step may add several liaisons at once, and it
passes when pre[i] holds and post[i] does not, in the state before the step,
for every liaison i that it makes.

Here an oracle answers the questions from the geometry of a product of
axis-aligned boxes, under this model: linear and monotone (one new part per
step, placed parts never move), connected (the new part touches a placed
part, and all its liaisons with placed parts are made in that step), and a
part goes in by one translation from infinity; it can come in along -d
when it could leave the placed parts along d, for some d in the motion set.
"""

from assembly_boxes import AXES6, blocks, face_contact

TRUE = ("and", ())
FALSE = ("or", ())


def var(i):
    return ("var", i)


def f_and(items):
    items = tuple(items)
    if FALSE in items:
        return FALSE
    items = tuple(x for x in items if x != TRUE)
    return items[0] if len(items) == 1 else ("and", items)


def f_or(items):
    items = tuple(items)
    if TRUE in items:
        return TRUE
    items = tuple(x for x in items if x != FALSE)
    return items[0] if len(items) == 1 else ("or", items)


def evaluate(f, state):
    """The value of formula f when exactly the liaisons in state are made."""
    tag = f[0]
    if tag == "var":
        return f[1] in state
    if tag == "and":
        return all(evaluate(g, state) for g in f[1])
    if tag == "or":
        return any(evaluate(g, state) for g in f[1])
    raise ValueError("answers are monotone formulas")


def show(f, names=None):
    """The formula as text, with liaison i written l<i+1> unless names given."""
    tag = f[0]
    if f == TRUE:
        return "true"
    if f == FALSE:
        return "false"
    if tag == "var":
        return names[f[1]] if names else "l%d" % (f[1] + 1)
    sep = " and " if tag == "and" else " or "
    return "(" + sep.join(show(g, names) for g in f[1]) + ")"


def liaisons_of(boxes):
    """The contact liaisons as a list of pairs (u, v) with u < v."""
    n = len(boxes)
    return [(u, v) for u in range(n) for v in range(u + 1, n)
            if face_contact(boxes[u], boxes[v]) is not None]


def answer_questions(boxes, liaisons, motions=AXES6):
    """The answers to Q1 and Q2 for every liaison, from the geometry."""
    n = len(boxes)
    at = [[k for k, (u, v) in enumerate(liaisons) if w in (u, v)] for w in range(n)]

    def present(w):  # part w is placed, when at least two parts are placed
        return f_or(var(k) for k in at[w])

    pre, post = [], []
    for (u, v) in liaisons:  # @line L1
        alone = any(not blocks(boxes[v], boxes[u], d) or not blocks(boxes[u], boxes[v], d)
                    for d in motions)
        pre.append(TRUE if alone else FALSE)  # @line L2
        terms = []
        for a, b in ((u, v), (v, u)):  # b comes in next to a
            # b is stuck when, for every d, some blocker of b along d is present
            stuck = f_and(f_or(present(w) for w in range(n)
                               if w != b and blocks(boxes[b], boxes[w], d))
                          for d in motions)
            terms.append(f_and((present(a), stuck)))
        post.append(f_or(terms))  # @line L3
    return pre, post


def generate(n, liaisons, pre, post):
    """The diagram of liaison states and its start states.

    A state is a frozenset of liaison indices. Returns (starts, arcs) where
    arcs maps a state to the list of states one passing step away.
    """
    adj = [0] * n
    for (u, v) in liaisons:
        adj[u] |= 1 << v
        adj[v] |= 1 << u
    full = frozenset(range(len(liaisons)))
    reach = 1
    while True:
        grow = reach
        for p in range(n):
            if reach >> p & 1:
                grow |= adj[p]
        if grow == reach:
            break
        reach = grow
    if reach != (1 << n) - 1:
        return [], {}, full          # a product in pieces has no sequence

    def made(q):
        return frozenset(k for k, (u, v) in enumerate(liaisons) if q >> u & 1 and q >> v & 1)

    def passes(x, delta):
        return all(evaluate(pre[i], x) and not evaluate(post[i], x) for i in delta)

    starts = []
    for k, (u, v) in enumerate(liaisons):  # @line L4
        q = 1 << u | 1 << v
        if passes(frozenset(), made(q)):
            starts.append((made(q), q))
    arcs = {}
    todo = list(starts)
    seen = {}
    while todo:  # @line L5
        x, q = todo.pop()
        if x in arcs:
            continue
        arcs[x] = []
        for p in range(n):  # @line L6
            if q >> p & 1 or not adj[p] & q:
                continue
            q2 = q | 1 << p
            y = made(q2)
            delta = y - x  # @line L7
            if passes(x, delta):  # @line L8
                arcs[x].append(y)  # @line L9
                if y not in seen:
                    seen[y] = q2
                    todo.append((y, q2))
    start_states = sorted({x for x, _ in starts}, key=sorted)
    return start_states, arcs, full


def count_sequences(n, liaisons, pre, post):
    """The number of liaison sequences, by counting paths in the diagram."""
    if n == 1:
        return 1
    starts, arcs, full = generate(n, liaisons, pre, post)
    memo = {}

    def paths(x):  # @line L10
        if x == full:
            return 1
        if x not in memo:
            memo[x] = sum(paths(y) for y in arcs.get(x, ()))
        return memo[x]

    return sum(paths(x) for x in starts)


def sequences(n, liaisons, pre, post):
    """Every liaison sequence as a tuple of states, from the first to the full one."""
    if n == 1:
        return [()]
    starts, arcs, full = generate(n, liaisons, pre, post)
    out = []

    def walk(x, path):
        if x == full:
            out.append(tuple(path))
            return
        for y in arcs.get(x, ()):
            walk(y, path + [y])

    for x in starts:
        walk(x, [x])
    return out
test_de_fazio_whitney_precedence_method.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/de-fazio-whitney-precedence-method/. The authors are listed in prov/RRPKFP.jsonl.

import itertools
import random

from assembly_boxes import AXES6, face_contact, free_by_sampling, random_boxes
from de_fazio_whitney_precedence_method import (
    answer_questions, count_sequences, evaluate, liaisons_of, sequences, show)

# ---- independent reference: every order of the parts, checked on the geometry ----


def feasible_orders(boxes, motions):
    """Orders in which each new part touches a placed part and can come in
    by one translation, checked by a sampled sweep."""
    n = len(boxes)
    cache = {}
    out = []
    for order in itertools.permutations(range(n)):
        ok = True
        for k in range(1, n):
            p = order[k]
            placed = frozenset(order[:k])
            key = (placed, p)
            if key not in cache:
                touches = any(face_contact(boxes[p], boxes[q]) is not None for q in placed)
                cache[key] = touches and any(
                    free_by_sampling([boxes[p]], [boxes[q] for q in placed], d) for d in motions)
            if not cache[key]:
                ok = False
                break
        if ok:
            out.append(order)
    return out


def image(order, liaisons):
    """The sequence of liaison states of a part order."""
    states = []
    for k in range(2, len(order) + 1):
        placed = set(order[:k])
        states.append(frozenset(i for i, (u, v) in enumerate(liaisons)
                                if u in placed and v in placed))
    return tuple(states)


def check(boxes, motions):
    liaisons = liaisons_of(boxes)
    pre, post = answer_questions(boxes, liaisons, motions)
    assert len(pre) == len(post) == len(liaisons)       # 2 questions per liaison
    n = len(boxes)
    got = sequences(n, liaisons, pre, post)
    assert len(got) == len(set(got))
    orders = feasible_orders(boxes, motions)
    assert set(got) == {image(o, liaisons) for o in orders}
    assert count_sequences(n, liaisons, pre, post) == len(got)
    return len(orders), len(got)


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
]
PLANE = ((1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1))

# ---- tests ----


def test_random_products_one_or_two_directions():
    rng = random.Random(21)
    for _ in range(70):
        n = rng.randint(1, 5)
        boxes = random_boxes(rng, n, size=3, max_side=3, connected=rng.random() < 0.85)
        motions = tuple(rng.sample(AXES6, rng.randint(1, 2)))
        check(boxes, motions)


def test_random_products_six_boxes():
    rng = random.Random(22)
    for _ in range(5):
        boxes = random_boxes(rng, 6, size=3, max_side=2, connected=True)
        motions = tuple(rng.sample(AXES6, rng.randint(1, 3)))
        check(boxes, motions)


def test_all_six_directions():
    rng = random.Random(23)
    for _ in range(25):
        n = rng.randint(2, 5)
        boxes = random_boxes(rng, n, size=3, max_side=3, connected=True)
        n_orders, _ = check(boxes, AXES6)
        # a box blocks another box along at most one of the six directions,
        # so with at most five others a box can always come in: every order
        # whose prefixes are connected is feasible
        connected_orders = sum(
            all(any(face_contact(boxes[o[k]], boxes[q]) for q in o[:k]) for k in range(1, n))
            for o in itertools.permutations(range(n)))
        assert n_orders == connected_orders


def test_example_frame():
    liaisons = liaisons_of(EXAMPLE)
    assert liaisons == [(0, 1), (0, 2), (0, 3), (1, 3), (1, 4), (2, 3), (2, 4)]
    pre, post = answer_questions(EXAMPLE, liaisons, PLANE)
    assert all(evaluate(p, frozenset()) for p in pre)
    n_orders, n_seq = check(EXAMPLE, PLANE)
    assert (n_orders, n_seq) == (64, 32)
    # the block cannot come in once the base, both posts and the top are placed
    closed = frozenset([0, 1, 4, 6])          # liaisons {0,1}, {0,2}, {1,4}, {2,4}
    for i in (2, 3, 5):                       # the liaisons of the block
        assert evaluate(post[i], closed)
    assert not any(evaluate(post[i], frozenset([0, 1, 2, 3, 5])) for i in range(7))
    assert "l" in show(post[2])

History

Bourjault, in his 1984 thesis at Besançon, used the liaison graph to generate assembly sequences from the answers to many yes or no questions. De Fazio and Whitney published the two question method in 1987 and a correction to it in 1988. Homem de Mello and Sanderson compared it with the AND/OR graph and with other representations around 1990. Later work replaced the person by geometric reasoning on blocking graphs.

References

  1. 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 two questions per liaison, the precedence relations as logical expressions, and the diagram of liaison sequences
  2. Thomas L. De Fazio and Daniel E. Whitney, Correction to Simplified generation of all mechanical assembly sequences, IEEE Journal of Robotics and Automation 4(6), 705 to 708 (1988), the corrected rules for reading the answers
  3. Alain Bourjault, Contribution à une approche méthodologique de l'assemblage automatisé: élaboration automatique des séquences opératoires, Thèse d'État, Université de Franche-Comté, Besançon, 1984, the liaison graph and the yes or no questions on the order of liaisons
  4. 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 comparison of the diagram of liaison states with the AND/OR graph and with precedence relations

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