From ff8f97f44a698e7db1c36c7dd779558e90fd78a8 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Wed, 2 Dec 2026 19:54:21 -0500 Subject: [PATCH] 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 --- OpenNest.Core/CNC/Thermal/HeatStepSchedule.cs | 19 +- .../CNC/Thermal/PlateHeatSimulation.cs | 310 ++++++++++++++++-- .../CNC/Thermal/ThermalParameters.cs | 6 + OpenNest.Tests/CNC/GpuHeatAcceleratorTests.cs | 6 +- .../CNC/PlateHeatSimulationTests.cs | 92 ++++++ docs/plate-heat-map.md | 39 ++- 6 files changed, 423 insertions(+), 49 deletions(-) diff --git a/OpenNest.Core/CNC/Thermal/HeatStepSchedule.cs b/OpenNest.Core/CNC/Thermal/HeatStepSchedule.cs index a6cd22b5..026da829 100644 --- a/OpenNest.Core/CNC/Thermal/HeatStepSchedule.cs +++ b/OpenNest.Core/CNC/Thermal/HeatStepSchedule.cs @@ -65,6 +65,16 @@ namespace OpenNest.CNC.Thermal /// split into. Past the cut, slots are whole. /// public (double Time, int Split) Next(double time) + { + var (slot, index, split) = StepAfter(time); + return (End(slot, index, split), split); + } + + /// + /// The step that ends first after : its slot, its place in the + /// slot (1 to the split) and the count the slot is split into. + /// + 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++; } } + /// When step (1 to ) of a slot ends. + 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) diff --git a/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs b/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs index a4d25fb3..b5f4916c 100644 --- a/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs +++ b/OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs @@ -25,8 +25,11 @@ namespace OpenNest.CNC.Thermal /// docs/plate-heat-map.md. /// /// - /// With 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 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. /// /// 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 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(); + var values = new List(); + 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); diff --git a/OpenNest.Core/CNC/Thermal/ThermalParameters.cs b/OpenNest.Core/CNC/Thermal/ThermalParameters.cs index 1387aeec..19dc7e56 100644 --- a/OpenNest.Core/CNC/Thermal/ThermalParameters.cs +++ b/OpenNest.Core/CNC/Thermal/ThermalParameters.cs @@ -70,6 +70,12 @@ namespace OpenNest.CNC.Thermal /// public IHeatAccelerator Accelerator { get; init; } + /// + /// Takes the short steps of cutting over the whole plate instead of only around the torch, + /// as an does. Slower; for comparing the two. + /// + internal bool WholePlateSteps { get; init; } + internal double MetersPerUnit => Units == Units.Millimeters ? 0.001 : 0.0254; internal double EffectiveGridContactSize => diff --git a/OpenNest.Tests/CNC/GpuHeatAcceleratorTests.cs b/OpenNest.Tests/CNC/GpuHeatAcceleratorTests.cs index 4c030209..a24d9970 100644 --- a/OpenNest.Tests/CNC/GpuHeatAcceleratorTests.cs +++ b/OpenNest.Tests/CNC/GpuHeatAcceleratorTests.cs @@ -9,8 +9,9 @@ namespace OpenNest.Tests.CNC; public class GpuHeatAcceleratorTests { // A framed part on slats: shared samples, a dropped slug, a part cut free and contact decay. + // The kernels take every step over the whole plate, so that is what they are compared with. private static (Plate Plate, CutSimulation Simulation, Func Thermal) Job( - SupportBed? bed) + SupportBed? bed, bool wholePlateSteps = false) { var program = new Program(); foreach (var (x, y, size) in new[] { (3.0, 3.0, 4.0), (0.0, 0.0, 10.0) }) @@ -39,6 +40,7 @@ public class GpuHeatAcceleratorTests CellSize = 0.25, SupportBed = bed, Accelerator = accelerator, + WholePlateSteps = wholePlateSteps, }); } @@ -56,7 +58,7 @@ public class GpuHeatAcceleratorTests private static void AssertMatchesTheProcessor(IHeatAccelerator accelerator, SupportBed? bed) { - var (plate, simulation, thermal) = Job(bed); + var (plate, simulation, thermal) = Job(bed, wholePlateSteps: true); var processor = new PlateHeatSimulation(plate, simulation, thermal(null)); using var heat = new PlateHeatSimulation(plate, simulation, thermal(accelerator)); Assert.True(heat.IsAccelerated); diff --git a/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs b/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs index b505eca4..fe3d600c 100644 --- a/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs +++ b/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs @@ -241,6 +241,98 @@ public class PlateHeatSimulationTests Assert.True(ripple < 0.1, $"peaks vary {ripple:P0} along the cut"); } + // Only the cells around the torch take the short steps of cutting. The picture has to stay + // close to the one from every cell taking them, at a slow feed and at one that crosses many + // cells in a step the rest of the plate takes. + [Theory] + [InlineData(100, 600)] + [InlineData(1600, 2000)] + public void ShortStepsAroundTheTorchGiveNearlyTheWholePlatesPicture(double feedrate, double rapid) + { + var plate = new Plate(48, 96); + plate.Parts.Add(new Part(new Drawing("frame", Frame(10, 6)), new Vector(4, 4))); + plate.Parts.Add(new Part(new Drawing("far", Frame(8, 3)), new Vector(60, 30))); + plate.Parts.Add(new Part(new Drawing("line", Line(20)), new Vector(20, 20.1))); + var simulation = CutSimulation.Build(plate, new CutParameters + { + Feedrate = feedrate, + RapidTravelRate = rapid, + PierceTime = TimeSpan.FromSeconds(0.2), + Units = Units.Inches, + }); + PlateHeatSimulation Run(bool wholePlateSteps) + { + var heat = new PlateHeatSimulation(plate, simulation, new ThermalParameters + { + Material = ThermalMaterial.MildSteel, + Thickness = 0.0598, + Units = Units.Inches, + CellSize = 0.25, + SupportBed = Slats, + WholePlateSteps = wholePlateSteps, + }); + heat.RunToEnd(TimeSpan.FromSeconds(5)); + return heat; + } + + var whole = Run(wholePlateSteps: true); + var around = Run(wholePlateSteps: false); + + // As the simulator colors it: the hottest half percent of peaks is full scale. + var hot = whole.Peaks.ToArray().Where(v => v > 0).Order().ToArray(); + var scale = hot[(int)(0.995 * (hot.Length - 1))]; + double[] Differences(ReadOnlySpan a, ReadOnlySpan b) + { + var differences = new double[a.Length]; + for (var i = 0; i < a.Length; i++) + differences[i] = System.Math.Abs(System.Math.Min(a[i], scale) - System.Math.Min(b[i], scale)) / scale; + Array.Sort(differences); + return differences; + } + + var peaks = Differences(whole.Peaks, around.Peaks); + var now = Differences(whole.Temperatures, around.Temperatures); + Assert.True(peaks[(int)(0.999 * (peaks.Length - 1))] < 0.03, $"peaks differ {peaks[(int)(0.999 * (peaks.Length - 1))]:P1} at the 99.9th percentile"); + Assert.True(peaks[^1] < 0.15, $"a peak differs {peaks[^1]:P1}"); + Assert.True(now[^1] < 0.03, $"a temperature differs {now[^1]:P1}"); + + double Sum(ReadOnlySpan values) + { + var sum = 0.0; + foreach (var value in values) + sum += value; + return sum; + } + Assert.Equal(Sum(whole.Temperatures), Sum(around.Temperatures), Sum(whole.Temperatures) * 1e-3); + } + + // A run stopped exactly on a step in the middle of a slot and carried on takes that slot's + // short steps in two lots, so it is no longer a straight run's: it may not leave checkpoints + // for a later seek to resume from. + [Fact] + public void StoppingOnAStepInsideASlotLeavesLaterSeeksExact() + { + var (plate, simulation) = Cut(Frame(10, 6), new Vector(8, 8)); + // Half-inch cells have one-second slots, cut into four at 100 in/min, so step ends are + // times a TimeSpan holds exactly. + var p = Thermal(20, Slats); + var schedule = new HeatStepSchedule(simulation, 1, 0.5, 1, 0.005); + var (slot, _, split) = schedule.StepAfter(simulation.TotalTime.TotalSeconds * 0.35); + Assert.Equal(4, split); + var stop = TimeSpan.FromSeconds(schedule.End(slot, 2, split)); + var later = TimeSpan.FromTicks((long)(simulation.TotalTime.Ticks * 0.8)); + + var heat = new PlateHeatSimulation(plate, simulation, p); + heat.AdvanceTo(stop); + heat.RunToEnd(); + heat.AdvanceTo(later); + + var straight = new PlateHeatSimulation(plate, simulation, p); + straight.AdvanceTo(later); + Assert.Equal(straight.Temperatures.ToArray(), heat.Temperatures.ToArray()); + Assert.Equal(straight.Peaks.ToArray(), heat.Peaks.ToArray()); + } + [Fact] public void CutoutSlugFallsAwayWithItsHeat() { diff --git a/docs/plate-heat-map.md b/docs/plate-heat-map.md index 74f212db..5f509c12 100644 --- a/docs/plate-heat-map.md +++ b/docs/plate-heat-map.md @@ -29,11 +29,23 @@ a removed heat-aware sequencer used a cheaper estimate of the same physics ([Seq that move's speed (half a cell where cells are under 4 mm), but not shorter than 5 ms for that. A step adds its heat all at once, so a longer one shows stripes along a straight cut; rapids and pierces keep the long steps (`HeatStepSchedule`). Splits come from a short list of counts, and - the boundaries depend on the timeline alone, so a replay takes the same steps. This limit does - not enter the choice of cell size, so a fast feed can take a few times longer to run. Sheet edges + the boundaries depend on the timeline alone, so a replay takes the same steps. 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. +- Short steps only around the torch: on the processor, the short steps of a slot are taken only by + the window of cells within four cells of where the torch put heat during those steps or during + the slot before them (which keeps the cells beside a fresh cut on short steps until their own + peak has passed). The cells touching the window hold their starting values meanwhile, and every + other cell takes one step as long as the short ones together (`StepInterval`). Heat moves about a + cell per slot, so the cells past the window change too slowly to need more. A piece that changes + inside a slot ends the long step there, and a new one starts; steps in which the torch adds no + heat are one long step for every cell. Compared with every cell taking the + short steps, on full sheets at 100 to 1600 in/min: peaks differ by under 1% of the color scale + at the 99th percentile and a few dozen cells of 115,200 by more than 5%, final temperatures by + under 0.1%, total heat by under 0.06%, and the stripe check is unchanged. For scale, halving + every step moves the peaks by 5-7% at the 99th percentile. So a fast feed no longer makes the + run longer. `ThermalParameters.WholePlateSteps` (internal) turns the window off for comparison. - 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 @@ -69,9 +81,10 @@ Each step runs a vector of cells at a time, with the links between neighbors of 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 scheduled step) keeps checkpoints of -the temperatures, peaks and event cursors, about every 500,000 cell updates and within 128 MB, -more widely spaced on large grids. The simulator's first run to the end, made to set the color +A straight run from the start (one never stopped short of a scheduled step, or partway through +a slot's run of short steps) keeps checkpoints of the temperatures, peaks and event cursors, about +every 500,000 cell updates of short steps and within 128 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 instead of the whole run, and gives exactly the state a straight run from @@ -92,15 +105,19 @@ a usable card, or when it fails while building or playing (out of memory, driver runs on the processor with the cell size that suits it. The simulation keeps the pieces, timeline and checkpoints and the card keeps the temperatures. -Its results are not bit for bit the processor's (devices may fuse a multiply and an add): measured -within one part in a million. The processor stays the reference. `GpuHeatAcceleratorTests` -compares the two within a tolerance, running the card's programs on ILGPU's processor emulation +On the card every cell takes the short steps, so its picture differs from the processor's by what +the window costs (above). Against the processor taking whole-plate steps too, its results are +within one part in a million, not bit for bit (devices may fuse a multiply and an add). The +processor stays the reference. `GpuHeatAcceleratorTests` compares the card with whole-plate steps +on the processor within a tolerance, running the card's programs on ILGPU's processor emulation everywhere and on a real card where there is one (skipped otherwise, as on build agents). A change to `DiffuseCells` or `Add` needs the same change in `OpenNest.Gpu/HeatKernels.cs`. -Measured on a Ryzen 7 3700X and an RTX 4060, two 5×10 ft nests, 100 and 400 in/min: 0.125 in -cells took 9-23 s on the processor and 0.8-1.6 s on the card with the previous step schedule, -which took more steps than this one. +Measured on a Ryzen 7 3700X and an RTX 4060, 5×10 ft nests, 0.25 in and 16 gauge mild steel at +100 to 1600 in/min, whole run: 0.25 in cells took 0.9-2.9 s on the processor before the window +and take 0.23-0.45 s with it; the card takes 0.45-1.0 s, most of it the fixed cost of starting +two programs per step, so at this cell size the processor is now the faster of the two. 0.125 in +cells take 1.3-6.2 s on the processor (11-22 s before) and 1.1-2.7 s on the card. ## Display