perf(thermal): take the heat map's short steps only around the torch

While the torch cuts, every cell of the plate took steps short enough to
follow it: 4 to 76 times more steps than diffusion needs. On the processor
only the cells within four cells of the torch's recent path take them now;
the rest of the plate takes one long step per slot. A full sheet at
quarter-inch cells runs in 0.23-0.45 s instead of 0.9-2.9 s, and a fast
feed no longer makes it slower.

Peaks stay within 1% of the color scale at the 99th percentile of the
whole-plate result. Graphics cards keep whole-plate steps. Decay factors
for the support bed are worked out per distinct contact fraction.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Fable 5.2 committed 2026-12-02 20:21:08 -05:00
1 parent 8493f8c7f8
commit ff8f97f44a
6 files changed
+423 -49

No files matched your search

+15 -4
View File
@@ -65,6 +65,16 @@ namespace OpenNest.CNC.Thermal
/// split into. Past the cut, slots are whole.
/// </summary>
public (double Time, int Split) Next(double time)
{
var (slot, index, split) = StepAfter(time);
return (End(slot, index, split), split);
}
/// <summary>
/// The step that ends first after <paramref name="time"/>: its slot, its place in the
/// slot (1 to the split) and the count the slot is split into.
/// </summary>
public (long Slot, int Index, int Split) StepAfter(double time)
{
var slot = (long)System.Math.Floor(time / SlotSeconds + Tolerance);
while (true)
@@ -73,14 +83,15 @@ namespace OpenNest.CNC.Thermal
var start = slot * SlotSeconds;
var index = System.Math.Max(1, (long)System.Math.Floor((time - start) / SlotSeconds * split + Tolerance) + 1);
if (index <= split)
{
var boundary = index == split ? (slot + 1) * SlotSeconds : start + SlotSeconds * index / split;
return (boundary, split);
}
return (slot, (int)index, split);
slot++;
}
}
/// <summary>When step <paramref name="index"/> (1 to <paramref name="split"/>) of a slot ends.</summary>
public double End(long slot, int index, int split) =>
index == split ? (slot + 1) * SlotSeconds : slot * SlotSeconds + SlotSeconds * index / split;
private static int SplitFor(double needed)
{
foreach (var split in Splits)
+278 -32
View File
@@ -25,8 +25,11 @@ namespace OpenNest.CNC.Thermal
/// docs/plate-heat-map.md.
/// </para>
/// <para>
/// With <see cref="ThermalParameters.Accelerator"/> large grids run on it, close to the CPU's
/// results but not bit for bit. Use one thread at a time, and dispose to release it.
/// While the torch cuts, steps are short enough to follow it, but only the cells around the
/// torch take them; the rest of the plate takes one step as long as diffusion allows.
/// With <see cref="ThermalParameters.Accelerator"/> large grids run on it, every cell taking
/// the short steps, so its picture is close to the CPU's (peaks within a few percent of the
/// color scale) but not the same. Use one thread at a time, and dispose to release it.
/// </para>
/// </summary>
public sealed class PlateHeatSimulation : IDisposable
@@ -40,7 +43,8 @@ namespace OpenNest.CNC.Thermal
// automatic. The first halving may take about a second on the processor, so a full sheet
// gets quarter-inch cells, and a couple of seconds on an accelerator, for longer cuts.
// Finer cells have to be quick: on a full sheet their hot lines are too thin to see and
// stretch the color scale. The torch travel limit can multiply the steps a few times.
// stretch the color scale. On an accelerator the torch travel limit can multiply the
// steps a few times.
private const double WorkBudget = 800_000_000;
private const double AcceleratedWorkBudget = 20_000_000_000;
private const double FinerWorkBudget = 60_000_000;
@@ -64,6 +68,17 @@ namespace OpenNest.CNC.Thermal
private const double FineCellMeters = 0.004;
private const double MinStepSeconds = 0.005;
// Only the cells around the torch take those short steps: those within this many cells
// of where it put heat during the steps and the slot before them. The slot before keeps
// the cells beside a fresh cut on short steps until their own peak has passed. Heat
// moves a cell in about a slot, so the cells past the margin change too slowly to need
// more than the one long step the rest of the plate takes.
private const int WindowMargin = 4;
// Decay factors for long steps of odd lengths (a slot cut where a piece changes) are
// kept up to this much memory.
private const long IntervalKeepBytes = 32L << 20;
// Samples of the torch's path per cell; fewer leave some cells with more than others.
private const int SamplesPerCell = 4;
@@ -73,7 +88,7 @@ namespace OpenNest.CNC.Thermal
private const double CheckpointWork = 500_000;
private const long CheckpointBytes = 128L << 20;
// A cancellable run looks for a request this often.
// A cancellable run looks for a request before its first step and this often after.
private const int CancelCheckSteps = 64;
// Going forward, a checkpoint this many steps past the current time beats stepping there.
@@ -96,11 +111,25 @@ namespace OpenNest.CNC.Thermal
private readonly double diffusionRate;
private readonly double lossRate;
private readonly float[] contactFraction;
// The distinct contact fractions (a bed repeats a few), and which one each cell has.
private readonly float[] contactValues;
private readonly int[] contactValueOf;
private readonly double contactRate;
// Each cell's decay for a scheduled step, by the count its slot is split into.
private readonly Dictionary<int, float[]> splitKeeps = new();
private readonly float[] partialStepKeep;
private double partialStepSeconds = -1;
// Each cell's decay for a long step over some of a slot's steps, by split and count.
private readonly Dictionary<(int Split, int Count), float[]> intervalKeeps = new();
private readonly bool windowed;
// The window: the cells that take short steps, as runs along rows. Its cells and the
// ones touching them are copied twice (a short step reads one copy and writes the
// other), and its peaks kept from before the long step; all laid out as the grid is.
private readonly List<(int Start, int Length)> windowRuns = new();
private float[] windowCurrent;
private float[] windowNext;
private float[] windowPeak;
private byte[] windowCells;
private readonly double maxStep;
private readonly HeatStepSchedule schedule;
private readonly IHeatKernel kernel;
@@ -174,6 +203,7 @@ namespace OpenNest.CNC.Thermal
// Through the bottom face only.
contactRate = parameters.ContactCoefficient / (volumetricHeat * thickness);
partialStepKeep = new float[count];
(contactValues, contactValueOf) = Distinct(contactFraction);
}
}
@@ -192,6 +222,7 @@ namespace OpenNest.CNC.Thermal
samples[i] = deposits[i].Sample;
kernel = parameters.Accelerator.Create(Columns, Rows, samples);
}
windowed = kernel == null && !parameters.WholePlateSteps;
Reset();
}
@@ -286,24 +317,34 @@ namespace OpenNest.CNC.Thermal
var taken = 0;
while (time < seconds)
{
if (++taken % CancelCheckSteps == 0)
if (taken++ % CancelCheckSteps == 0)
cancellationToken.ThrowIfCancellationRequested();
var (boundary, split) = schedule.Next(time);
var (slot, index, split) = schedule.StepAfter(time);
var boundary = schedule.End(slot, index, split);
var reaches = boundary <= seconds;
var end = reaches ? boundary : seconds;
// A whole scheduled step has exactly the nominal length, whatever the rounding
// of its ends, so every run through it computes the same.
var whole = reaches && onBoundary;
Step(whole ? maxStep / split : end - time, end, whole ? split : 0);
var count = 1;
var complete = true;
if (whole && windowed && split > 1)
count = IntervalSteps(slot, index, split, seconds, out complete);
if (count > 1)
StepInterval(slot, index, split, count);
else
Step(whole ? maxStep / split : end - time, end, whole ? split : 0);
onBoundary = reaches;
if (!whole)
{
// A straight run takes every interval whole; one cut short by the target has
// left its path.
if (!whole || !complete)
straight = false;
if (!straight || !whole)
continue;
}
if (straight && ++straightSteps % checkpointInterval == 0)
Record();
straightSteps += count;
Record();
}
}
@@ -385,6 +426,173 @@ namespace OpenNest.CNC.Thermal
(long)System.Math.Max(1, System.Math.Ceiling(bounds.Length / cell))
* (long)System.Math.Max(1, System.Math.Ceiling(bounds.Width / cell));
// The whole steps, from this one on, that go as one interval: up to the end of the slot
// or the step before one in which a piece changes (the same for every run), or, not
// complete, up to the target.
private int IntervalSteps(long slot, int index, int split, double seconds, out bool complete)
{
var pending = eventCursor;
var first = schedule.End(slot, index, split);
while (pending < events.Count && events[pending].Time <= first)
pending++;
complete = true;
var count = 1;
while (index + count <= split)
{
var end = schedule.End(slot, index + count, split);
if (pending < events.Count && events[pending].Time <= end)
break;
if (end > seconds)
{
complete = false;
break;
}
count++;
}
return count;
}
// Several whole steps of one slot at once. The window around the torch takes them one
// by one, as Step would, with the cells next to it held where they started; every
// other cell takes a single step of their combined length. Pieces change only in the
// first step (IntervalSteps), so the links hold throughout.
private void StepInterval(long slot, int index, int split, int count)
{
var start = time;
var firstEnd = schedule.End(slot, index, split);
var lastEnd = schedule.End(slot, index + count - 1, split);
var from = depositCursor;
while (depositCursor < deposits.Count && deposits[depositCursor].Time <= firstEnd)
depositCursor++;
for (var i = from; i < depositCursor; i++)
Add(deposits[i].Sample, temperature);
while (eventCursor < events.Count && events[eventCursor].Time <= firstEnd)
Apply(events[eventCursor]);
var to = depositCursor;
while (to < deposits.Count && deposits[to].Time <= lastEnd)
to++;
var seconds = count == split ? maxStep : maxStep * count / split;
var share = (float)(diffusionRate * seconds);
var keep = (float)System.Math.Exp(-lossRate * seconds);
var cellKeep = contactFraction == null ? null : IntervalKeep(split, count, seconds);
if (to == from)
{
// No heat from the torch in these steps, so one long step everywhere, the cells
// beside the last cut included.
Diffuse(share, keep, cellKeep);
time = lastEnd;
return;
}
FindWindow(start, from, to);
CopyWindow();
// The long step would also raise the window's peaks, from values the short steps
// replace.
Diffuse(share, keep, cellKeep);
foreach (var (first, length) in windowRuns)
Array.Copy(windowPeak, first, peak, first, length);
var stepSeconds = maxStep / split;
var stepShare = (float)(diffusionRate * stepSeconds);
var stepKeep = (float)System.Math.Exp(-lossRate * stepSeconds);
var stepCellKeep = contactFraction == null ? null : SplitKeep(split);
for (var k = 0; k < count; k++)
{
if (k > 0)
{
var end = schedule.End(slot, index + k, split);
for (; depositCursor < to && deposits[depositCursor].Time <= end; depositCursor++)
Add(deposits[depositCursor].Sample, windowCurrent);
}
foreach (var (first, length) in windowRuns)
DiffuseCells(windowCurrent, windowNext, first, first + length, stepShare, stepKeep, stepCellKeep);
(windowCurrent, windowNext) = (windowNext, windowCurrent);
}
foreach (var (first, length) in windowRuns)
Array.Copy(windowCurrent, first, temperature, first, length);
depositCursor = to;
time = lastEnd;
}
// Lists the window's cells in windowRuns: every cell within the margin of a cell that
// samples from to to, or those of the slot before the interval, put heat in.
private void FindWindow(double start, int from, int to)
{
windowCells ??= new byte[temperature.Length];
var first = from;
while (first > 0 && deposits[first - 1].Time > start - maxStep)
first--;
int firstRow = int.MaxValue, lastRow = -1, firstColumn = int.MaxValue, lastColumn = -1;
var previous = -1;
for (var i = first; i < to; i++)
{
var sample = deposits[i].Sample;
var corner = sample.Lower * Columns + sample.Left;
if (corner == previous)
continue;
previous = corner;
var left = System.Math.Max(0, sample.Left - WindowMargin);
var right = System.Math.Min(Columns - 1, sample.Left + 1 + WindowMargin);
var lower = System.Math.Max(0, sample.Lower - WindowMargin);
var upper = System.Math.Min(Rows - 1, sample.Lower + 1 + WindowMargin);
for (var row = lower; row <= upper; row++)
windowCells.AsSpan(row * Columns + left, right - left + 1).Fill(1);
firstRow = System.Math.Min(firstRow, lower);
lastRow = System.Math.Max(lastRow, upper);
firstColumn = System.Math.Min(firstColumn, left);
lastColumn = System.Math.Max(lastColumn, right);
}
windowRuns.Clear();
for (var row = firstRow; row <= lastRow; row++)
{
var cells = windowCells.AsSpan(row * Columns + firstColumn, lastColumn - firstColumn + 1);
var at = 0;
while (at < cells.Length)
{
var skip = cells[at..].IndexOf((byte)1);
if (skip < 0)
break;
at += skip;
var length = cells[at..].IndexOf((byte)0);
if (length < 0)
length = cells.Length - at;
windowRuns.Add((row * Columns + firstColumn + at, length));
at += length;
}
cells.Clear();
}
}
// Copies the window's cells, and the cells touching them, which keep these values while
// it steps.
private void CopyWindow()
{
windowCurrent ??= new float[temperature.Length];
windowNext ??= new float[temperature.Length];
windowPeak ??= new float[temperature.Length];
foreach (var (first, length) in windowRuns)
{
Array.Copy(peak, first, windowPeak, first, length);
var column = first % Columns;
var left = column > 0 ? first - 1 : first;
var cells = length + (column > 0 ? 1 : 0) + (column + length < Columns ? 1 : 0);
for (var at = left - Columns; at <= left + Columns; at += Columns)
{
if (at < 0 || at >= temperature.Length)
continue;
Array.Copy(temperature, at, windowCurrent, at, cells);
Array.Copy(temperature, at, windowNext, at, cells);
}
}
}
// split names the scheduled step length, or is zero for a step cut short.
private void Step(double seconds, double end, int split)
{
@@ -394,7 +602,7 @@ namespace OpenNest.CNC.Thermal
if (kernel == null)
{
for (var i = from; i < depositCursor; i++)
Add(deposits[i].Sample);
Add(deposits[i].Sample, temperature);
}
else if (depositCursor > from)
{
@@ -422,8 +630,9 @@ namespace OpenNest.CNC.Thermal
// Shares a sample between the four cells whose centers surround the torch, by how close
// it is to each, so heat moves smoothly across the grid with the torch. Only cells of
// the piece under the torch take a share, which keeps heat from crossing a kerf.
private void Add(HeatSample deposit)
// the piece under the torch take a share, which keeps heat from crossing a kerf. The
// heat goes into target: the grid, or a window's copy of it.
private void Add(HeatSample deposit, float[] target)
{
var piece = region[deposit.Cell];
if (piece == Removed)
@@ -440,10 +649,10 @@ namespace OpenNest.CNC.Thermal
// The cell under the torch always has a share, so the total is never zero.
var rise = deposit.Rise / (lowerLeft + lowerRight + upperLeft + upperRight);
temperature[lower + left] += rise * lowerLeft;
temperature[lower + right] += rise * lowerRight;
temperature[upper + left] += rise * upperLeft;
temperature[upper + right] += rise * upperRight;
target[lower + left] += rise * lowerLeft;
target[lower + right] += rise * lowerRight;
target[upper + left] += rise * upperLeft;
target[upper + right] += rise * upperRight;
}
private float Share(int cell, int piece, float weight) => region[cell] == piece ? weight : 0f;
@@ -463,7 +672,7 @@ namespace OpenNest.CNC.Thermal
var vectors = Rows > 2 ? (count - 2 * Columns) / width : 0;
var last = first + vectors * width;
DiffuseCells(0, System.Math.Min(first, count), share, keep, cellKeep);
DiffuseCells(temperature, next, 0, System.Math.Min(first, count), share, keep, cellKeep);
if (vectors > 0)
{
var chunks = count >= ParallelCells ? System.Math.Min(Environment.ProcessorCount, vectors) : 1;
@@ -483,14 +692,13 @@ namespace OpenNest.CNC.Thermal
});
}
}
DiffuseCells(last, count, share, keep, cellKeep);
DiffuseCells(temperature, next, last, count, share, keep, cellKeep);
(temperature, next) = (next, temperature);
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private void DiffuseCells(int start, int end, float share, float keep, float[] cellKeep)
private void DiffuseCells(float[] current, float[] result, int start, int end, float share, float keep, float[] cellKeep)
{
var current = temperature;
var columns = Columns;
var count = current.Length;
for (var i = start; i < end; i++)
@@ -505,7 +713,7 @@ namespace OpenNest.CNC.Thermal
var value = (t + share * flow) * (cellKeep == null ? keep : cellKeep[i]);
if (value < Negligible)
value = 0;
next[i] = value;
result[i] = value;
if (value > peak[i])
peak[i] = value;
}
@@ -567,13 +775,49 @@ namespace OpenNest.CNC.Thermal
return partialStepKeep;
}
// The decay over a long step of count of a slot's split steps; a whole slot's is the one
// an unsplit slot uses.
private float[] IntervalKeep(int split, int count, double seconds)
{
if (count == split)
return SplitKeep(1);
if (!intervalKeeps.TryGetValue((split, count), out var keep))
{
if ((intervalKeeps.Count + 1) * 4L * temperature.Length > IntervalKeepBytes)
intervalKeeps.Clear();
intervalKeeps[(split, count)] = keep = ContactKeep(seconds, new float[temperature.Length]);
}
return keep;
}
// The exponential is worked out once per distinct contact fraction, not per cell.
private float[] ContactKeep(double seconds, float[] keep)
{
var values = new float[contactValues.Length];
for (var i = 0; i < values.Length; i++)
values[i] = (float)System.Math.Exp(-(lossRate + contactRate * contactValues[i]) * seconds);
for (var i = 0; i < keep.Length; i++)
keep[i] = (float)System.Math.Exp(-(lossRate + contactRate * contactFraction[i]) * seconds);
keep[i] = values[contactValueOf[i]];
return keep;
}
private static (float[] Values, int[] IndexOf) Distinct(float[] source)
{
var seen = new Dictionary<float, int>();
var values = new List<float>();
var indexOf = new int[source.Length];
for (var i = 0; i < source.Length; i++)
{
if (!seen.TryGetValue(source[i], out var index))
{
seen[source[i]] = index = values.Count;
values.Add(source[i]);
}
indexOf[i] = index;
}
return (values.ToArray(), indexOf);
}
// The share of every cell over the bed: the overlap of each slat's top, or each grid
// point's square pad, with the cell, so slats narrower or wider than a cell both count.
// Null for a bed this model does not know.
@@ -755,16 +999,18 @@ namespace OpenNest.CNC.Thermal
aboveLink[i] = alive && i + Columns < region.Length && region[i + Columns] == piece ? 1f : 0f;
}
// Checkpoints: the state after every checkpointInterval steps of a straight run from
// the start (one never cut short by an earlier target), kept as the run passes them. A
// straight run to any later target takes exactly the same steps up to there.
// Checkpoints: the state of a straight run from the start (one never cut short by an
// earlier target) each time its step count passes another multiple of checkpointInterval,
// kept as the run passes them. A straight run to any later target takes exactly the same
// steps up to there, so it passes the same states.
private void Record()
{
var index = straightSteps / checkpointInterval - 1;
if (index != checkpoints.Count || index >= maxCheckpoints)
var number = straightSteps / checkpointInterval;
var last = checkpoints.Count == 0 ? 0 : checkpoints[^1].Number;
if (number <= last || checkpoints.Count >= maxCheckpoints)
return;
Synchronize();
checkpoints.Add(new Checkpoint(time, straightSteps, depositCursor, eventCursor,
checkpoints.Add(new Checkpoint(time, straightSteps, number, depositCursor, eventCursor,
(float[])temperature.Clone(), (float[])peak.Clone()));
}
@@ -947,7 +1193,7 @@ namespace OpenNest.CNC.Thermal
return inside;
}
private sealed record Checkpoint(double Time, int StraightSteps,
private sealed record Checkpoint(double Time, int StraightSteps, int Number,
int DepositCursor, int EventCursor, float[] Temperature, float[] Peak);
private sealed record PieceEvent(double Time, int[] Cells, bool IsCutout);
@@ -70,6 +70,12 @@ namespace OpenNest.CNC.Thermal
/// </summary>
public IHeatAccelerator Accelerator { get; init; }
/// <summary>
/// Takes the short steps of cutting over the whole plate instead of only around the torch,
/// as an <see cref="Accelerator"/> does. Slower; for comparing the two.
/// </summary>
internal bool WholePlateSteps { get; init; }
internal double MetersPerUnit => Units == Units.Millimeters ? 0.001 : 0.0254;
internal double EffectiveGridContactSize =>