diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs b/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs index 7aa05abb..cdb12e68 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPlanService.cs @@ -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 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. diff --git a/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs b/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs index 8f4a0b41..5cb4748a 100644 --- a/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs +++ b/OpenNest.Engine/CuttingPlanning/JointCuttingPlanSearch.cs @@ -277,6 +277,38 @@ internal static class JointCuttingPlanSearch } } + /// + /// Plans windows of a safest route again along a changed part order (see + /// ), every call drawing on one search budget. + /// + internal sealed class Resequencer(CuttingPlanSnapshot snapshot, CancellationToken token) + { + private readonly Walk walk = new(snapshot, token, []); + + /// True once the budget ran out; every later call returns null. + internal bool Exhausted { get; private set; } + + internal IReadOnlyList Cut(IReadOnlyList 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[] prerequisites, CancellationToken token) @@ -1736,9 +1768,42 @@ internal static class JointCuttingPlanSearch /// The holes, next along the tour, a safest-route step weighs for its next cut. 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) + /// + /// with the parts at through + /// of planned again, each by the safest-route step facing the + /// next part along it, from where the proposals before leave the + /// tool. The proposals after are kept as they are. The sequence must + /// match the order outside that window. Null when a part cannot be emitted. + /// + internal IReadOnlyList Resequence(IReadOnlyList 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(); Program program = null; OwnedExecution execution = null; diff --git a/OpenNest.Engine/CuttingPlanning/RaisedRapidRepair.cs b/OpenNest.Engine/CuttingPlanning/RaisedRapidRepair.cs new file mode 100644 index 00000000..7f49129a --- /dev/null +++ b/OpenNest.Engine/CuttingPlanning/RaisedRapidRepair.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using OpenNest.CNC.CuttingPlanning; + +namespace OpenNest.Engine.CuttingPlanning; + +/// +/// 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. +/// +internal static class RaisedRapidRepair +{ + /// Changed orders replayed per plate at most: each costs a full replay. + internal const int MaximumTrials = 200; + + /// The unmarked route was replayed from. + /// Marks and replays a route; null when it is refused. + internal static CuttingPlanResult Repair(CuttingPlanSnapshot snapshot, IReadOnlyList order, + CuttingPlanResult result, Func, CuttingPlanResult> replay, + CancellationToken token) + { + if (snapshot.PreservePartOrder || result.HeadRaises == 0) + return result; + var resequencer = new JointCuttingPlanSearch.Resequencer(snapshot, token); + var tried = new HashSet(); + var trials = 0; + while (result.HeadRaises > 0) + { + var sequence = order.Select(p => p.SourceOrdinal).ToArray(); + IReadOnlyList 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 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; + } +} diff --git a/OpenNest.Engine/CuttingPlanning/RaisedRapids.cs b/OpenNest.Engine/CuttingPlanning/RaisedRapids.cs index 674dcc94..394c1f09 100644 --- a/OpenNest.Engine/CuttingPlanning/RaisedRapids.cs +++ b/OpenNest.Engine/CuttingPlanning/RaisedRapids.cs @@ -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 Crossing(ReleasedContourState checker, FixedProgramPlacement proposal, - OwnedExecution execution, Vector arrival, bool tabLeadOuts, CancellationToken token) + /// + /// The places along an unmarked whose planner-chosen rapids cross parts + /// already cut, each with the source ordinals of the parts crossed, walked as replay walks it. + /// + internal static IReadOnlyList<(int Index, int[] Crossed)> Crossed(CuttingPlanSnapshot snapshot, + IReadOnlyList 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 Codes, HashSet 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(); + var parts = new HashSet(); 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); } /// diff --git a/OpenNest.Tests/CuttingPlanning/HeadRaisePlanningTests.cs b/OpenNest.Tests/CuttingPlanning/HeadRaisePlanningTests.cs index 97cf77d8..67c61d44 100644 --- a/OpenNest.Tests/CuttingPlanning/HeadRaisePlanningTests.cs +++ b/OpenNest.Tests/CuttingPlanning/HeadRaisePlanningTests.cs @@ -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() { diff --git a/docs/cutting-planner.md b/docs/cutting-planner.md index 3ee35b8b..bd7906bb 100644 --- a/docs/cutting-planner.md +++ b/docs/cutting-planner.md @@ -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.