perf(simulator): resume heat replays from checkpoints and vectorize the step

Scrubbing the Cut Simulator backward reset the heat model and replayed
from zero, so every frame cost a full run (~75 ms on N26-2EF, over a
second at 1/32 in cells).

- A straight run from the start now keeps checkpoints (temperature,
  peak, cursors) about every 500k cell updates, within 32 MB; the
  pieces are rebuilt from the event cursor. Going back, or jumping
  more than eight steps ahead, resumes from the latest checkpoint a
  straight run to the target passes, so the state is exactly that
  run's. Seeks on N26-2EF drop from 12-150 ms to about 1 ms.
- The diffusion step runs branch-free on Vector<float> with neighbor
  links precomputed as 0/1 weights when pieces change, and splits
  across processors on grids of 65,536 cells or more. A missing link
  adds a zero, so results stay bit-identical.
- Rises below 1e-30 K are flushed to zero: the heat front passed
  through subnormal floats, which made long runs 2-4x slower. Only
  cells below ~3e-18 K change, by at most 2e-25 K; N26-2EF's end state
  is bit-identical.

A full run on N26-2EF falls from ~150-180 ms to ~15-40 ms, so the
automatic cell size's work budget rises from 20M to 60M cell updates
(still about a tenth of a second); full sheets keep 0.5 in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-12-01 13:09:13 -05:00
1 parent 71196866d7
commit af999ba5d6
3 files changed
+329 -40

No files matched your search

