Algorithm Search⌘K

Algorithmadvanced

A* bend sequence search

Also called Gupta bend planner.

Gupta, Bourne, Kim and Krishnan's planner that searches bend orders with A*, with costs from tool changes and handling and collision checks from geometry.

Time
O(2^n n k^2 (n + log k)) worst
Space
O(2^n n k^2) extra
Where
k = number of tools; n = number of bends
Properties
deterministicexactiterative
Origin
Satyandra K. Gupta, David A. Bourne, K. H. Kim, S. S. Krishnan, 1998

A* bend sequence search plans the order of the bends of a sheet metal part on a press brake, and the tool of each bend, with A* search. A state is the set of bends already made, with the sign of the last bend and the last tool. The shape of the part depends only on the set of bends made, so a collision test of the next bend needs only this set. A step costs a turn of the part when the sign of the bend changes, and a tool change when the tool changes. Gupta, Bourne, Kim and Krishnan (1998) built a planner of this kind for a robotic press brake, with heuristics that can overestimate. This page gives a heuristic that is consistent, so the search returns a cheapest plan, and proves it. This page differs from bend sequence planning: that page states the problem and its costs, and this page is one exact search method for it.

In plain words

Bend the part in your head one bend at a time. After each bend, note which bends are done, the last tool and which way up the part was. That note is a state. From a state, try every bend left with every tool that fits it. If the part hits the punch or the die, drop that move. Else the move costs a tool change, a turn of the part, both or nothing.

A* always takes the open state with the least cost so far plus a guess of the cost to come. If some bend left needs the part the other way up, at least one more turn is needed. If the last tool does not fit some bend left, at least one more tool change is needed. The guess never says too much, so the first finished plan that A* takes is a cheapest one.

The problem

Input. A planar profile of n+1n + 1 flanges with integer lengths l0,…,lnl_0, \dots, l_n. Bend bb, for 1≤b≤n1 \le b \le n, joins flanges b−1b - 1 and bb, and turns the profile by 90 degrees to the left (sb=+1s_b = +1) or to the right (sb=−1s_b = -1) as you walk from flange 00 to flange nn. A list of kk tools, each a triple (w,D,m)(w, D, m): punch width, die width and smallest flange. Two weights flip≥0\textit{flip} \ge 0 and change≥0\textit{change} \ge 0.

Shape after a set of bends. A bend is either not done, and the profile is straight there, or done fully. So the shape after a set SS of bends does not depend on their order.

Collision rule. This is a toy rule, the model of the code. Put the part in the frame of bend bb: the bend at the origin, flange bb along +x+x and flange b−1b - 1 along +y+y, with the profile mirrored if sb=−1s_b = -1, which is the part turned over. Draw the profile with the bends of S∪{b}S \cup \{b\} done. Tool (w,D,m)(w, D, m) can make bend bb if both flanges next to bb have length at least mm (the fit), and no point of the profile is in the open punch region {x>0,y>0,∣x−y∣<w}\{x > 0, y > 0, \lvert x - y \rvert < w\} or in the open die region {x+y<0,∣x−y∣<D}\{x + y < 0, \lvert x - y \rvert < D\}. The punch is a blade of half width w/2w / \sqrt 2 along the bisector inside the bend, and the die is a block along the bisector outside it. The rule tests the part at the end of the stroke, not during it.

Cost. A plan is an order of all bends with a tool for each, where each bend can be made after the bends before it. It costs flip\textit{flip} for each pair of consecutive bends with different signs, and change\textit{change} for each pair with different tools.

Output. A plan of least cost, or "none" if no plan exists.

The algorithm

A state is u=(S,σ,τ)u = (S, \sigma, \tau): the set SS of bends done, the sign σ\sigma of the last bend (00 at the start) and the last tool τ\tau (none at the start). Let R=B∖SR = B \setminus S be the bends left. A tool fits a bend when both flanges next to it are at least its smallest flange; this ignores collisions. The heuristic is h(u)=0h(u) = 0 if R=∅R = \emptyset, and otherwise

h(u)=flip⋅φ(u)+change⋅ψ(u),h(u) = \textit{flip} \cdot \varphi(u) + \textit{change} \cdot \psi(u),

where φ(u)=1\varphi(u) = 1 if σ=0\sigma = 0 and RR holds bends of both signs, or σ≠0\sigma \ne 0 and some bend of RR has a sign other than σ\sigma; and ψ(u)=1\psi(u) = 1 if τ\tau is none and no one tool fits all bends of RR, or τ\tau is a tool that does not fit some bend of RR. Otherwise φ(u)=0\varphi(u) = 0 and ψ(u)=0\psi(u) = 0.

  1. A*-BENDS(l, s, T, flip, change)
  2. 1start ← (∅, 0, none); g[start] ← 0; put start in the queue with key h(start)
  3. 2while the queue is not empty
  4. 3take u = (S, σ, τ) of least key from the queue; if u is closed, skip it, else close it
  5. 4if S = B then return the plan along the parent links to u, with cost g[u]
  6. 5for each bend b ∉ S and each tool t that fits b
  7. 6if bend b with tool t after the bends of S collides then skip (b, t)
  8. 7v ← (S ∪ {b}, s_b, t); c ← flip · [σ ∉ {0, s_b}] + change · [τ ∉ {none, t}]
  9. 8if g[v] is not set or g[u] + c < g[v] then g[v] ← g[u] + c; parent[v] ← u; put v in the queue with key g[v] + h(v)
  10. 9return none

Line L3. The queue keeps old copies of a state when line L8 finds a cheaper path. A copy that comes out after the state is closed is skipped. There is no reopening of closed states, which is correct because hh is consistent (see A* search).

Line L6. The collision test depends on SS, bb and tt, and not on σ\sigma or τ\tau. The code caches it by (S,b,t)(S, b, t), so each test runs one time, however many states share the set SS.

