mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-11-28 02:41:34 -05:00
feat(cutting): repair safest-route head raises by local reorders
The safest-route fallback walks greedily and never revisits a part it has cut, so a rapid that passes over a cut part gets a head raise even where cutting two parts the other way round keeps the head down (N26-2DC plate 2: 5 raises). After the walk, each raised rapid now tries cutting its target before the earliest part crossed, and each crossed part just before or after the target. Only the moved parts and their neighbors are planned again; a change is kept only when the full replay breaks no more checks and raises fewer times, so a route can only get safer. Kept part orders are never changed. N26-2DC plate 2 drops to 1 raise and 2732.6 in of rapids (was 2804.8). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
332b8452b2
commit
c29085c9d7
6 files changed
+309
-16
No files matched your search
@@ -517,8 +517,27 @@ public static class CuttingPlanService
|
||||
// twice the strict search's budget. Replay still checks it against the captured input.
|
||||
var budget = (int)System.Math.Min(int.MaxValue, 2L * snapshot.ExpansionBudget);
|
||||
var order = JointCuttingPlanSearch.SafestRoute(snapshot.WithSearchLimits(budget, snapshot.MaxEntries), token);
|
||||
if (order == null)
|
||||
if (order == null || ReplaySafestRoute(snapshot, order, token) is not { } result)
|
||||
return null;
|
||||
// The walk never goes back to a part it cut: try cutting parts the other way round
|
||||
// where its rapids raise the head over them.
|
||||
try
|
||||
{
|
||||
result = RaisedRapidRepair.Repair(snapshot, order, result,
|
||||
changed => ReplaySafestRoute(snapshot, changed, token), token);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException)
|
||||
{
|
||||
// A route that cannot be read for its crossings keeps its raises.
|
||||
}
|
||||
result.Snapshot = snapshot;
|
||||
return result;
|
||||
}
|
||||
|
||||
// The route with its crossing rapids marked to raise the head, replayed; null when refused.
|
||||
private static CuttingPlanResult ReplaySafestRoute(CuttingPlanSnapshot snapshot,
|
||||
IReadOnlyList<FixedProgramPlacement> order, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
order = RaisedRapids.Mark(snapshot, order, token);
|
||||
@@ -528,11 +547,8 @@ public static class CuttingPlanService
|
||||
// A route that cannot be read for marking keeps its crossings as findings.
|
||||
}
|
||||
var result = ReplayPrograms(snapshot, order, 0, token, safestRoute: true);
|
||||
if (result.Status is not (CuttingPlanStatus.Ready or CuttingPlanStatus.BestEffort)
|
||||
|| result.SafestRoute is { Severe: > 0 })
|
||||
return null;
|
||||
result.Snapshot = snapshot;
|
||||
return result;
|
||||
return result.Status is not (CuttingPlanStatus.Ready or CuttingPlanStatus.BestEffort)
|
||||
|| result.SafestRoute is { Severe: > 0 } ? null : result;
|
||||
}
|
||||
|
||||
// Re-read EXACT selected programs with a fresh checker and native lead validation.
|
||||
|
||||
@@ -277,6 +277,38 @@ internal static class JointCuttingPlanSearch
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plans windows of a safest route again along a changed part order (see
|
||||
/// <see cref="Walk.Resequence"/>), every call drawing on one search budget.
|
||||
/// </summary>
|
||||
internal sealed class Resequencer(CuttingPlanSnapshot snapshot, CancellationToken token)
|
||||
{
|
||||
private readonly Walk walk = new(snapshot, token, []);
|
||||
|
||||
/// <summary>True once the budget ran out; every later call returns null.</summary>
|
||||
internal bool Exhausted { get; private set; }
|
||||
|
||||
internal IReadOnlyList<FixedProgramPlacement> Cut(IReadOnlyList<FixedProgramPlacement> order,
|
||||
int[] sequence, int from, int to)
|
||||
{
|
||||
if (Exhausted)
|
||||
return null;
|
||||
try
|
||||
{
|
||||
return walk.Resequence(order, sequence, from, to);
|
||||
}
|
||||
catch (BudgetExceededException)
|
||||
{
|
||||
Exhausted = true;
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Captured containment (never learned rules) and each host's placed cut contours.
|
||||
private static CuttingNestedOrder.Context NestedOrder(CuttingPlanSnapshot snapshot, Vector[] centers,
|
||||
HashSet<int>[] prerequisites, CancellationToken token)
|
||||
@@ -1736,9 +1768,42 @@ internal static class JointCuttingPlanSearch
|
||||
/// <summary>The holes, next along the tour, a safest-route step weighs for its next cut.</summary>
|
||||
private const int SafestHoleWindow = 4;
|
||||
|
||||
// One part's route from the node, its perimeter last. Null when it cannot be emitted.
|
||||
private SafestStep SafestPart(Node node, FixedProgramPlacement source)
|
||||
/// <summary>
|
||||
/// <paramref name="order"/> with the parts at <paramref name="from"/> through <paramref name="to"/>
|
||||
/// of <paramref name="sequence"/> planned again, each by the safest-route step facing the
|
||||
/// next part along it, from where the proposals before <paramref name="from"/> leave the
|
||||
/// tool. The proposals after <paramref name="to"/> are kept as they are. The sequence must
|
||||
/// match the order outside that window. Null when a part cannot be emitted.
|
||||
/// </summary>
|
||||
internal IReadOnlyList<FixedProgramPlacement> Resequence(IReadOnlyList<FixedProgramPlacement> order,
|
||||
int[] sequence, int from, int to)
|
||||
{
|
||||
var checker = snapshot.NewReleasedState();
|
||||
var position = snapshot.StartPoint;
|
||||
foreach (var proposal in order.Take(from))
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var execution = ExecutionMotionReader.Read(proposal.CopyProgram(), proposal.Location, position, token);
|
||||
checker.Check(execution, position, proposal.SourceOrdinal + 1, proposal.IsCutOff,
|
||||
proposal.FixedMotions(execution), token, snapshot.WarnsTabLeadOuts(proposal));
|
||||
position = execution.DeparturePoint;
|
||||
}
|
||||
var node = new Node([.. order.Take(from)], position, checker, null, null);
|
||||
for (var index = from; index <= to; index++)
|
||||
{
|
||||
if (SafestPart(node, snapshot.Placements[sequence[index]], sequence) is not { } step)
|
||||
return null;
|
||||
node = step.Node;
|
||||
}
|
||||
var kept = order.ToDictionary(p => p.SourceOrdinal);
|
||||
return [.. node.Order, .. sequence.Skip(to + 1).Select(ordinal => kept[ordinal])];
|
||||
}
|
||||
|
||||
// One part's route from the node, its perimeter last, facing the next part along the
|
||||
// sequence (a kept order's when none is given). Null when it cannot be emitted.
|
||||
private SafestStep SafestPart(Node node, FixedProgramPlacement source, int[] sequence = null)
|
||||
{
|
||||
sequence ??= KeptSequence;
|
||||
var arrival = node.Position;
|
||||
if (source.Prepared is not { } prepared)
|
||||
{
|
||||
@@ -1759,7 +1824,7 @@ internal static class JointCuttingPlanSearch
|
||||
// Recovery's contour solver first: its first route whose only violations, if any, are
|
||||
// where the arrival rapid crosses cut contours. It passes every check when it can.
|
||||
if (HasRecoverableHoles(source) && prepared.Count > 1 && prepared.PerimeterOrdinal <= MaximumRecoveryHoles
|
||||
&& RecoverPart(node, KeptSequence, source, new Attempt(null), arrivalMayCross: true).FirstOrDefault() is { } recovered)
|
||||
&& RecoverPart(node, sequence, source, new Attempt(null), arrivalMayCross: true).FirstOrDefault() is { } recovered)
|
||||
{
|
||||
var proposal = recovered.Node.Order[^1];
|
||||
return new(recovered.Node, Score(proposal, proposal.Execution, arrival, node.Checker.Copy(),
|
||||
@@ -1771,7 +1836,7 @@ internal static class JointCuttingPlanSearch
|
||||
var holes = Enumerable.Range(0, prepared.PerimeterOrdinal).ToArray();
|
||||
var centers = CuttingHoleOrder.Centers(prepared, approach, token);
|
||||
var remaining = CuttingHoleOrder.Plan(holes, centers, approach, null, token).ToList();
|
||||
var onward = LookAheadCenter(node, KeptSequence, source) - source.Location;
|
||||
var onward = LookAheadCenter(node, sequence, source) - source.Location;
|
||||
var choices = new List<ContourChoice>();
|
||||
Program program = null;
|
||||
OwnedExecution execution = null;
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using OpenNest.CNC.CuttingPlanning;
|
||||
|
||||
namespace OpenNest.Engine.CuttingPlanning;
|
||||
|
||||
/// <summary>
|
||||
/// Tries to take head raises out of a safest route by local changes to its part order. The
|
||||
/// greedy walk never goes back to a part it has cut, so a rapid that passes over one is raised
|
||||
/// even where cutting two parts the other way round would keep the head down. For each rapid
|
||||
/// that crosses parts already cut, it tries cutting the part the rapid goes to before the
|
||||
/// earliest part crossed, and each crossed part just before or just after it, planning only the
|
||||
/// parts whose place changed (and the ones beside them) again. A change is kept only when the
|
||||
/// replayed route breaks no more checks and raises the head fewer times, so it can never make a
|
||||
/// route worse. A kept part order is never changed.
|
||||
/// </summary>
|
||||
internal static class RaisedRapidRepair
|
||||
{
|
||||
/// <summary>Changed orders replayed per plate at most: each costs a full replay.</summary>
|
||||
internal const int MaximumTrials = 200;
|
||||
|
||||
/// <param name="order">The unmarked route <paramref name="result"/> was replayed from.</param>
|
||||
/// <param name="replay">Marks and replays a route; null when it is refused.</param>
|
||||
internal static CuttingPlanResult Repair(CuttingPlanSnapshot snapshot, IReadOnlyList<FixedProgramPlacement> order,
|
||||
CuttingPlanResult result, Func<IReadOnlyList<FixedProgramPlacement>, CuttingPlanResult> replay,
|
||||
CancellationToken token)
|
||||
{
|
||||
if (snapshot.PreservePartOrder || result.HeadRaises == 0)
|
||||
return result;
|
||||
var resequencer = new JointCuttingPlanSearch.Resequencer(snapshot, token);
|
||||
var tried = new HashSet<string>();
|
||||
var trials = 0;
|
||||
while (result.HeadRaises > 0)
|
||||
{
|
||||
var sequence = order.Select(p => p.SourceOrdinal).ToArray();
|
||||
IReadOnlyList<FixedProgramPlacement> repaired = null;
|
||||
CuttingPlanResult repairedResult = null;
|
||||
foreach (var (index, crossed) in RaisedRapids.Crossed(snapshot, order, token))
|
||||
{
|
||||
foreach (var candidate in Candidates(sequence, index, crossed))
|
||||
{
|
||||
if (trials == MaximumTrials || resequencer.Exhausted)
|
||||
return result;
|
||||
if (!tried.Add(string.Join(",", candidate)) || snapshot.Dependencies.FirstViolation(candidate) != null)
|
||||
continue;
|
||||
trials++;
|
||||
var (from, to) = Window(sequence, candidate);
|
||||
if (resequencer.Cut(order, candidate, from, to) is not { } changed
|
||||
|| replay(changed) is not { } replayed || !Better(replayed, result))
|
||||
continue;
|
||||
(repaired, repairedResult) = (changed, replayed);
|
||||
break;
|
||||
}
|
||||
if (repaired != null)
|
||||
break;
|
||||
}
|
||||
if (repaired == null)
|
||||
return result;
|
||||
(order, result) = (repaired, repairedResult);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// The orders worth trying for the part at 'index', whose rapids crossed the parts 'crossed'
|
||||
// (all cut before it): that part before the earliest of them, then each of them, latest
|
||||
// first, cut just before it and just after it.
|
||||
internal static IEnumerable<int[]> Candidates(int[] sequence, int index, int[] crossed)
|
||||
{
|
||||
var positions = crossed.Select(part => Array.IndexOf(sequence, part))
|
||||
.Where(position => position >= 0 && position < index).OrderDescending().ToArray();
|
||||
if (positions.Length == 0)
|
||||
yield break;
|
||||
yield return Move(sequence, index, positions[^1]);
|
||||
foreach (var position in positions)
|
||||
{
|
||||
// Removing the crossed part moves the target one place earlier.
|
||||
if (position != index - 1)
|
||||
yield return Move(sequence, position, index - 1);
|
||||
yield return Move(sequence, position, index);
|
||||
}
|
||||
}
|
||||
|
||||
// The sequence with the element at 'from' taken out and put back at 'to' (an index after removal).
|
||||
private static int[] Move(int[] sequence, int from, int to)
|
||||
{
|
||||
var moved = sequence.ToList();
|
||||
var part = moved[from];
|
||||
moved.RemoveAt(from);
|
||||
moved.Insert(to, part);
|
||||
return [.. moved];
|
||||
}
|
||||
|
||||
// The parts to plan again: every one whose place changed, the one before them (it was planned
|
||||
// facing a different next part) and the one after them (it is reached from somewhere else).
|
||||
private static (int From, int To) Window(int[] sequence, int[] candidate)
|
||||
{
|
||||
var first = 0;
|
||||
while (sequence[first] == candidate[first])
|
||||
first++;
|
||||
var last = sequence.Length - 1;
|
||||
while (sequence[last] == candidate[last])
|
||||
last--;
|
||||
return (System.Math.Max(0, first - 1), System.Math.Min(sequence.Length - 1, last + 1));
|
||||
}
|
||||
|
||||
// Breaks no more checks (most severe first) and raises the head fewer times.
|
||||
private static bool Better(CuttingPlanResult candidate, CuttingPlanResult known)
|
||||
{
|
||||
var severity = (candidate.SafestRoute ?? default).CompareTo(known.SafestRoute ?? default);
|
||||
return severity < 0 || severity == 0 && candidate.HeadRaises < known.HeadRaises;
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ internal static class RaisedRapids
|
||||
var execution = ExecutionMotionReader.Read(program, proposal.Location, position, token);
|
||||
var placement = proposal;
|
||||
var rapids = proposal.Prepared == null || proposal.IsCutOff ? []
|
||||
: Crossing(checker.Copy(), proposal, execution, position, snapshot.WarnsTabLeadOuts(proposal), token);
|
||||
: Crossing(checker.Copy(), proposal, execution, position, snapshot.WarnsTabLeadOuts(proposal), token).Codes;
|
||||
if (rapids.Count != 0)
|
||||
{
|
||||
var raised = HeadRaise.Mark(program, rapids);
|
||||
@@ -51,15 +51,43 @@ internal static class RaisedRapids
|
||||
return marked;
|
||||
}
|
||||
|
||||
// The own-code indices of the planner's rapids that cross parts already cut: the rapid itself,
|
||||
// or the call of the sub-program the rapid arrives at.
|
||||
private static HashSet<int> Crossing(ReleasedContourState checker, FixedProgramPlacement proposal,
|
||||
OwnedExecution execution, Vector arrival, bool tabLeadOuts, CancellationToken token)
|
||||
/// <summary>
|
||||
/// The places along an unmarked <paramref name="order"/> whose planner-chosen rapids cross parts
|
||||
/// already cut, each with the source ordinals of the parts crossed, walked as replay walks it.
|
||||
/// </summary>
|
||||
internal static IReadOnlyList<(int Index, int[] Crossed)> Crossed(CuttingPlanSnapshot snapshot,
|
||||
IReadOnlyList<FixedProgramPlacement> order, CancellationToken token)
|
||||
{
|
||||
var checker = snapshot.NewReleasedState();
|
||||
var position = snapshot.StartPoint;
|
||||
var crossed = new List<(int, int[])>();
|
||||
for (var index = 0; index < order.Count; index++)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var proposal = order[index];
|
||||
var execution = ExecutionMotionReader.Read(proposal.CopyProgram(), proposal.Location, position, token);
|
||||
if (proposal.Prepared != null && !proposal.IsCutOff
|
||||
&& Crossing(checker.Copy(), proposal, execution, position, snapshot.WarnsTabLeadOuts(proposal), token)
|
||||
.Parts is { Count: > 0 } parts)
|
||||
crossed.Add((index, [.. parts.Order()]));
|
||||
checker.Check(execution, position, proposal.SourceOrdinal + 1, proposal.IsCutOff,
|
||||
proposal.FixedMotions(execution), token, snapshot.WarnsTabLeadOuts(proposal));
|
||||
position = execution.DeparturePoint;
|
||||
}
|
||||
return crossed;
|
||||
}
|
||||
|
||||
// The own-code indices of the planner's rapids that cross parts already cut (the rapid itself,
|
||||
// or the call of the sub-program the rapid arrives at) and the source ordinals of those parts.
|
||||
private static (HashSet<int> Codes, HashSet<int> Parts) Crossing(ReleasedContourState checker,
|
||||
FixedProgramPlacement proposal, OwnedExecution execution, Vector arrival, bool tabLeadOuts,
|
||||
CancellationToken token)
|
||||
{
|
||||
var isFixed = proposal.FixedMotions(execution);
|
||||
var strict = checker.Check(execution, arrival, proposal.SourceOrdinal + 1, false, isFixed, token,
|
||||
tabLeadOuts).Strict;
|
||||
var codes = new HashSet<int>();
|
||||
var parts = new HashSet<int>();
|
||||
foreach (var finding in strict)
|
||||
{
|
||||
if (finding.Kind != PostVerificationKind.RapidCrossing || finding.RapidEnd is not { } end)
|
||||
@@ -75,9 +103,13 @@ internal static class RaisedRapids
|
||||
else if (motion.CallCode is int call
|
||||
&& (index == 0 || execution.Motions[index - 1].CallCode != call))
|
||||
codes.Add(call);
|
||||
else
|
||||
continue;
|
||||
if (finding.OtherPartNumber is int other && other - 1 != proposal.SourceOrdinal)
|
||||
parts.Add(other - 1);
|
||||
}
|
||||
}
|
||||
return codes;
|
||||
return (codes, parts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -109,6 +109,60 @@ public class HeadRaisePlanningTests
|
||||
Assert.All(result.ProposedOrder, p => Assert.False(HeadRaise.IsMarked(p.CopyProgram())));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Repair_CutsThePartBeyondTheWallBeforeIt()
|
||||
{
|
||||
// A safest route that cuts the wall, the left square, then the right one raises the head
|
||||
// over the wall; cutting the right square before the wall keeps it down.
|
||||
var (_, plate) = WallPlate();
|
||||
var snapshot = CuttingPlanService.Capture(CuttingPlanRequest.ForPlate(plate,
|
||||
confirmedParameters: ExplicitContourTests.Parameters(), preservePartOrder: false), default);
|
||||
var order = new JointCuttingPlanSearch.Resequencer(snapshot, default).Cut([], [0, 1, 2], 0, 2);
|
||||
var raised = CuttingPlanService.ReplayPrograms(snapshot, RaisedRapids.Mark(snapshot, order, default), 0,
|
||||
default, safestRoute: true);
|
||||
Assert.Equal(1, raised.HeadRaises);
|
||||
var (index, crossed) = Assert.Single(RaisedRapids.Crossed(snapshot, order, default));
|
||||
Assert.Equal(2, index);
|
||||
Assert.Equal(new[] { 0 }, crossed); // The wall.
|
||||
|
||||
var repaired = RaisedRapidRepair.Repair(snapshot, order, raised, changed => CuttingPlanService.ReplayPrograms(
|
||||
snapshot, RaisedRapids.Mark(snapshot, changed, default), 0, default, safestRoute: true), default);
|
||||
|
||||
Assert.Equal(CuttingPlanStatus.Ready, repaired.Status);
|
||||
Assert.Equal(0, repaired.HeadRaises);
|
||||
Assert.Equal(new[] { 2, 0, 1 }, repaired.ProposedOrder.Select(p => p.SourceOrdinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Repair_NeverChangesAKeptOrder()
|
||||
{
|
||||
var (_, plate) = WallPlate();
|
||||
var snapshot = CuttingPlanService.Capture(CuttingPlanRequest.ForPlate(plate,
|
||||
confirmedParameters: ExplicitContourTests.Parameters(), preservePartOrder: true), default);
|
||||
var result = CuttingPlanService.PlanSafestRoute(snapshot, default);
|
||||
|
||||
Assert.Equal(1, result.HeadRaises);
|
||||
Assert.Equal(new[] { 0, 1, 2 }, result.ProposedOrder.Select(p => p.SourceOrdinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RepairCandidates_MoveThePartOrWhatItCrossed()
|
||||
{
|
||||
// Part 7 at index 3 crossed part 5 (index 1) and part 9 (index 0).
|
||||
int[] sequence = [9, 5, 6, 7, 8];
|
||||
|
||||
var candidates = RaisedRapidRepair.Candidates(sequence, 3, [5, 9]).ToArray();
|
||||
|
||||
Assert.Equal(new[]
|
||||
{
|
||||
new[] { 7, 9, 5, 6, 8 }, // Before the earliest crossed part.
|
||||
new[] { 9, 6, 5, 7, 8 }, // Part 5 just before it,
|
||||
new[] { 9, 6, 7, 5, 8 }, // and just after it.
|
||||
new[] { 5, 6, 9, 7, 8 },
|
||||
new[] { 5, 6, 7, 9, 8 },
|
||||
}, candidates);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StrictPlan_NeverMarksARapid()
|
||||
{
|
||||
|
||||
@@ -960,6 +960,18 @@ regenerated program are marked; a rapid into or inside a locked program or a cut
|
||||
rapid inside a hole sub-program after its arrival, keeps its crossing as a finding. The checker sets a raised rapid's crossings apart
|
||||
instead of reporting them, in replay and in pre-post verification alike.
|
||||
|
||||
The walk never goes back to a part it has cut, so a free-order route then tries local changes to
|
||||
its order where it raises the head (`RaisedRapidRepair`). For a part whose planner-chosen rapids
|
||||
cross parts already cut, it tries that part just before the earliest part crossed, then each
|
||||
crossed part, latest first, just before and just after it, keeping every prerequisite. Only the
|
||||
parts whose place changed, the part before them (planned facing a different next part) and the
|
||||
part after them are planned again by the walk's own step, each facing the next part along the
|
||||
changed order; the rest keep their programs. Each change is marked and replayed in full, and the
|
||||
first that breaks no more checks (tiers as above) and raises the head fewer times is kept; the
|
||||
search then starts again from the new route. It stops when no change helps, after 200 replays or
|
||||
when its expansion budget (the plate's) runs out, so it can only make a route safer. A kept order
|
||||
is never changed.
|
||||
|
||||
The batch walks both the free order and the current order, replays each against its captured
|
||||
input with fresh checks, and keeps the one with the lower severity, then fewer head raises, then
|
||||
the shorter rapid travel; a route that passes every check without a raise is taken at once.
|
||||
|
||||
Reference in new issue
Block a user