Algorithm Search⌘K

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)
Properties
deterministicexactiterative
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 O(N)O(N) 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 kk axes, usually k=3k = 3 for a solid or k=2k = 2 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 xx, D(x)=min⁡y mold∥x−y∥2D(x) = \min_{y \text{ mold}} \lVert x - y \rVert^2, the squared Euclidean distance between cell centres, as an exact integer.
  • The regional maxima of DD over the metal cells. A plateau is a maximal connected set of metal cells with one value cc of DD, 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 D<cD < c. These are the hot spot candidates, sorted by DD from the largest.

What the distance measures. D(x)\sqrt{D(x)} is the distance from the centre of xx 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 D(x)−12\sqrt{D(x)} - \frac12 cells. The squares are kept because they are integers, and taking the square root does not change the order.

The algorithm

  1. HOT-SPOTS(grid)
  2. 1f(x) ← 0 for each mold cell x, and ∞ for each metal cell
  3. 2for each axis a = 1, ..., k
  4. 3for each line of cells along axis a: replace f on the line by LOWER-ENVELOPE(f on the line)
  5. 4D ← f
  6. 5group the metal cells into plateaus of equal D, connected under the full neighbourhood
  7. 6keep a plateau if every cell next to it has a smaller D
  8. 7return the kept plateaus with their values, the largest first

LOWER-ENVELOPE at line L3. For a line f(0),…,f(n−1)f(0), \dots, f(n-1) it returns d(q)=min⁡p((q−p)2+f(p))d(q) = \min_p \bigl((q - p)^2 + f(p)\bigr). Each pp with a finite f(p)f(p) gives a parabola Pp(u)=(u−p)2+f(p)P_p(u) = (u - p)^2 + f(p), and dd is their lower envelope at the integers. All parabolas have the same shape, so two of them, p<rp < r, cross at exactly one point,

s(p,r)=(f(r)+r2)−(f(p)+p2)2(r−p),s(p, r) = \frac{\bigl(f(r) + r^2\bigr) - \bigl(f(p) + p^2\bigr)}{2(r - p)},

and PrP_r 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 rr, it pops the top parabola vv while s(v,r)s(v, r) is at or before the start of vv, since PrP_r is then lower on the whole interval of vv. A second pass reads off d(q)d(q) from the interval that holds qq. Each point is pushed and popped at most once, so the time is O(n)O(n).

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, f(x)f(x) is the squared distance to the nearest mold cell on the line of xx along axis 1. After the pass over axis 2, it is the distance to the nearest mold cell in the plane of xx 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 DD.

Example