Exact test. All points of the profile are integer. A point of a segment is p+λ(q−p)p + \lambda (q - p) with 0≤λ≤10 \le \lambda \le 1, and each open half plane ax+cy<ka x + c y < k of a region keeps an open interval of λ\lambda. The code cuts the interval with each half plane in rational arithmetic and asks if what is left is empty. A segment that only touches the boundary of the punch region does not collide, and the test sees that exactly.

Example

The lipped channel of bend sequence planning: l=(1,4,6,4,1)l = (1, 4, 6, 4, 1), all four signs +1+1, so lip, wall, base, wall, lip. The tools are STANDARD =(3,2,1)= (3, 2, 1) and GOOSENECK =(1,4,2)= (1, 4, 2), with flip=2\textit{flip} = 2 and change=1\textit{change} = 1. GOOSENECK does not fit the lip bends b1b_1 and b4b_4, since a lip of 1 is shorter than its smallest flange of 2.

The collision tests. A lip bend after the wall next to it collides: after b2b_2, the base stands up at the end of the wall and enters the punch region when b1b_1 is made. The second wall bend needs GOOSENECK. For b3b_3 after {b1,b2,b4}\{b_1, b_2, b_4\}, the profile in the frame of b3b_3 is the wall from (0,0)(0, 0) to (4,0)(4, 0) and its lip to (4,1)(4, 1), then the base from (0,0)(0, 0) to (0,6)(0, 6), the other wall to (4,6)(4, 6) and its lip to (4,5)(4, 5). With STANDARD, w=3w = 3, and the point (4,5)(4, 5) has ∣x−y∣=1<3\lvert x - y \rvert = 1 < 3, a collision. With GOOSENECK, w=1w = 1, the lip at x=4x = 4, 5≤y≤65 \le y \le 6 has ∣x−y∣≥1\lvert x - y \rvert \ge 1, so it only touches the boundary, and the wall at y=6y = 6, x≤4x \le 4 has ∣x−y∣≥2\lvert x - y \rvert \ge 2. No collision.

The search. At the start, all signs are equal and STANDARD fits all bends, so h=0h = 0. Every state with last tool STANDARD also has h=0h = 0. A state with last tool GOOSENECK and a lip left has h=1h = 1.

states taken at line L3 key count
the start; {1},{2},{3},{4}\{1\}, \{2\}, \{3\}, \{4\}; {1,2},{1,3},{1,4},{2,4},{3,4}\{1,2\}, \{1,3\}, \{1,4\}, \{2,4\}, \{3,4\}; {1,2,4},{1,3,4}\{1,2,4\}, \{1,3,4\}, all with STANDARD 0 12
{2}\{2\}, {3}\{3\}, {1,2,4}\{1,2,4\}, {1,3,4}\{1,3,4\} with GOOSENECK, then {1,2,3,4}\{1,2,3,4\} with GOOSENECK 1 5

The state {1,2,3,4}\{1,2,3,4\} with GOOSENECK passes line L4 with cost 1. The plan is b1,b2,b4b_1, b_2, b_4 with STANDARD and b3b_3 with GOOSENECK: one tool change, no turn. A* takes 17 states from the queue, and uniform cost search, which is the same code with h=0h = 0, takes 24. A check of all 4!=244! = 24 orders finds 6 feasible orders, the ones with b1b_1 before b2b_2 and b4b_4 before b3b_3, each with one tool change at best, so the least cost is 1.

Correctness

Theorem. A*-BENDS returns a plan of least cost if a plan exists, and none otherwise.

The proof has three parts. First, plans are exactly the paths from the start to a state with S=BS = B in the graph of lines L5 to L7, with the same cost, because the shape and the collision test depend only on SS and the step cost depends only on σ\sigma, τ\tau, bb and tt. Second, hh is consistent: for each move from uu to vv with cost cc, h(u)≤c+h(v)h(u) \le c + h(v). Take φ\varphi. If φ(u)=1\varphi(u) = 1 and the move turns the part, it pays flip\textit{flip}. If it does not turn the part, some bend of the other sign is still left in vv, so φ(v)=1\varphi(v) = 1. At the start, the bends left have both signs, so after the first bend some bend of the other sign is left. The same holds for ψ\psi, because a move uses a tool that fits its bend. With h=0h = 0 at the goals, consistency gives admissibility. Third, A* with a consistent heuristic and no reopening returns a cheapest path to a goal set, or reports that none is reachable, as on the A* search page. The exact clipping makes line L6 the collision rule of the page, with no error from rounding. The full proof is below.

Proof: A*-BENDS returns a cheapest bend plan, or none if there is no planfull

We use the definitions of the page. B={1,…,n}B = \{1, \dots, n\} is the set of bends, sb∈{+1,−1}s_b \in \{+1, -1\} is the sign of bend bb, and TT is the list of kk tools. A tool tt fits bend bb when min⁡(lb−1,lb)≥mt\min(l_{b-1}, l_b) \ge m_t. For a set S⊆BS \subseteq B and b∉Sb \notin S, write coll(S,b,t)\mathrm{coll}(S, b, t) for the result of the collision rule of the page: the profile with the bends of S∪{b}S \cup \{b\} done, in the frame of bend bb, meets the open punch region or the open die region of tt. A plan is a sequence (b1,t1),…,(bn,tn)(b_1, t_1), \dots, (b_n, t_n) in which b1,…,bnb_1, \dots, b_n is an order of BB, each tit_i fits bib_i, and coll({b1,…,bi−1},bi,ti)\mathrm{coll}(\{b_1, \dots, b_{i-1}\}, b_i, t_i) is false for each ii. Its cost is

cost=∑i=2n(flip⋅[sbi−1≠sbi]+change⋅[ti−1≠ti]).\mathrm{cost} = \sum_{i=2}^{n} \bigl(\textit{flip} \cdot [s_{b_{i-1}} \ne s_{b_i}] + \textit{change} \cdot [t_{i-1} \ne t_i]\bigr).

