Files
OpenNest/OpenNest.Tests/CNC/PlateHeatSimulationTests.cs
T
ajandClaude Opus 5.5 af999ba5d6 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>
2026-12-01 13:09:13 -05:00

403 lines
16 KiB
C#

using OpenNest.CNC;
using OpenNest.CNC.Thermal;
using OpenNest.Geometry;
using OpenNest.Support;
namespace OpenNest.Tests.CNC;
public class PlateHeatSimulationTests
{
private static readonly CutParameters Cutting = new()
{
Feedrate = 100, // in/min
RapidTravelRate = 600,
PierceTime = TimeSpan.FromSeconds(1),
Units = Units.Inches,
};
private static ThermalParameters Thermal(double surfaceCoefficient = 0, SupportBed? bed = null,
double contactCoefficient = 200) => new()
{
Material = ThermalMaterial.MildSteel,
Thickness = 0.25,
Units = Units.Inches,
AbsorbedPower = 1000,
SurfaceCoefficient = surfaceCoefficient,
CellSize = 0.5,
SupportBed = bed,
ContactCoefficient = contactCoefficient,
};
// Joules per kelvin held by one cell of the grid above.
private static double CellCapacity(ThermalParameters p)
{
var dx = p.CellSize * 0.0254;
return p.Material.Density * p.Material.SpecificHeat * p.Thickness * 0.0254 * dx * dx;
}
// A part with one contour, its perimeter.
private static Program Square(double size)
{
var program = new Program();
program.Codes.Add(new RapidMove(0, 0));
program.Codes.Add(new LinearMove(0, size));
program.Codes.Add(new LinearMove(size, size));
program.Codes.Add(new LinearMove(size, 0));
program.Codes.Add(new LinearMove(0, 0));
return program;
}
// A square part with a square cutout in its middle: the hole counterclockwise, then the
// perimeter clockwise. A gap leaves the perimeter that far short of its start, as a tab does.
private static Program Frame(double size, double hole, double gap = 0)
{
var a = (size - hole) / 2;
var b = a + hole;
var program = new Program();
program.Codes.Add(new RapidMove(a, a));
program.Codes.Add(new LinearMove(b, a));
program.Codes.Add(new LinearMove(b, b));
program.Codes.Add(new LinearMove(a, b));
program.Codes.Add(new LinearMove(a, a));
program.Codes.Add(new RapidMove(0, 0));
program.Codes.Add(new LinearMove(0, size));
program.Codes.Add(new LinearMove(size, size));
program.Codes.Add(new LinearMove(size, 0));
program.Codes.Add(new LinearMove(gap, 0));
return program;
}
private static Program Line(double length)
{
var program = new Program();
program.Codes.Add(new RapidMove(0, 0));
program.Codes.Add(new LinearMove(length, 0));
return program;
}
private static (Plate Plate, CutSimulation Simulation) Cut(Program program, Vector location)
{
var plate = new Plate(48, 96);
plate.Parts.Add(new Part(new Drawing("part", program), location));
return (plate, CutSimulation.Build(plate, Cutting));
}
private static double TorchOnSeconds(CutSimulation simulation) => simulation.Steps
.Where(s => s.Kind is CutSimulationStepKind.Cut or CutSimulationStepKind.Pierce)
.Sum(s => s.Duration.TotalSeconds);
private static double TotalHeat(PlateHeatSimulation heat, ThermalParameters p)
{
var sum = 0.0;
foreach (var t in heat.Temperatures)
sum += t;
return sum * CellCapacity(p);
}
[Fact]
public void WithoutSurfaceLossAllAbsorbedEnergyStaysInTheSheet()
{
var (plate, simulation) = Cut(Line(20), new Vector(10, 10));
var p = Thermal();
var heat = new PlateHeatSimulation(plate, simulation, p);
heat.RunToEnd(TimeSpan.FromSeconds(30));
var expected = p.AbsorbedPower * TorchOnSeconds(simulation);
Assert.Equal(expected, TotalHeat(heat, p), expected * 1e-4);
}
[Fact]
public void SurfaceLossDecaysHeatExponentially()
{
var (plate, simulation) = Cut(Line(20), new Vector(10, 10));
var p = Thermal(surfaceCoefficient: 20);
var heat = new PlateHeatSimulation(plate, simulation, p);
heat.RunToEnd();
var atEnd = TotalHeat(heat, p);
heat.RunToEnd(TimeSpan.FromSeconds(120));
var thickness = p.Thickness * 0.0254;
var rate = 2 * p.SurfaceCoefficient / (p.Material.Density * p.Material.SpecificHeat * thickness);
Assert.Equal(System.Math.Exp(-rate * 120), TotalHeat(heat, p) / atEnd, 3);
}
private static PlateHeatSimulation Automatic(Plate plate) =>
new(plate, CutSimulation.Build(plate, Cutting), new ThermalParameters
{
Material = ThermalMaterial.MildSteel,
Thickness = 0.25,
Units = Units.Inches,
});
[Fact]
public void SmallPlateGetsFinerCells()
{
var plate = new Plate(6, 16);
plate.Parts.Add(new Part(new Drawing("part", Frame(4, 2)), new Vector(1, 1)));
Assert.Equal(0.5 / 8, Automatic(plate).CellSize);
}
[Fact]
public void LargePlateWithALongCutKeepsHalfInchCells()
{
var plate = new Plate(60, 120);
var drawing = new Drawing("part", Square(25));
for (var x = 0; x < 2; x++)
for (var y = 0; y < 4; y++)
plate.Parts.Add(new Part(drawing, new Vector(2 + x * 28, 2 + y * 28)));
Assert.Equal(0.5, Automatic(plate).CellSize);
}
[Fact]
public void HeatSpreadsFromTheCut()
{
var (plate, simulation) = Cut(Line(4), new Vector(20, 20));
var heat = new PlateHeatSimulation(plate, simulation, Thermal());
heat.RunToEnd();
var near = heat.CellAt(new Vector(22, 20.1));
var away = heat.CellAt(new Vector(22, 23.1));
Assert.True(heat.Temperatures[near] > 0);
var awayAtEnd = heat.Temperatures[away];
heat.RunToEnd(TimeSpan.FromSeconds(60));
Assert.True(heat.Temperatures[away] > awayAtEnd);
Assert.True(heat.Temperatures[near] < heat.Peaks[near]);
Assert.True(heat.Peaks[near] > heat.Peaks[away]);
}
[Fact]
public void CutoutSlugFallsAwayWithItsHeat()
{
// A 10 in part at (8, 8) with a 6 in hole from 10 to 16.
var (plate, simulation) = Cut(Frame(10, 6), new Vector(8, 8));
var heat = new PlateHeatSimulation(plate, simulation, Thermal());
heat.RunToEnd();
var inside = heat.CellAt(new Vector(13, 13));
Assert.True(heat.IsRemoved(inside));
Assert.Equal(0f, heat.Temperatures[inside]);
Assert.False(heat.IsRemoved(heat.CellAt(new Vector(9.25, 13))));
Assert.False(heat.IsRemoved(heat.CellAt(new Vector(5, 5))));
}
[Theory]
[InlineData(0)]
[InlineData(0.03)] // a tab leaves the perimeter open
public void PartAroundACutoutKeepsItsHeat(double gap)
{
var (plate, simulation) = Cut(Frame(10, 6, gap), new Vector(8, 8));
var heat = new PlateHeatSimulation(plate, simulation, Thermal());
heat.RunToEnd();
// The ring between the hole and the perimeter is the part, not a slug.
var ring = heat.CellAt(new Vector(9.25, 13.25));
Assert.False(heat.IsRemoved(ring));
Assert.True(heat.Temperatures[ring] > 0);
Assert.True(heat.IsRemoved(heat.CellAt(new Vector(13, 13))));
}
[Fact]
public void CutFreePartKeepsItsHeatAcrossTheKerf()
{
var (plate, simulation) = Cut(Square(6), new Vector(10, 10));
var heat = new PlateHeatSimulation(plate, simulation, Thermal());
heat.RunToEnd();
double PartHeat()
{
var sum = 0.0;
for (var i = 0; i < heat.Temperatures.Length; i++)
{
var c = heat.CellCenter(i);
if (c.X > 10 && c.X < 16 && c.Y > 10 && c.Y < 16)
sum += heat.Temperatures[i];
}
return sum;
}
var before = PartHeat();
heat.RunToEnd(TimeSpan.FromSeconds(120));
Assert.True(before > 0);
Assert.False(heat.IsRemoved(heat.CellAt(new Vector(13, 13))));
Assert.Equal(before, PartHeat(), before * 1e-4);
}
[Fact]
public void GoingBackInTimeReplaysTheSameState()
{
var (plate, simulation) = Cut(Frame(10, 6), new Vector(8, 8));
var heat = new PlateHeatSimulation(plate, simulation, Thermal(20));
var middle = TimeSpan.FromTicks(simulation.TotalTime.Ticks / 2);
heat.AdvanceTo(middle);
var first = heat.Temperatures.ToArray();
heat.RunToEnd();
heat.AdvanceTo(middle);
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);
[Fact]
public void CellOverASlatCoolsFasterThanOneBetweenSlats()
{
// The same cut on a slat's center line and midway between two slats.
double Retained(double y)
{
var (plate, simulation) = Cut(Line(4), new Vector(20, y));
var bare = new PlateHeatSimulation(plate, simulation, Thermal(20));
var onSlats = new PlateHeatSimulation(plate, simulation, Thermal(20, Slats));
bare.RunToEnd(TimeSpan.FromSeconds(60));
onSlats.RunToEnd(TimeSpan.FromSeconds(60));
var cell = onSlats.CellAt(new Vector(22, y));
return onSlats.Temperatures[cell] / bare.Temperatures[cell];
}
var over = Retained(10.25);
var between = Retained(12.25);
Assert.True(over < between, $"over a slat {over}, between slats {between}");
Assert.True(between < 1);
}
[Fact]
public void WithoutABedTheModelIsUnchanged()
{
var (plate, simulation) = Cut(Square(6), new Vector(10, 10));
var before = new PlateHeatSimulation(plate, simulation, Thermal(20));
before.RunToEnd(TimeSpan.FromSeconds(60));
// The plate's own bed is used only when passed in.
plate.SupportBed = Slats;
var after = new PlateHeatSimulation(plate, simulation, Thermal(20));
after.RunToEnd(TimeSpan.FromSeconds(60));
var noContact = new PlateHeatSimulation(plate, simulation, Thermal(20, Slats, contactCoefficient: 0));
noContact.RunToEnd(TimeSpan.FromSeconds(60));
Assert.False(after.UsesSupportBed);
Assert.True(after.SupportFractions.IsEmpty);
Assert.Equal(before.Temperatures.ToArray(), after.Temperatures.ToArray());
Assert.Equal(before.Peaks.ToArray(), after.Peaks.ToArray());
Assert.Equal(before.Temperatures.ToArray(), noContact.Temperatures.ToArray());
}
[Fact]
public void FullSlatContactDecaysHeatThroughBothPaths()
{
// Slats as wide as their pitch cover the whole sheet.
var (plate, simulation) = Cut(Line(20), new Vector(10, 10));
var p = Thermal(20, new SupportSlats(SlatAxis.Y, pitch: 1, thickness: 1, offset: 0.5), contactCoefficient: 300);
var heat = new PlateHeatSimulation(plate, simulation, p);
Assert.All(heat.SupportFractions.ToArray(), f => Assert.Equal(1f, f, 5));
heat.RunToEnd();
var atEnd = TotalHeat(heat, p);
heat.RunToEnd(TimeSpan.FromSeconds(60));
var thickness = p.Thickness * 0.0254;
var capacity = p.Material.Density * p.Material.SpecificHeat * thickness;
var rate = (2 * p.SurfaceCoefficient + p.ContactCoefficient) / capacity;
Assert.Equal(System.Math.Exp(-rate * 60), TotalHeat(heat, p) / atEnd, 3);
}
[Fact]
public void SlatFractionsFollowTheSlatsOverlapNotTheCells()
{
// 0.75 in slats centered on 2, 6, 10...: a half-inch cell from 9.5 to 10 is 3/4 on one.
var (plate, simulation) = Cut(Line(4), new Vector(20, 20));
var heat = new PlateHeatSimulation(plate, simulation,
Thermal(bed: new SupportSlats(SlatAxis.X, pitch: 4, thickness: 0.75, offset: 2)));
Assert.True(heat.UsesSupportBed);
Assert.Equal(0.75f, heat.SupportFractions[heat.CellAt(new Vector(30, 9.75))], 5);
Assert.Equal(0.75f, heat.SupportFractions[heat.CellAt(new Vector(30, 10.25))], 5);
Assert.Equal(0f, heat.SupportFractions[heat.CellAt(new Vector(30, 12.25))]);
}
[Theory]
[InlineData(1, 1, 1)]
[InlineData(2, -1, 1)]
[InlineData(3, -1, -1)]
[InlineData(4, 1, -1)]
public void SlatsAndGridPointsMirrorWithThePlateQuadrant(int quadrant, int signX, int signY)
{
var plate = new Plate(48, 96) { Quadrant = quadrant };
var simulation = CutSimulation.Build(plate, Cutting);
// Slats along X sit at Y = ±2, ±6...; slats along Y at X = ±2, ±6....
var alongX = new PlateHeatSimulation(plate, simulation, Thermal(bed: Slats));
Assert.Equal(1f, alongX.SupportFractions[alongX.CellAt(new Vector(signX * 30.25, signY * 2.25))]);
Assert.Equal(0f, alongX.SupportFractions[alongX.CellAt(new Vector(signX * 30.25, signY * 4.25))]);
var alongY = new PlateHeatSimulation(plate, simulation,
Thermal(bed: new SupportSlats(SlatAxis.Y, pitch: 4, thickness: 1, offset: 2)));
Assert.Equal(1f, alongY.SupportFractions[alongY.CellAt(new Vector(signX * 6.25, signY * 30.25))]);
Assert.Equal(0f, alongY.SupportFractions[alongY.CellAt(new Vector(signX * 4.25, signY * 30.25))]);
// Grid points at (±1.25, ±1.25) + 3 in steps, each on a 1/8 in pad in the middle of a cell.
var grid = new PlateHeatSimulation(plate, simulation, Thermal(bed: new SupportGrid(3, 3, 1.25, 1.25)));
var pad = 0.125 * 0.125 / (0.5 * 0.5);
Assert.Equal((float)pad, grid.SupportFractions[grid.CellAt(new Vector(signX * 4.25, signY * 7.25))], 5);
Assert.Equal(0f, grid.SupportFractions[grid.CellAt(new Vector(signX * 4.75, signY * 7.25))]);
}
[Theory]
[InlineData("304 Stainless", "Stainless steel")]
[InlineData("SS", "Stainless steel")]
[InlineData("Aluminum 5052", "Aluminum")]
[InlineData("A36", "Mild steel")]
[InlineData("", "Mild steel")]
public void MaterialNamesPickAPreset(string name, string expected) =>
Assert.Equal(expected, ThermalMaterial.ForName(name).Name);
}