feat(planner): heat start limit replaces the heat weight

Plan Cutting's heat-aware order is now one setting, "Don't start above (°C
rise)" (CuttingParameters.HeatStartLimit, 0 = off, saved per material and
thickness), with the same rule for single parts and for the lines of large
grids: before each next piece, estimate the temperature where it starts when
the tool gets there; cut the plain order's next piece when it is at or under
the limit, else the nearest piece under it, else the coolest. A move across
parts already cut is a heat jump, reached with the head raised and counted in
HeatRaises; parts that cannot take a raise are reached head-down only when
nothing else is ready. The weighted block layouts and the grid prototype's
static switch and Alternate mode are gone; every-other-line on the washer
grid falls out of the rule.

The rule counts the heat of the part just cut: leaving it out halved the
raises on a 0.06 in sheet but left the starts' P90 at 32-36 C instead of
about 3 C. Re-plans after a learned order rule replay the parts already cut
into the estimate and the crossing test, and an order the heat never moved
stays the plain one, so a limit the estimate never reaches changes nothing.

Measured (HeatOrderMeasurementTests, docs/plate-heat-map.md): washer grid
line starts 63 -> 6 C for +1.5% travel and 1-2 raises; 0.06 in sheet zone
P95 -25% for +10-15% travel, +2% cut time; 0.25 in sheet at 10 C zone P95
-18% for +15% travel (the old weight: -10% for +51%). No fallback raises.
Limit 0 is byte-identical (characterization digests, problem-nest
part-order and grid areas pass).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-12-02 23:42:47 -05:00
1 parent 14461a2938
commit 9315d7394c
21 files changed
+647 -734

No files matched your search