The graph GG. The nodes are the start u0=(∅,0,⊥)u_0 = (\emptyset, 0, \bot) and the triples (S,σ,τ)(S, \sigma, \tau) with S⊆BS \subseteq B not empty, σ∈{+1,−1}\sigma \in \{+1, -1\} and τ\tau a tool. From u=(S,σ,τ)u = (S, \sigma, \tau) there is an arc to v=(S∪{b},sb,t)v = (S \cup \{b\}, s_b, t) for each b∉Sb \notin S and each tool tt that fits bb with coll(S,b,t)\mathrm{coll}(S, b, t) false, with the cost

c(u,v)=flip⋅[σ∉{0,sb}]+change⋅[τ∉{⊥,t}]≥0.c(u, v) = \textit{flip} \cdot [\sigma \notin \{0, s_b\}] + \textit{change} \cdot [\tau \notin \{\bot, t\}] \ge 0.

These are the arcs that lines L5 to L7 make. The goals are the nodes with S=BS = B.

Lemma 1 (the state model). The plans are in one to one correspondence with the paths in GG from u0u_0 to a goal, and a plan and its path have the same cost.

Proof. The function profile_after builds the profile from the set of done bends and the bend bb only: it walks from flange bb to flange nn, and from flange b−1b - 1 to flange 00, and turns at bend jj if and only if jj is in the set. So coll(S,b,t)\mathrm{coll}(S, b, t) depends only on SS, bb and tt. This is the claim of the page that the shape does not depend on the order of the bends.

Given a plan, let Si={b1,…,bi}S_i = \{b_1, \dots, b_i\} and ui=(Si,sbi,ti)u_i = (S_i, s_{b_i}, t_i) for i≥1i \ge 1. Each step ui−1→uiu_{i-1} \to u_i is an arc of GG, because tit_i fits bib_i and coll(Si−1,bi,ti)\mathrm{coll}(S_{i-1}, b_i, t_i) is false, and unu_n is a goal. The arc u0→u1u_0 \to u_1 costs 0, since σ=0\sigma = 0 and τ=⊥\tau = \bot. For i≥2i \ge 2 the arc costs flip⋅[sbi−1≠sbi]+change⋅[ti−1≠ti]\textit{flip} \cdot [s_{b_{i-1}} \ne s_{b_i}] + \textit{change} \cdot [t_{i-1} \ne t_i], the ii-th term of the plan cost. Conversely, each arc adds one new bend to SS, so a path from u0u_0 to a goal has exactly nn arcs, each adds one bend with a tool that fits it and does not collide, and reading off the pairs (b,t)(b, t) gives a plan. The two maps are inverse to each other, and the costs agree term by term. □\square

Lemma 2 (the heuristic is consistent). For each arc u→vu \to v of GG, h(u)≤c(u,v)+h(v)h(u) \le c(u, v) + h(v). Also h=0h = 0 at each goal. Hence h(u)≤h∗(u)h(u) \le h^*(u), the least cost of a path from uu to a goal, for each node uu from which a goal is reachable.

Proof. Let u=(S,σ,τ)u = (S, \sigma, \tau), let the arc add bend bb with tool tt, so v=(S∪{b},sb,t)v = (S \cup \{b\}, s_b, t), and let R=B∖SR = B \setminus S and R′=R∖{b}R' = R \setminus \{b\}. Write c=cφ+cψc = c_\varphi + c_\psi with cφ=flip⋅[σ∉{0,sb}]c_\varphi = \textit{flip} \cdot [\sigma \notin \{0, s_b\}] and cψ=change⋅[τ∉{⊥,t}]c_\psi = \textit{change} \cdot [\tau \notin \{\bot, t\}]. Since h=flip⋅φ+change⋅ψh = \textit{flip} \cdot \varphi + \textit{change} \cdot \psi when R≠∅R \ne \emptyset, it is enough to show

flip⋅φ(u)≤cφ+flip⋅φ(v),change⋅ψ(u)≤cψ+change⋅ψ(v),\textit{flip} \cdot \varphi(u) \le c_\varphi + \textit{flip} \cdot \varphi(v), \qquad \textit{change} \cdot \psi(u) \le c_\psi + \textit{change} \cdot \psi(v),

with φ(v)=ψ(v)=0\varphi(v) = \psi(v) = 0 when R′=∅R' = \emptyset. The weights are not negative, so each inequality holds when its left side is 0. Assume the left side is not 0.

The term φ\varphi. Case σ≠0\sigma \ne 0. Some b′∈Rb' \in R has sb′≠σs_{b'} \ne \sigma. If sb≠σs_b \ne \sigma, then cφ=flipc_\varphi = \textit{flip}, and we are done. If sb=σs_b = \sigma, then b′≠bb' \ne b, so b′∈R′b' \in R', and the last sign of vv is sb=σ≠sb′s_b = \sigma \ne s_{b'}. So φ(v)=1\varphi(v) = 1. Case σ=0\sigma = 0. Then u=u0u = u_0 and RR holds bends of both signs. The bend bb has one sign, so some b′∈Rb' \in R has sb′=−sbs_{b'} = -s_b, and b′≠bb' \ne b, so b′∈R′b' \in R' and φ(v)=1\varphi(v) = 1.

The term ψ\psi. Case τ≠⊥\tau \ne \bot. Some b′∈Rb' \in R is not fit by τ\tau. If t≠τt \ne \tau, then cψ=changec_\psi = \textit{change}, and we are done. If t=τt = \tau, then tt fits bb, because the arc exists, so b′≠bb' \ne b, b′∈R′b' \in R', and the last tool tt of vv does not fit b′b'. So ψ(v)=1\psi(v) = 1. Case τ=⊥\tau = \bot. No one tool fits all bends of RR. If tt fit all bends of R′R', then tt would fit all bends of R=R′∪{b}R = R' \cup \{b\}, since it fits bb. So some b′∈R′b' \in R' is not fit by tt, and ψ(v)=1\psi(v) = 1.

