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.
- Solves
- Bend sequence planning
- 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
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 flanges with integer lengths . Bend , for , joins flanges and , and turns the profile by 90 degrees to the left () or to the right () as you walk from flange to flange . A list of tools, each a triple : punch width, die width and smallest flange. Two weights and .
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 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 : the bend at the origin, flange along and flange along , with the profile mirrored if , which is the part turned over. Draw the profile with the bends of done. Tool can make bend if both flanges next to have length at least (the fit), and no point of the profile is in the open punch region or in the open die region . The punch is a blade of half width 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 for each pair of consecutive bends with different signs, and for each pair with different tools.
Output. A plan of least cost, or "none" if no plan exists.
The algorithm
A state is : the set of bends done, the sign of the last bend ( at the start) and the last tool (none at the start). Let 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 if , and otherwise
where if and holds bends of both signs, or and some bend of has a sign other than ; and if is none and no one tool fits all bends of , or is a tool that does not fit some bend of . Otherwise and .
A*-BENDS(l, s, T, flip, change)- 1
start ← (∅, 0, none); g[start] ← 0; put start in the queue with key h(start) - 2
while the queue is not empty - 3
take u = (S, σ, τ) of least key from the queue; if u is closed, skip it, else close it - 4
if S = B then return the plan along the parent links to u, with cost g[u] - 5
for each bend b ∉ S and each tool t that fits b - 6
if bend b with tool t after the bends of S collides then skip (b, t) - 7
v ← (S ∪ {b}, s_b, t); c ← flip · [σ ∉ {0, s_b}] + change · [τ ∉ {none, t}] - 8
if 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) - 9
return 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 is consistent (see A* search).
Line L6. The collision test depends on , and , and not on or . The code caches it by , so each test runs one time, however many states share the set .
Exact test. All points of the profile are integer. A point of a segment is with , and each open half plane of a region keeps an open interval of . 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: , all four signs , so lip, wall, base, wall, lip. The tools are STANDARD and GOOSENECK , with and . GOOSENECK does not fit the lip bends and , 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 , the base stands up at the end of the wall and enters the punch region when is made. The second wall bend needs GOOSENECK. For after , the profile in the frame of is the wall from to and its lip to , then the base from to , the other wall to and its lip to . With STANDARD, , and the point has , a collision. With GOOSENECK, , the lip at , has , so it only touches the boundary, and the wall at , has . No collision.
The search. At the start, all signs are equal and STANDARD fits all bends, so . Every state with last tool STANDARD also has . A state with last tool GOOSENECK and a lip left has .
| states taken at line L3 | key | count |
|---|---|---|
| the start; ; ; , all with STANDARD | 0 | 12 |
| , , , with GOOSENECK, then with GOOSENECK | 1 | 5 |
The state with GOOSENECK passes line L4 with cost 1. The plan is with STANDARD and with GOOSENECK: one tool change, no turn. A* takes 17 states from the queue, and uniform cost search, which is the same code with , takes 24. A check of all orders finds 6 feasible orders, the ones with before and before , 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 in the graph of lines L5 to L7, with the same cost, because the shape and the collision test depend only on and the step cost depends only on , , and . Second, is consistent: for each move from to with cost , . Take . If and the move turns the part, it pays . If it does not turn the part, some bend of the other sign is still left in , so . 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 , because a move uses a tool that fits its bend. With 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. is the set of bends, is the sign of bend , and is the list of tools. A tool fits bend when . For a set and , write for the result of the collision rule of the page: the profile with the bends of done, in the frame of bend , meets the open punch region or the open die region of . A plan is a sequence in which is an order of , each fits , and is false for each . Its cost is
The graph . The nodes are the start and the triples with not empty, and a tool. From there is an arc to for each and each tool that fits with false, with the cost
These are the arcs that lines L5 to L7 make. The goals are the nodes with .
Lemma 1 (the state model). The plans are in one to one correspondence with the paths in from 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 only: it walks from flange to flange , and from flange to flange , and turns at bend if and only if is in the set. So depends only on , and . This is the claim of the page that the shape does not depend on the order of the bends.
Given a plan, let and for . Each step is an arc of , because fits and is false, and is a goal. The arc costs 0, since and . For the arc costs , the -th term of the plan cost. Conversely, each arc adds one new bend to , so a path from to a goal has exactly arcs, each adds one bend with a tool that fits it and does not collide, and reading off the pairs gives a plan. The two maps are inverse to each other, and the costs agree term by term.
Lemma 2 (the heuristic is consistent). For each arc of , . Also at each goal. Hence , the least cost of a path from to a goal, for each node from which a goal is reachable.
Proof. Let , let the arc add bend with tool , so , and let and . Write with and . Since when , it is enough to show
with when . The weights are not negative, so each inequality holds when its left side is 0. Assume the left side is not 0.
The term . Case . Some has . If , then , and we are done. If , then , so , and the last sign of is . So . Case . Then and holds bends of both signs. The bend has one sign, so some has , and , so and .
The term . Case . Some is not fit by . If , then , and we are done. If , then fits , because the arc exists, so , , and the last tool of does not fit . So . Case . No one tool fits all bends of . If fit all bends of , then would fit all bends of , since it fits . So some is not fit by , and .
So when . When , that is , the left sides are 0: for , would need two bends in , and with gives ; for , is not possible because fits all of , and not fitting forces , so . So the inequality holds in this case too.
A goal has , so . For admissibility, take a cheapest path from to a goal. Adding the inequalities for gives .
Lemma 3 (exact clipping). For a segment with integer end points and a finite set of strict inequalities 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 with . For one inequality, let and , so the point satisfies it if and only if . If , this holds for all when and for none when ; the code returns false in the second case and ignores the inequality in the first. If , it holds if and only if with , an open upper bound. If , it holds if and only if , an open lower bound. The set of good is therefore an interval with the lower end , the largest of 0 and the lower bounds, and the upper end , 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 , or with both ends closed. This is the last test of the code. All values are rationals in Fraction, so each comparison is exact.
The punch region is the set of four strict inequalities , , and , and the die region is , and . So by Lemma 3, collides computes exactly, and line L6 removes exactly the arcs that does not have. The cache of line L6 is keyed by , 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 states are closed.
Proof. By Lemma 3 and the remark after it, lines L5 to L8 generate exactly the arcs of with their costs. Lines L1 to L9 are A* on from 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, is consistent with at the goals. For such a heuristic, A* without reopening takes each state from the queue at most once, with 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 , the reduced costs are not negative, and the cost of a path in is its cost in minus plus at its end. A* with key is Dijkstra's algorithm on , whose keys are . Dijkstra's algorithm with nonnegative costs takes each node from the queue with its least distance, in order of that distance. Each goal has , so the first goal taken has the least 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.
has at most nodes, so at most that many states are closed. Each closed state puts at most entries in the queue, so the queue empties after finitely many steps, and the search ends.
Complexity
The states are the start and the triples with a set of bends, so there are at most of them. Each is closed at most one time.
- Lines L5 to L8. A closed state tries at most moves. Each computes in and puts at most one entry in the queue. So there are entries, and each queue operation costs .
- Line L6. With the cache, there are at most collision tests. Each clips segments against two regions of at most 4 half planes, in .
The total time is , and the extra space is for the queue, with 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 , but over sets, not orders: for there are sets against orders. A good 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 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 . 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 and a consistent , the cost is at most 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 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 , 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 , the bend and the tool . A cache keyed by alone, or by , gives the result of one tool to another. In the example, after collides with STANDARD but not with GOOSENECK. A key that adds and 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 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 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 . 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.
# 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
- 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
- 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
- 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
- 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*
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 0RQ6RW Edit this page History Report an error Markdown