A 2D section with a block of 5×55 \times 5 cells joined by a bar one cell thick to a boss of 3×33 \times 3 cells, with mold around it (# is metal and . is mold):

.............
.#####.......
.#####..###..
.###########.
.#####..###..
.#####.......
.............

The values of DD on the middle row are

column 0 1 2 3 4 5 6 7 8 9 10 11 12
DD 0 1 4 9 5 2 1 1 2 4 2 1 0

The cell (3,4)(3, 4) has D=5D = 5: its nearest mold cells are (2,6)(2, 6) and (4,6)(4, 6), one row and two columns away, beside the start of the bar, so 12+22=51^2 + 2^2 = 5. The algorithm returns two hot spots: D=9D = 9 at (3,3)(3, 3), the centre of the block, and D=4D = 4 at (3,9)(3, 9), the centre of the boss. The bar between them has D=1D = 1, 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 1,…,a1, \dots, a, each cell holds the squared distance to the nearest mold cell that agrees with it in the other coordinates; for a=ka = k this is the full distance. Third, every metal cell has D≥1D \ge 1 and every mold cell has D=0D = 0, 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 {y:D(y)≥D(x)}\{y : D(y) \ge D(x)\} that holds xx 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 kk axes, and a cell is a vector xx of kk integer indices. M0M_0 is the set of mold cells, which is not empty. For a real number uu and a cell index pp with a finite value f(p)f(p), the parabola of pp is Pp(u)=(u−p)2+f(p)P_p(u) = (u - p)^2 + f(p).

Lemma 1 (two parabolas). For p<rp < r, the difference Pr(u)−Pp(u)=(f(r)+r2)−(f(p)+p2)−2u(r−p)P_r(u) - P_p(u) = \bigl(f(r) + r^2\bigr) - \bigl(f(p) + p^2\bigr) - 2u(r - p) is strictly decreasing in uu and is zero at

s(p,r)=(f(r)+r2)−(f(p)+p2)2(r−p).s(p, r) = \frac{\bigl(f(r) + r^2\bigr) - \bigl(f(p) + p^2\bigr)}{2(r - p)}.

So Pr(u)≤Pp(u)P_r(u) \le P_p(u) if and only if u≥s(p,r)u \ge s(p, r).

Proof. Expand both squares: the terms u2u^2 cancel, and what is left is linear in uu with the slope −2(r−p)<0-2(r - p) < 0. □\square

Lemma 2 (the lower envelope). For a line f(0),…,f(n−1)f(0), \dots, f(n-1) in which some values may be infinite, LOWER-ENVELOPE returns d(q)=min⁡pPp(q)d(q) = \min_p P_p(q) over the pp with f(p)f(p) finite, and d(q)=∞d(q) = \infty for all qq if there are none.

Proof. The procedure takes the finite points in increasing order and keeps a stack v1<⋯<vmv_1 < \dots < v_m with breakpoints z1=−∞z_1 = -\infty and zj=s(vj−1,vj)z_j = s(v_{j-1}, v_j) for j≥2j \ge 2. Let FF be the function equal to PvjP_{v_j} on [zj,zj+1)[z_j, z_{j+1}), with zm+1=∞z_{m+1} = \infty. Let EE be the minimum of the parabolas of all points processed so far. While the procedure processes a new point rr, these hold:

  • (I1) z1<z2<⋯<zmz_1 < z_2 < \dots < z_m;
  • (I2) F(u)=min⁡j≤mPvj(u)F(u) = \min_{j \le m} P_{v_j}(u) for all real uu;
  • (I3) min⁡(F(u),Pr(u))=min⁡(E(u),Pr(u))\min\bigl(F(u), P_r(u)\bigr) = \min\bigl(E(u), P_r(u)\bigr) for all real uu.

Before the first pop for rr, the stack is the result of the earlier steps, so (I1) and (I2) hold by induction and F=EF = E, which gives (I3). For the first point, the stack is empty and the procedure pushes it with z1=−∞z_1 = -\infty, and all three hold.

A pop. Let m≥2m \ge 2 and s(vm,r)≤zms(v_m, r) \le z_m. For u≥zmu \ge z_m, Lemma 1 gives Pr(u)≤Pvm(u)=F(u)P_r(u) \le P_{v_m}(u) = F(u). Let F−F^- be the function of the stack without vmv_m, in which Pvm−1P_{v_{m-1}} runs from zm−1z_{m-1} to ∞\infty.

(I2) for F−F^-: on (−∞,zm)(-\infty, z_m), F−=FF^- = F, which is the minimum over all mm parabolas, so also over the first m−1m - 1. On [zm−1,zm)[z_{m-1}, z_m), which is not empty by (I1), Pvm−1=F≤PviP_{v_{m-1}} = F \le P_{v_i} for every i<m−1i < m - 1. By Lemma 1, Pvm−1−PviP_{v_{m-1}} - P_{v_i} is decreasing, so it stays at most 0 for all u≥zmu \ge z_m as well.

(I3) for F−F^-: on (−∞,zm)(-\infty, z_m) nothing changes. On [zm,∞)[z_m, \infty), min⁡(F,Pr)=Pr\min(F, P_r) = P_r, as shown above. Also Pvm≤Pvm−1P_{v_m} \le P_{v_{m-1}} there, by Lemma 1, since zm=s(vm−1,vm)z_m = s(v_{m-1}, v_m). So Pr≤Pvm≤Pvm−1=F−P_r \le P_{v_m} \le P_{v_{m-1}} = F^-, and min⁡(F−,Pr)=Pr\min(F^-, P_r) = P_r too.

(I1) holds for the shorter stack. So a pop keeps the invariants.

A push. The loop stops when m=1m = 1 or s=s(vm,r)>zms = s(v_m, r) > z_m, and the procedure pushes rr with zm+1=sz_{m+1} = s. Then (I1) holds. Let GG be the new stack function: FF on (−∞,s)(-\infty, s) and PrP_r on [s,∞)[s, \infty). We show that G=min⁡(F,Pr)G = \min(F, P_r), which by (I3) is the minimum of all parabolas processed so far, so that (I2) and G=EG = E hold for the next point.

  • On [s,∞)[s, \infty): Pr≤PvmP_r \le P_{v_m} by Lemma 1. Also s>zms > z_m, so F=PvmF = P_{v_m} there, and G=Pr=min⁡(F,Pr)G = P_r = \min(F, P_r).
  • On (−∞,s)(-\infty, s): Pr>PvmP_r > P_{v_m} by Lemma 1, and Pvm≥FP_{v_m} \ge F by (I2). So min⁡(F,Pr)=F=G\min(F, P_r) = F = G.

The read-out. After the last point, F=EF = E is the lower envelope of all finite parabolas. For an integer qq, the procedure finds the index jj with zj<q≤zj+1z_j < q \le z_{j+1}, by moving right while zj+1<qz_{j+1} < q, and returns Pvj(q)P_{v_j}(q). If q<zj+1q < z_{j+1} this is F(q)F(q). If q=zj+1q = z_{j+1}, the two parabolas PvjP_{v_j} and Pvj+1P_{v_{j+1}} are equal at qq, so the value is F(q)F(q) again.

Exactness. Every breakpoint is a fraction of integers with a positive denominator 2(r−p)2(r - p). The procedure compares a/b≤c/ea/b \le c/e as ae≤cba e \le c b and a/b<qa/b < q as a<qba < q b, with integers only, so no comparison is rounded. If no value is finite, the stack stays empty, and every d(q)d(q) is infinite. □\square

Lemma 3 (one axis at a time). After the passes over the axes 1,…,a1, \dots, a, every cell xx holds

fa(x)=min⁡{∑i≤a(xi−yi)2  :  y∈M0,  yi=xi for all i>a},f_a(x) = \min \Bigl\{ \sum_{i \le a} (x_i - y_i)^2 \;:\; y \in M_0, \; y_i = x_i \text{ for all } i > a \Bigr\},

with the minimum of an empty set equal to ∞\infty.

Proof. By induction on aa. For a=0a = 0, the set holds only y=xy = x if xx is a mold cell and is empty otherwise, so f0(x)=0f_0(x) = 0 or ∞\infty, as set by line L1. For the step, the pass over axis aa works on the line of cells that agree with xx in all coordinates except the aa-th. By Lemma 2 it sets

fa(x)=min⁡p((xa−p)2+fa−1(x with xa replaced by p)).f_a(x) = \min_p \Bigl((x_a - p)^2 + f_{a-1}(x \text{ with } x_a \text{ replaced by } p)\Bigr).

Put in fa−1f_{a-1} from the induction hypothesis. The cells yy in the inner minimum have ya=py_a = p, and the outer minimum runs over all pp. So the two minima join into one minimum over the mold cells yy with yi=xiy_i = x_i for i>ai > a, of (xa−ya)2+∑i<a(xi−yi)2(x_a - y_a)^2 + \sum_{i < a} (x_i - y_i)^2. That is the claim for aa. □\square

Theorem 1 (the distance). After line L4, D(x)=min⁡y∈M0∥x−y∥2D(x) = \min_{y \in M_0} \lVert x - y \rVert^2 for every cell xx, and every value is a finite integer.

Proof. Lemma 3 with a=ka = k has no constraint left on yy. M0M_0 is not empty, so the minimum is finite. All values are sums and minima of integers. □\square

Theorem 2 (the maxima). Call a plateau a connected set of metal cells with one value cc of DD, 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 D<cD < c. 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 D=0D = 0, and a metal cell has D≥1D \ge 1, since its nearest mold cell is a different cell with integer coordinates. So a neighbour with D=c≥1D = c \ge 1 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 cc 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 D>cD > c sets the flag to false. A neighbour with D=cD = c is in the plateau, by maximality. So the flag stays true if and only if every neighbour outside the plateau has D<cD < c, which is the definition of a regional maximum. Line L7 sorts the kept plateaus by their value. ■\blacksquare

Complexity

Each pass of lines L2 and L3 calls LOWER-ENVELOPE on lines that together hold every cell once, in O(N)O(N) time, so the transform costs O(kN)O(kN). Lines L5 and L6 visit each metal cell once and look at its 3k−13^k - 1 neighbours, in O(3kN)O(3^k N) time. The total is O(3kN)O(3^k N), which is O(N)O(N) for k=2k = 2 or 33. The extra space is the array of distances and the search stack, O(N)O(N).

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 V/AV/A, 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 TT, the largest distance is T/2T/2 and the modulus is T/2T/2. For a long square bar of side aa, they are a/2a/2 and a/4a/4; for a long cylinder of radius rr, rr and r/2r/2; for a sphere of radius rr, rr and r/3r/3. So a plate with T=2T = 2 cm (distance 1, modulus 1) and a sphere with r=1.5r = 1.5 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 AA.

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.

casting_hot_spot_detection.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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.

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