So h(u)≤c(u,v)+h(v)h(u) \le c(u, v) + h(v) when R′≠∅R' \ne \emptyset. When R′=∅R' = \emptyset, that is R={b}R = \{b\}, the left sides are 0: for φ\varphi, σ=0\sigma = 0 would need two bends in RR, and σ≠0\sigma \ne 0 with sb≠σs_b \ne \sigma gives cφ=flipc_\varphi = \textit{flip}; for ψ\psi, τ=⊥\tau = \bot is not possible because tt fits all of RR, and τ≠⊥\tau \ne \bot not fitting bb forces t≠τt \ne \tau, so cψ=changec_\psi = \textit{change}. So the inequality holds in this case too.

A goal has R=∅R = \emptyset, so h=0h = 0. For admissibility, take a cheapest path u=w0,w1,…,wru = w_0, w_1, \dots, w_r from uu to a goal. Adding the inequalities h(wj)≤c(wj,wj+1)+h(wj+1)h(w_{j}) \le c(w_j, w_{j+1}) + h(w_{j+1}) for j=0,…,r−1j = 0, \dots, r - 1 gives h(u)≤∑jc(wj,wj+1)+h(wr)=h∗(u)h(u) \le \sum_j c(w_j, w_{j+1}) + h(w_r) = h^*(u). □\square

Lemma 3 (exact clipping). For a segment [p,q][p, q] with integer end points and a finite set of strict inequalities ax+cy<ka x + c y < k with integer coefficients, _meets_open returns true if and only if some point of the segment satisfies all of them.

Proof. The points of the segment are p+λ(q−p)p + \lambda (q - p) with λ∈[0,1]\lambda \in [0, 1]. For one inequality, let α=apx+cpy−k\alpha = a p_x + c p_y - k and β=a(qx−px)+c(qy−py)\beta = a (q_x - p_x) + c (q_y - p_y), so the point satisfies it if and only if α+βλ<0\alpha + \beta \lambda < 0. If β=0\beta = 0, this holds for all λ\lambda when α<0\alpha < 0 and for none when α≥0\alpha \ge 0; the code returns false in the second case and ignores the inequality in the first. If β>0\beta > 0, it holds if and only if λ<r\lambda < r with r=−α/βr = -\alpha / \beta, an open upper bound. If β<0\beta < 0, it holds if and only if λ>r\lambda > r, an open lower bound. The set of good λ\lambda is therefore an interval with the lower end lo\mathrm{lo}, the largest of 0 and the lower bounds, and the upper end hi\mathrm{hi}, the smallest of 1 and the upper bounds. An end is open when it comes from an inequality, and closed when it is the 0 or the 1 of the segment. When an inequality gives the same value as the current end, the code marks the end open, which is the tighter of the two. The interval is not empty if and only if lo<hi\mathrm{lo} < \mathrm{hi}, or lo=hi\mathrm{lo} = \mathrm{hi} with both ends closed. This is the last test of the code. All values are rationals in Fraction, so each comparison is exact. □\square

The punch region {x>0,y>0,∣x−y∣<w}\{x > 0, y > 0, \lvert x - y \rvert < w\} is the set of four strict inequalities −x<0-x < 0, −y<0-y < 0, x−y<wx - y < w and −x+y<w-x + y < w, and the die region is x+y<0x + y < 0, x−y<Dx - y < D and −x+y<D-x + y < D. So by Lemma 3, collides computes coll(S,b,t)\mathrm{coll}(S, b, t) exactly, and line L6 removes exactly the arcs that GG does not have. The cache of line L6 is keyed by (S,b,t)(S, b, t), and by Lemma 1 the result depends on nothing else, so the cache returns the same value as a new test.

Theorem. A*-BENDS returns a plan of least cost if a plan exists, and none otherwise. It ends after at most 1+2k⋅2n1 + 2k \cdot 2^n states are closed.

Proof. By Lemma 3 and the remark after it, lines L5 to L8 generate exactly the arcs of GG with their costs. Lines L1 to L9 are A* on GG from u0u_0 with the goal test when a state leaves the queue (line L4), lazy deletion of old queue entries (line L3), and no reopening of closed states. By Lemma 2, hh is consistent with h=0h = 0 at the goals. For such a heuristic, A* without reopening takes each state from the queue at most once, with gg equal to the least cost of a path from the start, and the first goal it takes has the least cost of all goals reachable from the start. If no goal is reachable, the queue becomes empty and A* reports none. This is the result stated on the A* search page (Hart, Nilsson and Raphael 1968).

For completeness of this note, here is the core step. With a consistent hh, the reduced costs c′(u,v)=c(u,v)−h(u)+h(v)c'(u, v) = c(u, v) - h(u) + h(v) are not negative, and the cost of a path in c′c' is its cost in cc minus h(u0)h(u_0) plus hh at its end. A* with key g+hg + h is Dijkstra's algorithm on c′c', whose keys are g+h−h(u0)g + h - h(u_0). Dijkstra's algorithm with nonnegative costs takes each node from the queue with its least distance, in order of that distance. Each goal has h=0h = 0, so the first goal taken has the least gg among all goals.

By Lemma 1, the path that line L4 follows back through the parent links is a plan of the same cost, and a cheaper plan would give a cheaper path to a goal. So the plan has least cost. If no plan exists, no goal is reachable, by Lemma 1 again, and line L9 returns none.

GG has at most 1+2n⋅2k1 + 2^n \cdot 2k nodes, so at most that many states are closed. Each closed state puts at most nknk entries in the queue, so the queue empties after finitely many steps, and the search ends. □\square

Complexity

The states are the start and the triples (S,sb,t)(S, s_b, t) with SS a set of bends, so there are at most 1+2n⋅2k1 + 2^n \cdot 2k of them. Each is closed at most one time.

  • Lines L5 to L8. A closed state tries at most nkn k moves. Each computes hh in O(n)O(n) and puts at most one entry in the queue. So there are O(2nnk2)O(2^n n k^2) entries, and each queue operation costs O(log⁡(2nnk2))=O(n+log⁡k)O(\log(2^n n k^2)) = O(n + \log k).
  • Line L6. With the cache, there are at most 2nnk2^n n k collision tests. Each clips n+1n + 1 segments against two regions of at most 4 half planes, in O(n)O(n).