+1 -1
View File
@@ -59,7 +59,7 @@ Releases: follow [the release procedure](docs/releasing.md) and `scripts/Publish
- Cutoffs persist as definitions on `Plate.CutOffs`; apply through `RegenerateCutOffs`, never preview parts. Preserve sequence positions. Batch planning must finish before mutation and roll back on failure. Cut order comes from Plan Cutting or the user (no automatic part sequencers); use `PlateSequencing.OrderCutOffsFirst`/`PlaceCutOffs` for cutoff dependencies, with nominal spans/reference identity rather than trimmed geometry/names.
- A cutoff starts only at the origin-side edge: stock can be oversize, so the far edge is unknown. Only a head-locked overcut (`CutOff.HeadLockOvercut`, `HeadHeightLock` markers) may start its far-edge segment there; posts refuse it without lock codes.
- Fixed emissions (locked programs, drawing-pinned contours) are accepted as given: their violations warn on an UNVERIFIED proposal and never steer the search, while every planner-chosen motion stays strict. Plates without them must keep the `PlanningCharacterizationTests` digests.
- A `HeadRaise` marker (a rapid made head-up over cut parts) is the safest-route fallback's last resort, added only after the strict search fails; the strict search never marks a rapid. Designed raises are the rapid out of a cutout's slug after its lead-out, marked at emission (see the cutting planner doc; no lead-out or an overcut keeps the head down), and the heat jumps an opt-in `HeatWeight` plans between blocks of parts (counted in `HeatRaises`; weight 0 must stay byte-identical). Every post must raise before a marked rapid or refuse the nest.
- A `HeadRaise` marker (a rapid made head-up over cut parts) is the safest-route fallback's last resort, added only after the strict search fails; the strict search never marks a rapid. Designed raises are the rapid out of a cutout's slug after its lead-out, marked at emission (see the cutting planner doc; no lead-out or an overcut keeps the head down), and the heat jumps an opt-in `HeatStartLimit` (°C) plans to cooler parts or grid lines (counted in `HeatRaises`; limit 0 must stay byte-identical). Every post must raise before a marked rapid or refuse the nest.
- An empty diagnostic is not a clear result unless `IsComplete`. Posting must run checks before writing CNC output; warnings require explicit per-attempt consent, never a persisted bypass. Keep inputs stable through analysis/cancellation.
- Preserve symbolic G-code variable definitions/references in file round trips. Keep training bitmaps by default; inference checks predictor availability before scalar-only extraction.
@@ -39,7 +39,7 @@ internal static class OwnedCuttingParameters
TabSizeMaxWidth = Dimension(source.TabSizeMaxWidth),
SliceTippingSlugs = source.SliceTippingSlugs,
LabelMode = source.LabelMode,
HeatWeight = Dimension(source.HeatWeight)
HeatStartLimit = Dimension(source.HeatStartLimit)
};
}
@@ -102,10 +102,10 @@ internal static class StateFingerprint
else if (p.LabelMode == PartLabelMode.PartNumber)
text.Append("partLabelNumber;");
// Only when set, so fingerprints taken before the setting existed still match.
if (p.HeatWeight != 0)
if (p.HeatStartLimit != 0)
{
text.Append("heatWeight;");
Number(p.HeatWeight);
text.Append("heatStartLimit;");
Number(p.HeatStartLimit);
}
text.Append('}');
}
@@ -119,10 +119,11 @@ namespace OpenNest.CNC.CuttingStrategy
public PartLabelMode LabelMode { get; set; }
/// <summary>
/// Seconds of travel Plan Cutting's part order may spend to cut a part one degree Celsius
/// cooler, by an estimate of the heat the parts cut before it left (see
/// docs/plate-heat-map.md#sequencing). Zero, the default, orders by travel alone.
/// The temperature rise, in °C, above which Plan Cutting's order does not start the next part
/// (or line of a large grid), by an estimate of the heat the parts cut before it left; it
/// goes to the nearest part under the limit instead (see docs/plate-heat-map.md#sequencing).
/// Zero, the default, orders by travel alone.
/// </summary>
public double HeatWeight { get; set; }
public double HeatStartLimit { get; set; }
}
}
+2 -2
View File
@@ -140,7 +140,7 @@ public static class MachineCuttingDefaults
TabSizeMaxWidth = parameters.TabSizeMaxWidth * scale,
SliceTippingSlugs = parameters.SliceTippingSlugs,
LabelMode = parameters.LabelMode,
HeatWeight = parameters.HeatWeight,
HeatStartLimit = parameters.HeatStartLimit,
PierceClearance = parameters.PierceClearance * scale,
PierceDiameter = parameters.PierceDiameter * scale,
Unknown = previous?.Unknown,
@@ -159,7 +159,7 @@ public static class MachineCuttingDefaults
parameters.TabSizeMaxWidth = cutting.TabSizeMaxWidth * scale;
parameters.SliceTippingSlugs = cutting.SliceTippingSlugs;
parameters.LabelMode = cutting.ResolvedLabelMode;
parameters.HeatWeight = double.IsFinite(cutting.HeatWeight) && cutting.HeatWeight > 0 ? cutting.HeatWeight : 0;
parameters.HeatStartLimit = double.IsFinite(cutting.HeatStartLimit) && cutting.HeatStartLimit > 0 ? cutting.HeatStartLimit : 0;
parameters.PierceClearance = cutting.PierceClearance * scale;
parameters.PierceDiameter = cutting.PierceDiameter * scale;
}
+4 -3
View File
@@ -54,11 +54,12 @@ public class ThicknessCuttingConfig
: PartLabelMode.Off;
/// <summary>
/// Travel seconds Plan Cutting may spend to cut a part one degree cooler (docs/plate-heat-map.md);
/// 0 orders by travel alone. Written only when set.
/// The estimated temperature rise, in °C, above which Plan Cutting's order does not start the
/// next part or grid line (docs/plate-heat-map.md#sequencing); 0 orders by travel alone.
/// Written only when set.
/// </summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public double HeatWeight { get; set; }
public double HeatStartLimit { get; set; }
public double PierceClearance { get; set; } = 0.0625;
@@ -1,148 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using OpenNest.Geometry;
namespace OpenNest.Engine.CuttingPlanning;
/// <summary>How a heat-aware grid order picks its next line (prototype).</summary>
internal enum GridHeatMode
{
/// <summary>Every other line out, the lines skipped on the way back.</summary>
Alternate,
/// <summary>
/// The nearest line whose start is estimated at or under <see cref="GridHeatSetting.LimitCelsius"/>
/// when the head would reach it; the coolest start when none is.
/// </summary>
Limit,
}
/// <summary>A heat-aware grid order's mode and, for <see cref="GridHeatMode.Limit"/>, its start limit in °C.</summary>
internal sealed record GridHeatSetting(GridHeatMode Mode, double LimitCelsius = 0);
/// <summary>
/// PROTOTYPE. Reorders the lines of a large grid's serpentine (<see cref="CuttingGridOrder.Lines"/>)
/// so that no line starts where the cut so far left the sheet hot. Each line keeps its parts in
/// order and is cut from whichever end lies nearer the tool; only which line comes next changes.
/// The temperature is <see cref="CuttingHeatOrder.HeatEstimate"/>, keeping every part's heat. A
/// move to a line whose straight rapid passes over a part already cut is a heat jump: the search
/// reaches that line's first part with the head raised, as for <see cref="CuttingHeatOrder"/>.
/// Runs only with a heat weight and <see cref="Setting"/> set; otherwise the serpentine stands.
/// </summary>
internal static class CuttingGridHeatOrder
{
/// <summary>The prototype's switch, set by measurement harnesses; null keeps the serpentine.</summary>
internal static GridHeatSetting Setting { get; set; }
/// <returns>The order and the parts it reaches across parts already cut.</returns>
internal static (int[] Order, int[] Jumps) Plan(int[][] lines, Vector start, IReadOnlyList<CuttingHeatItem> items,
CuttingHeat heat, GridHeatSetting setting, CancellationToken token)
{
var estimate = new CuttingHeatOrder.HeatEstimate(heat, int.MaxValue);
var boxes = lines.Select(line => line.Select(part => items[part].Extent).ToList().GetBoundingBox()).ToArray();
var cut = new bool[lines.Length];
var order = new List<int>(lines.Sum(line => line.Length));
var jumps = new List<int>();
var position = start;
var last = -1;
var alternate = setting.Mode == GridHeatMode.Alternate ? AlternateLines(lines.Length).GetEnumerator() : null;
for (var step = 0; step < lines.Length; step++)
{
token.ThrowIfCancellationRequested();
int line;
bool reversed;
bool jump;
if (alternate != null)
{
alternate.MoveNext();
line = alternate.Current;
reversed = NearerEnd(lines[line], position, items);
jump = Crosses(position, items[First(lines[line], reversed)].Arrival, lines, boxes, cut, items, last);
}
else
(line, reversed, jump) = ByLimit(lines, boxes, cut, position, items, estimate, setting.LimitCelsius, last);
var parts = reversed ? lines[line].Reverse().ToArray() : lines[line];
if (jump)
jumps.Add(parts[0]);
foreach (var part in parts)
{
var item = items[part];
estimate.Cut(item, estimate.TravelSeconds(position.DistanceTo(item.Arrival)));
order.Add(part);
position = item.Exit;
last = part;
}
cut[line] = true;
}
return (order.ToArray(), jumps.ToArray());
}
// 0, 2, 4, ... then the lines skipped, from the far end back.
private static IEnumerable<int> AlternateLines(int count)
{
for (var line = 0; line < count; line += 2)
yield return line;
for (var line = count % 2 == 0 ? count - 1 : count - 2; line >= 1; line -= 2)
yield return line;
}
private static (int Line, bool Reversed, bool Jump) ByLimit(int[][] lines, Box[] boxes, bool[] cut, Vector position,
IReadOnlyList<CuttingHeatItem> items, CuttingHeatOrder.HeatEstimate estimate, double limit, int last)
{
var candidates = new List<(int Line, bool Reversed, double Travel, double Temperature)>();
for (var line = 0; line < lines.Length; line++)
{
if (cut[line])
continue;
foreach (var reversed in new[] { false, true })
{
var first = items[First(lines[line], reversed)];
var travel = estimate.TravelSeconds(position.DistanceTo(first.Arrival));
candidates.Add((line, reversed, travel, estimate.TemperatureAt(first.Extent.Center, estimate.Time + travel)));
}
}
var cool = candidates.Where(c => c.Temperature <= limit).OrderBy(c => c.Travel).ThenBy(c => c.Line).ToList();
if (cool.Count == 0)
{
var coolest = candidates.OrderBy(c => c.Temperature).ThenBy(c => c.Travel).First();
return (coolest.Line, coolest.Reversed, Crosses(position, items[First(lines[coolest.Line], coolest.Reversed)].Arrival,
lines, boxes, cut, items, last));
}
// Nearest first; a move across cut parts also costs the head raise.
(int Line, bool Reversed, bool Jump) best = default;
var bestCost = double.PositiveInfinity;
foreach (var candidate in cool)
{
if (candidate.Travel >= bestCost)
break;
var jump = Crosses(position, items[First(lines[candidate.Line], candidate.Reversed)].Arrival, lines, boxes, cut,
items, last);
var cost = candidate.Travel + (jump ? CuttingHeatOrder.RaiseSeconds : 0);
if (cost < bestCost)
(best, bestCost) = ((candidate.Line, candidate.Reversed, jump), cost);
}
return best;
}
private static bool NearerEnd(int[] line, Vector position, IReadOnlyList<CuttingHeatItem> items) =>
position.DistanceTo(items[line[^1]].Arrival) < position.DistanceTo(items[line[0]].Arrival);
private static int First(int[] line, bool reversed) => reversed ? line[^1] : line[0];
// Whether the straight move passes over a part already cut, other than the one it leaves.
private static bool Crosses(Vector from, Vector to, int[][] lines, Box[] boxes, bool[] cut,
IReadOnlyList<CuttingHeatItem> items, int leaving)
{
for (var line = 0; line < lines.Length; line++)
{
if (!cut[line] || !CuttingHeatOrder.SegmentHitsBox(from, to, boxes[line]))
continue;
foreach (var part in lines[line])
if (part != leaving && CuttingHeatOrder.SegmentHitsBox(from, to, items[part].Extent))
return true;
}
return false;
}
}
@@ -8,17 +8,18 @@ using OpenNest.Geometry;
namespace OpenNest.Engine.CuttingPlanning;
/// <summary>
/// What a heat-aware part order needs: the weight (travel seconds worth one degree Celsius), the
/// sheet's material and thickness, and the feeds and pierce time the cut is timed with.
/// What a heat-aware part order needs: the start limit (the estimated temperature rise, in °C,
/// above which the next part or line is not started), the sheet's material and thickness, and the
/// feeds and pierce time the cut is timed with.
/// </summary>
internal sealed record CuttingHeat(double Weight, ThermalParameters Thermal, CutParameters Times)
internal sealed record CuttingHeat(double StartLimit, ThermalParameters Thermal, CutParameters Times)
{
/// <summary>Null unless a positive weight, a thickness and usable feeds make heat matter.</summary>
internal static CuttingHeat For(double weight, ThermalParameters thermal, CutParameters times) =>
double.IsFinite(weight) && weight > 0 && thermal is { Thickness: > 0 } && double.IsFinite(thermal.Thickness)
/// <summary>Null unless a positive limit, a thickness and usable feeds make heat matter.</summary>
internal static CuttingHeat For(double startLimit, ThermalParameters thermal, CutParameters times) =>
double.IsFinite(startLimit) && startLimit > 0 && thermal is { Thickness: > 0 } && double.IsFinite(thermal.Thickness)
&& times is { Feedrate: > 0, RapidTravelRate: > 0 } && double.IsFinite(times.Feedrate)
&& double.IsFinite(times.RapidTravelRate)
? new(weight, thermal, times) : null;
? new(startLimit, thermal, times) : null;
}
/// <summary>
@@ -31,217 +32,291 @@ internal readonly record struct CuttingHeatItem(Vector Arrival, Vector Exit, Box
bool CanRaise = true);
/// <summary>
/// Spreads Plan Cutting's heat by cutting the plate in blocks. The parts are grouped into blocks
/// (two halves cut from opposite ends of the sheet toward each other, or a grid of squares), each
/// toured on its own like the plain order, and the cut moves between blocks: each next part is the
/// next of the current block or of another, whichever costs least in travel seconds plus
/// <see cref="CuttingHeat.Weight"/> times the heat estimated where it is cut
/// (<see cref="HeatEstimate"/>). A move to another block whose straight line passes over the
/// extent of a part already cut is a jump: it also costs <see cref="RaiseSeconds"/>, and the search
/// reaches that part with the head raised instead of keeping it head-down. Within a block the tour
/// is the plain tour's and stays strict. Of the plain tour and each block layout, the order with
/// the least of that cost, summed over the order, is kept; ties keep the plain tour. A proposal like
/// the plain tour: the search still checks every motion along it. See docs/plate-heat-map.md#sequencing.
/// Keeps Plan Cutting from starting work where the cut so far left the sheet hot. The work comes
/// in pieces in a plain order: single parts along the plain tour, or the lines of a large grid's
/// serpentine (<see cref="CuttingGridOrder.Lines"/>), each cut in order from whichever end lies
/// nearer. Before each piece the rule estimates the temperature where it starts when the tool gets
/// there (<see cref="HeatEstimate"/>): the plain order's next piece is cut when it is at or under
/// <see cref="CuttingHeat.StartLimit"/>; otherwise the nearest piece under the limit, counting
/// <see cref="RaiseSeconds"/> for a move across cut parts; otherwise the coolest. A move whose
/// straight rapid passes over a part already cut is a heat jump: the search reaches that piece's
/// first part with the head raised. A part that cannot take a raise is reached across cut parts
/// head-down only when no other piece is ready. A proposal like the plain order: the search still
/// checks every motion along it. See docs/plate-heat-map.md#sequencing.
/// </summary>
internal static class CuttingHeatOrder
{
/// <summary>What a jump's head raise and lowering is taken to cost, in seconds.</summary>
internal const double RaiseSeconds = 2;
// What reaching a part head-down across cut parts costs: more than any other move.
private const double BlockedSeconds = 1e9;
// Fewer parts than this per front leave nothing to alternate.
private const int MinimumFrontParts = 2;
// Grid layouts tried: this many squares along the parts' long side.
private static readonly int[] GridDivisions = [2, 3, 4, 6];
/// <param name="plain">The plain tour of <paramref name="parts"/>.</param>
/// <param name="plain">The plain tour of the parts.</param>
/// <param name="items">Every part's data, by ordinal.</param>
/// <param name="blockTour">Tours some parts from a start, toward an endpoint when one is given,
/// as the plain order would.</param>
/// <returns>The cheapest order, and the parts it jumps to across parts already cut (none for
/// the plain tour).</returns>
internal static (int[] Order, int[] Jumps) Plan(int[] plain, IReadOnlyList<int> parts, Vector start,
/// <param name="prerequisites">Each part's prerequisites, by ordinal; those outside the tour are ignored.</param>
/// <param name="cutBefore">When the rest of a plate is planned again, the parts already cut, in
/// order from <paramref name="origin"/>: their heat counts and a rapid over them is a jump.</param>
/// <param name="movedBefore">Whether the heat moved the order of the parts already cut.</param>
/// <returns>The order, the parts it jumps to across parts already cut, and whether the heat moved
/// it. An order the heat never moved, here or before, is the plain one with no jumps.</returns>
internal static (int[] Order, int[] Jumps, bool Moved) Plan(int[] plain, Vector start,
IReadOnlyList<CuttingHeatItem> items, IReadOnlyList<IReadOnlyCollection<int>> prerequisites, CuttingHeat heat,
Func<IReadOnlyList<int>, Vector, Vector?, int[]> blockTour, CancellationToken token)
CancellationToken token, IReadOnlyList<int> cutBefore = null, Vector origin = default, bool movedBefore = false)
{
if (heat == null || parts.Count < 2 * MinimumFrontParts)
return (plain, []);
var best = (Order: plain, Jumps: Array.Empty<int>());
var bestCost = Cost(plain, [], start, items, heat);
foreach (var blocks in Layouts(parts, start, items, blockTour))
{
token.ThrowIfCancellationRequested();
if (Interleave(blocks, parts, start, items, prerequisites, heat, token) is not { } candidate)
continue;
var cost = Cost(candidate.Order, candidate.Jumps, start, items, heat);
if (cost < bestCost - 1e-9)
(best, bestCost) = (candidate, cost);
}
return best;
if (heat == null || plain.Length < 2)
return (plain, [], false);
return Walk(plain.Select(part => new[] { part }).ToArray(), false, start, items, prerequisites, heat,
HeatEstimate.MaxDeposits, token, cutBefore ?? [], origin, movedBefore);
}
/// <summary>
/// The order's travel seconds, plus <see cref="RaiseSeconds"/> per jump, plus the weight times
/// the heat estimated where each part is cut: the sum the next part is chosen by.
/// </summary>
internal static double Cost(IReadOnlyList<int> order, IReadOnlyCollection<int> jumps, Vector start,
IReadOnlyList<CuttingHeatItem> items, CuttingHeat heat)
{
var estimate = new HeatEstimate(heat);
var position = start;
var total = jumps.Count * RaiseSeconds;
foreach (var part in order)
{
var item = items[part];
var travel = estimate.TravelSeconds(position.DistanceTo(item.Arrival));
total += travel + heat.Weight * estimate.TemperatureAt(item.Extent.Center, estimate.Time + travel);
estimate.Cut(item, travel);
position = item.Exit;
}
return total;
}
/// <summary>The start-limit rule over a grid's serpentine lines, each cut from its nearer end.</summary>
internal static (int[] Order, int[] Jumps, bool Moved) PlanLines(int[][] lines, Vector start,
IReadOnlyList<CuttingHeatItem> items, CuttingHeat heat, CancellationToken token) =>
Walk(lines, true, start, items, null, heat, int.MaxValue, token, [], start, false);
// The block layouts tried: two fronts across the long axis and across the short one, then grids.
private static IEnumerable<int[][]> Layouts(IReadOnlyList<int> parts, Vector start,
IReadOnlyList<CuttingHeatItem> items, Func<IReadOnlyList<int>, Vector, Vector?, int[]> blockTour)
{
var bounds = parts.Select(p => items[p].Extent).ToList().GetBoundingBox();
var alongX = bounds.Length >= bounds.Width; // Length runs along X.
foreach (var axis in new[] { alongX, !alongX })
yield return Fronts(parts, start, items, bounds, axis, blockTour);
var longSide = System.Math.Max(bounds.Length, bounds.Width);
if (!(longSide > 0))
yield break;
foreach (var division in GridDivisions)
{
var side = longSide / division;
var columns = System.Math.Max(1, (int)System.Math.Round(bounds.Length / side));
var rows = System.Math.Max(1, (int)System.Math.Round(bounds.Width / side));
var cellWidth = bounds.Length / columns;
var cellHeight = bounds.Width / rows;
var cells = parts.GroupBy(part =>
{
var center = items[part].Extent.Center;
var column = cellWidth > 0 ? System.Math.Clamp((int)((center.X - bounds.Left) / cellWidth), 0, columns - 1) : 0;
var row = cellHeight > 0 ? System.Math.Clamp((int)((center.Y - bounds.Bottom) / cellHeight), 0, rows - 1) : 0;
return row * columns + column;
}).OrderBy(cell => cell.Key).ToArray();
if (cells.Length < 2)
continue;
yield return cells.Select(cell =>
{
var column = cell.Key % columns;
var row = cell.Key / columns;
// Each block is toured from its corner nearest the start, where the cut comes from.
var corner = new Vector(
System.Math.Clamp(start.X, bounds.Left + column * cellWidth, bounds.Left + (column + 1) * cellWidth),
System.Math.Clamp(start.Y, bounds.Bottom + row * cellHeight, bounds.Bottom + (row + 1) * cellHeight));
return blockTour(cell.ToArray(), corner, null);
}).ToArray();
}
}
// The two halves of the parts, split along the axis where their cut length is shared equally,
// each toured from its own end of the parts toward the split.
private static int[][] Fronts(IReadOnlyList<int> parts, Vector start, IReadOnlyList<CuttingHeatItem> items,
Box bounds, bool alongX, Func<IReadOnlyList<int>, Vector, Vector?, int[]> blockTour)
{
double Along(Vector point) => alongX ? point.X : point.Y;
double Across(Vector point) => alongX ? point.Y : point.X;
Vector At(double along, double across) => alongX ? new Vector(along, across) : new Vector(across, along);
var (low, high) = alongX ? (bounds.Left, bounds.Right) : (bounds.Bottom, bounds.Top);
var (lowAcross, highAcross) = alongX ? (bounds.Bottom, bounds.Top) : (bounds.Left, bounds.Right);
var nearLow = System.Math.Abs(Along(start) - low) <= System.Math.Abs(Along(start) - high);
// Nearest the start first; equal positions keep the given order.
var sorted = parts.OrderBy(p => nearLow ? Along(items[p].Extent.Center) : -Along(items[p].Extent.Center)).ToArray();
var weights = sorted.Select(p => System.Math.Max(items[p].CutLength, 1e-9)).ToArray();
var half = weights.Sum() / 2;
var split = 0;
for (var sum = 0.0; split < sorted.Length && sum + weights[split] <= half; split++)
sum += weights[split];
split = System.Math.Clamp(split, MinimumFrontParts, sorted.Length - MinimumFrontParts);
var near = sorted.Take(split).ToArray();
var far = sorted.Skip(split).ToArray();
var meetAlong = (Along(items[near[^1]].Extent.Center) + Along(items[far[0]].Extent.Center)) / 2;
var meet = At(meetAlong, (lowAcross + highAcross) / 2);
var farStart = At(nearLow ? high : low, System.Math.Clamp(Across(start), lowAcross, highAcross));
return [blockTour(near, start, meet), blockTour(far, farStart, meet)];
}
// Cuts along the blocks, each step the next part of whichever block costs least: travel seconds
// plus weighted heat, plus RaiseSeconds for a move to another block across a part already cut,
// which becomes a jump. Null when no block's next part may be cut (a prerequisite waits deeper
// in another block).
private static (int[] Order, int[] Jumps)? Interleave(int[][] blocks, IReadOnlyList<int> parts, Vector start,
private static (int[] Order, int[] Jumps, bool Moved) Walk(int[][] pieces, bool reversible, Vector start,
IReadOnlyList<CuttingHeatItem> items, IReadOnlyList<IReadOnlyCollection<int>> prerequisites, CuttingHeat heat,
CancellationToken token)
int maxDeposits, CancellationToken token, IReadOnlyList<int> cutBefore, Vector origin, bool movedBefore)
{
var inSet = parts.ToHashSet();
var cut = new HashSet<int>();
var cutExtents = new List<(int Part, Box Extent)>(parts.Count);
var heads = new int[blocks.Length];
var estimate = new HeatEstimate(heat);
var order = new int[parts.Count];
var plain = (pieces.SelectMany(piece => piece).ToArray(), Array.Empty<int>(), false);
var state = new WalkState(pieces, items, prerequisites, cutBefore);
var estimate = new HeatEstimate(heat, maxDeposits);
var replayed = origin;
foreach (var part in cutBefore)
{
estimate.Cut(items[part], estimate.TravelSeconds(replayed.DistanceTo(items[part].Arrival)));
replayed = items[part].Exit;
}
var limit = heat.StartLimit;
var order = new List<int>(pieces.Sum(piece => piece.Length));
var jumps = new List<int>();
var position = start;
var current = -1;
var last = -1;
for (var step = 0; step < order.Length; step++)
var lastPiece = -1;
var lastPart = cutBefore.Count != 0 ? cutBefore[^1] : -1;
var moved = false;
for (var step = 0; step < pieces.Length; step++)
{
token.ThrowIfCancellationRequested();
var chosen = -1;
var chosenCost = double.MaxValue;
var chosenJump = false;
// The current block first, so a tie keeps cutting along it.
foreach (var block in Enumerable.Range(0, blocks.Length).OrderBy(b => b == current ? 0 : 1))
var chosen = Successor(state, lastPiece, lastPart, reversible, position, estimate, limit, ref moved)
?? Nearest(state, reversible, position, lastPart, estimate, limit);
if (chosen is not { } next)
return plain; // A prerequisite outside any piece: keep the plain order.
var parts = next.Reversed ? pieces[next.Piece].Reverse().ToArray() : pieces[next.Piece];
if (next.Jump)
jumps.Add(parts[0]);
foreach (var part in parts)
{
if (heads[block] >= blocks[block].Length)
continue;
var part = blocks[block][heads[block]];
if (prerequisites[part].Any(p => inSet.Contains(p) && !cut.Contains(p)))
continue;
var item = items[part];
var jump = block != current && current >= 0 && Crosses(position, item.Arrival, cutExtents, last, part);
// A part that cannot be reached head-up is reached head-down, as the plain tour's
// leg would be, and only when no other block's part may come next.
var blocked = jump && !item.CanRaise;
if (blocked)
jump = false;
var travel = estimate.TravelSeconds(position.DistanceTo(item.Arrival));
var cost = (blocked ? BlockedSeconds : 0) + travel + (jump ? RaiseSeconds : 0)
+ heat.Weight * estimate.TemperatureAt(item.Extent.Center, estimate.Time + travel);
if (cost < chosenCost)
(chosen, chosenCost, chosenJump) = (block, cost, jump);
estimate.Cut(item, estimate.TravelSeconds(position.DistanceTo(item.Arrival)));
order.Add(part);
position = item.Exit;
lastPart = part;
}
if (chosen < 0)
return null;
var next = blocks[chosen][heads[chosen]++];
var nextItem = items[next];
estimate.Cut(nextItem, estimate.TravelSeconds(position.DistanceTo(nextItem.Arrival)));
order[step] = next;
if (chosenJump)
jumps.Add(next);
cut.Add(next);
cutExtents.Add((next, nextItem.Extent));
position = nextItem.Exit;
current = chosen;
last = next;
state.Finish(next.Piece);
lastPiece = next.Piece;
}
return (order, jumps.ToArray());
// The crossing test alone never moves the plain order: its legs are the search's to judge.
return moved || movedBefore ? (order.ToArray(), jumps.ToArray(), moved) : plain;
}
// Whether the straight move from one point to another passes over the cut extent of a part
// already cut, other than the part it leaves and the part it reaches.
private static bool Crosses(Vector from, Vector to, List<(int Part, Box Extent)> cut, int leaving, int reaching)
private readonly record struct Choice(int Piece, bool Reversed, bool Jump);
// The plain order's next piece, when it is ready, under the limit and reached without crossing
// a part already cut; moved is set when it is over the limit.
private static Choice? Successor(WalkState state, int lastPiece, int lastPart, bool reversible,
Vector position, HeatEstimate estimate, double limit, ref bool moved)
{
foreach (var (part, extent) in cut)
if (part != leaving && part != reaching && SegmentHitsBox(from, to, extent))
var next = state.NextAfter(lastPiece);
if (next < 0 || !state.Ready(next))
return null;
var reversed = reversible && state.NearerEnd(next, position);
var first = state.First(next, reversed);
var item = state.Items[first];
var travel = estimate.TravelSeconds(position.DistanceTo(item.Arrival));
if (estimate.TemperatureAt(item.Arrival, estimate.Time + travel) > limit)
{
moved = true;
return null;
}
// Taken here only head-down; a leg across cut parts is weighed against the others. The
// plain order's own leg is as the plain order would cut it but for the parts this order
// cut ahead of it, and those cut before a replan, which the plain order did not know.
var plainLeg = next == lastPiece + 1 && !reversed;
return !state.Crosses(position, item.Arrival, lastPart, first, plainLeg ? next : -1)
? new Choice(next, reversed, false) : null;
}
// The nearest ready piece under the limit, a raise counted as RaiseSeconds; else the coolest.
// Pieces whose first part cannot take a raise and is reached across cut parts come last.
private static Choice? Nearest(WalkState state, bool reversible, Vector position, int lastPart,
HeatEstimate estimate, double limit)
{
var candidates = new List<(int Piece, bool Reversed, int First, double Travel)>();
foreach (var piece in state.Remaining())
{
if (!state.Ready(piece))
continue;
foreach (var reversed in reversible && state.Pieces[piece].Length > 1 ? [false, true] : new[] { false })
{
var first = state.First(piece, reversed);
candidates.Add((piece, reversed, first,
estimate.TravelSeconds(position.DistanceTo(state.Items[first].Arrival))));
}
}
if (candidates.Count == 0)
return null;
candidates.Sort((a, b) => a.Travel != b.Travel ? a.Travel.CompareTo(b.Travel)
: a.Piece != b.Piece ? a.Piece.CompareTo(b.Piece) : a.Reversed.CompareTo(b.Reversed));
var temperatures = new double[candidates.Count];
var known = new bool[candidates.Count];
double Temperature(int index)
{
if (!known[index])
{
var c = candidates[index];
temperatures[index] = estimate.TemperatureAt(state.Items[c.First].Arrival, estimate.Time + c.Travel);
known[index] = true;
}
return temperatures[index];
}
// 0: reached head-down, 1: a jump, 2: blocked (crosses cut parts, cannot be raised).
var kinds = new int[candidates.Count];
int Kind(int index)
{
if (kinds[index] == 0)
{
var c = candidates[index];
kinds[index] = !state.Crosses(position, state.Items[c.First].Arrival, lastPart, c.First) ? 1
: state.Items[c.First].CanRaise ? 2 : 3;
}
return kinds[index] - 1;
}
Choice Take(int index) => new(candidates[index].Piece, candidates[index].Reversed, Kind(index) == 1);
var best = -1;
var bestCost = double.PositiveInfinity;
var blockedCool = -1;
for (var i = 0; i < candidates.Count && candidates[i].Travel < bestCost; i++)
{
if (Temperature(i) > limit)
continue;
var kind = Kind(i);
if (kind == 2)
{
if (blockedCool < 0)
blockedCool = i;
continue;
}
var cost = candidates[i].Travel + (kind == 1 ? RaiseSeconds : 0);
if (cost < bestCost)
(best, bestCost) = (i, cost);
}
if (best >= 0)
return Take(best);
// None under the limit can be reached: the coolest that can, nearest first on ties.
var byTemperature = Enumerable.Range(0, candidates.Count).OrderBy(Temperature).ThenBy(i => i).ToArray();
foreach (var index in byTemperature)
if (Kind(index) != 2)
return Take(index);
return Take(blockedCool >= 0 ? blockedCool : byTemperature[0]);
}
// The pieces cut so far and the parts in them, for readiness and the crossing test.
private sealed class WalkState
{
private readonly bool[] done;
private readonly bool[] cutParts;
private readonly HashSet<int> inWalk;
private readonly IReadOnlyList<IReadOnlyCollection<int>> prerequisites;
private readonly Box[] boxes;
private readonly List<int> finished = [];
private readonly IReadOnlyList<int> cutBefore;
private int firstRemaining;
internal WalkState(int[][] pieces, IReadOnlyList<CuttingHeatItem> items,
IReadOnlyList<IReadOnlyCollection<int>> prerequisites, IReadOnlyList<int> cutBefore)
{
this.cutBefore = cutBefore;
Pieces = pieces;
Items = items;
this.prerequisites = prerequisites;
done = new bool[pieces.Length];
cutParts = new bool[items.Count];
inWalk = pieces.SelectMany(piece => piece).ToHashSet();
boxes = pieces.Select(piece => piece.Length == 1 ? items[piece[0]].Extent
: piece.Select(part => items[part].Extent).ToList().GetBoundingBox()).ToArray();
}
internal int[][] Pieces { get; }
internal IReadOnlyList<CuttingHeatItem> Items { get; }
internal void Finish(int piece)
{
done[piece] = true;
foreach (var part in Pieces[piece])
cutParts[part] = true;
finished.Add(piece);
while (firstRemaining < done.Length && done[firstRemaining])
firstRemaining++;
}
internal IEnumerable<int> Remaining()
{
for (var piece = firstRemaining; piece < done.Length; piece++)
if (!done[piece])
yield return piece;
}
// The first piece not yet cut after the given one in the plain order, or -1.
internal int NextAfter(int piece)
{
for (var next = System.Math.Max(piece + 1, firstRemaining); next < done.Length; next++)
if (!done[next])
return next;
return -1;
}
// Whether every prerequisite of the piece's parts, other than its own, is cut.
internal bool Ready(int piece)
{
if (prerequisites == null)
return true;
return false;
var parts = Pieces[piece];
foreach (var part in parts)
foreach (var prerequisite in prerequisites[part])
if (!cutParts[prerequisite] && inWalk.Contains(prerequisite) && Array.IndexOf(parts, prerequisite) < 0)
return false;
return true;
}
internal bool NearerEnd(int piece, Vector position)
{
var parts = Pieces[piece];
return parts.Length > 1
&& position.DistanceTo(Items[parts[^1]].Arrival) < position.DistanceTo(Items[parts[0]].Arrival);
}
internal int First(int piece, bool reversed) => reversed ? Pieces[piece][^1] : Pieces[piece][0];
// Whether the straight move passes over the cut extent of a part already cut, other than
// the part it leaves and the part it reaches; with an index of the plain order, only parts
// cut after it in that order count, besides those cut before the walk.
internal bool Crosses(Vector from, Vector to, int leaving, int reaching, int inOrderBefore = -1)
{
foreach (var part in cutBefore)
if (part != leaving && part != reaching && SegmentHitsBox(from, to, Items[part].Extent))
return true;
foreach (var piece in finished)
{
if (piece < inOrderBefore)
continue;
if (!SegmentHitsBox(from, to, boxes[piece]))
continue;
foreach (var part in Pieces[piece])
if (part != leaving && part != reaching && SegmentHitsBox(from, to, Items[part].Extent))
return true;
}
return false;
}
}
// Liang-Barsky clipping of the segment against the box.
@@ -70,7 +70,7 @@ public sealed class CuttingPlanRequest
/// <summary>
/// The feeds, rapid rate and pierce time the cut is timed with, in <see cref="Units"/>, for a
/// heat-aware part order (<see cref="CuttingParameters.HeatWeight"/>); null takes
/// heat-aware part order (<see cref="CuttingParameters.HeatStartLimit"/>); null takes
/// <see cref="CutParameters.Default"/>.
/// </summary>
public CutParameters CutTimes { get; init; }
@@ -203,6 +203,9 @@ public sealed class CuttingPlanSnapshot
/// </summary>
internal HashSet<int> HeatJumps { get; } = [];
/// <summary>Whether the heat start limit has moved the part order of this search's plan so far.</summary>
internal bool HeatMoved { get; set; }
// A worker-only search variant over the same owned capture. Never recapture the live plate:
// both proposals retain the identical freshness record and confirmed settings.
internal CuttingPlanSnapshot WithSearchLimits(int expansionBudget, int maxEntries) =>
@@ -504,7 +507,7 @@ public sealed class CuttingPlanResult
public int HeadRaises { get; init; }
/// <summary>
/// Rapids a heat-aware order (<see cref="CuttingParameters.HeatWeight"/>) raises the head on to
/// Rapids a heat-aware order (<see cref="CuttingParameters.HeatStartLimit"/>) raises the head on to
/// jump across cut parts to a cooler area; designed, not a fallback, and not in <see cref="HeadRaises"/>.
/// </summary>
public int HeatRaises { get; init; }
@@ -713,16 +713,16 @@ public static class CuttingPlanService
private static bool SameBits(double source, double proposed) =>
BitConverter.DoubleToInt64Bits(source) == BitConverter.DoubleToInt64Bits(proposed);
// The heat a heat-aware part order weighs, from the confirmed parameters' weight, material and
// thickness and the request's feeds; null when the weight is zero or nothing to estimate with.
// The heat a heat-aware part order limits, from the confirmed parameters' start limit, material
// and thickness and the request's feeds; null when the limit is zero or nothing to estimate with.
private static CuttingHeat Heat(CuttingPlanRequest request)
{
var parameters = request.ConfirmedParameters;
if (parameters == null || !(parameters.HeatWeight > 0))
if (parameters == null || !(parameters.HeatStartLimit > 0))
return null;
var times = request.CutTimes ?? CutParameters.Default;
var thermal = ThermalParameters.For(parameters.MaterialName, parameters.Grade, parameters.Thickness, request.Units);
return CuttingHeat.For(parameters.HeatWeight, thermal, new CutParameters
return CuttingHeat.For(parameters.HeatStartLimit, thermal, new CutParameters
{
Feedrate = times.Feedrate,
RapidTravelRate = times.RapidTravelRate,
@@ -241,7 +241,7 @@ internal static class JointCuttingPlanSearch
// order; when another part follows it now, it is planned again, in the same
// place, facing that one.
var back = attempt.Crossed.Min(part => Array.IndexOf(sequence, part));
var rest = Tour(snapshot, sequence[back..], attempt.BoundaryAt(back).Position, nesting);
var rest = Tour(snapshot, sequence[back..], attempt.BoundaryAt(back).Position, nesting, sequence[..back]);
var replan = back > 0 && rest.Length != 0 && rest[0] != sequence[back] ? back - 1 : back;
resume = attempt.BoundaryAt(replan);
sequence = [.. sequence.Take(back), .. rest];
@@ -314,21 +314,23 @@ internal static class JointCuttingPlanSearch
// cut-off in turn is costed from its other end too, and keeps that end when the tour is
// shorter. The parts before a sheet separator then finish beside the end it can be cut from,
// rather than beside its origin-side start when that start lies beyond parts already cut.
// When the rest of the plate is planned again, the parts cut before it count for the heat order.
private static int[] Tour(CuttingPlanSnapshot snapshot, IReadOnlyList<int> parts, Vector start,
CuttingNestedOrder.Context nesting) =>
Heated(snapshot, parts, start, nesting, TravelTour(snapshot, parts, start, nesting));
CuttingNestedOrder.Context nesting, IReadOnlyList<int> cutBefore = null) =>
Heated(snapshot, parts, start, nesting, TravelTour(snapshot, parts, start, nesting), cutBefore);
// A large aligned grid's serpentine; with a heat weight and the prototype's setting, its lines
// reordered so none starts where the sheet is hot (CuttingGridHeatOrder).
// A large aligned grid's serpentine; with a heat start limit, its lines reordered so none
// starts where the sheet is hot (CuttingHeatOrder.PlanLines).
private static int[] GridOrder(CuttingPlanSnapshot snapshot, Box[] extents, CuttingNestedOrder.Context nesting,
CancellationToken token)
{
if (snapshot.Heat == null || CuttingGridHeatOrder.Setting is not { } setting)
return CuttingGridOrder.Plan(extents, snapshot.StartPoint, token);
if (CuttingGridOrder.Lines(extents, snapshot.StartPoint, token) is not { } lines)
return null;
var (order, jumps) = CuttingGridHeatOrder.Plan(lines, snapshot.StartPoint, HeatItems(snapshot, nesting),
snapshot.Heat, setting, token);
if (snapshot.Heat == null)
return lines.SelectMany(line => line).ToArray();
var (order, jumps, moved) = CuttingHeatOrder.PlanLines(lines, snapshot.StartPoint, HeatItems(snapshot, nesting),
snapshot.Heat, token);
snapshot.HeatMoved = moved;
snapshot.HeatJumps.Clear();
snapshot.HeatJumps.UnionWith(jumps);
return order;
@@ -338,19 +340,19 @@ internal static class JointCuttingPlanSearch
snapshot.HeatItems ??= snapshot.Placements.Select((placement, part) =>
HeatItem(placement, nesting.Centers[part], (nesting.Exits ?? nesting.Centers)[part])).ToArray();
// With a heat weight, the order may instead move between blocks of parts (CuttingHeatOrder)
// when that spreads the heat for less than the weight is worth; the parts it jumps to across
// cut parts are reached with the head raised. Parts nested in other parts keep the travel
// With a heat start limit, the order leaves the tour for the nearest part the heat estimate
// puts under the limit whenever the tour's next part is hotter (CuttingHeatOrder); the parts
// it jumps to across cut parts are reached with the head raised. Parts nested in other parts keep the travel
// tour, which keeps each host's group together.
private static int[] Heated(CuttingPlanSnapshot snapshot, IReadOnlyList<int> parts, Vector start,
CuttingNestedOrder.Context nesting, int[] order)
CuttingNestedOrder.Context nesting, int[] order, IReadOnlyList<int> cutBefore)
{
if (snapshot.Heat == null || parts.Any(part => nesting.Inside[part].Count != 0))
return order;
var items = HeatItems(snapshot, nesting);
var (heated, jumps) = CuttingHeatOrder.Plan(order, parts, start, items, nesting.Prerequisites, snapshot.Heat,
(block, from, toward) => CuttingPartOrder.Plan(block, nesting.Centers, from, nesting.Prerequisites,
nesting.Token, toward, nesting.Exits, nesting.Visits), nesting.Token);
var (heated, jumps, moved) = CuttingHeatOrder.Plan(order, start, items, nesting.Prerequisites, snapshot.Heat,
nesting.Token, cutBefore, snapshot.StartPoint, cutBefore != null && snapshot.HeatMoved);
snapshot.HeatMoved = moved || cutBefore != null && snapshot.HeatMoved;
// A replan keeps the jumps of the parts already cut and decides those of the rest anew.
snapshot.HeatJumps.ExceptWith(parts);
snapshot.HeatJumps.UnionWith(jumps);
+1 -1
View File
@@ -45,7 +45,7 @@ public class CuttingParametersDto
public PartLabelMode LabelMode { get; set; }
// Written only when set, so files and settings saved without it are unchanged.
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
public double HeatWeight { get; set; }
public double HeatStartLimit { get; set; }
// Read only: the old on/off part label option, which meant the number with its bend groups.
// Never written; files saved with it load as PartNumberAndBendGroups.
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
+2 -2
View File
@@ -95,7 +95,7 @@ public static class CuttingParametersSerializer
NoBedTabMaxWidth = parameters.TabSizeMaxWidth,
SliceTippingSlugs = parameters.SliceTippingSlugs,
LabelMode = parameters.LabelMode,
HeatWeight = parameters.HeatWeight,
HeatStartLimit = parameters.HeatStartLimit,
};
}
@@ -132,7 +132,7 @@ public static class CuttingParametersSerializer
TabSizeMaxWidth = dto.NoBedTabMaxWidth,
SliceTippingSlugs = dto.SliceTippingSlugs,
LabelMode = dto.ResolvedLabelMode,
HeatWeight = double.IsFinite(dto.HeatWeight) && dto.HeatWeight > 0 ? dto.HeatWeight : 0,
HeatStartLimit = double.IsFinite(dto.HeatStartLimit) && dto.HeatStartLimit > 0 ? dto.HeatStartLimit : 0,
};
}
@@ -6,11 +6,9 @@ using OpenNest.Geometry;
namespace OpenNest.Tests.CuttingPlanning;
// CuttingGridHeatOrder.Setting is static: tests that set it share one collection, so they never overlap.
[Collection(nameof(CuttingGridHeatOrder))]
public class CuttingGridHeatOrderTests
{
private static CuttingHeat Heat() => CuttingHeat.For(0.03,
private static CuttingHeat Heat(double limit) => CuttingHeat.For(limit,
ThermalParameters.For("Mild Steel", null, 0.125, Units.Inches), CutParameters.Default);
// Lines of parts one inch apart, the lines along Y, in serpentine order and direction.
@@ -32,34 +30,40 @@ public class CuttingGridHeatOrderTests
return (lines, items.ToArray());
}
[Fact]
public void Alternate_CutsEveryOtherLineThenTheRestBack()
{
var (lines, items) = Lines(5, 3);
var (order, jumps) = CuttingGridHeatOrder.Plan(lines, new Vector(0, -1), items, Heat(),
new GridHeatSetting(GridHeatMode.Alternate), CancellationToken.None);
var lineOrder = order.Select(part => part / 3).Distinct().ToArray();
Assert.Equal([0, 2, 4, 3, 1], lineOrder);
Assert.Equal(15, order.Distinct().Count());
// Line 3 sits beside line 4, the last cut; line 1 is reached across line 2.
Assert.Single(jumps);
Assert.Contains(jumps[0], lines[1]);
}
private static int[] LineOrder(int[] order, int length) => order.Select(part => part / length).Distinct().ToArray();
[Fact]
public void NoLimit_KeepsTheSerpentine()
public void HighLimit_KeepsTheSerpentine()
{
var (lines, items) = Lines(6, 4);
var (order, jumps) = CuttingGridHeatOrder.Plan(lines, new Vector(0, -1), items, Heat(),
new GridHeatSetting(GridHeatMode.Limit, double.PositiveInfinity), CancellationToken.None);
var (order, jumps, _) = CuttingHeatOrder.PlanLines(lines, new Vector(0, -1), items, Heat(1e6), CancellationToken.None);
Assert.Equal(lines.SelectMany(line => line), order);
Assert.Empty(jumps);
}
[Fact]
public void Limit_SkipsTheLineBesideTheOneJustCut()
{
var (lines, items) = Lines(8, 20);
var (order, jumps, _) = CuttingHeatOrder.PlanLines(lines, new Vector(0, -1), items, Heat(1), CancellationToken.None);
Assert.Equal(items.Length, order.Distinct().Count());
var lineOrder = LineOrder(order, 20);
Assert.NotEqual(Enumerable.Range(0, 8), lineOrder);
// The second line is not the neighbor of the first: its start is hot.
Assert.True(System.Math.Abs(lineOrder[1] - lineOrder[0]) > 1);
// Every line keeps its parts in order, cut from one end or the other.
foreach (var line in lines)
{
var cut = order.Where(line.Contains).ToArray();
Assert.True(cut.SequenceEqual(line) || cut.SequenceEqual(line.Reverse()));
}
Assert.All(jumps, jump => Assert.Contains(lines, line => line[0] == jump || line[^1] == jump));
}
private static Plate Grid()
{
var drawing = TestHelpers.MakeSquareDrawing(0.75);
@@ -70,46 +74,27 @@ public class CuttingGridHeatOrderTests
return plate;
}
private static CuttingPlanResult Plan(double weight)
private static CuttingPlanResult Plan(double limit)
{
var parameters = ExplicitContourTests.Parameters();
parameters.MaterialName = "Mild Steel";
parameters.Thickness = 0.125;
parameters.HeatWeight = weight;
parameters.HeatStartLimit = limit;
return CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(Grid(), Vector.Zero, confirmedParameters: parameters));
}
private static string[] Order(CuttingPlanResult result) =>
result.ProposedOrder.Select(p => $"{p.SourceOrdinal}:{ExplicitContourTests.Fingerprint(p.CopyProgram())}").ToArray();
[Fact]
public void WithoutSetting_GridKeepsTheSerpentineWhateverTheWeight()
{
Assert.Null(CuttingGridHeatOrder.Setting);
Assert.Equal(Order(Plan(0)), Order(Plan(0.5)));
}
[Fact]
public void Alternate_PlansReadyWithMarkedHeatRaises()
public void Limit_GridPlansReadyWithMarkedHeatRaises()
{
var serpentine = Plan(0);
CuttingGridHeatOrder.Setting = new GridHeatSetting(GridHeatMode.Alternate);
try
{
var heated = Plan(0.03);
var heated = Plan(1);
Assert.Equal(CuttingPlanStatus.Ready, heated.Status);
Assert.False(heated.IsSafestRouteFallback);
Assert.Equal(0, heated.HeadRaises);
Assert.True(heated.HeatRaises > 0);
Assert.Equal(heated.HeatRaises, heated.ProposedOrder.Count(p => HeadRaise.IsMarked(p.CopyProgram())));
Assert.NotEqual(serpentine.ProposedOrder.Select(p => p.SourceOrdinal),
heated.ProposedOrder.Select(p => p.SourceOrdinal));
}
finally
{
CuttingGridHeatOrder.Setting = null;
}
Assert.Equal(CuttingPlanStatus.Ready, heated.Status);
Assert.False(heated.IsSafestRouteFallback);
Assert.Equal(0, heated.HeadRaises);
Assert.True(heated.HeatRaises > 0);
Assert.Equal(heated.HeatRaises, heated.ProposedOrder.Count(p => HeadRaise.IsMarked(p.CopyProgram())));
Assert.NotEqual(serpentine.ProposedOrder.Select(p => p.SourceOrdinal),
heated.ProposedOrder.Select(p => p.SourceOrdinal));
}
}
@@ -9,16 +9,16 @@ namespace OpenNest.Tests.CuttingPlanning;
public class CuttingHeatOrderTests
{
private static CuttingParameters Parameters(double weight)
private static CuttingParameters Parameters(double limit)
{
var parameters = ExplicitContourTests.Parameters();
parameters.MaterialName = "Mild Steel";
parameters.Thickness = 0.125;
parameters.HeatWeight = weight;
parameters.HeatStartLimit = limit;
return parameters;
}
// A dense grid of small squares: the run of neighbors the heat weight spreads out.
// A dense grid of small squares: the run of neighbors whose heat builds up.
private static Plate Grid(int columns = 10, int rows = 10, double size = 0.75, double gap = 0.25)
{
var drawing = TestHelpers.MakeSquareDrawing(size);
@@ -29,8 +29,8 @@ public class CuttingHeatOrderTests
return plate;
}
private static CuttingPlanResult Plan(Plate plate, double weight) =>
CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(plate, Vector.Zero, confirmedParameters: Parameters(weight)));
private static CuttingPlanResult Plan(Plate plate, double limit) =>
CuttingPlanService.Plan(CuttingPlanRequest.ForPlate(plate, Vector.Zero, confirmedParameters: Parameters(limit)));
private static string[] Order(CuttingPlanResult result) =>
result.ProposedOrder.Select(p => $"{p.SourceOrdinal}:{ExplicitContourTests.Fingerprint(p.CopyProgram())}").ToArray();
@@ -38,27 +38,27 @@ public class CuttingHeatOrderTests
[Fact]
public void Setting_RoundTripsAndIsLeftOutWhenOff()
{
var on = CuttingParametersSerializer.Serialize(Parameters(0.25));
var on = CuttingParametersSerializer.Serialize(Parameters(25));
var off = CuttingParametersSerializer.Serialize(Parameters(0));
Assert.Contains("heatWeight", on, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("heatWeight", off, StringComparison.OrdinalIgnoreCase);
Assert.Equal(0.25, CuttingParametersSerializer.Deserialize(on).HeatWeight);
Assert.Equal(0, CuttingParametersSerializer.Deserialize(off).HeatWeight);
Assert.Contains("heatStartLimit", on, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("heatStartLimit", off, StringComparison.OrdinalIgnoreCase);
Assert.Equal(25, CuttingParametersSerializer.Deserialize(on).HeatStartLimit);
Assert.Equal(0, CuttingParametersSerializer.Deserialize(off).HeatStartLimit);
}
[Fact]
public void Setting_IsCopiedAndChangesTheFingerprintOnlyWhenSet()
{
Assert.Equal(0.25, OwnedCuttingParameters.Copy(Parameters(0.25)).HeatWeight);
Assert.Equal(25, OwnedCuttingParameters.Copy(Parameters(25)).HeatStartLimit);
var withoutProperty = StateFingerprint.Of(Parameters(0));
Assert.DoesNotContain("heatWeight", withoutProperty);
Assert.NotEqual(withoutProperty, StateFingerprint.Of(Parameters(0.25)));
Assert.DoesNotContain("heatStartLimit", withoutProperty);
Assert.NotEqual(withoutProperty, StateFingerprint.Of(Parameters(25)));
}
[Fact]
public void WeightOff_PlansTheTravelOrder()
public void LimitOff_PlansTheTravelOrder()
{
var plain = Plan(Grid(), 0);
var again = Plan(Grid(), 0);
@@ -69,7 +69,7 @@ public class CuttingHeatOrderTests
}
[Fact]
public void HighWeight_JumpsBetweenBlocksWithMarkedRaises()
public void LowLimit_LeavesTheTourWithMarkedRaises()
{
var plain = Plan(Grid(), 0);
var heated = Plan(Grid(), 1);
@@ -82,4 +82,76 @@ public class CuttingHeatOrderTests
Assert.NotEqual(plain.ProposedOrder.Select(p => p.SourceOrdinal), heated.ProposedOrder.Select(p => p.SourceOrdinal));
Assert.Equal(heated.HeatRaises, heated.ProposedOrder.Count(p => HeadRaise.IsMarked(p.CopyProgram())));
}
private static CuttingHeat Heat(double limit) => CuttingHeat.For(limit,
OpenNest.CNC.Thermal.ThermalParameters.For("Mild Steel", null, 0.125, Units.Inches), CutParameters.Default);
// A row of parts one inch apart along X, each reached and left at its center.
private static CuttingHeatItem[] Row(int count) => Enumerable.Range(0, count).Select(i =>
{
var center = new Vector(i, 0);
return new CuttingHeatItem(center, center, new Box(i - 0.4, -0.4, 0.8, 0.8), 3, 1);
}).ToArray();
private static IReadOnlyCollection<int>[] NoPrerequisites(int count) =>
Enumerable.Range(0, count).Select(_ => (IReadOnlyCollection<int>)Array.Empty<int>()).ToArray();
[Fact]
public void HighLimit_KeepsThePlainTour()
{
var items = Row(10);
var plain = Enumerable.Range(0, 10).ToArray();
var (order, jumps, _) = CuttingHeatOrder.Plan(plain, new Vector(-1, 0), items, NoPrerequisites(10), Heat(1e6),
CancellationToken.None);
Assert.Equal(plain, order);
Assert.Empty(jumps);
}
[Fact]
public void LowLimit_SkipsTheHotNeighborForTheNearestCoolPart()
{
var items = Row(10);
var plain = Enumerable.Range(0, 10).ToArray();
var (order, jumps, _) = CuttingHeatOrder.Plan(plain, new Vector(-1, 0), items, NoPrerequisites(10), Heat(1),
CancellationToken.None);
Assert.Equal(plain, order.Order());
Assert.NotEqual(plain, order);
Assert.Equal(0, order[0]);
Assert.NotEqual(1, order[1]);
// A move back over a cut part is a jump.
Assert.NotEmpty(jumps);
}
[Fact]
public void Limit_WaitsForPrerequisites()
{
var items = Row(6);
var plain = new[] { 0, 1, 2, 3, 4, 5 };
var prerequisites = NoPrerequisites(6);
prerequisites[5] = [1];
var (order, _, _) = CuttingHeatOrder.Plan(plain, new Vector(-1, 0), items, prerequisites, Heat(1),
CancellationToken.None);
Assert.True(Array.IndexOf(order, 1) < Array.IndexOf(order, 5));
}
[Fact]
public void Limit_ReachesAPartThatCannotBeRaisedHeadDownOnlyWhenNothingElseIsReady()
{
var items = Row(5);
// Part 1 cannot take a raise; reaching it from beyond part 2 crosses part 2.
items[1] = items[1] with { CanRaise = false };
var plain = new[] { 0, 1, 2, 3, 4 };
var (order, jumps, _) = CuttingHeatOrder.Plan(plain, new Vector(-1, 0), items, NoPrerequisites(5), Heat(1),
CancellationToken.None);
Assert.DoesNotContain(1, jumps);
Assert.Equal(plain, order.Order());
}
}
@@ -1,184 +0,0 @@
using System.Diagnostics;
using System.Globalization;
using OpenNest.CNC;
using OpenNest.CNC.CuttingPlanning;
using OpenNest.CNC.Thermal;
using OpenNest.Engine.CuttingPlanning;
using OpenNest.IO;
using Xunit.Abstractions;
namespace OpenNest.Tests.CuttingPlanning;
/// <summary>
/// PROTOTYPE measurement of <see cref="CuttingGridHeatOrder"/> on a large grid plate: the
/// serpentine, every other line, and the start-limit rule at each limit. Opt-in: set
/// OPENNEST_GRID_HEAT_PLATE to "path.nest:1" and optionally OPENNEST_GRID_HEAT_LIMITS to "20,30,45".
/// </summary>
[Trait("Category", "HeatOrder")]
[Collection(nameof(CuttingGridHeatOrder))]
public class GridHeatOrderMeasurementTests(ITestOutputHelper output)
{
[SkippableFact]
public void GridHeatOrder_Measure()
{
var item = Environment.GetEnvironmentVariable("OPENNEST_GRID_HEAT_PLATE");
Skip.If(string.IsNullOrWhiteSpace(item), "Set OPENNEST_GRID_HEAT_PLATE to measure heat-aware grid orders.");
var split = item!.LastIndexOf(':');
var path = item[..split].Trim();
var number = int.Parse(item[(split + 1)..], CultureInfo.InvariantCulture);
var limits = (Environment.GetEnvironmentVariable("OPENNEST_GRID_HEAT_LIMITS") ?? "20,30,45")
.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(l => double.Parse(l.Trim(), CultureInfo.InvariantCulture));
var modes = (Environment.GetEnvironmentVariable("OPENNEST_GRID_HEAT_MODES") ?? "serpentine,alternate,limit")
.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(m => m.Trim()).ToHashSet();
var settings = new List<GridHeatSetting?>();
if (modes.Contains("serpentine"))
settings.Add(null);
if (modes.Contains("alternate"))
settings.Add(new GridHeatSetting(GridHeatMode.Alternate));
if (modes.Contains("limit"))
settings.AddRange(limits.Select(l => new GridHeatSetting(GridHeatMode.Limit, l)));
try
{
foreach (var setting in settings)
{
CuttingGridHeatOrder.Setting = setting;
var line = Measure(path, number, setting);
output.WriteLine(line);
Console.WriteLine(line);
}
}
finally
{
CuttingGridHeatOrder.Setting = null;
}
}
private static string Measure(string path, int number, GridHeatSetting? setting)
{
Nest nest;
using (var stream = File.OpenRead(path))
nest = new NestReader(stream).Read();
var plate = nest.Plates[number - 1];
var parameters = plate.CuttingParameters ?? ProblemNestRegressionTests.DefaultParameters();
parameters.MaterialName = nest.Material?.Name;
parameters.Grade = nest.Material?.Grade;
parameters.Thickness = nest.Thickness;
// Any weight turns heat on; the grid order reads only the setting.
parameters.HeatWeight = setting == null ? 0 : 0.03;
var label = setting == null ? "serpentine" : setting.Mode == GridHeatMode.Alternate ? "alternate"
: FormattableString.Invariant($"limit {setting.LimitCelsius:0} C");
var watch = Stopwatch.StartNew();
var proposal = CuttingPlanBatch.Capture([plate], parameters, preservePartOrder: false, [number],
units: nest.Units).Plan();
var planSeconds = watch.Elapsed.TotalSeconds;
var result = proposal.Plates[0].Result;
if (!proposal.CanApply && !proposal.CanApplyWithWarnings)
return $"{label}: {result.Status}, not applied: " + string.Join(" | ", result.Findings.Take(4).Select(f => f.Message));
var commit = proposal.Apply(acceptWarnings: true);
if (commit.Status != CuttingCommitStatus.Applied)
return $"{label}: {result.Status}, apply {commit.Status}";
var cut = CutParameters.Default;
cut.Units = nest.Units;
var simulation = CutSimulation.Build(plate, cut);
var (p95, p75, starts) = Heat(plate, simulation, nest);
var sorted = starts.Order().ToArray();
double At(double q) => sorted.Length == 0 ? 0 : sorted[(int)(q * (sorted.Length - 1))];
return FormattableString.Invariant(
$"{label}: {result.Status}{(result.IsSafestRouteFallback ? " (safest route)" : "")}, travel {result.RapidDistance:0}, ")
+ FormattableString.Invariant(
$"cut {simulation.TotalTime.TotalMinutes:0.0} min, raises {result.HeadRaises}, heat raises {result.HeatRaises}, ")
+ FormattableString.Invariant($"zone P95 {p95:0.0} P75 {p75:0.0}, ")
+ FormattableString.Invariant(
$"line starts ({sorted.Length}) median {At(0.5):0.0} P90 {At(0.9):0.0} max {At(1):0.0}, plan {planSeconds:0} s");
}
// The zone percentiles of HeatOrderMeasurementTests (4 in squares, sampled every 10 s), and the
// mean temperature over each line's first part when the cut reaches it. A line starts where
// the move from the part before is longer than 1.5 times the median move between parts.
private static (double P95, double P75, List<double> Starts) Heat(Plate plate, CutSimulation simulation, Nest nest)
{
var boxes = plate.Parts.Select(p => p.BoundingBox).ToArray();
var centers = boxes.Select(b => b.Center).ToArray();
// Lines run along the axis consecutive parts mostly share; a line starts where its bin changes.
var tolerance = 0.25 * boxes.Min(b => System.Math.Min(b.Length, b.Width));
var sameX = Enumerable.Range(1, centers.Length - 1).Count(i => System.Math.Abs(centers[i].X - centers[i - 1].X) < tolerance);
var sameY = Enumerable.Range(1, centers.Length - 1).Count(i => System.Math.Abs(centers[i].Y - centers[i - 1].Y) < tolerance);
var bins = CuttingGridOrder.Bins(centers.Select(c => sameX >= sameY ? c.X : c.Y).ToArray(), tolerance,
CancellationToken.None) ?? new int[centers.Length];
var lineStarts = Enumerable.Range(0, centers.Length).Where(i => i == 0 || bins[i] != bins[i - 1]).ToArray();
var heat = new PlateHeatSimulation(plate, simulation, new ThermalParameters
{
Material = ThermalMaterial.ForName($"{nest.Material?.Name} {nest.Material?.Grade}"),
Thickness = nest.Thickness,
Units = nest.Units,
SupportBed = plate.SupportBed,
});
var zone = nest.Units == Units.Millimeters ? 4 * 25.4 : 4.0;
var per = System.Math.Max(1, (int)System.Math.Round(zone / heat.CellSize));
var zoneColumns = (heat.Columns + per - 1) / per;
var zoneRows = (heat.Rows + per - 1) / per;
var hottest = new double[zoneColumns * zoneRows];
var seen = new bool[hottest.Length];
var sums = new double[hottest.Length];
var counts = new int[hottest.Length];
var end = simulation.TotalTime.TotalSeconds + 30;
var events = new SortedSet<(double Time, int Part)>();
for (var t = 10.0; t <= end; t += 10)
events.Add((t, -1));
foreach (var part in lineStarts)
events.Add((simulation.PartStarts[part].TotalSeconds, part));
var starts = new List<double>();
foreach (var (time, part) in events)
{
heat.AdvanceTo(TimeSpan.FromSeconds(time));
var temperatures = heat.Temperatures;
if (part >= 0)
{
var box = plate.Parts[part].BoundingBox;
double sum = 0;
var count = 0;
for (var row = 0; row < heat.Rows; row++)
{
var y = heat.OriginY + (row + 0.5) * heat.CellSize;
if (y < box.Bottom || y > box.Top)
continue;
for (var column = 0; column < heat.Columns; column++)
{
var x = heat.OriginX + (column + 0.5) * heat.CellSize;
var index = row * heat.Columns + column;
if (x < box.Left || x > box.Right || heat.IsRemoved(index))
continue;
sum += temperatures[index];
count++;
}
}
if (count > 0)
starts.Add(sum / count);
continue;
}
Array.Clear(sums);
Array.Clear(counts);
for (var row = 0; row < heat.Rows; row++)
for (var column = 0; column < heat.Columns; column++)
{
var index = row * heat.Columns + column;
if (heat.IsRemoved(index))
continue;
var z = row / per * zoneColumns + column / per;
sums[z] += temperatures[index];
counts[z]++;
}
for (var z = 0; z < hottest.Length; z++)
if (counts[z] > 0)
{
seen[z] = true;
hottest[z] = System.Math.Max(hottest[z], sums[z] / counts[z]);
}
}
var values = hottest.Where((_, z) => seen[z]).Order().ToArray();
return values.Length == 0 ? (0, 0, starts)
: (values[(int)(0.95 * (values.Length - 1))], values[(int)(0.75 * (values.Length - 1))], starts);
}
}
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Globalization;
using OpenNest.CNC;
using OpenNest.CNC.CuttingPlanning;
using OpenNest.CNC.Thermal;
@@ -9,36 +10,40 @@ using Xunit.Abstractions;
namespace OpenNest.Tests.CuttingPlanning;
/// <summary>
/// Measures how a heat weight changes a plate's plan: the hottest-zone percentiles from
/// <see cref="PlateHeatSimulation"/>, travel, cut time and head raises. Opt-in: set
/// OPENNEST_HEAT_PLATES to "path.nest:2;other.nest:1" (1-based plate numbers) and optionally
/// OPENNEST_HEAT_WEIGHTS to "0,0.1,0.2". See docs/plate-heat-map.md#sequencing.
/// Measures how a heat start limit changes a plate's plan: the temperature where each part (or,
/// on a grid, each line) starts and the hottest-zone percentiles from <see cref="PlateHeatSimulation"/>,
/// travel, cut time and head raises. Opt-in: set OPENNEST_HEAT_PLATES to "path.nest:2;other.nest:1"
/// (1-based plate numbers) and optionally OPENNEST_HEAT_LIMITS to "0,15,30" (°C, 0 = off). See
/// docs/plate-heat-map.md#sequencing.
/// </summary>
[Trait("Category", "HeatOrder")]
public class HeatOrderMeasurementTests(ITestOutputHelper output)
{
private const string PlatesVariable = "OPENNEST_HEAT_PLATES";
private const string WeightsVariable = "OPENNEST_HEAT_WEIGHTS";
[SkippableFact]
public void HeatOrder_Measure()
{
var plates = Environment.GetEnvironmentVariable(PlatesVariable);
Skip.If(string.IsNullOrWhiteSpace(plates), $"Set {PlatesVariable} to measure heat-aware plans.");
var weights = (Environment.GetEnvironmentVariable(WeightsVariable) ?? "0,0.1,0.2")
.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(w => double.Parse(w.Trim(), System.Globalization.CultureInfo.InvariantCulture))
.ToArray();
var plates = Environment.GetEnvironmentVariable("OPENNEST_HEAT_PLATES");
Skip.If(string.IsNullOrWhiteSpace(plates), "Set OPENNEST_HEAT_PLATES to measure heat-aware plans.");
var limits = Numbers("OPENNEST_HEAT_LIMITS", "0,15,20,30,45");
foreach (var item in plates!.Split(';', StringSplitOptions.RemoveEmptyEntries))
{
var split = item.LastIndexOf(':');
var path = item[..split].Trim();
var number = int.Parse(item[(split + 1)..]);
foreach (var weight in weights)
output.WriteLine(Measure(path, number, weight));
var number = int.Parse(item[(split + 1)..], CultureInfo.InvariantCulture);
foreach (var limit in limits)
{
var line = Measure(path, number, limit);
output.WriteLine(line);
Console.WriteLine(line);
}
}
}
internal static string Measure(string path, int number, double weight)
private static double[] Numbers(string variable, string fallback) =>
(Environment.GetEnvironmentVariable(variable) ?? fallback).Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(v => double.Parse(v.Trim(), CultureInfo.InvariantCulture)).ToArray();
private static string Measure(string path, int number, double limit)
{
Nest nest;
using (var stream = File.OpenRead(path))
@@ -48,14 +53,16 @@ public class HeatOrderMeasurementTests(ITestOutputHelper output)
parameters.MaterialName = nest.Material?.Name;
parameters.Grade = nest.Material?.Grade;
parameters.Thickness = nest.Thickness;
parameters.HeatWeight = weight;
parameters.HeatStartLimit = limit;
var label = FormattableString.Invariant(
$"{Path.GetFileNameWithoutExtension(path)} plate {number} ({plate.Parts.Count} parts, {nest.Thickness} in) ")
+ (limit == 0 ? "off" : FormattableString.Invariant($"limit {limit:0} C"));
var watch = Stopwatch.StartNew();
var proposal = CuttingPlanBatch.Capture([plate], parameters, preservePartOrder: false, [number],
units: nest.Units).Plan();
var planSeconds = watch.Elapsed.TotalSeconds;
var planned = proposal.Plates[0];
var result = planned.Result;
var label = $"{Path.GetFileNameWithoutExtension(path)} plate {number} ({plate.Parts.Count} parts, {nest.Thickness} in) w={weight}";
if (!proposal.CanApply && !proposal.CanApplyWithWarnings)
return $"{label}: {result.Status}, not applied: " + string.Join(" | ", result.Findings.Take(4).Select(f => f.Message));
var commit = proposal.Apply(acceptWarnings: true);
@@ -64,24 +71,44 @@ public class HeatOrderMeasurementTests(ITestOutputHelper output)
var cut = CutParameters.Default;
cut.Units = nest.Units;
var simulation = CutSimulation.Build(plate, cut);
var zone = double.TryParse(Environment.GetEnvironmentVariable("OPENNEST_HEAT_ZONE"),
System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var size) ? size : 4.0;
var (p95, p75) = Zones(plate, simulation, nest, zone, Environment.GetEnvironmentVariable("OPENNEST_HEAT_DUMP") is { Length: > 0 } dump
? Path.Combine(dump, $"{Path.GetFileNameWithoutExtension(path)}-{number}-w{weight}") : null);
return $"{label}: {result.Status}{(result.IsSafestRouteFallback ? " (safest route)" : "")}"
+ $"{(planned.KeptCurrentOrder ? " (kept order)" : "")}, travel {result.RapidDistance:0.0}, "
+ $"cut {simulation.TotalTime.TotalSeconds:0.0} s, raises {result.HeadRaises}, heat raises {result.HeatRaises}, "
+ $"zone P95 {p95:0.0}, P75 {p75:0.0}, expansions {result.Expansions}, plan {planSeconds:0.0} s";
var (p95, p75, starts) = Heat(plate, simulation, nest);
var sorted = starts.Order().ToArray();
double At(double q) => sorted.Length == 0 ? 0 : sorted[(int)(q * (sorted.Length - 1))];
return FormattableString.Invariant(
$"{label}: {result.Status}{(result.IsSafestRouteFallback ? " (safest route)" : "")}")
+ FormattableString.Invariant(
$"{(planned.KeptCurrentOrder ? " (kept order)" : "")}, travel {result.RapidDistance:0.0}, ")
+ FormattableString.Invariant(
$"cut {simulation.TotalTime.TotalSeconds:0.0} s, raises {result.HeadRaises}, heat raises {result.HeatRaises}, ")
+ FormattableString.Invariant($"zone P95 {p95:0.0} P75 {p75:0.0}, ")
+ FormattableString.Invariant(
$"starts ({sorted.Length}) median {At(0.5):0.0} P90 {At(0.9):0.0} max {At(1):0.0}, plan {planSeconds:0.0} s");
}
// The hottest average over each 4 in square during the cut, as the 95th and 75th percentile
// over squares. Cells whose slug fell away do not count.
internal static (double P95, double P75) Zones(Plate plate, CutSimulation simulation, Nest nest, double zoneInches = 4,
string? dump = null)
// over squares (sampled every second, every 10 s past 1,000 parts), and the mean temperature
// over each start's part when the cut reaches it. Cells whose slug fell away do not count. On
// a grid (CuttingGridOrder.Bins along the axis consecutive parts mostly share) a start is a
// line's first part; otherwise every part.
private static (double P95, double P75, List<double> Starts) Heat(Plate plate, CutSimulation simulation, Nest nest)
{
if (dump != null)
File.WriteAllLines(dump + "-order.csv", plate.Parts.Select(p => FormattableString.Invariant(
$"{p.BoundingBox.Center.X},{p.BoundingBox.Center.Y},{p.BoundingBox.Length},{p.BoundingBox.Width}")));
var boxes = plate.Parts.Select(p => p.BoundingBox).ToArray();
var centers = boxes.Select(b => b.Center).ToArray();
int[] lineStarts;
var tolerance = 0.25 * boxes.Min(b => System.Math.Min(b.Length, b.Width));
var grid = plate.Parts.Count >= CuttingGridOrder.MinimumParts
&& CuttingGridOrder.Lines(boxes, OpenNest.Geometry.Vector.Zero, CancellationToken.None) != null;
if (grid)
{
var sameX = Enumerable.Range(1, centers.Length - 1).Count(i => System.Math.Abs(centers[i].X - centers[i - 1].X) < tolerance);
var sameY = Enumerable.Range(1, centers.Length - 1).Count(i => System.Math.Abs(centers[i].Y - centers[i - 1].Y) < tolerance);
var bins = CuttingGridOrder.Bins(centers.Select(c => sameX >= sameY ? c.X : c.Y).ToArray(), tolerance,
CancellationToken.None) ?? new int[centers.Length];
lineStarts = Enumerable.Range(0, centers.Length).Where(i => i == 0 || bins[i] != bins[i - 1]).ToArray();
}
else
lineStarts = Enumerable.Range(0, centers.Length).ToArray();
var heat = new PlateHeatSimulation(plate, simulation, new ThermalParameters
{
Material = ThermalMaterial.ForName($"{nest.Material?.Name} {nest.Material?.Grade}"),
@@ -89,7 +116,7 @@ public class HeatOrderMeasurementTests(ITestOutputHelper output)
Units = nest.Units,
SupportBed = plate.SupportBed,
});
var zone = nest.Units == Units.Millimeters ? zoneInches * 25.4 : zoneInches;
var zone = nest.Units == Units.Millimeters ? 4 * 25.4 : 4.0;
var per = System.Math.Max(1, (int)System.Math.Round(zone / heat.CellSize));
var zoneColumns = (heat.Columns + per - 1) / per;
var zoneRows = (heat.Rows + per - 1) / per;
@@ -98,12 +125,43 @@ public class HeatOrderMeasurementTests(ITestOutputHelper output)
var sums = new double[hottest.Length];
var counts = new int[hottest.Length];
var end = simulation.TotalTime.TotalSeconds + 30;
for (var t = 1.0; t <= end; t += 1.0)
var interval = plate.Parts.Count > 1000 ? 10.0 : 1.0;
var events = new SortedSet<(double Time, int Part)>();
for (var t = interval; t <= end; t += interval)
events.Add((t, -1));
foreach (var part in lineStarts)
events.Add((simulation.PartStarts[part].TotalSeconds, part));
var starts = new List<double>();
foreach (var (time, part) in events)
{
heat.AdvanceTo(TimeSpan.FromSeconds(t));
heat.AdvanceTo(TimeSpan.FromSeconds(time));
var temperatures = heat.Temperatures;
if (part >= 0)
{
var box = boxes[part];
double sum = 0;
var count = 0;
for (var row = 0; row < heat.Rows; row++)
{
var y = heat.OriginY + (row + 0.5) * heat.CellSize;
if (y < box.Bottom || y > box.Top)
continue;
for (var column = 0; column < heat.Columns; column++)
{
var x = heat.OriginX + (column + 0.5) * heat.CellSize;
var index = row * heat.Columns + column;
if (x < box.Left || x > box.Right || heat.IsRemoved(index))
continue;
sum += temperatures[index];
count++;
}
}
if (count > 0)
starts.Add(sum / count);
continue;
}
Array.Clear(sums);
Array.Clear(counts);
var temperatures = heat.Temperatures;
for (var row = 0; row < heat.Rows; row++)
for (var column = 0; column < heat.Columns; column++)
{
@@ -121,15 +179,8 @@ public class HeatOrderMeasurementTests(ITestOutputHelper output)
hottest[z] = System.Math.Max(hottest[z], sums[z] / counts[z]);
}
}
if (dump != null)
{
var peaks = heat.Peaks.ToArray();
File.WriteAllLines(dump + "-peaks.csv", Enumerable.Range(0, heat.Rows).Select(row => string.Join(",",
Enumerable.Range(0, heat.Columns).Select(column => heat.IsRemoved(row * heat.Columns + column) ? "nan"
: peaks[row * heat.Columns + column].ToString(System.Globalization.CultureInfo.InvariantCulture)))));
}
var values = hottest.Where((_, z) => seen[z]).OrderBy(v => v).ToArray();
return values.Length == 0 ? (0, 0)
: (values[(int)(0.95 * (values.Length - 1))], values[(int)(0.75 * (values.Length - 1))]);
var values = hottest.Where((_, z) => seen[z]).Order().ToArray();
return values.Length == 0 ? (0, 0, starts)
: (values[(int)(0.95 * (values.Length - 1))], values[(int)(0.75 * (values.Length - 1))], starts);
}
}
+14 -11
View File
@@ -39,7 +39,7 @@ namespace OpenNest.Controls
private readonly ComboBox cboLabelMode;
private readonly NumericUpDown nudPierceClearance;
private readonly NumericUpDown nudPierceDiameter;
private readonly NumericUpDown nudHeatWeight;
private readonly NumericUpDown nudHeatStartLimit;
private CuttingParameters loaded;
@@ -324,15 +324,18 @@ namespace OpenNest.Controls
AddSection("Heat");
var heatGrid = ControlFactory.SettingsGrid(0);
nudHeatWeight = CreateNumeric(0, 0.01);
nudHeatWeight.Maximum = 100;
AddRow(heatGrid, "Spread heat (s per °C):", nudHeatWeight, 0, "0 = off");
toolTip.SetToolTip(nudHeatWeight,
"Plan Cutting cuts the parts in blocks and moves to a cooler block when the heat estimated where "
+ "the next part is cut, times this many seconds per degree, outweighs the extra travel. A move "
+ "across parts already cut raises the head. 0 orders the parts by travel alone.");
nudHeatStartLimit = CreateNumeric(0, 5);
nudHeatStartLimit.DecimalPlaces = 0;
nudHeatStartLimit.Maximum = 1000;
AddRow(heatGrid, "Don't start above (°C rise):", nudHeatStartLimit, 0, "0 = off");
toolTip.SetToolTip(nudHeatStartLimit,
"Before each part (or each line of a large grid), Plan Cutting estimates how far the sheet where it "
+ "starts has warmed from the parts already cut. Above this rise it goes to the nearest part that is "
+ "cooler, or the coolest when none is. A move across parts already cut raises the head. The "
+ "estimate is uncalibrated: compare settings rather than trusting the degrees. 0 orders the parts by "
+ "travel alone.");
column.Controls.Add(heatGrid);
nudHeatWeight.ValueChanged += (s, e) => OnParametersChanged();
nudHeatStartLimit.ValueChanged += (s, e) => OnParametersChanged();
Controls.Add(layout);
@@ -406,7 +409,7 @@ namespace OpenNest.Controls
parameters.TabSizeMaxWidth = (double)nudTabSizeMax.Value;
parameters.SliceTippingSlugs = chkSliceSlugs.Checked;
parameters.LabelMode = (PartLabelMode)System.Math.Max(0, cboLabelMode.SelectedIndex);
parameters.HeatWeight = (double)nudHeatWeight.Value;
parameters.HeatStartLimit = (double)nudHeatStartLimit.Value;
return parameters;
}
@@ -436,7 +439,7 @@ namespace OpenNest.Controls
cboLabelMode.SelectedIndex = System.Enum.IsDefined(p.LabelMode) ? (int)p.LabelMode : (int)PartLabelMode.Off;
nudPierceClearance.Value = Clamp(nudPierceClearance, p.PierceClearance);
nudPierceDiameter.Value = Clamp(nudPierceDiameter, p.PierceDiameter);
nudHeatWeight.Value = Clamp(nudHeatWeight, p.HeatWeight);
nudHeatStartLimit.Value = Clamp(nudHeatStartLimit, p.HeatStartLimit);
chkRoundLeadInAngles.Checked = p.RoundLeadInAngles;
nudLeadInAngleIncrement.Value = Clamp(nudLeadInAngleIncrement, p.LeadInAngleIncrement);
nudLeadInAngleIncrement.Enabled = p.RoundLeadInAngles;
+39 -21
View File
@@ -913,31 +913,49 @@ overlap check may likewise be accepted with warnings. `CanApply` and parameterle
explicit review path. `CuttingPlanService.Apply` still rejects best-effort results directly.
Acceptance never skips the separate pre-post checks or grants posting consent.
### Heat blocks
### Heat start limit
With `CuttingParameters.HeatWeight` above 0 (seconds of travel per °C, off by default; saved per
material and thickness, see [machine cutting defaults](machine-cutting-defaults.md)), `Tour` may
replace the plain tour of a plate without nested parts by an order that spreads the cut's heat
(`CuttingHeatOrder`). Large grids keep their serpentine. Candidates are the plain tour, two
cutting fronts (the plate split where half the cut length lies on each side, along its long and
its short axis, each half toured toward the split) and blocks on 2x2, 3x3, 4x4 and 6x6 grids,
each block toured with the plain tour from its corner nearest the start. Blocks are interleaved
greedily: each step takes the ready block head with the least cost, the current block first on
ties. A move to another block whose straight rapid crosses the box of a part already cut is a
heat jump. Each order is scored as travel seconds, plus 2 s per jump, plus the weight times the
temperature estimated at each part when the tool reaches it, and the cheapest wins; ties keep the
plain tour. The estimate is the removed sequencer's
([plate heat map](plate-heat-map.md#sequencing)): a Gaussian per finished part, spreading and
fading with time, fed by the Cut Simulator's feeds and pierce (`CuttingPlanRequest.CutTimes`,
`CutParameters.Default` when not given).
With `CuttingParameters.HeatStartLimit` above 0 (an estimated temperature rise in °C, off by
default; saved per material and thickness, see [machine cutting defaults](machine-cutting-defaults.md)),
the order does not start work where the cut so far left the sheet hot (`CuttingHeatOrder`). The
rule is the same for single parts and for the lines of a large grid: before each next piece of
work it estimates the temperature where the piece starts when the tool gets there. The plain
order's next piece is cut when it is at or under the limit and reached without crossing a part
already cut; otherwise the nearest ready piece under the limit (travel seconds, plus 2 s for a
move across cut parts); otherwise the coolest. Prerequisites are respected, and a piece whose
first part cannot take a raise (below) is reached across cut parts only when no other piece is
ready.
The arrival rapid of a part the order reaches by a heat jump is raised in the strict search
- Parts: the pieces are the plain tour's parts, on plates without parts nested in others. The
heat of every part counts, the one just cut included; leaving the latest part out (the heat
right behind the torch) made the rule fire far less without spreading the heat (see
[sequencing](plate-heat-map.md#sequencing)). When the search re-plans the rest of a plate
after a learned order rule, the parts already cut count for the heat and for crossings.
- Grids: the pieces are the serpentine's lines (`CuttingGridOrder.Lines`). Each keeps its parts
in order and is cut from whichever end lies nearer the tool; only which line comes next
changes. The estimate keeps every part's heat. On a plate of washers this is every other line
out and the rest back, without being told.
A leg of the plain order is checked for crossings only against parts the rule cut ahead of it
and parts cut before a re-plan; the plain order's own legs over parts it cut in order are the
search's to judge, as without the limit. So a limit the estimate never reaches leaves the plain
order unchanged. The estimate is the removed sequencer's ([plate heat map](plate-heat-map.md#sequencing)):
a Gaussian per finished part, spreading and fading with time, fed by the Cut Simulator's feeds and
pierce (`CuttingPlanRequest.CutTimes`, `CutParameters.Default` when not given), and taken at the
next piece's arrival. It is uncalibrated, so the limit compares orders rather than promising a
temperature.
A move to a piece whose straight rapid crosses the box of a part already cut is a heat jump. The
arrival rapid of a part the order reaches by a heat jump is raised in the strict search
(`ReleasedContourState.RaisesArrival`), so its crossings are not findings, and marked `HEAD RAISE`
before replay (`RaisedRapids.MarkHeatJumps`). Such a jump is designed: it is counted in
`CuttingPlanResult.HeatRaises`, not `HeadRaises`, and each is listed as a note. A part with a
locked program or a cut-off cannot carry the mark, so a move to one that crosses cut parts costs so
much it is taken only when nothing else is ready, and then is checked head-down as before. With the
weight at 0 nothing here runs, and plans are byte-identical to the plain tour's.
locked program or a cut-off cannot carry the mark (`CuttingHeatItem.CanRaise`), so it is reached
head-down as before. With the limit at 0 nothing here runs, and plans are byte-identical to the
plain tour's and the plain serpentine's.
Once the estimate is calibrated against FLIR readings, the rule could insert a dwell before a
start when no order keeps it under the limit; that is future work.
### Safest-route fallback when the search runs out
@@ -968,7 +986,7 @@ before the rapid in the part's program, which saves with the nest. A sub-program
so it is never marked: when the rapid arrives at a hole sub-program (a round hole is cut as one),
the comment goes directly before the part's own call, and the call's arrival rapid is the raised
one (`ExecutionMotion.CallCode` names the call a sub-program's motions run in). Apart from the
slug exits below and the heat jumps of an opt-in heat weight ([Heat blocks](#heat-blocks)), this is
slug exits below and the heat jumps of an opt-in heat start limit ([Heat start limit](#heat-start-limit)), this is
the only place a raise is added, so a plate the strict search can plan never gets one: it is the
last resort for a route no search kept head-down, not a shortcut.
+1 -1
View File
@@ -28,7 +28,7 @@ save them on close; thicknesses matching none stay blank.
Every setting in Plan Cutting's Cutting Parameters dialog and the Place Lead-in panel is kept on
the nest's machine thickness: leads on the Outside Cuts and Inside Cuts tabs, lead-in angle
rounding, tabs, [slug slicing](support-tabs.md#slug-slices), [part label etching](label-box.md#etching-the-label) (off, part number, or part number and bend groups), pierce and the [heat weight](cutting-planner.md#heat-blocks) on the Tabs & Pierce tab
rounding, tabs, [slug slicing](support-tabs.md#slug-slices), [part label etching](label-box.md#etching-the-label) (off, part number, or part number and bend groups), pierce and the [heat start limit](cutting-planner.md#heat-start-limit) on the Tabs & Pierce tab
(`ThicknessConfig.Cutting`). So 0.25 in can
tab parts while 0.5 in tabs none, and in Database mode every workstation gets the same
settings. The dialog names what it edits above its fields ("Saved for Fiber 1 · Mild Steel A36
+60 -26
View File
@@ -3,7 +3,7 @@
`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 and never changes the plate;
Plan Cutting's opt-in heat weight orders parts with a cheaper estimate of the same physics ([Sequencing](#sequencing)).
Plan Cutting's opt-in heat start limit orders parts with a cheaper estimate of the same physics ([Sequencing](#sequencing)).
## Model
@@ -120,37 +120,71 @@ bed, and its heat label says whether the sheet is cooled by air only or by air a
## Sequencing
Plan Cutting's part order spreads the heat when the cutting parameters set `HeatWeight` (seconds
of travel per °C, 0 = off, saved per material and thickness on the Tabs & Pierce tab). The order
is still Plan Cutting's: it cuts the parts in blocks or from two fronts and moves to a cooler block
when the estimated heat outweighs the travel; a move across parts already cut raises the head
(`HEAD RAISE`, counted as heat raises). See [heat blocks](cutting-planner.md#heat-blocks). This
simulation only scores finished plans; the order uses a cheaper estimate, ported from the
sequencer removed earlier:
Plan Cutting's part order keeps work from starting where the sheet is hot when the cutting
parameters set `HeatStartLimit` (an estimated temperature rise in °C, 0 = off, saved per material
and thickness on the Tabs & Pierce tab as "Don't start above (°C rise)"). Before each part, or
each line of a large grid, the order estimates the temperature where it starts: the tour's next
piece when that is at or under the limit, else the nearest under it, else the coolest. A move
across parts already cut raises the head (`HEAD RAISE`, counted as heat raises). See
[heat start limit](cutting-planner.md#heat-start-limit). This simulation only scores finished
plans; the order uses a cheaper estimate, ported from the sequencer removed earlier:
- 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.
and fading with the surface loss; for single parts only the latest 200 parts count, for grid
lines every part does. It is read at the next piece's arrival.
- Torch-on time comes from each part's cut length and pierces at the Cut Simulator's feeds and
pierce time (`CutParameters`, this PC's saved values in the desktop, `CutParameters.Default`
elsewhere), and travel time at its rapid rate.
Measured with `HeatOrderMeasurementTests` (opt-in, `OPENNEST_HEAT_PLATES`), default timing
(100 in/min cut, 300 in/min rapid, 0.5 s pierce), against the plan with the weight off. The zone
metric is the hottest average over each 4 in square during the cut, as a percentile over zones:
Neither model is calibrated, so a limit compares orders rather than promising a temperature (the
estimate runs hotter than this simulation right beside a part just cut). Once the model is
calibrated against FLIR readings, the planner could insert a dwell (delay) before a start when no
order keeps it under the limit; that is future work.
| Plate | Weight | Travel | Cut time | Heat raises | Zone P95 | Zone P75 |
|-------|--------|--------|----------|-------------|----------|----------|
| Dense small parts (121 parts, 0.12 in) | 0.03 | +162% | +7.8% | 25 | −30% | −30% |
| | 0.1 | +237% | +11.4% | 37 | −37% | −37% |
| | 0.3 | +338% | +16.2% | 57 | −34% | −34% |
| 130 parts, 0.25 in | 0.1 | 0 | 0 | 0 | 0 | 0 |
| | 1 | +51% | +5.1% | 41 | −10% | −11% |
| 110 parts, 0.12 in, locked programs | 0.03 | +98% | +1.4% | 0 | −23% | −13% |
| | 0.1 | +303% | +4.4% | 0 | −29% | −24% |
Measured with `HeatOrderMeasurementTests` (opt-in, `OPENNEST_HEAT_PLATES`, `OPENNEST_HEAT_LIMITS`),
default timing (100 in/min cut, 300 in/min rapid, 0.5 s pierce), against the plan with the limit
off. Zone is the hottest average over each 4 in square during the cut, as a percentile over zones;
starts are this simulation's mean temperature over each part (on the grid, each line's first part)
when the cut reaches it, median / P90 in °C:
No plan gained a fallback head raise. Thin sheets of dense small parts gain most; thick sheets,
where the sheet carries the heat away faster than the order moves, barely change below a weight of
1. Parts with locked programs cannot carry a raise, so the order reaches them head-down. Above
about 0.3 the extra jumps stop helping. Calibrate the absorbed power and feeds against FLIR
thermal-camera readings before tuning further.
| Plate | Limit | Travel | Cut time | Heat raises | Zone P95 | Zone P75 | Starts |
|-------|-------|--------|----------|-------------|----------|----------|--------|
| Washers, 5,742 parts in a grid, 0.179 in | off | | | | | | 63 / 106 |
| | 15 °C | +1.5% | +0.1% | 2 | −6% | −12% | 6.3 / 9.0 |
| | 20–30 °C | +1.4% | +0.1% | 1 | −6% | −13% | 6.1 / 8.9 |
| | 45 °C | +1.4% | +0.1% | 1 | −7% | −12% | 6.8 / 8.8 |
| Thin parts, 132 parts, 0.06 in | off | | | | | | 13.2 / 37.5 |
| | 10 °C | +17% | +2.7% | 40 | −24% | −28% | 1.8 / 2.8 |
| | 15 °C | +15% | +2.3% | 37 | −25% | −26% | 1.8 / 3.3 |
| | 20 °C | +10% | +1.6% | 56 | −26% | −29% | 0.8 / 2.5 |
| | 30 °C | +10% | +1.6% | 60 | −25% | −28% | 0.8 / 5.7 |
| | 45 °C | +9% | +1.4% | 55 | −20% | −27% | 0.8 / 7.9 |
| 30 parts, 0.12 in | off | | | | | | 4.9 / 24.0 |
| | 10 °C | +1.6% | +0.4% | 14 | −16% | −8% | 1.1 / 4.0 |
| | 15 °C | +3.6% | +0.8% | 11 | −15% | −11% | 0.6 / 2.2 |
| | 20 °C | +4.5% | +1.1% | 8 | −12% | −6% | 1.0 / 16.1 |
| | 30–45 °C | 0 | 0 | 0 | 0 | 0 | unchanged |
| 33 parts, 0.12 in (off has one fallback raise) | 10 °C | +30% | +5.9% | 17 | −10% | −13% | 1.0 / 3.5 |
| | 15 °C | +28% | +5.5% | 14 | −8% | −13% | 0.8 / 4.0 |
| | 20 °C | +26% | +5.1% | 9 | −2% | −8% | 1.3 / 7.2 |
| | 30–45 °C | 0 | 0 | 0 | 0 | 0 | unchanged |
| 130 parts, 0.25 in | 10 °C | +15% | +1.5% | 28 | −18% | −12% | 1.8 / 4.5 |
| | 15 °C | +9% | +0.9% | 18 | −12% | −6% | 1.9 / 8.6 |
| | 20 °C | +3.3% | +0.3% | 8 | −8% | −3% | 2.5 / 8.9 |
| | 30–45 °C | 0 | 0 | 0 | 0 | 0 | unchanged |
Second sheets of the thin and 30-part nests matched their first. No plan gained a fallback head
raise. On the grid the limit lowers every line's start from about 63 °C to 6 °C for about 1.5%
more travel: every other line out and the rest back fell out of the rule. The hottest zones fall
less (−6%), since the heat right behind the torch cannot be fixed by order. Thin sheets gain
most; on them every neighbor of a part just cut is over a low limit, so the rule leaves the tour
for about every other part, and higher limits do not always take fewer raises, since the parts
they skip are left scattered. A limit the estimate never reaches leaves the plan exactly as with
the limit off. Leaving the part just cut out of the estimate (the heat right behind the torch)
was tried for single parts and dropped: it halved the raises on the thin sheet but left the
starts' P90 at 32–36 °C, where counting it brings them to about 3 °C.
The weighted block order this replaced (a travel-seconds-per-°C weight choosing among two cutting
fronts and 2x2-6x6 blocks) cut the 0.25 in sheet's zone P95 by 10% for 51% more travel, 5.1%
more cut time and 41 raises; the 10 °C limit cuts it by 18% for 15%, 1.5% and 28.