Sub topic 8
Consistent Heuristics and the Triangle Inequality
This chapter assumes you have read the earlier chapters on the A loop, the binary-heap implementation with a closed set, and admissible heuristics. You should be comfortable reading the astar(start, goal, neighbors, h) function from the implementation chapter and with the idea that an admissible heuristic never overestimates the true remaining cost h(n).
Admissibility protects the final answer. It says nothing about how the search behaves along the way. Consistency is a stronger, local condition. It makes the closed set safe, and it makes A* behave like a cleaner version of Dijkstra's algorithm.
The Definition
A heuristic h is consistent (also called monotone) if, for every node n and every successor n' reached by an edge of cost c(n, n'):
- h(n) ≤ c(n, n') + h(n')
- h(goal) = 0
In words, the estimate at n can drop by no more than the cost of the step you take. If moving one edge costs 1, the heuristic can fall by at most 1 across that edge.
This is a triangle inequality. Picture three points: n, its neighbor n', and the goal. The direct estimate from n to the goal must not exceed the detour that goes through n' first.
The condition applies to every edge, so you can check it mechanically. On a directed graph it applies to each edge in its own direction. On an undirected graph each edge counts once in each direction, which gives |h(n) − h(n')| ≤ c(n, n').
Consistency Implies Admissibility
Take any node n and an optimal path from n to the goal: n = n0, n1, ..., nk = goal. Apply the inequality one edge at a time:
h(n0) ≤ c(n0, n1) + h(n1) ≤ c(n0, n1) + c(n1, n2) + h(n2) ≤ ... ≤ (total path cost) + h(goal)
Since h(goal) = 0, h(n) ≤ h*(n). Every consistent heuristic is therefore admissible. The proof needs h(goal) = 0. A heuristic that satisfies the edge inequality everywhere but gives the goal a value of 3 can overestimate everywhere by 3.
The converse fails. A heuristic can be admissible and still inconsistent, and the next sections show why that matters.
What Consistency Buys: f Never Decreases
Suppose A* reaches n' from n. Then g(n') = g(n) + c(n, n'), and:
f(n') = g(n) + c(n, n') + h(n') ≥ g(n) + h(n) = f(n)
The inequality step is exactly the consistency condition. Along any path, f values never decrease. So A pops nodes from the heap in nondecreasing order of f. The next chapter turns this into the optimality proof. The practical consequence for now is that the first time a node is popped, its g value is already optimal*. No cheaper route to it can turn up later. That is why the implementation chapter's astar can skip any node already in closed.
A* is Dijkstra on reduced costs
The same algebra has a second reading. Define a reduced edge cost:
c'(n, n') = c(n, n') − h(n) + h(n')
Consistency is exactly the statement c'(n, n') ≥ 0. Along any path from the start, the reduced costs telescope to g(n) + h(n) − h(start), which is f(n) minus a constant. Running Dijkstra on the reduced costs therefore expands nodes in the same order as A on the original costs. Dijkstra requires non-negative edge weights, so a consistent heuristic is precisely one that keeps A inside Dijkstra's correctness conditions. An inconsistent heuristic creates negative reduced edges, and Dijkstra's "settled means final" rule breaks.
When Admissible Is Not Enough
Here is a four-node directed graph with an admissible heuristic that is inconsistent on one edge.
The true remaining costs are h(S) = 5, h(A) = 4, h(B) = 3, and h(G) = 0. Every h value is at or below h*, so the heuristic is admissible. The edge A → B fails consistency because 4 > 1 + 0.
Running the closed-set astar from the implementation chapter on this graph:
import heapq
from itertools import count
def astar(start, goal, neighbors, h):
tie = count()
open_heap = [(h(start), next(tie), start)]
g = {start: 0}
parent = {start: None}
closed = set()
while open_heap:
_, _, node = heapq.heappop(open_heap)
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], g[goal]
if node in closed:
continue
closed.add(node)
for nxt, cost in neighbors(node):
new_g = g[node] + cost
if new_g < g.get(nxt, float('inf')):
g[nxt] = new_g
parent[nxt] = node
heapq.heappush(open_heap, (new_g + h(nxt), next(tie), nxt))
return None, float('inf')
edges = {'S': [('A', 1), ('B', 3)], 'A': [('B', 1)], 'B': [('G', 3)], 'G': []}
hvals = {'S': 0, 'A': 4, 'B': 0, 'G': 0}
print(astar('S', 'G', lambda n: edges[n], hvals.get))
# (['S', 'A', 'B', 'G'], 6)The trace explains the result:
- Pop S. Push A with f = 1 + 4 = 5 and B with f = 3 + 0 = 3.
- Pop B (f = 3) and close it with g = 3, which is not optimal. Push G with g = 6.
- Pop A (f = 5). It finds B at g = 2, updates
parent[B]to A, and pushes B with f = 2. - Pop B again. It is in
closed, so it is skipped and its improvement never reaches G. - Pop G and return.
The reported cost is 6, but the returned path actually costs 5. The parent pointer was fixed while G's g value was not. This is worse than a plain suboptimal answer, because the path and the cost disagree, and tests that check only one of them will miss the bug.
Fix: reopen nodes instead of closing them
If your heuristic may be inconsistent, let a node be expanded again whenever a cheaper g is found. A simple way is to store g in the heap entry and skip only stale entries:
import heapq
from itertools import count
def astar_reopen(start, goal, neighbors, h):
tie = count()
open_heap = [(h(start), next(tie), 0, start)]
g = {start: 0}
parent = {start: None}
while open_heap:
_, _, node_g, node = heapq.heappop(open_heap)
if node_g > g[node]:
continue # stale entry; a cheaper route was found later
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1], g[goal]
for nxt, cost in neighbors(node):
new_g = g[node] + cost
if new_g < g.get(nxt, float('inf')):
g[nxt] = new_g
parent[nxt] = node
heapq.heappush(open_heap, (new_g + h(nxt), next(tie), new_g, nxt))
return None, float('inf')
edges = {'S': [('A', 1), ('B', 3)], 'A': [('B', 1)], 'B': [('G', 3)], 'G': []}
hvals = {'S': 0, 'A': 4, 'B': 0, 'G': 0}
print(astar_reopen('S', 'G', lambda n: edges[n], hvals.get))
# (['S', 'A', 'B', 'G'], 5)With an admissible heuristic this returns the optimal cost. The price is re-expansion. B is expanded twice here, and on adversarial graphs an inconsistent heuristic can force exponentially many re-expansions. With a consistent heuristic the stale-entry check does the same work as the closed set, so astar_reopen is a safe default when you cannot verify consistency.
Checking Consistency in Code
When the state space is small enough to enumerate, test every edge directly:
def check_consistency(nodes, neighbors, h, goal, eps=1e-9):
violations = []
if abs(h(goal)) > eps:
violations.append(('goal', goal, h(goal)))
for n in nodes:
for nxt, cost in neighbors(n):
if h(n) > cost + h(nxt) + eps:
violations.append((n, nxt, h(n) - cost - h(nxt)))
return violations
edges = {'S': [('A', 1), ('B', 3)], 'A': [('B', 1)], 'B': [('G', 3)], 'G': []}
hvals = {'S': 0, 'A': 4, 'B': 0, 'G': 0}
print(check_consistency(edges, lambda n: edges[n], hvals.get, 'G'))
# [('A', 'B', 3)]The eps tolerance matters for heuristics that use floating-point values such as math.sqrt(2). Without it, rounding can report false violations. For large or implicit spaces, run the check on random samples of states as a test. Sampling cannot prove consistency, but it catches most mistakes.
Recognizing Consistent Heuristics
Most heuristics you will meet in practice are consistent, often for structural reasons:
| Situation | Consistent? | Reason |
|---|---|---|
| Manhattan distance, 4-connected grid, unit costs | Yes | One move changes the distance by exactly 1 |
| Euclidean distance with any edge cost ≥ straight-line length | Yes | The geometric triangle inequality holds |
| Exact cost in a relaxed problem | Yes | Shortest-path distances in any graph satisfy the triangle inequality |
| max(h1, h2) with h1, h2 consistent | Yes | Each term satisfies the inequality, so the max does too |
| h(n) = 0 everywhere | Yes | A* becomes uniform-cost search |
| Random or learned values capped at h* | Often not | Neighboring estimates can jump by more than one edge cost |
| Manhattan with diagonal moves allowed | No | Inadmissible, so not consistent either |
The relaxed-problem row is the main reason consistency is common. A heuristic that is an exact shortest-path distance in some simpler graph inherits that graph's triangle inequality, as long as every real edge is also present in the simpler graph at the same or lower cost.
Common Errors
- Checking only one direction on directed graphs. The inequality applies to each edge as it points. Asymmetric costs, such as uphill versus downhill, need separate checks.
- Forgetting h(goal) = 0. An offset heuristic can pass every edge check and still overestimate.
- Scaling a heuristic and assuming consistency survives. Multiplying by w > 1, as weighted A* does later in the tutorial, generally breaks both consistency and admissibility.
- Mixing heuristics carelessly. The max of consistent heuristics is consistent, but switching between heuristics based on the node can create violations at the boundaries.
Exercise
On a 4-connected grid with unit step costs, a heuristic is defined as h(n) = 2 × Manhattan(n, goal) for cells in the left half of the map and Manhattan(n, goal) elsewhere. Is it consistent? Is it admissible?
Show answer
It is neither. Doubling Manhattan distance can exceed the true cost, so the heuristic is not admissible, and every consistent heuristic is admissible. Consistency also fails at the boundary: stepping from a left-half cell with h = 2d into a right-half cell with h = d − 1 or d lowers h by about d, far more than the step cost of 1.
Exercise
In the S, A, B, G example, change only h(B) so the heuristic becomes consistent while staying admissible. What range of values works, and does the closed-set astar then return cost 5?
Show answer
Consistency on A → B needs 4 ≤ 1 + h(B), so h(B) ≥ 3. Admissibility needs h(B) ≤ h*(B) = 3. The edge S → B gives 0 ≤ 3 + h(B), and B → G gives h(B) ≤ 3 + 0, so both hold. That leaves only h(B) = 3. With it, B enters the heap with f = 6 through S and f = 5 through A, so A (f = 5) and the cheaper B entry are popped before the stale one. B is first closed with g = 2, and the search returns (['S', 'A', 'B', 'G'], 5).