The total time is O(2nnk2(n+log⁡k))O(2^n n k^2 (n + \log k)), and the extra space is O(2nnk2)O(2^n n k^2) for the queue, with O(2nnk)O(2^n n k) for the cache. The numbers in the clipping are fractions with numerators and denominators at most the total length of the profile, so each operation takes constant time on the real RAM. The search is exponential in nn, but over sets, not orders: for n=7n = 7 there are 27=1282^7 = 128 sets against 7!=50407! = 5040 orders. A good hh cuts the number of states taken from the queue, as in the example, but not the worst case.

Properties

  • Exact. The plan has least cost, because hh is consistent, and the collision test is exact.
  • Complete. If no plan exists, the search ends with none after it closes each reachable state.
  • Deterministic. Ties in the queue go to the state put in first, so the same input gives the same plan.
  • Lower bound only from tools and signs. The heuristic is at most flip+change\textit{flip} + \textit{change}. It ignores collisions, which is what keeps it admissible, and also what keeps it weak on parts where the geometry forces several tool changes.

Variants and improvements

  • Heuristics that overestimate. Gupta, Bourne, Kim and Krishnan (1998) estimate the cost to go from their tooling and grasping planners. For example, the regrip estimate is the number of groups of bends that one grip can reach, minus one, times the cost of a regrip. Such estimates can be too high, so A* is faster but its plan is only near optimal. Weighted A* is a controlled form of this: with key g+whg + w h and a consistent hh, the cost is at most ww times the least cost.
  • Regrips and grasps. For a robot, add the grip to the state, and charge a regrip when the next bend cannot be made with the current grip. The heuristic then adds a lower bound on the regrips left.
  • Two stages. Radin, Shpitalni and Hartman (1997) first find any feasible order with a fast search, then improve its cost within a time limit. This gives an answer fast on large parts, without a guarantee.
  • Graph search over sets. Shpitalni and Saddan (1994) state the bend order and the tools as one graph search. The search on this page is one form of it, with A* as the method.
  • Swept collisions and real tools. A real planner checks the motion of the part during the stroke against the true punch, die and machine shapes, in 3D, with collision detection. The search stays the same; only line L6 changes. A good cache at line L6 matters more then, since each test is costly.

When to use it

Use it when a part has few enough bends that the 2n2^n sets of bends fit in memory, and you want a plan of least cost, or a proof that no plan exists for the given tools. The search grows as 2n2^n, so for parts with many more bends, use an estimate that can overestimate, or the two-stage search, and accept a plan that may not be optimal. Use it with a collision test that matches the machine. The toy rule on this page shows the method, not a press brake. The lengths of the flanges should come from the flat pattern and the formed shape, with springback compensation, so that the profile that line L6 tests is the profile that the brake makes.

Pitfalls

  • Cache key at line L6. The collision test depends on the set SS, the bend bb and the tool tt. A cache keyed by SS alone, or by (S,b)(S, b), gives the result of one tool to another. In the example, b3b_3 after {b1,b2,b4}\{b_1, b_2, b_4\} collides with STANDARD but not with GOOSENECK. A key that adds σ\sigma and τ\tau is correct but wastes tests.
  • Old copies at line L3. Without the check that a state is closed, an old copy of a state with a higher key is expanded again. The plan stays correct, but the work grows. If instead the code marks a state closed when line L8 puts it in the queue, a cheaper path found later is lost, and the plan can cost too much.
  • Goal test at line L8. Test for S=BS = B when a state leaves the queue at line L4, not when line L8 puts it in. The first full state put in the queue need not be the cheapest one.
  • A heuristic that sees collisions. It is tempting to add a tool change to hh when the last tool "will collide later". A collision depends on the bends made before, so such a guess can be too high, and with no reopening at line L3 the plan can then cost too much.
  • Rounding at line L6. In the example, the lip of the last wall touches the boundary of the GOOSENECK punch region at (4,5)(4, 5). A floating point test with a tolerance can call this a collision, and then the search reports that no plan exists.

Implementations

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.

a_star_bend_sequencing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/a-star-bend-sequencing/. The authors are listed in prov/0RQ6RW.jsonl.

"""A* search for a cheapest bend sequence, with an admissible heuristic.

Model, as on the page (a planar profile model of a press brake):
- The part is a profile of flanges with integer lengths l[0], ..., l[n].
  Bend i (1 <= i <= n) joins flange i-1 and flange i and turns the
  profile by 90 degrees, to the left (sign +1) or to the right (sign -1)
  when you walk from flange 0 to flange n. A bend is either not done
  (the profile is straight there) or done fully.
- A tool is (punch width w, die width D, smallest flange m). Bend b can use
  tool t only if both flanges next to b have length at least m (the static
  fit) and, after the bend, no segment of the profile enters the open punch
  region or the open die region (the collision test).
- The part is turned over for a bend of sign -1, so that the punch is always
  on the inside of the bend. Two bends in a row with different signs cost
  `flip`. Two bends in a row with different tools cost `change`.

The search state is (done bends, sign of the last bend, last tool). All
geometry is on integer points, and the clipping in the collision test uses
Fraction, so it is exact.
"""

import heapq
from collections import namedtuple
from fractions import Fraction

Tool = namedtuple("Tool", ["width", "die", "min_flange"])
Plan = namedtuple("Plan", ["cost", "steps", "expanded"])
# steps: a list of (bend, tool index) in the order of the plan.


def _rot(d, e):
    """Turn the direction d by 90 degrees: to the left if e = +1, to the right if e = -1."""
    x, y = d
    return (-y, x) if e > 0 else (y, -x)


