Algorithmadvanced
Casting hot spot detection
Also called thermal centre detection.
Finds the last regions of a casting to solidify, as maxima of a distance transform or by vector element methods, so risers can be placed to feed them.
- Time
- O(3^k N) worst
- Space
- O(N) extra
- Where
- N = number of cells of the grid; k = number of axes of the grid (2 or 3)
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- B. Ravi, M. N. Srinivasan, 1996
Casting hot spot detection finds the regions of a casting that solidify last. Shrinkage porosity forms there unless a riser feeds them, so they decide where the risers go. The exact answer comes from a thermal simulation, a solution of the heat equation with latent heat over the casting and the mold. A fast geometric proxy is the distance from each point of the casting to the mold: points far from the mold lose heat last, and the local maxima of this distance lie on the medial axis of the casting. This page computes the proxy on a voxel grid: an exact squared Euclidean distance transform by the method of Felzenszwalb and Huttenlocher, with integer arithmetic, followed by the regional maxima of the distance. It runs in time for a fixed dimension. The maxima are a geometric proxy, not a thermal solution, and the page shows where the proxy and Chvorinov's rule disagree.
In plain words
Metal in a mold cools from the outside in. The last spots to turn solid are the ones deepest inside the metal, far from the cold mold. Those spots shrink without any liquid left nearby to fill them, so holes form there. A foundry engineer wants to know where these spots are, to put an extra reservoir of liquid metal next to each.
The method cuts the casting into small cubes, measures for each cube how far it is from the nearest piece of mold, and reports the cubes that are farther than all cubes around them. Those are the likely last spots. It is a quick guess from the shape alone. A heat flow simulation gives the true answer.
The problem
Input. A grid of cells with axes, usually for a solid or for a section, in which each cell is metal or mold. At least one cell is mold. In practice, the voxelized casting is surrounded by a layer of mold cells.
Output.
- For every cell , , the squared Euclidean distance between cell centres, as an exact integer.
- The regional maxima of over the metal cells. A plateau is a maximal connected set of metal cells with one value of , where two cells are connected when they differ by at most 1 in every index (8 neighbours in 2D, 26 in 3D). A plateau is a regional maximum when every cell next to it has . These are the hot spot candidates, sorted by from the largest.
What the distance measures. is the distance from the centre of to the centre of the nearest mold cell. The surface of the casting lies half a cell from the centres of the mold cells next to it, so the distance to the surface is about cells. The squares are kept because they are integers, and taking the square root does not change the order.
The algorithm
HOT-SPOTS(grid)- 1
f(x) ← 0 for each mold cell x, and ∞ for each metal cell - 2
for each axis a = 1, ..., k - 3
for each line of cells along axis a: replace f on the line by LOWER-ENVELOPE(f on the line) - 4
D ← f - 5
group the metal cells into plateaus of equal D, connected under the full neighbourhood - 6
keep a plateau if every cell next to it has a smaller D - 7
return the kept plateaus with their values, the largest first
LOWER-ENVELOPE at line L3. For a line it returns . Each with a finite gives a parabola , and is their lower envelope at the integers. All parabolas have the same shape, so two of them, , cross at exactly one point,
and is lower to the right of it. The procedure goes through the points in order and keeps a stack of the parabolas of the envelope with the points where each starts. Before it pushes , it pops the top parabola while is at or before the start of , since is then lower on the whole interval of . A second pass reads off from the interval that holds . Each point is pushed and popped at most once, so the time is .
The crossing points are fractions with integer numerators and positive denominators, and the implementation compares them by cross multiplication, with no division. So the transform is exact: no rounding can change a distance or the order of two distances.
Lines L2 to L4. The squared distance is a sum over the axes, so the minimum over all mold cells splits into one minimum per axis. After the pass over axis 1, is the squared distance to the nearest mold cell on the line of along axis 1. After the pass over axis 2, it is the distance to the nearest mold cell in the plane of spanned by axes 1 and 2, and so on.
Lines L5 and L6. A graph search from each metal cell not yet seen collects the cells of its plateau, and on the way looks at every neighbour. The plateau is kept if no neighbour has a larger .
Example
A 2D section with a block of cells joined by a bar one cell thick to a boss of cells, with mold around it (# is metal and . is mold):
.............
.#####.......
.#####..###..
.###########.
.#####..###..
.#####.......
.............
The values of on the middle row are
| column | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 4 | 9 | 5 | 2 | 1 | 1 | 2 | 4 | 2 | 1 | 0 |
The cell has : its nearest mold cells are and , one row and two columns away, beside the start of the bar, so . The algorithm returns two hot spots: at , the centre of the block, and at , the centre of the boss. The bar between them has , so it freezes first and cuts the boss off from the block. A riser on the block does not feed the boss, which needs its own riser or a thicker connection. This is the reasoning of feeding design in riser design by the modulus method.
Correctness
The proof in the proofs folder has three steps. First, two parabolas of the line meet once, so the stack procedure keeps the invariant that its stack function equals the lower envelope of the parabolas seen so far, and the read-out is exact at every integer. Second, after the passes over the axes , each cell holds the squared distance to the nearest mold cell that agrees with it in the other coordinates; for this is the full distance. Third, every metal cell has and every mold cell has , so the graph search collects exactly the plateaus, and the test of line L6 is the definition of a regional maximum.
The tests compare the transform with a brute force minimum over all mold cells, on random grids in 1, 2, 3 and 4 dimensions. They compare the hot spots with a second definition: a metal cell is in a regional maximum if and only if the connected part of the set that holds has no cell with a larger value.
Proof: HOT-SPOTS computes the exact squared distance to the mold and returns exactly the regional maximafull
We use the definitions of the page. The grid has axes, and a cell is a vector of integer indices. is the set of mold cells, which is not empty. For a real number and a cell index with a finite value , the parabola of is .
Lemma 1 (two parabolas). For , the difference is strictly decreasing in and is zero at
So if and only if .
Proof. Expand both squares: the terms cancel, and what is left is linear in with the slope .
Lemma 2 (the lower envelope). For a line in which some values may be infinite, LOWER-ENVELOPE returns over the with finite, and for all if there are none.
Proof. The procedure takes the finite points in increasing order and keeps a stack with breakpoints and for . Let be the function equal to on , with . Let be the minimum of the parabolas of all points processed so far. While the procedure processes a new point , these hold:
- (I1) ;
- (I2) for all real ;
- (I3) for all real .
Before the first pop for , the stack is the result of the earlier steps, so (I1) and (I2) hold by induction and , which gives (I3). For the first point, the stack is empty and the procedure pushes it with , and all three hold.
A pop. Let and . For , Lemma 1 gives . Let be the function of the stack without , in which runs from to .
(I2) for : on , , which is the minimum over all parabolas, so also over the first . On , which is not empty by (I1), for every . By Lemma 1, is decreasing, so it stays at most 0 for all as well.
(I3) for : on nothing changes. On , , as shown above. Also there, by Lemma 1, since . So , and too.
(I1) holds for the shorter stack. So a pop keeps the invariants.
A push. The loop stops when or , and the procedure pushes with . Then (I1) holds. Let be the new stack function: on and on . We show that , which by (I3) is the minimum of all parabolas processed so far, so that (I2) and hold for the next point.
- On : by Lemma 1. Also , so there, and .
- On : by Lemma 1, and by (I2). So .
The read-out. After the last point, is the lower envelope of all finite parabolas. For an integer , the procedure finds the index with , by moving right while , and returns . If this is . If , the two parabolas and are equal at , so the value is again.
Exactness. Every breakpoint is a fraction of integers with a positive denominator . The procedure compares as and as , with integers only, so no comparison is rounded. If no value is finite, the stack stays empty, and every is infinite.
Lemma 3 (one axis at a time). After the passes over the axes , every cell holds
with the minimum of an empty set equal to .
Proof. By induction on . For , the set holds only if is a mold cell and is empty otherwise, so or , as set by line L1. For the step, the pass over axis works on the line of cells that agree with in all coordinates except the -th. By Lemma 2 it sets
Put in from the induction hypothesis. The cells in the inner minimum have , and the outer minimum runs over all . So the two minima join into one minimum over the mold cells with for , of . That is the claim for .
Theorem 1 (the distance). After line L4, for every cell , and every value is a finite integer.
Proof. Lemma 3 with has no constraint left on . is not empty, so the minimum is finite. All values are sums and minima of integers.
Theorem 2 (the maxima). Call a plateau a connected set of metal cells with one value of , under the full neighbourhood, that is maximal with this property. A plateau is a regional maximum if every cell outside it that is a neighbour of one of its cells has . HOT-SPOTS returns each regional maximum exactly once, with its value, and nothing else, sorted by value from the largest.
Proof. A mold cell has , and a metal cell has , since its nearest mold cell is a different cell with integer coordinates. So a neighbour with is a metal cell. The search at line L5 starts at a metal cell not yet seen and adds every metal neighbour with the same value that is not yet seen. This is a graph search on the graph whose nodes are the metal cells of value and whose edges join neighbours, so it collects exactly the connected component of the start cell, which is its plateau. Every cell of the plateau is marked seen, so no later search starts in it, and each plateau is found once.
During the search, line L6 looks at every neighbour of every cell of the plateau. A neighbour with sets the flag to false. A neighbour with is in the plateau, by maximality. So the flag stays true if and only if every neighbour outside the plateau has , which is the definition of a regional maximum. Line L7 sorts the kept plateaus by their value.
Complexity
Each pass of lines L2 and L3 calls LOWER-ENVELOPE on lines that together hold every cell once, in time, so the transform costs . Lines L5 and L6 visit each metal cell once and look at its neighbours, in time. The total is , which is for or . The extra space is the array of distances and the search stack, .
Properties
- Exact. All values are integers, and the breakpoints of the envelope are compared by cross multiplication, so the distances and their order are exact.
- Deterministic. The plateaus come out sorted by value, and ties by their first cell.
- A proxy. The result depends only on the shape. It does not know the metal, the mold material, chills, sleeves, the gating, or the heat that a thin core receives from both sides.
- Resolution. The distances are between cell centres, so a feature thinner than a cell is lost, and the position of a hot spot is known to a cell.
Variants and improvements
- The modulus instead of the distance. By Chvorinov's rule, freezing time grows with the modulus , not with the distance to the mold. The two agree in their order for sections of one shape, but not across shapes. For a plate of thickness , the largest distance is and the modulus is . For a long square bar of side , they are and ; for a long cylinder of radius , and ; for a sphere of radius , and . So a plate with cm (distance 1, modulus 1) and a sphere with cm (distance 1.5, modulus 0.5) are ranked in opposite orders: the distance says that the sphere freezes last, and the rule says that the plate does.
- Modulus vector method. Ravi and Srinivasan compute at points of the casting a vector from the geometry around them, in the direction in which the local modulus grows, and follow these vectors to the hot spots. This uses more of the shape than the distance to the nearest point of the mold.
- Thermal simulation. A solution of the heat equation with latent heat, by the finite difference method on the same voxel grid or the finite element method on a mesh, gives the last points to freeze directly, and also handles the mold, chills and the alloy. It costs much more and needs material data.
- Other distance transforms. A chamfer distance with integer weights is faster to code but not Euclidean, and its maxima move on diagonal sections. A distance on a tetrahedral mesh or on the solid model, through its medial axis, avoids the voxel resolution.
- Distance to the cooling surface only. Faces against an insulating sleeve or another section of the casting do not cool. Marking them as metal, not mold, before the transform moves the hot spots towards them, in the same way as the modulus method leaves such faces out of .
When to use it
Use it early in casting design, on a voxel model, to see quickly where the thick regions are and which of them are cut off from each other by thin sections. It is a good start for the placement of risers and for the zones of the modulus method. Do not use it to size risers, and check the final design with a simulation.
Pitfalls
- Treating the maxima as the thermal answer. The distance ignores how much metal is around a point, the heating of the mold in concave corners, cores with metal on both sides, and all process data. Inside corners and junctions are worse than their distance says.
- No mold layer. If the casting touches the edge of the grid, the edge is not mold, and the distances there are too large. Pad the grid with mold cells.
- Plateaus. Plates and long bars of even thickness give large flat plateaus or ridges of equal distance, not single points. A riser can sit anywhere along them, and a step in thickness of one cell can split or join them.
- Small maxima from noise. A voxelized surface has steps that make small regional maxima of low value. Ignore maxima below a threshold, or keep only those whose value is much larger than the surroundings.
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/casting-hot-spot-detection/. The authors are listed in prov/NAYQYF.jsonl.
"""Hot spot candidates of a voxel casting from an exact distance transform.
The casting is a grid of cells in k dimensions (k = 2 for a section, k = 3
for a solid), stored as a flat list in row-major order with a shape tuple.
A cell is 1 for metal and 0 for mold. The grid must contain at least one mold
cell; pad the casting with a layer of mold cells to model the mold around it.
`squared_edt` returns, for each cell, the squared Euclidean distance from its
centre to the centre of the nearest mold cell. It uses the lower envelope of
parabolas of Felzenszwalb and Huttenlocher, one axis at a time, with integer
arithmetic only, so the result is exact.
`hot_spots` returns the regional maxima of this distance over the metal cells:
connected plateaus of equal value whose neighbours all have smaller values.
They are a geometric proxy for the places that freeze last, not a solution of
the heat equation.
"""
from itertools import product
from typing import List, Optional, Sequence, Tuple
Shape = Tuple[int, ...]
Cell = Tuple[int, ...]
def _check(mask: Sequence[int], shape: Shape) -> None:
if not shape or any(s <= 0 for s in shape):
raise ValueError("shape must be a non-empty tuple of positive sizes")
size = 1
for s in shape:
size *= s
if len(mask) != size:
raise ValueError("mask length does not match the shape")
if any(m not in (0, 1) for m in mask):
raise ValueError("mask cells must be 0 (mold) or 1 (metal)")
if all(m == 1 for m in mask):
raise ValueError("the grid has no mold cell")
def _strides(shape: Shape) -> List[int]:
strides = [1] * len(shape)
for a in range(len(shape) - 2, -1, -1):
strides[a] = strides[a + 1] * shape[a + 1]
return strides
def lower_envelope_1d(f: Sequence[Optional[int]]) -> List[Optional[int]]:
"""Return d[q] = min over p with f[p] not None of (q - p)^2 + f[p].
None stands for an infinite value. If every f[p] is None, every d[q] is
None. The parabola of p is (q - p)^2 + f[p]; the parabolas of the stack v
form the lower envelope, and parabola v[j] is lowest on the interval that
starts at the breakpoint z[j], stored as an exact fraction num / den with
den > 0.
"""
n = len(f)
# @line L3
v: List[int] = []
znum: List[int] = []
zden: List[int] = []
for q in range(n):
if f[q] is None:
continue
while v:
p = v[-1]
num = (f[q] + q * q) - (f[p] + p * p)
den = 2 * (q - p)
# The parabolas of p and q cross at s = num / den. If s is at or
# before the start of the interval of p, then p is never lowest.
if len(v) > 1 and num * zden[-1] <= znum[-1] * den:
v.pop()
znum.pop()
zden.pop()
continue
break
if v:
p = v[-1]
znum.append((f[q] + q * q) - (f[p] + p * p))
zden.append(2 * (q - p))
else:
znum.append(0) # unused: the first interval starts at -infinity
zden.append(1)
v.append(q)
if not v:
return [None] * n
d: List[Optional[int]] = [None] * n
j = 0
for q in range(n):
# Move right while the next interval starts before q (z < q).
while j + 1 < len(v) and znum[j + 1] < q * zden[j + 1]:
j += 1
p = v[j]
d[q] = (q - p) * (q - p) + f[p]
return d
def squared_edt(mask: Sequence[int], shape: Shape) -> List[int]:
"""Squared Euclidean distance from each cell to the nearest mold cell."""
_check(mask, shape)
# @line L1
f: List[Optional[int]] = [0 if m == 0 else None for m in mask]
strides = _strides(shape)
# @line L2
for a, n in enumerate(shape):
other = [range(s) for b, s in enumerate(shape) if b != a]
for rest in product(*other):
base = 0
k = 0
for b in range(len(shape)):
if b == a:
continue
base += rest[k] * strides[b]
k += 1
idx = [base + i * strides[a] for i in range(n)]
line = lower_envelope_1d([f[i] for i in idx])
for i, val in zip(idx, line):
f[i] = val
# @line L4
# Every cell now has a finite value, since some mold cell exists and the
# passes reach it along the axes one after another.
return [int(x) for x in f]
def _unravel(i: int, shape: Shape) -> Cell:
out = []
for s in reversed(shape):
out.append(i % s)
i //= s
return tuple(reversed(out))
def _neighbours(cell: Cell, shape: Shape):
for off in product((-1, 0, 1), repeat=len(shape)):
if not any(off):
continue
nb = tuple(c + o for c, o in zip(cell, off))
if all(0 <= x < s for x, s in zip(nb, shape)):
yield nb
def hot_spots(mask: Sequence[int], shape: Shape) -> List[Tuple[int, List[Cell]]]:
"""Regional maxima of the squared distance over the metal cells.
Returns a list of (squared distance, sorted cells of the plateau), with
the largest distance first and ties in the order of the first cell.
Plateaus are connected under the full neighbourhood (8 cells in 2D, 26
in 3D).
"""
dist = squared_edt(mask, shape)
strides = _strides(shape)
def flat(c: Cell) -> int:
return sum(x * s for x, s in zip(c, strides))
seen = [False] * len(mask)
result: List[Tuple[int, List[Cell]]] = []
# @line L5
for start in range(len(mask)):
if mask[start] != 1 or seen[start]:
continue
value = dist[start]
seen[start] = True
stack = [_unravel(start, shape)]
plateau: List[Cell] = []
is_max = True
while stack:
cell = stack.pop()
plateau.append(cell)
for nb in _neighbours(cell, shape):
j = flat(nb)
# @line L6
if dist[j] > value:
is_max = False
elif dist[j] == value and mask[j] == 1 and not seen[j]:
seen[j] = True
stack.append(nb)
if is_max:
result.append((value, sorted(plateau)))
# @line L7
result.sort(key=lambda r: (-r[0], r[1][0]))
return result
def from_rows(rows: Sequence[str]) -> Tuple[List[int], Shape]:
"""Read a 2D grid from strings, '#' for metal and '.' for mold."""
if not rows or any(len(r) != len(rows[0]) for r in rows):
raise ValueError("rows must be non-empty and of equal length")
mask = []
for r in rows:
for ch in r:
if ch == "#":
mask.append(1)
elif ch == ".":
mask.append(0)
else:
raise ValueError("unknown cell character")
return mask, (len(rows), len(rows[0]))
test_casting_hot_spot_detection.py 178 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/casting-hot-spot-detection/. The authors are listed in prov/NAYQYF.jsonl.
import random
import unittest
from itertools import product
from casting_hot_spot_detection import from_rows, hot_spots, lower_envelope_1d, squared_edt
PAGE_ROWS = [
".............",
".#####.......",
".#####..###..",
".###########.",
".#####..###..",
".#####.......",
".............",
]
def cells_of(shape):
return list(product(*[range(s) for s in shape]))
def brute_edt(mask, shape):
cells = cells_of(shape)
mold = [c for c, m in zip(cells, mask) if m == 0]
out = []
for c in cells:
out.append(min(sum((a - b) ** 2 for a, b in zip(c, y)) for y in mold))
return out
def brute_hot_cells(mask, shape, dist):
"""Cells in regional maxima, by a second definition.
A metal cell x lies in a regional maximum if and only if the connected
component of x in the upper set {y metal : D(y) >= D(x)} has no cell with
D > D(x). The plateau of x is then that whole component.
"""
cells = cells_of(shape)
index = {c: i for i, c in enumerate(cells)}
result = {}
for c, m in zip(cells, mask):
if m != 1:
continue
v = dist[index[c]]
comp = {c}
stack = [c]
top = v
while stack:
x = stack.pop()
for off in product((-1, 0, 1), repeat=len(shape)):
y = tuple(a + o for a, o in zip(x, off))
if y in index and y not in comp:
j = index[y]
if mask[j] == 1 and dist[j] >= v:
comp.add(y)
stack.append(y)
top = max(top, dist[j])
if top == v:
result[c] = (v, frozenset(comp))
return result
def random_mask(rng, shape, p):
mask = [1 if rng.random() < p else 0 for _ in range(len(cells_of(shape)))]
if all(m == 1 for m in mask):
mask[rng.randrange(len(mask))] = 0
return mask
class LowerEnvelopeTest(unittest.TestCase):
def test_random_lines_match_brute_force(self):
rng = random.Random(7)
for _ in range(400):
n = rng.randint(1, 15)
f = [None if rng.random() < 0.4 else rng.randint(0, 30) for _ in range(n)]
got = lower_envelope_1d(f)
for q in range(n):
vals = [(q - p) ** 2 + f[p] for p in range(n) if f[p] is not None]
self.assertEqual(got[q], min(vals) if vals else None)
def test_ties_and_equal_values(self):
self.assertEqual(lower_envelope_1d([0, None, None, None, 0]), [0, 1, 4, 1, 0])
self.assertEqual(lower_envelope_1d([5, 5, 5]), [5, 5, 5])
self.assertEqual(lower_envelope_1d([None, None]), [None, None])
class EDTTest(unittest.TestCase):
def test_random_2d_matches_brute_force(self):
rng = random.Random(11)
for _ in range(80):
shape = (rng.randint(1, 12), rng.randint(1, 12))
mask = random_mask(rng, shape, rng.choice([0.5, 0.8, 0.95]))
self.assertEqual(squared_edt(mask, shape), brute_edt(mask, shape))
def test_random_3d_matches_brute_force(self):
rng = random.Random(13)
for _ in range(25):
shape = (rng.randint(1, 6), rng.randint(1, 6), rng.randint(1, 6))
mask = random_mask(rng, shape, rng.choice([0.6, 0.9, 0.98]))
self.assertEqual(squared_edt(mask, shape), brute_edt(mask, shape))
def test_one_and_four_dimensions(self):
rng = random.Random(17)
for _ in range(30):
shape = (rng.randint(1, 20),)
mask = random_mask(rng, shape, 0.8)
self.assertEqual(squared_edt(mask, shape), brute_edt(mask, shape))
for _ in range(5):
shape = (3, 4, 3, 4)
mask = random_mask(rng, shape, 0.9)
self.assertEqual(squared_edt(mask, shape), brute_edt(mask, shape))
def test_page_example(self):
mask, shape = from_rows(PAGE_ROWS)
d = squared_edt(mask, shape)
row3 = d[3 * 13:4 * 13]
self.assertEqual(row3, [0, 1, 4, 9, 5, 2, 1, 1, 2, 4, 2, 1, 0])
def test_bad_input(self):
with self.assertRaises(ValueError):
squared_edt([1, 1, 1, 1], (2, 2))
with self.assertRaises(ValueError):
squared_edt([1, 0, 1], (2, 2))
with self.assertRaises(ValueError):
squared_edt([1, 0, 2, 0], (2, 2))
with self.assertRaises(ValueError):
squared_edt([], ())
with self.assertRaises(ValueError):
from_rows(["#.", "#"])
class HotSpotTest(unittest.TestCase):
def test_page_example(self):
mask, shape = from_rows(PAGE_ROWS)
self.assertEqual(hot_spots(mask, shape), [(9, [(3, 3)]), (4, [(3, 9)])])
def test_cube_has_one_centre(self):
n = 7
shape = (n, n, n)
mask = [1 if all(1 <= x <= n - 2 for x in c) else 0 for c in cells_of(shape)]
self.assertEqual(hot_spots(mask, shape), [(9, [(3, 3, 3)])])
def test_plate_is_one_plateau(self):
shape = (4, 8, 8)
mask = [1 if (1 <= c[0] <= 2 and 1 <= c[1] <= 6 and 1 <= c[2] <= 6) else 0 for c in cells_of(shape)]
spots = hot_spots(mask, shape)
# A plate two cells thick: every metal cell is next to the mold.
self.assertEqual(len(spots), 1)
self.assertEqual(spots[0][0], 1)
self.assertEqual(len(spots[0][1]), 2 * 6 * 6)
def test_random_grids_match_second_definition(self):
rng = random.Random(23)
trials = [(rng.randint(2, 11), rng.randint(2, 11)) for _ in range(60)]
trials += [(rng.randint(2, 6), rng.randint(2, 6), rng.randint(2, 6)) for _ in range(20)]
for shape in trials:
mask = random_mask(rng, shape, rng.choice([0.6, 0.85, 0.97]))
dist = squared_edt(mask, shape)
spots = hot_spots(mask, shape)
expect = brute_hot_cells(mask, shape, dist)
got = {}
for value, plateau in spots:
comp = frozenset(plateau)
for c in plateau:
self.assertNotIn(c, got)
got[c] = (value, comp)
self.assertEqual(got, expect)
values = [v for v, _ in spots]
self.assertEqual(values, sorted(values, reverse=True))
if any(mask):
self.assertEqual(values[0], max(d for d, m in zip(dist, mask) if m == 1))
if __name__ == "__main__":
unittest.main()
History
Before computers, foundry engineers found hot spots at junctions by drawing the largest circle that fits in the section, since the junction of two walls holds a larger circle than either wall. Ravi and Srinivasan (1996) computed hot spots on solid models with the modulus vector method. The squared Euclidean distance transform in linear time, by the lower envelope of parabolas one axis at a time, is due to Felzenszwalb and Huttenlocher, in a report of 2004 and in Theory of Computing in 2012.
References
- B. Ravi and M. N. Srinivasan, Casting solidification analysis by modulus vector method, International Journal of Cast Metals Research 9(1), 1996, 1 to 7, the modulus vector at points of a casting from its geometry, and the hot spots found by following these vectors (general locator)
- Pedro F. Felzenszwalb and Daniel P. Huttenlocher, Distance transforms of sampled functions, Theory of Computing 8(19), 2012, 415 to 428, the lower envelope of parabolas for the one-dimensional squared distance transform in linear time, and its use one axis at a time in higher dimensions
- John Campbell, Complete Casting Handbook, 2nd edition, Butterworth-Heinemann, 2015, the chapter on feeding, the hot spots at junctions and the largest inscribed circle as a guide to them (general locator)
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 NAYQYF Edit this page History Report an error Markdown