From 97055c98be4dec1150831130de98ca5218ef153b Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Mon, 30 Nov 2026 22:46:07 -0500 Subject: [PATCH] feat(sequencing): add a parked heat-aware part sequencer Add SequenceMethod.HeatAware (100, outside PEP's numbering) and SequenceParameters.HeatWeight. HeatAwareSequencer orders parts forward by travel seconds plus the weight times the heat estimated where each part is cut, from HeatSpreadEstimate: a Gaussian blob per finished part that widens with conduction and fades with surface loss. Without a thickness it is nearest neighbor. PlateSequencing.Apply takes the sheet's thermal parameters for it and still places cut-offs as before. The method and weight persist in the cutting settings DTO. Plan Cutting does not use the method and no UI offers it: its strict search refuses rapids over parts cut free, so a heat-spreading order needs 53-78 head raises per plate on the measured nests. docs/plate-heat-map.md records the numbers; revisit once thermal readings calibrate the model. Co-Authored-By: Claude Opus 5.5 --- .../CuttingPlanning/OwnedCuttingParameters.cs | 3 +- .../CNC/CuttingPlanning/StateFingerprint.cs | 1 + .../CNC/CuttingStrategy/SequenceParameters.cs | 19 +- .../CNC/Thermal/HeatSpreadEstimate.cs | 107 +++++++++++ .../CNC/Thermal/ThermalParameters.cs | 12 ++ OpenNest.Engine/Sequencing/HeatAwareOrder.cs | 97 ++++++++++ .../Sequencing/HeatAwareSequencer.cs | 88 +++++++++ .../Sequencing/PartSequencerFactory.cs | 8 +- OpenNest.Engine/Sequencing/PlateSequencing.cs | 13 +- .../CuttingParametersSerializerTests.cs | 39 ++++ .../SupportGridPersistenceTests.cs | 16 ++ OpenNest.IO/CuttingParametersDto.cs | 1 + OpenNest.IO/CuttingParametersSerializer.cs | 4 + .../Sequencing/HeatAwareSequencerTests.cs | 167 ++++++++++++++++++ docs/nest-file-format.md | 3 + docs/plate-heat-map.md | 45 ++++- 16 files changed, 614 insertions(+), 9 deletions(-) create mode 100644 OpenNest.Core/CNC/Thermal/HeatSpreadEstimate.cs create mode 100644 OpenNest.Engine/Sequencing/HeatAwareOrder.cs create mode 100644 OpenNest.Engine/Sequencing/HeatAwareSequencer.cs create mode 100644 OpenNest.Tests/Sequencing/HeatAwareSequencerTests.cs diff --git a/OpenNest.Core/CNC/CuttingPlanning/OwnedCuttingParameters.cs b/OpenNest.Core/CNC/CuttingPlanning/OwnedCuttingParameters.cs index 2472b0c1..f09c5903 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/OwnedCuttingParameters.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/OwnedCuttingParameters.cs @@ -57,7 +57,8 @@ internal static class OwnedCuttingParameters DistanceMediumSmall = Dimension(sequence.DistanceMediumSmall), AlternateRowsColumns = sequence.AlternateRowsColumns, AlternateCutoutsWithinRowColumn = sequence.AlternateCutoutsWithinRowColumn, - MinDistanceBetweenRowsColumns = Dimension(sequence.MinDistanceBetweenRowsColumns) + MinDistanceBetweenRowsColumns = Dimension(sequence.MinDistanceBetweenRowsColumns), + HeatWeight = Dimension(sequence.HeatWeight) }, Assignment = new AssignmentParameters { diff --git a/OpenNest.Core/CNC/CuttingPlanning/StateFingerprint.cs b/OpenNest.Core/CNC/CuttingPlanning/StateFingerprint.cs index f4a5009e..73bc19b3 100644 --- a/OpenNest.Core/CNC/CuttingPlanning/StateFingerprint.cs +++ b/OpenNest.Core/CNC/CuttingPlanning/StateFingerprint.cs @@ -120,6 +120,7 @@ internal static class StateFingerprint Flag(s.AlternateRowsColumns); Flag(s.AlternateCutoutsWithinRowColumn); Number(s.MinDistanceBetweenRowsColumns); + Number(s.HeatWeight); text.Append('}'); } diff --git a/OpenNest.Core/CNC/CuttingStrategy/SequenceParameters.cs b/OpenNest.Core/CNC/CuttingStrategy/SequenceParameters.cs index 75c32bb2..2493a071 100644 --- a/OpenNest.Core/CNC/CuttingStrategy/SequenceParameters.cs +++ b/OpenNest.Core/CNC/CuttingStrategy/SequenceParameters.cs @@ -1,6 +1,7 @@ namespace OpenNest.CNC.CuttingStrategy { - // Values match PEP Technology's numbering scheme (value 6 intentionally skipped) + // Values 1-8 match PEP Technology's numbering scheme (value 6 intentionally skipped); + // OpenNest's own methods start at 100, outside PEP's range. public enum SequenceMethod { RightSide = 1, @@ -10,10 +11,20 @@ namespace OpenNest.CNC.CuttingStrategy EdgeStart = 5, LeftSide = 7, RightSideAlt = 8, + + /// + /// Travel time plus times the estimated heat + /// where each candidate part starts: it leaves the hot zone, but goes no further than that. + /// See docs/plate-heat-map.md. + /// + HeatAware = 100, } public class SequenceParameters { + /// The new parameters start with, in seconds per °C. + public const double DefaultHeatWeight = 0.15; + public SequenceMethod Method { get; set; } = SequenceMethod.Advanced; public double SmallCutoutWidth { get; set; } = 1.5; public double SmallCutoutHeight { get; set; } = 1.5; @@ -23,5 +34,11 @@ namespace OpenNest.CNC.CuttingStrategy public bool AlternateRowsColumns { get; set; } = true; public bool AlternateCutoutsWithinRowColumn { get; set; } = true; public double MinDistanceBetweenRowsColumns { get; set; } = 0.25; + + /// + /// only: seconds of travel worth one °C less heat + /// where the next part starts. Zero orders by travel alone (nearest neighbor). + /// + public double HeatWeight { get; set; } = DefaultHeatWeight; } } diff --git a/OpenNest.Core/CNC/Thermal/HeatSpreadEstimate.cs b/OpenNest.Core/CNC/Thermal/HeatSpreadEstimate.cs new file mode 100644 index 00000000..2cb4666c --- /dev/null +++ b/OpenNest.Core/CNC/Thermal/HeatSpreadEstimate.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using OpenNest.Geometry; + +namespace OpenNest.CNC.Thermal +{ + /// + /// A cheap stand-in for for choosing a cut order: each finished + /// part leaves a Gaussian blob of the heat its cut put in (absorbed power times its torch-on + /// time), as wide as the part to begin with, widening as the heat conducts (4αΔt) and fading + /// with the loss from both faces. It ignores kerfs and dropped slugs. Like the grid model, its + /// temperatures are relative, for comparing orders. See docs/plate-heat-map.md. + /// + public sealed class HeatSpreadEstimate + { + /// + /// The most recent parts whose heat is summed; older blobs have spread into a near-uniform + /// background that hardly changes which part is next, and leaving them out keeps a large + /// plate's order from growing with the cube of its part count. + /// + public const int MaxDeposits = 200; + + private readonly List deposits = new(); + private readonly double diffusivity; + private readonly double heatCapacity; + private readonly double loss; + private readonly double squareMeters; + + public HeatSpreadEstimate(ThermalParameters thermal) + { + Thermal = thermal ?? throw new ArgumentNullException(nameof(thermal)); + var meters = thermal.MetersPerUnit; + var material = thermal.Material; + var thickness = thermal.Thickness * meters; + HasThickness = double.IsFinite(thermal.Thickness) && thermal.Thickness > 0; + diffusivity = material.Diffusivity / (meters * meters); + heatCapacity = material.Density * material.SpecificHeat * thickness; + loss = HasThickness ? 2 * thermal.SurfaceCoefficient / heatCapacity : 0; + squareMeters = meters * meters; + + // Stand-in feeds until the controller's process tables are known; the same ones the + // order comparisons in docs/plate-heat-map.md were made with. + var inches = HasThickness ? thermal.Thickness * meters / 0.0254 : 0; + var inchesPerMinute = inches <= 0.135 ? 400 : inches <= 0.26 ? 150 : 80; + var unitsPerInch = 0.0254 / meters; + FeedRate = inchesPerMinute * unitsPerInch / 60; + RapidRate = 3000 * unitsPerInch / 60; + PierceSeconds = inches <= 0.26 ? 0.5 : 1.5; + } + + public ThermalParameters Thermal { get; } + + /// False when the thickness is missing: the estimate is then always zero. + public bool HasThickness { get; } + + /// Stand-in cutting feed for the thickness, in units per second. + public double FeedRate { get; } + + /// Stand-in head-up travel rate, in units per second. + public double RapidRate { get; } + + /// Stand-in pierce dwell for the thickness, in seconds. + public double PierceSeconds { get; } + + /// Torch-on seconds for a part with this much cut length and these pierces. + public double TorchSeconds(double cutLength, int pierces) => + System.Math.Max(0, cutLength) / FeedRate + System.Math.Max(0, pierces) * PierceSeconds; + + /// Seconds to travel head-up. + public double TravelSeconds(double distance) => distance / RapidRate; + + /// + /// Adds a finished part's heat: of absorbed power centered + /// at , spread to begin with over + /// (square units; a quarter of the part's squared diagonal), as of + /// seconds into the cut. + /// + public void Add(Vector center, double spread2, double torchSeconds, double time) + { + if (!HasThickness || torchSeconds <= 0) + return; + if (deposits.Count == MaxDeposits) + deposits.RemoveAt(0); + deposits.Add(new(center, Thermal.AbsorbedPower * torchSeconds, time, System.Math.Max(spread2, 0))); + } + + /// The estimated temperature rise, in °C, at and . + public double TemperatureAt(Vector at, double time) + { + var total = 0.0; + foreach (var deposit in deposits) + { + var elapsed = System.Math.Max(0, time - deposit.Time); + var spread2 = 4 * diffusivity * elapsed + deposit.Spread2; + if (spread2 <= 0) + continue; + var dx = at.X - deposit.Center.X; + var dy = at.Y - deposit.Center.Y; + total += deposit.Energy / (heatCapacity * System.Math.PI * spread2 * squareMeters) + * System.Math.Exp(-(dx * dx + dy * dy) / spread2 - loss * elapsed); + } + return total; + } + + private readonly record struct Deposit(Vector Center, double Energy, double Time, double Spread2); + } +} diff --git a/OpenNest.Core/CNC/Thermal/ThermalParameters.cs b/OpenNest.Core/CNC/Thermal/ThermalParameters.cs index 7bb1d855..6037f668 100644 --- a/OpenNest.Core/CNC/Thermal/ThermalParameters.cs +++ b/OpenNest.Core/CNC/Thermal/ThermalParameters.cs @@ -3,6 +3,18 @@ namespace OpenNest.CNC.Thermal /// Inputs to . Lengths are in the plate's units. public sealed class ThermalParameters { + /// + /// Parameters for a sheet of this stock material name and grade + /// () and thickness, with the default power and loss. + /// + public static ThermalParameters For(string materialName, string grade, double thickness, Units units) => + new() + { + Material = ThermalMaterial.ForName($"{materialName} {grade}"), + Thickness = thickness, + Units = units, + }; + public ThermalMaterial Material { get; init; } = ThermalMaterial.MildSteel; /// Sheet thickness in . diff --git a/OpenNest.Engine/Sequencing/HeatAwareOrder.cs b/OpenNest.Engine/Sequencing/HeatAwareOrder.cs new file mode 100644 index 00000000..d42bc7ea --- /dev/null +++ b/OpenNest.Engine/Sequencing/HeatAwareOrder.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using OpenNest.CNC.Thermal; +using OpenNest.Geometry; + +namespace OpenNest.Engine.Sequencing +{ + /// + /// What the heat-aware order needs of one part: where its cut starts and ends, its cut extent + /// (where its heat goes) and how long the torch is on. + /// + internal readonly record struct HeatAwareItem(Vector Entry, Vector Exit, Box Extent, double TorchSeconds) + { + internal Vector Center => Extent.Center; + + /// The heat's initial spread: a quarter of the extent's squared diagonal. + internal double Spread2 => (Extent.Length * Extent.Length + Extent.Width * Extent.Width) / 4; + } + + /// + /// Orders parts forward from a start point: each next part is the dependency-ready one with the + /// least travel seconds plus weight times the estimated heat (°C) at its center when the + /// tool gets there, from a of the parts already cut. So the + /// route leaves a hot zone, but only as far as it must. Without a thickness, or with no weight, + /// it is a nearest-neighbor order by travel. It ignores whether a move passes over parts already + /// cut; see docs/plate-heat-map.md#sequencing. + /// + internal static class HeatAwareOrder + { + /// Every part's data, by ordinal. + /// The ordinals to order; prerequisites outside this set count as cut. + /// The tool position before the first part. + /// Ordinals that must come before each part; must be acyclic. + /// Parts already cut, in order, from : their heat + /// is laid down first. Null for none. + /// Where the tool was before . + internal static int[] Plan(IReadOnlyList items, IReadOnlyList parts, Vector start, + IReadOnlyList> prerequisites, ThermalParameters thermal, double weight, + CancellationToken token, IReadOnlyList done = null, Vector? origin = null) + { + var estimate = new HeatSpreadEstimate(thermal ?? new ThermalParameters()); + var heated = estimate.HasThickness && double.IsFinite(weight) && weight > 0; + + var time = 0.0; + if (done is { Count: > 0 }) + { + var position = origin ?? start; + foreach (var part in done) + { + var item = items[part]; + time += estimate.TravelSeconds(position.DistanceTo(item.Entry)) + item.TorchSeconds; + estimate.Add(item.Center, item.Spread2, item.TorchSeconds, time); + position = item.Exit; + } + } + + var pending = new HashSet(parts); + var remaining = parts.ToList(); + var order = new int[parts.Count]; + var current = start; + for (var step = 0; step < order.Length; step++) + { + token.ThrowIfCancellationRequested(); + var best = -1; + var bestCost = double.MaxValue; + foreach (var part in remaining) + { + if (prerequisites[part].Any(pending.Contains)) + continue; + var item = items[part]; + var travel = estimate.TravelSeconds(current.DistanceTo(item.Entry)); + var cost = heated ? travel + weight * estimate.TemperatureAt(item.Center, time + travel) : travel; + // Strictly cheaper only, so ties keep the given order. + if (cost < bestCost) + { + best = part; + bestCost = cost; + } + } + if (best < 0) + throw new InvalidOperationException("Part prerequisites form a cycle."); + + var chosen = items[best]; + time += estimate.TravelSeconds(current.DistanceTo(chosen.Entry)) + chosen.TorchSeconds; + if (heated) + estimate.Add(chosen.Center, chosen.Spread2, chosen.TorchSeconds, time); + current = chosen.Exit; + order[step] = best; + pending.Remove(best); + remaining.Remove(best); + } + return order; + } + } +} diff --git a/OpenNest.Engine/Sequencing/HeatAwareSequencer.cs b/OpenNest.Engine/Sequencing/HeatAwareSequencer.cs new file mode 100644 index 00000000..a977ab74 --- /dev/null +++ b/OpenNest.Engine/Sequencing/HeatAwareSequencer.cs @@ -0,0 +1,88 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using OpenNest.CNC; +using OpenNest.CNC.CuttingStrategy; +using OpenNest.CNC.Thermal; +using OpenNest.Converters; +using OpenNest.Geometry; + +namespace OpenNest.Engine.Sequencing +{ + /// + /// : cuts forward from the plate's origin corner, each next + /// part the one with the least travel seconds plus + /// times the estimated heat where it is cut (). Each part's cut + /// length, pierces, entry and exit come from its program as it stands. Cut-offs carry no heat + /// here and go last; + /// then moves each before the parts it crosses. Without a thickness the order is nearest neighbor. + /// Like every sequencer it returns the route exit-first, so the forward order comes back reversed. + /// + public class HeatAwareSequencer : IPartSequencer + { + private readonly SequenceParameters parameters; + private readonly ThermalParameters thermal; + + /// The sheet's material and thickness; null orders by travel alone. + public HeatAwareSequencer(SequenceParameters parameters, ThermalParameters thermal) + { + this.parameters = parameters; + this.thermal = thermal; + } + + public List Sequence(IReadOnlyList parts, Plate plate) + { + if (parts.Count == 0) + return new List(); + + var heated = parts.Where(p => !p.BaseDrawing.IsCutOff).ToList(); + var estimate = new HeatSpreadEstimate(thermal ?? new ThermalParameters()); + var items = heated.Select(part => ItemOf(part, estimate)).ToArray(); + var none = new IReadOnlyCollection[items.Length]; + System.Array.Fill(none, System.Array.Empty()); + var bounds = plate.BoundingBox(includeParts: false); + var order = HeatAwareOrder.Plan(items, Enumerable.Range(0, items.Length).ToArray(), + new Vector(bounds.X, bounds.Y), none, thermal, parameters.HeatWeight, CancellationToken.None); + + var forward = order.Select(i => heated[i]).Concat(parts.Where(p => p.BaseDrawing.IsCutOff)); + return forward.Reverse().Select(part => new SequencedPart { Part = part }).ToList(); + } + + private static HeatAwareItem ItemOf(Part part, HeatSpreadEstimate estimate) + { + var box = part.BoundingBox; + var entities = ConvertProgram.ToGeometry(DisplayPerimeterTail.WithoutTail(part.Program)) + .Where(entity => entity is Line or Arc).ToList(); + var length = 0.0; + var pierces = 0; + var torchOn = false; + Vector? entry = null; + var exit = box.Center; + foreach (var entity in entities) + { + var cuts = CutsMaterial(entity.Layer); + if (cuts) + { + length += entity.Length; + if (!torchOn) + pierces++; + entry ??= Start(entity) + part.Location; + exit = End(entity) + part.Location; + } + torchOn = cuts; + } + return entry is { } start + ? new HeatAwareItem(start, exit, box, estimate.TorchSeconds(length, pierces)) + : new HeatAwareItem(box.Center, box.Center, box, 0); + } + + // Layers cut with the torch on (scribes etch, rapids and tabs travel head-up or uncut). + private static bool CutsMaterial(Layer layer) => + layer == SpecialLayers.Cut || layer == SpecialLayers.Display || layer == SpecialLayers.Leadin + || layer == SpecialLayers.Leadout || layer == SpecialLayers.Break; + + private static Vector Start(Entity entity) => entity is Line line ? line.StartPoint : ((Arc)entity).StartPoint(); + + private static Vector End(Entity entity) => entity is Line line ? line.EndPoint : ((Arc)entity).EndPoint(); + } +} diff --git a/OpenNest.Engine/Sequencing/PartSequencerFactory.cs b/OpenNest.Engine/Sequencing/PartSequencerFactory.cs index 85a837a1..1522be10 100644 --- a/OpenNest.Engine/Sequencing/PartSequencerFactory.cs +++ b/OpenNest.Engine/Sequencing/PartSequencerFactory.cs @@ -1,11 +1,16 @@ using System; using OpenNest.CNC.CuttingStrategy; +using OpenNest.CNC.Thermal; namespace OpenNest.Engine.Sequencing { public static class PartSequencerFactory { - public static IPartSequencer Create(SequenceParameters parameters) + /// + /// The sheet's material and thickness, which only + /// reads; without them it orders by travel alone. + /// + public static IPartSequencer Create(SequenceParameters parameters, ThermalParameters thermal = null) { return parameters.Method switch { @@ -15,6 +20,7 @@ namespace OpenNest.Engine.Sequencing SequenceMethod.EdgeStart => new EdgeStartSequencer(), SequenceMethod.LeastCode => new LeastCodeSequencer(), SequenceMethod.Advanced => new AdvancedSequencer(parameters), + SequenceMethod.HeatAware => new HeatAwareSequencer(parameters, thermal), _ => throw new NotSupportedException( $"Sequence method '{parameters.Method}' is not supported." ), diff --git a/OpenNest.Engine/Sequencing/PlateSequencing.cs b/OpenNest.Engine/Sequencing/PlateSequencing.cs index b81111fc..dc5d5eff 100644 --- a/OpenNest.Engine/Sequencing/PlateSequencing.cs +++ b/OpenNest.Engine/Sequencing/PlateSequencing.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using OpenNest.CNC.CuttingStrategy; +using OpenNest.CNC.Thermal; using OpenNest.CutOffs; using OpenNest.Engine.CuttingPlanning; @@ -10,18 +11,22 @@ namespace OpenNest.Engine.Sequencing public static class PlateSequencing { /// Sequences the plates present when the operation starts. - public static void ApplyAll(IEnumerable plates, SequenceParameters parameters) + /// The sheets' material and thickness, for + /// ; see . + public static void ApplyAll(IEnumerable plates, SequenceParameters parameters, ThermalParameters thermal = null) { // Reordering parts can make PlateManager replace the trailing empty // plate. Snapshot before applying so those events cannot invalidate // enumeration of the nest's live plate collection. foreach (var plate in plates.ToArray()) - Apply(plate, parameters); + Apply(plate, parameters, thermal); } - public static void Apply(Plate plate, SequenceParameters parameters) + /// The sheet's material and thickness, for + /// ; see . + public static void Apply(Plate plate, SequenceParameters parameters, ThermalParameters thermal = null) { - var sequencer = PartSequencerFactory.Create(parameters); + var sequencer = PartSequencerFactory.Create(parameters, thermal); // Cut-first parts (test coupons) get their own route ahead of the rest, // so they stay grouped instead of interleaving with the main route. diff --git a/OpenNest.IO.Tests/CuttingParametersSerializerTests.cs b/OpenNest.IO.Tests/CuttingParametersSerializerTests.cs index eb70e48f..1cc7de0e 100644 --- a/OpenNest.IO.Tests/CuttingParametersSerializerTests.cs +++ b/OpenNest.IO.Tests/CuttingParametersSerializerTests.cs @@ -74,6 +74,7 @@ public class CuttingParametersSerializerTests [InlineData(SequenceMethod.EdgeStart)] [InlineData(SequenceMethod.LeftSide)] [InlineData(SequenceMethod.RightSideAlt)] + [InlineData(SequenceMethod.HeatAware)] public void SettingsRoundTrip_PreservesAllFieldsAndSequenceMethods(SequenceMethod method) { var original = CreateParameters(); @@ -83,6 +84,43 @@ public class CuttingParametersSerializerTests AssertEquivalent(original, RoundTrip(original)); } + [Fact] + public void HeatAwareOrder_RoundTripsAsItsNumberWithItsWeight() + { + var original = new CuttingParameters + { + Sequencing = new SequenceParameters { Method = SequenceMethod.HeatAware, HeatWeight = 0.4 }, + }; + + var json = CuttingParametersSerializer.Serialize(original); + var restored = CuttingParametersSerializer.Deserialize(json); + + // Written as PEP-style numbers; OpenNest's own methods are numbered outside PEP's range. + Assert.Contains("\"method\":100", json); + Assert.Contains("\"heatWeight\":0.4", json); + Assert.Equal(SequenceMethod.HeatAware, restored.Sequencing.Method); + Assert.Equal(0.4, restored.Sequencing.HeatWeight); + } + + [Fact] + public void Deserialize_SequencingWithoutHeatWeight_UsesTheDefaultWeight() + { + var restored = CuttingParametersSerializer.Deserialize("""{ "sequencing": { "method": 3 } }"""); + + Assert.Equal(SequenceMethod.Advanced, restored.Sequencing.Method); + Assert.Equal(SequenceParameters.DefaultHeatWeight, restored.Sequencing.HeatWeight); + } + + [Fact] + public void Deserialize_NegativeHeatWeight_UsesTheDefaultWeight() + { + var restored = CuttingParametersSerializer.Deserialize( + """{ "sequencing": { "method": 100, "heatWeight": -2 } }"""); + + Assert.Equal(SequenceMethod.HeatAware, restored.Sequencing.Method); + Assert.Equal(SequenceParameters.DefaultHeatWeight, restored.Sequencing.HeatWeight); + } + [Fact] public void Deserialize_LegacySettings_PreservesValuesAndUsesMissingFieldDefaults() { @@ -341,6 +379,7 @@ public class CuttingParametersSerializerTests AlternateRowsColumns = false, AlternateCutoutsWithinRowColumn = false, MinDistanceBetweenRowsColumns = 0.8, + HeatWeight = 0.35, }, }; diff --git a/OpenNest.IO.Tests/SupportGridPersistenceTests.cs b/OpenNest.IO.Tests/SupportGridPersistenceTests.cs index a60141e7..da9b0a2e 100644 --- a/OpenNest.IO.Tests/SupportGridPersistenceTests.cs +++ b/OpenNest.IO.Tests/SupportGridPersistenceTests.cs @@ -121,6 +121,22 @@ public class SupportGridPersistenceTests Assert.Equal(0, CuttingParametersSerializer.Deserialize("{}").TabSizeMaxWidth); } + [Fact] + public void HeatAwarePartOrderRoundTripsInAPlatesCuttingParameters() + { + var nest = NestWith(null); + nest.Plates[0].CuttingParameters = new CuttingParameters + { + Sequencing = new SequenceParameters { Method = SequenceMethod.HeatAware, HeatWeight = 0.25 }, + }; + + var (restored, _) = RoundTrip(ArchiveBytes(nest)); + + var sequencing = restored.Plates[0].CuttingParameters.Sequencing; + Assert.Equal(SequenceMethod.HeatAware, sequencing.Method); + Assert.Equal(0.25, sequencing.HeatWeight); + } + [Fact] public void SettingsSavedWithTheRetiredTabHeldLengthStillRead() { diff --git a/OpenNest.IO/CuttingParametersDto.cs b/OpenNest.IO/CuttingParametersDto.cs index 72423364..c096f5c2 100644 --- a/OpenNest.IO/CuttingParametersDto.cs +++ b/OpenNest.IO/CuttingParametersDto.cs @@ -113,6 +113,7 @@ public class CuttingParametersDto public bool AlternateRowsColumns { get; set; } = true; public bool AlternateCutoutsWithinRowColumn { get; set; } = true; public double MinDistanceBetweenRowsColumns { get; set; } = 0.25; + public double HeatWeight { get; set; } = SequenceParameters.DefaultHeatWeight; } public class AssignmentDto diff --git a/OpenNest.IO/CuttingParametersSerializer.cs b/OpenNest.IO/CuttingParametersSerializer.cs index c9f1939b..a84d2cd1 100644 --- a/OpenNest.IO/CuttingParametersSerializer.cs +++ b/OpenNest.IO/CuttingParametersSerializer.cs @@ -290,6 +290,7 @@ public static class CuttingParametersSerializer AlternateRowsColumns = parameters.AlternateRowsColumns, AlternateCutoutsWithinRowColumn = parameters.AlternateCutoutsWithinRowColumn, MinDistanceBetweenRowsColumns = parameters.MinDistanceBetweenRowsColumns, + HeatWeight = parameters.HeatWeight, }; private static SequenceParameters FromSequenceDto(SequenceDto dto) => dto == null @@ -305,6 +306,9 @@ public static class CuttingParametersSerializer AlternateRowsColumns = dto.AlternateRowsColumns, AlternateCutoutsWithinRowColumn = dto.AlternateCutoutsWithinRowColumn, MinDistanceBetweenRowsColumns = dto.MinDistanceBetweenRowsColumns, + // A negative or nonfinite weight cannot be meant; it reads as the default. + HeatWeight = double.IsFinite(dto.HeatWeight) && dto.HeatWeight >= 0 + ? dto.HeatWeight : SequenceParameters.DefaultHeatWeight, }; private static AssignmentDto ToAssignmentDto(AssignmentParameters parameters) => parameters == null diff --git a/OpenNest.Tests/Sequencing/HeatAwareSequencerTests.cs b/OpenNest.Tests/Sequencing/HeatAwareSequencerTests.cs new file mode 100644 index 00000000..aaa2fafb --- /dev/null +++ b/OpenNest.Tests/Sequencing/HeatAwareSequencerTests.cs @@ -0,0 +1,167 @@ +using OpenNest.CNC.CuttingStrategy; +using OpenNest.CNC.Thermal; +using OpenNest.CutOffs; +using OpenNest.Engine.Sequencing; +using OpenNest.Geometry; + +namespace OpenNest.Tests.Sequencing; + +public class HeatAwareSequencerTests +{ + private static readonly ThermalParameters QuarterInchSteel = ThermalParameters.For("Mild steel", "A36", 0.25, Units.Inches); + + private static readonly IReadOnlyCollection[] NoPrerequisites = [[], [], []]; + + // A long hot part beside a short cool one, and another short one far along. + private static HeatAwareItem[] HotNeighbor() => + [ + Item(1, 0, 60), + Item(2, 0, 10), + Item(20, 0, 10), + ]; + + private static HeatAwareItem Item(double x, double y, double seconds) => + new(new Vector(x, y), new Vector(x, y), new Box(x - 0.5, y - 0.5, 1, 1), seconds); + + [Fact] + public void WithoutWeight_ItIsNearestNeighbor() + { + var order = HeatAwareOrder.Plan(HotNeighbor(), [0, 1, 2], Vector.Zero, NoPrerequisites, + QuarterInchSteel, 0, default); + + Assert.Equal([0, 1, 2], order); + } + + [Fact] + public void WithoutThickness_ItIsNearestNeighbor() + { + var order = HeatAwareOrder.Plan(HotNeighbor(), [0, 1, 2], Vector.Zero, NoPrerequisites, + ThermalParameters.For("Mild steel", "A36", 0, Units.Inches), 0.15, default); + + Assert.Equal([0, 1, 2], order); + } + + [Fact] + public void AHotNeighbor_IsLeftUntilTheRouteComesBack() + { + var order = HeatAwareOrder.Plan(HotNeighbor(), [0, 1, 2], Vector.Zero, NoPrerequisites, + QuarterInchSteel, 0.15, default); + + Assert.Equal([0, 2, 1], order); + } + + [Fact] + public void ItGoesOnlyAsFarAsTheHotZone() + { + // Two cool parts beyond the hot neighbor: the nearer one clear of the heat comes next, + // not the farthest. + HeatAwareItem[] items = [Item(1, 0, 60), Item(2, 0, 10), Item(12, 0, 10), Item(40, 0, 10)]; + + var order = HeatAwareOrder.Plan(items, [0, 1, 2, 3], Vector.Zero, [[], [], [], []], + QuarterInchSteel, 0.15, default); + + Assert.Equal(0, order[0]); + Assert.Equal(2, order[1]); + } + + [Fact] + public void APrerequisite_StillComesFirst() + { + // The hot neighbor must follow the first part (as a nested part precedes its host). + IReadOnlyCollection[] prerequisites = [[], [0], []]; + + var order = HeatAwareOrder.Plan(HotNeighbor(), [1, 0, 2], Vector.Zero, prerequisites, + QuarterInchSteel, 0.15, default); + + Assert.True(Array.IndexOf(order, 0) < Array.IndexOf(order, 1)); + Assert.Equal([0, 1, 2], order.Order()); + } + + [Fact] + public void PartsAlreadyCut_LeaveTheirHeat() + { + // Re-planning parts 1 and 2 after part 0 was cut: part 1 sits in part 0's heat. + var order = HeatAwareOrder.Plan(HotNeighbor(), [1, 2], new Vector(1, 0), NoPrerequisites, + QuarterInchSteel, 0.15, default, done: [0], origin: Vector.Zero); + + Assert.Equal([2, 1], order); + } + + [Fact] + public void Estimate_FadesAndSpreadsWithTime() + { + var estimate = new HeatSpreadEstimate(QuarterInchSteel); + estimate.Add(Vector.Zero, 0.5, 30, 0); + + var atOnce = estimate.TemperatureAt(Vector.Zero, 0); + var later = estimate.TemperatureAt(Vector.Zero, 60); + var aside = estimate.TemperatureAt(new Vector(3, 0), 0); + var asideLater = estimate.TemperatureAt(new Vector(3, 0), 60); + + Assert.True(atOnce > later); + Assert.True(aside < atOnce); + Assert.True(asideLater > aside, "Heat conducts outward."); + } + + [Fact] + public void Sequencer_ReturnsTheForwardOrderExitFirst() + { + var plate = new Plate(60, 30); + var parts = Enumerable.Range(0, 3).Select(i => TestHelpers.MakePartAt(5 + i * 10, 5)).ToList(); + foreach (var part in parts) + plate.Parts.Add(part); + + // No thickness: nearest neighbor from the plate's origin corner. + var result = new HeatAwareSequencer(new SequenceParameters { Method = SequenceMethod.HeatAware }, null) + .Sequence(parts, plate); + + Assert.Equal(new[] { parts[2], parts[1], parts[0] }, result.Select(r => r.Part)); + } + + [Fact] + public void Apply_CutsAHotNeighborLater() + { + // Ten small squares in a row; with a heavy weight the next part is never the one beside + // the part just cut. + var plate = new Plate(120, 20); + var parts = Enumerable.Range(0, 10).Select(i => TestHelpers.MakePartAt(1 + i * 1.5, 1)).ToList(); + foreach (var part in parts) + plate.Parts.Add(part); + var parameters = new SequenceParameters { Method = SequenceMethod.HeatAware, HeatWeight = 5 }; + + PlateSequencing.Apply(plate, parameters, QuarterInchSteel); + + var order = plate.Parts.Select(part => parts.IndexOf(part)).ToArray(); + Assert.Equal(Enumerable.Range(0, 10), order.Order()); + Assert.Equal(0, order[0]); + Assert.Contains(order.Zip(order.Skip(1)), pair => System.Math.Abs(pair.First - pair.Second) > 1); + } + + [Fact] + public void Apply_KeepsCutOffsBeforeThePartsTheyCross() + { + var plate = new Plate(60, 30); + var left = TestHelpers.MakePartAt(5, 5); + var right = TestHelpers.MakePartAt(40, 5); + plate.Parts.Add(left); + plate.Parts.Add(right); + plate.CutOffs.Add(new CutOff(new Vector(20, 0), CutOffAxis.Vertical)); + plate.RegenerateCutOffs(new CutOffSettings()); + + PlateSequencing.Apply(plate, new SequenceParameters { Method = SequenceMethod.HeatAware }, QuarterInchSteel); + + var applied = plate.Parts.ToList(); + Assert.Contains(applied, p => p.BaseDrawing.IsCutOff); + Assert.Equal(2, applied.Count(p => !p.BaseDrawing.IsCutOff)); + // The cut-off rules already hold: applying them again changes nothing. + Assert.Equal(applied, PlateSequencing.OrderCutOffsFirst(applied, plate)); + } + + [Fact] + public void Factory_CreatesTheHeatAwareSequencer() + { + var sequencer = PartSequencerFactory.Create(new SequenceParameters { Method = SequenceMethod.HeatAware }); + + Assert.IsType(sequencer); + } +} diff --git a/docs/nest-file-format.md b/docs/nest-file-format.md index 4b10629f..e2f5b017 100644 --- a/docs/nest-file-format.md +++ b/docs/nest-file-format.md @@ -150,6 +150,9 @@ preserving the old default selection behavior. `OpenNest.IO.CuttingParametersSer cross-platform DTO mapping; the desktop settings serializer delegates to it so existing saved settings keep their JSON contract. Settings are independent of the saved part programs: restoring settings never regenerates those programs. +`sequencing.method` is written as its number (PEP's 1-8, or 100 for OpenNest's +[heat-aware order](plate-heat-map.md#sequencing)) with `sequencing.heatWeight` +(seconds per °C); a file without the weight, or with a negative one, reads 0.15. Lead settings are external (the perimeter) and internal (every cutout, full circles included). Older files and desktop settings also stored diff --git a/docs/plate-heat-map.md b/docs/plate-heat-map.md index b5856c0d..6b174019 100644 --- a/docs/plate-heat-map.md +++ b/docs/plate-heat-map.md @@ -2,8 +2,8 @@ `OpenNest.Core/CNC/Thermal/PlateHeatSimulation.cs` estimates how heat builds up in the sheet while a [cut simulation](cut-time-estimates.md) plays. The Cut Simulator shows it under the cut -trail (Heat: Now or Peak so far). It is a display and analysis aid: no sequencer uses it yet, and -it never changes the plate. +trail (Heat: Now or Peak so far). It is a display and analysis aid and never changes the plate; +a parked [heat-aware sequencer](#sequencing) uses a cheaper estimate of the same physics. ## Model @@ -32,3 +32,44 @@ compare cut orders of one plate, not as real values. The simulator colors the field against the 99.5th percentile of the whole cut's peaks: a pierce puts its energy into a single cell, and scaling to that cell would hide the areas where heat builds up. Cells whose slug fell away are transparent. + +## Sequencing + +`SequenceMethod.HeatAware` (100, outside PEP's 1-8 numbering) is a heat-aware part sequencer, +parked until thermal-camera readings calibrate the model. It is available to +`PlateSequencing.Apply(plate, parameters, thermal)` only: Plan Cutting does not use it, and no UI +offers it. The method and `SequenceParameters.HeatWeight` (seconds per °C, 0.15 by default) are +saved with the cutting settings. + +- Order (`OpenNest.Engine/Sequencing/HeatAwareOrder.cs`): a forward greedy from the plate's origin + corner. The next part is the one with the least travel seconds plus `HeatWeight` times the + estimated temperature at its center when the tool gets there. Cut-offs go last in its route, and + `OrderCutOffsFirst` places them as for every method. Without a thickness it is nearest neighbor. +- Estimate (`HeatSpreadEstimate`): each finished part leaves a Gaussian blob of its energy + (`AbsorbedPower` times its torch-on time), as wide as the part to begin with (a quarter of its + squared diagonal), widening by 4αΔt and fading with the surface loss; only the latest 200 parts + count. Torch-on time comes from each part's cut length and pierces at stand-in feeds by + thickness: 400 in/min up to 0.135 in, 150 up to 0.26 in, 80 above, a 0.5 s pierce up to 0.26 in + and 1.5 s above, and 3000 in/min travel. + +Why it is parked: Plan Cutting does not follow `SequenceMethod`. It plans its own shortest tour +(nearest neighbor, 2-opt, Or-opt), which already travels a fraction of the row-based `Advanced` +sequencer's distance, so the heat order's travel savings over `Advanced` do not carry over. And its +strict search refuses head-down rapids over parts already cut free. A heat-spreading order skips +neighbors and comes back to them across cut parts, so the search stalls, learns rules, and ends on +its shortest tour or the safest-route fallback; a heat order used only where it does not stall +moved the zone metric by noise (±3-5%). Kept as given through Plan Cutting, the heat order does +spread the heat, at this cost against the planned shortest tour (2ER and N26-2GT, weights 0.1-0.4, +stand-in feeds): + +| Plate | Travel | Cut time | Head raises (tour: 0) | Zone P95 | Zone P75 | +|-------|--------|----------|-----------------------|----------|----------| +| 2ER plate 1 (130 parts, 0.25 in) | +52 to +82% | +0.8 to +1.2% | 59-78 | −14 to −18% | −18 to −23% | +| N26-2GT plate 1 (112 parts, 0.09 in) | +50 to +65% | +2.3 to +3.1% | 54-62 | −24 to −25% | −26 to −28% | +| N26-2GT plate 2 (148 parts, 0.09 in) | +64 to +102% | +1.8 to +2.8% | 53-75 | −12 to −20% | −18 to −24% | + +The zone metric is the hottest average over each 4 in square during the cut, as a percentile over +zones; pierces and hole clusters inside one part set the hottest cell whatever the order. The head +raises are the safest-route fallback's last-resort markers, which the strict search never adds, so +a heat order that spreads heat would need designed head raises (or rapids routed around cut parts). +Revisit once the absorbed power and feeds are calibrated.