def profile_after(lengths, signs, done, b):
    """Segments of the profile after the bends in `done` and bend b, in the frame of bend b.

    In this frame bend b is at the origin and turns to the left, flange b
    runs along +x and flange b-1 along +y, so the inside of the bend is the
    open quadrant x > 0, y > 0. If bend b turns to the right, the whole
    profile is mirrored, which is the part turned over.
    """
    n = len(lengths) - 1
    mirror = signs[b]
    segs = []
    p, d = (0, 0), (1, 0)
    for j in range(b, n + 1):
        q = (p[0] + lengths[j] * d[0], p[1] + lengths[j] * d[1])
        segs.append((p, q))
        p = q
        if j < n and (j + 1) in done:
            d = _rot(d, signs[j + 1] * mirror)
    p, d = (0, 0), (0, 1)
    for j in range(b - 1, -1, -1):
        q = (p[0] + lengths[j] * d[0], p[1] + lengths[j] * d[1])
        segs.append((p, q))
        p = q
        if j > 0 and j in done:
            d = _rot(d, -signs[j] * mirror)
    return segs


def _meets_open(seg, halfplanes):
    """True if the segment meets the open set {a x + c y < k for each (a, c, k)}.

    The points of the segment are p + s (q - p) with 0 <= s <= 1. Each strict
    inequality keeps an open interval of s. The set is not empty if and only
    if the largest lower end is below the smallest upper end, or they are
    equal and both ends are closed (that is, only s = 0 or s = 1 bounds).
    """
    (px, py), (qx, qy) = seg
    lo, lo_open = Fraction(0), False
    hi, hi_open = Fraction(1), False
    for a, c, k in halfplanes:
        alpha = a * px + c * py - k
        beta = a * (qx - px) + c * (qy - py)
        if beta == 0:
            if alpha >= 0:
                return False
            continue
        r = Fraction(-alpha, beta)
        if beta > 0:
            if r < hi or (r == hi and not hi_open):
                hi, hi_open = r, True
        else:
            if r > lo or (r == lo and not lo_open):
                lo, lo_open = r, True
    if lo < hi:
        return True
    return lo == hi and not lo_open and not hi_open


def collides(lengths, signs, done, b, tool):
    """True if bend b, made with `tool` after the bends in `done`, hits the punch or the die."""
    w, die, _ = tool
    punch = [(-1, 0, 0), (0, -1, 0), (1, -1, w), (-1, 1, w)]  # x > 0, y > 0, |x - y| < w
    below = [(1, 1, 0), (1, -1, die), (-1, 1, die)]  # x + y < 0, |x - y| < die
    for seg in profile_after(lengths, signs, done, b):
        if _meets_open(seg, punch) or _meets_open(seg, below):
            return True
    return False


def fits(lengths, b, tool):
    """The static fit: both flanges next to bend b are at least the smallest flange of the tool."""
    return min(lengths[b - 1], lengths[b]) >= tool.min_flange


def heuristic(n, signs, fit_mask, state, flip, change):
    """The admissible heuristic of the page.

    flip   if some bend left has a sign other than the last sign
           (or, at the start, if the bends left have both signs);
    change if the last tool does not fit some bend left
           (or, at the start, if no one tool fits all bends left).
    """
    done, last_sign, last_tool = state
    left = [b for b in range(1, n + 1) if not done >> b & 1]
    if not left:
        return 0
    h = 0
    left_signs = {signs[b] for b in left}
    if (last_sign == 0 and len(left_signs) > 1) or (last_sign != 0 and left_signs != {last_sign}):
        h += flip
    if last_tool < 0:
        common = ~0
        for b in left:
            common &= fit_mask[b]
        if common == 0:
            h += change
    elif any(not fit_mask[b] >> last_tool & 1 for b in left):
        h += change
    return h


def a_star_bends(lengths, signs, tools, flip=1, change=1, use_h=True):
    """A cheapest feasible bend sequence, or None if there is none.

    `signs` is indexed 1..n (signs[0] is not used). Returns Plan(cost, steps,
    expanded), where `expanded` counts the states taken from the queue.
    With use_h=False the search is uniform cost search (h = 0).
    """
    n = len(lengths) - 1
    k = len(tools)
    full = sum(1 << b for b in range(1, n + 1))
    fit_mask = [0] * (n + 1)
    for b in range(1, n + 1):
        for t in range(k):
            if fits(lengths, b, tools[t]):
                fit_mask[b] |= 1 << t

    def h(state):
        return heuristic(n, signs, fit_mask, state, flip, change) if use_h else 0

    hits = {}  # (done, b, t) -> collision; it depends on the done set only, not on the last sign or tool

    def blocked(done, done_set, b, t):
        key = (done, b, t)
        if key not in hits:
            hits[key] = collides(lengths, signs, done_set, b, tools[t])
        return hits[key]

    start = (0, 0, -1)  # @line L1
    g = {start: 0}
    parent = {start: None}
    tick = 0
    queue = [(h(start), tick, start)]
    closed = set()
    expanded = 0
    while queue:  # @line L2
        _, _, u = heapq.heappop(queue)  # @line L3
        if u in closed:
            continue
        closed.add(u)
        expanded += 1
        done, last_sign, last_tool = u
        if done == full:  # @line L4
            steps = []
            while parent[u] is not None:
                p = parent[u]
                steps.append(((u[0] ^ p[0]).bit_length() - 1, u[2]))
                u = p
            steps.reverse()
            return Plan(g[(full, last_sign, last_tool)], steps, expanded)
        done_set = {b for b in range(1, n + 1) if done >> b & 1}
        for b in range(1, n + 1):  # @line L5
            if done >> b & 1:
                continue
            for t in range(k):
                if not fit_mask[b] >> t & 1:
                    continue
                if blocked(done, done_set, b, t):  # @line L6
                    continue
                v = (done | 1 << b, signs[b], t)  # @line L7
                step = (flip if last_sign not in (0, signs[b]) else 0) + (change if last_tool not in (-1, t) else 0)
                cost = g[u] + step
                if v not in g or cost < g[v]:  # @line L8
                    g[v] = cost
                    parent[v] = u
                    tick += 1
                    heapq.heappush(queue, (cost + h(v), tick, v))
    return None  # @line L9