+269 -38
View File
@@ -1,7 +1,12 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using OpenNest.Geometry;
using OpenNest.Support;
using FloatVector = System.Numerics.Vector<float>;
using Simd = System.Numerics.Vector;
namespace OpenNest.CNC.Thermal
{
@@ -26,8 +31,8 @@ namespace OpenNest.CNC.Thermal
private const int MaxCells = 400_000;
private const int MaxSamplesPerStep = 10_000;
// Cell updates for a whole run when the cell size is automatic: about a quarter second.
private const double WorkBudget = 20_000_000;
// Cell updates for a whole run when the cell size is automatic: about a tenth of a second.
private const double WorkBudget = 60_000_000;
private const int MaxHalvings = 3;
// Explicit diffusion is stable below a quarter on a square grid; the cap keeps timing
@@ -35,6 +40,23 @@ namespace OpenNest.CNC.Thermal
private const double StabilityFactor = 0.2;
private const double MaxStepSeconds = 1.0;
// Checkpoints come every this many cell updates of a run (about a millisecond), so going
// back costs at most that much stepping, and share at most this much memory (temperature
// and peak per cell); a long run on a large grid spaces them further apart.
private const double CheckpointWork = 500_000;
private const long CheckpointBytes = 32L << 20;
// Going forward, a checkpoint this many steps past the current time beats stepping there.
private const int SkipAheadSteps = 8;
// A rise below this is set to zero. The front of the spreading heat passes through
// subnormal floats, which cost the processor about a hundred times a normal operation;
// dropping them changes no cell above about 1e-18 K.
private const float Negligible = 1e-30f;
// Grids this large split each step's cells across processors.
private const int ParallelCells = 65_536;
private readonly List<Deposit> deposits = new();
private readonly List<PieceEvent> events = new();
private readonly int[] region;
@@ -49,6 +71,15 @@ namespace OpenNest.CNC.Thermal
private readonly float[] partialStepKeep;
private double partialStepSeconds = -1;
private readonly double maxStep;
private readonly float[] leftLink;
private readonly float[] rightLink;
private readonly float[] belowLink;
private readonly float[] aboveLink;
private readonly List<Checkpoint> checkpoints = new();
private readonly int checkpointInterval;
private readonly int maxCheckpoints;
private bool straight;
private int straightSteps;
private int depositCursor;
private int eventCursor;
private int nextRegion;
@@ -82,6 +113,10 @@ namespace OpenNest.CNC.Thermal
temperature = new float[count];
next = new float[count];
peak = new float[count];
leftLink = new float[count];
rightLink = new float[count];
belowLink = new float[count];
aboveLink = new float[count];
var metersPerUnit = parameters.MetersPerUnit;
var dx = cell * metersPerUnit;
@@ -105,6 +140,12 @@ namespace OpenNest.CNC.Thermal
}
}
maxCheckpoints = (int)System.Math.Max(1, CheckpointBytes / (8L * count));
var runSteps = System.Math.Ceiling(simulation.TotalTime.TotalSeconds / maxStep);
checkpointInterval = (int)System.Math.Clamp(System.Math.Max(
System.Math.Ceiling(CheckpointWork / count), System.Math.Ceiling(runSteps / maxCheckpoints)),
1, int.MaxValue);
BuildDeposits(parameters.AbsorbedPower / (volumetricHeat * thickness * dx * dx));
BuildPieceEvents();
Reset();
@@ -160,14 +201,40 @@ namespace OpenNest.CNC.Thermal
public Vector CellCenter(int index) =>
new(OriginX + (index % Columns + 0.5) * CellSize, OriginY + (index / Columns + 0.5) * CellSize);
/// <summary>Runs the model to <paramref name="target"/>, restarting first to go back in time.</summary>
/// <summary>
/// Runs the model to <paramref name="target"/>. Going back in time, or far ahead, resumes
/// from the latest checkpoint a straight run from the start would have passed, so the
/// state is exactly that run's.
/// </summary>
public void AdvanceTo(TimeSpan target)
{
var seconds = target.TotalSeconds;
var checkpoint = CheckpointBefore(seconds);
if (seconds < time)
Reset();
{
if (checkpoint == null)
Reset();
else
Restore(checkpoint);
}
else if (checkpoint != null && checkpoint.Time - time > SkipAheadSteps * maxStep)
{
Restore(checkpoint);
}
while (time < seconds)
Step(System.Math.Min(maxStep, seconds - time));
{
var step = System.Math.Min(maxStep, seconds - time);
var previous = time;
Step(step);
if (step != maxStep)
{
straight = false;
continue;
}
if (straight && ++straightSteps % checkpointInterval == 0)
Record(previous);
}
}
/// <summary>Runs the whole cut, then <paramref name="cooling"/> more.</summary>
@@ -177,11 +244,11 @@ namespace OpenNest.CNC.Thermal
{
Array.Clear(temperature);
Array.Clear(peak);
Array.Clear(region);
ResetPieces();
depositCursor = 0;
eventCursor = 0;
nextRegion = 0;
time = 0;
straight = true;
straightSteps = 0;
}
/// <summary>Index of the largest value, or -1 when every value is zero or less.</summary>
@@ -203,8 +270,9 @@ namespace OpenNest.CNC.Thermal
// The finest cell, from the coarsest default halved down to the finest, whose whole run
// (every cell, every time step) stays within the work budget. Halving the cell costs up
// to sixteen times the work: four times the cells and, once diffusion limits the step,
// four times the steps. Going back in time replays from the start, so the budget keeps a
// replay to a fraction of a second; large sheets stay at the coarsest.
// four times the steps. The budget keeps the first run, which also sets the color scale, to
// about a tenth of a second (going back resumes from a checkpoint); large sheets stay at
// the coarsest.
internal static double AutomaticCellSize(Box bounds, double seconds, ThermalParameters parameters)
{
var coarsest = parameters.Units == Units.Millimeters ? 12 : 0.5;
@@ -240,12 +308,17 @@ namespace OpenNest.CNC.Thermal
temperature[deposit.Cell] += deposit.Rise;
}
while (eventCursor < events.Count && events[eventCursor].Time <= end)
Apply(events[eventCursor++]);
Apply(events[eventCursor]);
Diffuse(seconds);
time = end;
}
// One explicit step: each cell takes share times the difference to each neighbor of its
// own piece, then decays. A link weight is 1 between cells of one piece and 0 otherwise
// (and for every link of a removed cell, which holds no heat), so the sum runs without
// branches. A missing link adds a zero, leaving the sum exactly as if it were skipped,
// which keeps the results bit for bit those of the cell-by-cell form.
private void Diffuse(double seconds)
{
var share = (float)(diffusionRate * seconds);
@@ -253,41 +326,99 @@ namespace OpenNest.CNC.Thermal
var cellKeep = contactFraction == null ? null
: seconds == maxStep ? fullStepKeep
: PartialStepKeep(seconds);
var columns = Columns;
var current = temperature;
for (var row = 0; row < Rows; row++)
// Vectors cover the rows with a neighbor above and below; the first and last rows,
// and any remainder, go cell by cell.
var count = temperature.Length;
var width = FloatVector.Count;
var first = Rows > 2 ? Columns : count;
var vectors = Rows > 2 ? (count - 2 * Columns) / width : 0;
var last = first + vectors * width;
DiffuseCells(0, System.Math.Min(first, count), share, keep, cellKeep);
if (vectors > 0)
{
var rowStart = row * columns;
for (var column = 0; column < columns; column++)
var chunks = count >= ParallelCells ? System.Math.Min(Environment.ProcessorCount, vectors) : 1;
if (chunks <= 1)
{
var i = rowStart + column;
var piece = region[i];
if (piece == Removed)
DiffuseVectors(first, last, share, keep, cellKeep);
}
else
{
var perChunk = (vectors + chunks - 1) / chunks;
Parallel.For(0, chunks, chunk =>
{
next[i] = 0;
continue;
}
var t = current[i];
var flow = 0f;
if (column > 0 && region[i - 1] == piece)
flow += current[i - 1] - t;
if (column < columns - 1 && region[i + 1] == piece)
flow += current[i + 1] - t;
if (row > 0 && region[i - columns] == piece)
flow += current[i - columns] - t;
if (row < Rows - 1 && region[i + columns] == piece)
flow += current[i + columns] - t;
var value = (t + share * flow) * (cellKeep == null ? keep : cellKeep[i]);
next[i] = value;
if (value > peak[i])
peak[i] = value;
var start = first + chunk * perChunk * width;
var end = System.Math.Min(last, start + perChunk * width);
if (start < end)
DiffuseVectors(start, end, share, keep, cellKeep);
});
}
}
DiffuseCells(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)
{
var current = temperature;
var columns = Columns;
var count = current.Length;
for (var i = start; i < end; i++)
{
var t = current[i];
var left = i > 0 ? current[i - 1] : 0f;
var right = i + 1 < count ? current[i + 1] : 0f;
var below = i >= columns ? current[i - columns] : 0f;
var above = i + columns < count ? current[i + columns] : 0f;
var flow = leftLink[i] * (left - t) + rightLink[i] * (right - t)
+ belowLink[i] * (below - t) + aboveLink[i] * (above - t);
var value = (t + share * flow) * (cellKeep == null ? keep : cellKeep[i]);
if (value < Negligible)
value = 0;
next[i] = value;
if (value > peak[i])
peak[i] = value;
}
}
// The same sum as DiffuseCells, a vector of cells at a time; every neighbor index is
// inside the grid because the range skips the first and last rows.
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private void DiffuseVectors(int start, int end, float share, float keep, float[] cellKeep)
{
var width = FloatVector.Count;
var columns = (nuint)Columns;
ref var current = ref MemoryMarshal.GetArrayDataReference(temperature);
ref var result = ref MemoryMarshal.GetArrayDataReference(next);
ref var high = ref MemoryMarshal.GetArrayDataReference(peak);
ref var leftWeight = ref MemoryMarshal.GetArrayDataReference(leftLink);
ref var rightWeight = ref MemoryMarshal.GetArrayDataReference(rightLink);
ref var belowWeight = ref MemoryMarshal.GetArrayDataReference(belowLink);
ref var aboveWeight = ref MemoryMarshal.GetArrayDataReference(aboveLink);
ref var decay = ref cellKeep == null ? ref Unsafe.NullRef<float>() : ref MemoryMarshal.GetArrayDataReference(cellKeep);
var shares = new FloatVector(share);
var keeps = new FloatVector(keep);
var negligible = new FloatVector(Negligible);
for (var index = start; index < end; index += width)
{
var i = (nuint)index;
var t = Simd.LoadUnsafe(ref current, i);
var flow = Simd.LoadUnsafe(ref leftWeight, i) * (Simd.LoadUnsafe(ref current, i - 1) - t)
+ Simd.LoadUnsafe(ref rightWeight, i) * (Simd.LoadUnsafe(ref current, i + 1) - t)
+ Simd.LoadUnsafe(ref belowWeight, i) * (Simd.LoadUnsafe(ref current, i - columns) - t)
+ Simd.LoadUnsafe(ref aboveWeight, i) * (Simd.LoadUnsafe(ref current, i + columns) - t);
var value = (t + shares * flow)
* (cellKeep == null ? keeps : Simd.LoadUnsafe(ref decay, i));
value = Simd.ConditionalSelect(Simd.LessThan(value, negligible), default, value);
Simd.StoreUnsafe(value, ref result, i);
var old = Simd.LoadUnsafe(ref high, i);
Simd.StoreUnsafe(Simd.ConditionalSelect(Simd.GreaterThan(value, old), value, old), ref high, i);
}
}
// Each cell's decay over one step: the air from both faces plus the bed under it. An
// exponential factor stays stable however strong the contact. Most steps are full
// length; playback ends each frame on a shorter one, kept until its length changes.
@@ -372,6 +503,14 @@ namespace OpenNest.CNC.Thermal
private void Apply(PieceEvent piece)
{
ApplyToPieces(piece);
foreach (var cell in piece.Cells)
LinkAround(cell);
}
private void ApplyToPieces(PieceEvent piece)
{
eventCursor++;
// Only skeleton cells change: a part cut free earlier (one nested in this cutout)
// stays its own piece.
if (piece.IsCutout)
@@ -395,6 +534,95 @@ namespace OpenNest.CNC.Thermal
}
}
// The pieces depend only on how many events have run, so they are rebuilt rather than
// kept with each checkpoint.
private void ResetPieces()
{
Array.Clear(region);
eventCursor = 0;
nextRegion = 0;
LinkAll();
}
private void LinkAll()
{
for (var i = 0; i < region.Length; i++)
Link(i);
}
// A changed cell changes its own links and its neighbors' links to it.
private void LinkAround(int cell)
{
Link(cell);
var column = cell % Columns;
if (column > 0)
Link(cell - 1);
if (column < Columns - 1)
Link(cell + 1);
if (cell >= Columns)
Link(cell - Columns);
if (cell + Columns < region.Length)
Link(cell + Columns);
}
private void Link(int i)
{
var piece = region[i];
var column = i % Columns;
var alive = piece != Removed;
leftLink[i] = alive && column > 0 && region[i - 1] == piece ? 1f : 0f;
rightLink[i] = alive && column < Columns - 1 && region[i + 1] == piece ? 1f : 0f;
belowLink[i] = alive && i >= Columns && region[i - Columns] == piece ? 1f : 0f;
aboveLink[i] = alive && i + Columns < region.Length && region[i + Columns] == piece ? 1f : 0f;
}
// Checkpoints: the state after every checkpointInterval full 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.
private void Record(double previousTime)
{
var index = straightSteps / checkpointInterval - 1;
if (index != checkpoints.Count || index >= maxCheckpoints)
return;
checkpoints.Add(new Checkpoint(time, previousTime, straightSteps, depositCursor, eventCursor,
(float[])temperature.Clone(), (float[])peak.Clone()));
}
// The latest checkpoint a straight run to the target passes: its last step was a full
// one, so the run had at least a full step left before it.
private Checkpoint CheckpointBefore(double seconds)
{
for (var i = checkpoints.Count - 1; i >= 0; i--)
{
if (seconds - checkpoints[i].PreviousTime >= maxStep)
return checkpoints[i];
}
return null;
}
private void Restore(Checkpoint checkpoint)
{
if (checkpoint.EventCursor != eventCursor)
{
if (checkpoint.EventCursor < eventCursor)
{
Array.Clear(region);
eventCursor = 0;
nextRegion = 0;
}
while (eventCursor < checkpoint.EventCursor)
ApplyToPieces(events[eventCursor]);
LinkAll();
}
checkpoint.Temperature.CopyTo(temperature, 0);
checkpoint.Peak.CopyTo(peak, 0);
depositCursor = checkpoint.DepositCursor;
time = checkpoint.Time;
straight = true;
straightSteps = checkpoint.StraightSteps;
}
// Heat goes in where the torch is, in proportion to the time it spends there.
private void BuildDeposits(double risePerSecond)
{
@@ -531,6 +759,9 @@ namespace OpenNest.CNC.Thermal
private readonly record struct Deposit(double Time, int Cell, float Rise);
private sealed record Checkpoint(double Time, double PreviousTime, int StraightSteps,
int DepositCursor, int EventCursor, float[] Temperature, float[] Peak);
private sealed record PieceEvent(double Time, int[] Cells, bool IsCutout);
}
}
@@ -246,6 +246,45 @@ public class PlateHeatSimulationTests
Assert.Equal(first, heat.Temperatures.ToArray());
}
[Fact]
public void SeekingAcrossCheckpointsGivesAStraightRunsState()
{
// Fine cells make a run long enough to pass several checkpoints.
var plate = new Plate(12, 12);
plate.Parts.Add(new Part(new Drawing("part", Frame(10, 6)), new Vector(1, 1)));
var simulation = CutSimulation.Build(plate, Cutting);
var p = new ThermalParameters
{
Material = ThermalMaterial.MildSteel,
Thickness = 0.25,
Units = Units.Inches,
CellSize = 0.125,
SupportBed = Slats,
};
TimeSpan At(double fraction) => TimeSpan.FromTicks((long)(simulation.TotalTime.Ticks * fraction));
(float[] Temperatures, float[] Peaks) Straight(double fraction)
{
var fresh = new PlateHeatSimulation(plate, simulation, p);
fresh.AdvanceTo(At(fraction));
return (fresh.Temperatures.ToArray(), fresh.Peaks.ToArray());
}
var heat = new PlateHeatSimulation(plate, simulation, p);
heat.RunToEnd();
// Playback frames leave the model between full steps before each seek.
foreach (var fraction in new[] { 0.9, 0.6, 0.35, 0.1, 0.95 })
{
for (var frame = 1; frame <= 3; frame++)
heat.AdvanceTo(heat.Time + TimeSpan.FromSeconds(0.04));
heat.AdvanceTo(At(fraction));
var (temperatures, peaks) = Straight(fraction);
Assert.Equal(temperatures, heat.Temperatures.ToArray());
Assert.Equal(peaks, heat.Peaks.ToArray());
}
}
// Slats along X, one every 4 in, 1 in wide, centered at 2, 6, 10... in from the origin.
private static readonly SupportSlats Slats = new(SlatAxis.X, pitch: 4, thickness: 1, offset: 2);
+21 -2
View File
@@ -9,7 +9,7 @@ a parked [heat-aware sequencer](#sequencing) uses a cheaper estimate of the same
- A grid over the plate's bounds. Unless `CellSize` is set, cells start at 0.5 in (12 mm) and
halve, down to 1/16 in (1.5 mm), while the whole run (cells times time steps) stays within
20 million cell updates, about a quarter second to replay. Halving costs up to sixteen times
60 million cell updates, about a tenth of a second. Halving costs up to sixteen times
the work, since diffusion shortens the time step with the cell's area, so small plates and short
cuts get fine cells and full sheets keep 0.5 in. Any size is made coarser on sheets that would
need more than 400,000 cells. Each cell holds its temperature rise above ambient. Finer cells
@@ -18,7 +18,10 @@ a parked [heat-aware sequencer](#sequencing) uses a cheaper estimate of the same
- Heat in: while the torch is on (cuts and pierces), `AbsorbedPower` watts go into the cell under
the torch, in proportion to the time spent there. Scribes add nothing.
- Conduction: explicit finite differences between the four neighbors of the same piece, with the
time step kept below the stability limit and at most 1 s. Sheet edges are insulated.
time step kept below the stability limit and at most 1 s. Sheet edges are insulated. A rise
below 1e-30 °C is set to zero: the front of the spreading heat would otherwise pass through
subnormal floats, which make each step several times slower. It changes no cell above about
1e-18 °C.
- Loss: convection from both faces at `SurfaceCoefficient` (W/m²·K), plus, when
`ThermalParameters.SupportBed` is given, contact with the bed through the bottom face at
`ContactCoefficient` (W/m²·K) times each cell's share of area over the bed. The share is the
@@ -48,6 +51,22 @@ heat carried off by the melt beyond `AbsorbedPower`, kerf width and warping. The
(1000 W by default) is an uncalibrated guess, so the temperatures are relative; use them to
compare cut orders of one plate, not as real values.
## Playback and seeking
Each step runs a vector of cells at a time, with the links between neighbors of one piece
precomputed as 1 or 0 whenever the pieces change; grids of 65,536 cells or more split each
step across processors. Neither changes a result bit.
A straight run from the start (one never stopped short of a full step) keeps checkpoints of the
temperatures, peaks and event cursors, about every 500,000 cell updates and within 32 MB, more
widely spaced on large grids. The simulator's first run to the end, made to set the color
scale, lays them down. Going back in time, or more than eight steps ahead, resumes from the
latest checkpoint that a straight run to the target passes, so a seek steps through at most one
checkpoint's interval (about a millisecond on a small plate) instead of the whole run, and gives
exactly the state a straight run from the start gives. The pieces are rebuilt from the event
cursor rather than stored. Playing forward frame by frame continues from the current state, as
before.
## Display
The simulator colors the field against the 99.5th percentile of the whole cut's peaks: a pierce