def plan_cost(lengths, signs, tools, steps, flip=1, change=1):
    """The cost of a plan, or None if a step is not feasible. Used to check plans."""
    n = len(lengths) - 1
    if sorted(b for b, _ in steps) != list(range(1, n + 1)):
        return None
    done = set()
    cost = 0
    last_sign, last_tool = 0, -1
    for b, t in steps:
        if not fits(lengths, b, tools[t]) or collides(lengths, signs, done, b, tools[t]):
            return None
        if last_sign not in (0, signs[b]):
            cost += flip
        if last_tool not in (-1, t):
            cost += change
        last_sign, last_tool = signs[b], t
        done.add(b)
    return cost


if __name__ == "__main__":
    # The lipped channel of the page: STANDARD and GOOSENECK, flip 2, change 1.
    lengths = [1, 4, 6, 4, 1]
    signs = [0, 1, 1, 1, 1]
    tools = [Tool(3, 2, 1), Tool(1, 4, 2)]
    print(a_star_bends(lengths, signs, tools, flip=2, change=1))
test_a_star_bend_sequencing.py 205 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/a-star-bend-sequencing/. The authors are listed in prov/0RQ6RW.jsonl.

import random
import unittest
from fractions import Fraction
from functools import lru_cache
from itertools import permutations

import a_star_bend_sequencing as m
from a_star_bend_sequencing import Tool, a_star_bends, collides, fits, heuristic, plan_cost, profile_after

STANDARD = Tool(3, 2, 1)
GOOSENECK = Tool(1, 4, 2)
LIPPED = ([1, 4, 6, 4, 1], [0, 1, 1, 1, 1])


def feasible_tools(lengths, signs, tools, done, b, cache):
    key = (frozenset(done), b)
    if key not in cache:
        cache[key] = [t for t in range(len(tools)) if fits(lengths, b, tools[t]) and not collides(lengths, signs, set(done), b, tools[t])]
    return cache[key]


def brute_force(lengths, signs, tools, flip, change):
    """Try every order of the bends. For each order, choose the tools by a small DP."""
    n = len(lengths) - 1
    cache = {}
    best = None
    count = 0
    for order in permutations(range(1, n + 1)):
        done = set()
        dp = {-1: 0}  # last tool -> least number of tool changes so far
        for b in order:
            ok = feasible_tools(lengths, signs, tools, done, b, cache)
            new = {}
            for t in ok:
                new[t] = min(c + (1 if last not in (-1, t) else 0) for last, c in dp.items())
            dp = new
            if not dp:
                break
            done.add(b)
        if not dp:
            continue
        count += 1
        flips = sum(1 for a, c in zip(order, order[1:]) if signs[a] != signs[c])
        cost = flip * flips + change * min(dp.values())
        if best is None or cost < best:
            best = cost
    return best, count


def random_instance(rng, n, alternate=0.5):
    """A random profile. Signs change with probability `alternate`; a profile
    whose signs alternate is a staircase, which is often feasible, and one
    with many equal signs curls up and often is not."""
    lengths = [rng.randint(1, 4) for _ in range(n + 1)]
    signs = [0, rng.choice((1, -1))]
    for _ in range(n - 1):
        signs.append(-signs[-1] if rng.random() < alternate else signs[-1])
    tools = [Tool(rng.randint(1, 2), rng.randint(1, 4), rng.randint(1, 2)) for _ in range(rng.randint(1, 3))]
    return lengths, signs[: n + 1], tools


class TestGeometry(unittest.TestCase):
    def test_profile_of_the_last_wall_bend(self):
        lengths, signs = LIPPED
        segs = profile_after(lengths, signs, {1, 2, 4}, 3)
        self.assertEqual(
            segs,
            [((0, 0), (4, 0)), ((4, 0), (4, 1)), ((0, 0), (0, 6)), ((0, 6), (4, 6)), ((4, 6), (4, 5))],
        )
        self.assertTrue(collides(lengths, signs, {1, 2, 4}, 3, STANDARD))
        self.assertFalse(collides(lengths, signs, {1, 2, 4}, 3, GOOSENECK))

    def test_mirror_for_a_bend_to_the_right(self):
        # The same channel with all signs flipped is the same part turned over.
        lengths, signs = LIPPED
        flipped = [0] + [-s for s in signs[1:]]
        for done in (set(), {1}, {1, 2}, {1, 2, 4}):
            for b in range(1, 5):
                if b not in done:
                    self.assertEqual(profile_after(lengths, signs, done, b), profile_after(lengths, flipped, done, b))

    def test_open_region_against_sampling(self):
        # Endpoints are integer and the region has coefficients in {-1, 0, 1},
        # so every clipping bound is a multiple of 1/L for a segment of length L.
        # A nonempty open interval then holds a multiple of 1/(2L).
        rng = random.Random(7)
        for _ in range(3000):
            p = (rng.randint(-4, 4), rng.randint(-4, 4))
            length = rng.randint(1, 5)
            d = rng.choice(((1, 0), (-1, 0), (0, 1), (0, -1)))
            q = (p[0] + length * d[0], p[1] + length * d[1])
            planes = [(rng.randint(-1, 1), rng.randint(-1, 1), rng.randint(-3, 3)) for _ in range(rng.randint(1, 4))]
            sampled = False
            for j in range(2 * length + 1):
                s = Fraction(j, 2 * length)
                x = p[0] + s * (q[0] - p[0])
                y = p[1] + s * (q[1] - p[1])
                if all(a * x + c * y < k for a, c, k in planes):
                    sampled = True
                    break
            self.assertEqual(m._meets_open((p, q), planes), sampled, (p, q, planes))


class TestSearch(unittest.TestCase):
    def test_lipped_channel(self):
        lengths, signs = LIPPED
        tools = [STANDARD, GOOSENECK]
        plan = a_star_bends(lengths, signs, tools, flip=2, change=1)
        self.assertEqual(plan.cost, 1)
        self.assertEqual(plan.steps, [(1, 0), (2, 0), (4, 0), (3, 1)])
        self.assertEqual(plan_cost(lengths, signs, tools, plan.steps, 2, 1), 1)
        self.assertEqual(brute_force(lengths, signs, tools, 2, 1), (1, 6))
        self.assertEqual(plan.expanded, 17)
        self.assertEqual(a_star_bends(lengths, signs, tools, 2, 1, use_h=False).expanded, 24)

    def test_no_plan(self):
        # With only the standard punch the last wall bend always hits a lip.
        lengths, signs = LIPPED
        self.assertIsNone(a_star_bends(lengths, signs, [STANDARD]))
        self.assertEqual(brute_force(lengths, signs, [STANDARD], 1, 1), (None, 0))

    def test_empty_and_single(self):
        self.assertEqual(a_star_bends([5], [0], [STANDARD]).cost, 0)
        self.assertEqual(a_star_bends([2, 2], [0, -1], [STANDARD]).steps, [(1, 0)])

    def test_against_brute_force(self):
        rng = random.Random(2024)
        found = 0
        found7 = 0
        for trial in range(210):
            n = 1 + trial % 7
            lengths, signs, tools = random_instance(rng, n, 0.5 if trial % 3 == 0 else 0.85)
            flip, change = rng.randint(0, 3), rng.randint(0, 3)
            want, _ = brute_force(lengths, signs, tools, flip, change)
            plan = a_star_bends(lengths, signs, tools, flip, change)
            ucs = a_star_bends(lengths, signs, tools, flip, change, use_h=False)
            if want is None:
                self.assertIsNone(plan)
                self.assertIsNone(ucs)
                continue
            found += 1
            found7 += n == 7
            self.assertEqual(plan.cost, want, (lengths, signs, tools, flip, change))
            self.assertEqual(ucs.cost, want)
            self.assertEqual(plan_cost(lengths, signs, tools, plan.steps, flip, change), want)
            self.assertLessEqual(plan.expanded, ucs.expanded)
        self.assertGreater(found, 80)
        self.assertGreater(found7, 4)

    def test_heuristic_is_consistent_and_admissible(self):
        rng = random.Random(99)
        for trial in range(40):
            n = 2 + trial % 5
            lengths, signs, tools = random_instance(rng, n, 0.85)
            flip, change = rng.randint(1, 3), rng.randint(1, 3)
            k = len(tools)
            full = sum(1 << b for b in range(1, n + 1))
            fit_mask = [0] * (n + 1)
            for b in range(1, n + 1):
                for t in range(k):
                    if fits(lengths, b, tools[t]):
                        fit_mask[b] |= 1 << t

            def moves(state):
                done, s, t0 = state
                dset = {b for b in range(1, n + 1) if done >> b & 1}
                for b in range(1, n + 1):
                    if done >> b & 1:
                        continue
                    for t in range(k):
                        if fit_mask[b] >> t & 1 and not collides(lengths, signs, dset, b, tools[t]):
                            c = (flip if s not in (0, signs[b]) else 0) + (change if t0 not in (-1, t) else 0)
                            yield (done | 1 << b, signs[b], t), c

            @lru_cache(maxsize=None)
            def to_go(state):
                if state[0] == full:
                    return 0
                best = None
                for v, c in moves(state):
                    r = to_go(v)
                    if r is not None and (best is None or c + r < best):
                        best = c + r
                return best

            seen = {(0, 0, -1)}
            stack = [(0, 0, -1)]
            while stack:
                u = stack.pop()
                hu = heuristic(n, signs, fit_mask, u, flip, change)
                exact = to_go(u)
                if exact is not None:
                    self.assertLessEqual(hu, exact)
                for v, c in moves(u):
                    self.assertLessEqual(hu, c + heuristic(n, signs, fit_mask, v, flip, change))
                    if v not in seen:
                        seen.add(v)
                        stack.append(v)


if __name__ == "__main__":
    unittest.main()

History

A* comes from Hart, Nilsson and Raphael (1968). For bend sequences, de Vin and others (1994) and Shpitalni and Saddan (1994) stated the choice of bend order and tools as a search over partial sequences, with collision tests from the geometry. Radin, Shpitalni and Hartman (1997) gave a two-stage method. Gupta, Bourne, Kim and Krishnan (1998) built a planner for a robotic press brake, in which a central operation planner runs A* over partial bend sequences and calls planners for tools, grasps and robot motion for costs and feasibility. They chose estimates that can be too high, on purpose, for speed, and reported near optimal plans. The consistent heuristic on this page is weaker but makes the search exact.

References

  1. S. K. Gupta, D. A. Bourne, K. H. Kim and S. S. Krishnan, Automated process planning for sheet metal bending operations, Journal of Manufacturing Systems 17(5), 1998, 338 to 360, the central operation planner that runs A* over partial bend sequences, the tooling, grasping and moving planners that give the costs and the feasibility tests, and the heuristics that can overestimate, chosen for speed
  2. Peter E. Hart, Nils J. Nilsson and Bertram Raphael, A formal basis for the heuristic determination of minimum cost paths, IEEE Transactions on Systems Science and Cybernetics 4(2), 1968, 100 to 107, the A* algorithm, the optimality of its result with an admissible heuristic, and the consistency condition under which no state is expanded twice
  3. M. Shpitalni and D. Saddan, Automatic determination of bending sequence in sheet metal products, CIRP Annals 43(1), 1994, 23 to 26, the bend sequence and the tools stated as one graph search, an earlier form of the search on this page
  4. B. Radin, M. Shpitalni and I. Hartman, Two-stage algorithm for determination of the bending sequence in sheet metal products, Journal of Mechanical Design 119(2), 1997, 259 to 266, a fast search for a feasible sequence, then a search for a cheaper one within a time limit, the main alternative to A*
  5. L. J. de Vin, J. de Vries, A. H. Streppel, E. J. W. Klaassen and H. J. J. Kals, The generation of bending sequences in a CAPP system for sheet-metal components, Journal of Materials Processing Technology 41(3), 1994, 331 to 339, bend sequences from a search with collision and tolerance tests and handling rules

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