diff --git a/OpenNest.Engine/CuttingPlanning/CuttingPartOrder.cs b/OpenNest.Engine/CuttingPlanning/CuttingPartOrder.cs index 73716836..42ea7c99 100644 --- a/OpenNest.Engine/CuttingPlanning/CuttingPartOrder.cs +++ b/OpenNest.Engine/CuttingPlanning/CuttingPartOrder.cs @@ -2,7 +2,9 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading; +using OpenNest.Diagnostics; using OpenNest.Geometry; +using Extent = OpenNest.Diagnostics.PostVerificationGeometry.Extent; namespace OpenNest.Engine.CuttingPlanning; @@ -27,6 +29,15 @@ internal static class CuttingPartOrder /// Upper bound on rounds of placing slender parts at their visit points. internal const int MaxVisitRounds = 8; + /// Routes at least this long index their parts for Or-opt, which then skips far gaps. + internal const int IndexedParts = 64; + + // The share of legs short enough to be found through the index; the rest are always tried. + private const double ReachQuantile = 0.95; + + // Widens the Or-opt search radius past any rounding in the distances it is derived from. + private const double IndexSlack = 1e-6; + /// The part ordinals to order; prerequisites outside this set count as done. /// One representative point per part ordinal. /// The modeled tool position before the first of these parts. @@ -71,14 +82,17 @@ internal static class CuttingPartOrder /// moved to the gap where that detour is shortest, and the tour is improved again with those /// points. Null keeps the center tour exactly. /// + /// Tours of at least this many parts skip Or-opt gaps too far to + /// help; the tour is the same either way. internal static int[] Plan(IReadOnlyList centers, Vector start, IReadOnlyList> prerequisites, CancellationToken token, Vector? endpoint = null, - IReadOnlyList exits = null, IReadOnlyList> visits = null) + IReadOnlyList exits = null, IReadOnlyList> visits = null, + int indexedParts = IndexedParts) { var count = centers.Count; var order = NearestNeighbor(centers, exits ?? centers, start, prerequisites, token); var position = new int[count]; - Improve(order, centers, exits, start, prerequisites, position, token, endpoint); + Improve(order, centers, exits, start, prerequisites, position, token, endpoint, indexedParts); if (visits == null || !visits.Any(points => points is { Count: > 0 })) return order; @@ -91,19 +105,20 @@ internal static class CuttingPartOrder changed |= Relocate(order, arrive, leave, visits, start, prerequisites, position, token, endpoint); if (!changed) break; - Improve(order, arrive, leave, start, prerequisites, position, token, endpoint); + Improve(order, arrive, leave, start, prerequisites, position, token, endpoint, indexedParts); } return order; } private static void Improve(int[] order, IReadOnlyList centers, IReadOnlyList exits, Vector start, - IReadOnlyList> prerequisites, int[] position, CancellationToken token, Vector? endpoint) + IReadOnlyList> prerequisites, int[] position, CancellationToken token, Vector? endpoint, + int indexedParts) { for (var pass = 0; pass < MaxPasses; pass++) { token.ThrowIfCancellationRequested(); var improved = TwoOpt(order, centers, exits, start, prerequisites, position, token, endpoint); - improved |= OrOpt(order, centers, exits ?? centers, start, prerequisites, position, token, endpoint); + improved |= OrOpt(order, centers, exits ?? centers, start, prerequisites, position, token, endpoint, indexedParts); if (!improved) break; } @@ -234,10 +249,14 @@ internal static class CuttingPartOrder { var improved = false; var count = order.Length; + if (count < 2) + return false; var leave = exits ?? centers; - // The terminal edge belongs to every delta: reversing the route's tail swaps which - // endpoint-side center faces the fixed final position. - double Tail(Vector from) => endpoint is { } e ? from.DistanceTo(e) : 0; + // The route's legs, forward and backward, measured once per order rather than for every + // run they belong to; each is the very value the run would measure itself. + var legs = new double[count + 1]; + var backs = new double[count]; + Measure(0, count); for (var i = 0; i < count - 1; i++) { token.ThrowIfCancellationRequested(); @@ -247,29 +266,48 @@ internal static class CuttingPartOrder { if (exits != null) { - forward += leave[order[j - 1]].DistanceTo(centers[order[j]]); - reversed += leave[order[j]].DistanceTo(centers[order[j - 1]]); + forward += legs[j]; + reversed += backs[j]; } - var before = Point(i - 1).DistanceTo(centers[order[i]]) + forward - + (j + 1 < count ? leave[order[j]].DistanceTo(centers[order[j + 1]]) : Tail(leave[order[j]])); + var before = legs[i] + forward + legs[j + 1]; var after = Point(i - 1).DistanceTo(centers[order[j]]) + reversed + (j + 1 < count ? leave[order[i]].DistanceTo(centers[order[j + 1]]) : Tail(leave[order[i]])); if (after >= before - Epsilon || !CanReverse(order, i, j, prerequisites, position)) continue; Array.Reverse(order, i, j - i + 1); improved = true; + Measure(i, j + 1); // The run is reversed now; its legs are re-measured from scratch. forward = reversed = 0; for (var k = i + 1; k <= j && exits != null; k++) { - forward += leave[order[k - 1]].DistanceTo(centers[order[k]]); - reversed += leave[order[k]].DistanceTo(centers[order[k - 1]]); + forward += legs[k]; + reversed += backs[k]; } } } return improved; Vector Point(int index) => index < 0 ? start : leave[order[index]]; + + // The terminal edge belongs to every delta: reversing the route's tail swaps which + // endpoint-side center faces the fixed final position. + double Tail(Vector from) => endpoint is { } e ? from.DistanceTo(e) : 0; + + // legs[k] runs into order[k] (legs[count] to the open end); backs[k] from order[k] back to + // order[k - 1], as the run would travel it reversed. Only those touching order[from..to] + // are measured. + void Measure(int from, int to) + { + for (var k = from; k <= to && k < count; k++) + { + legs[k] = Point(k - 1).DistanceTo(centers[order[k]]); + if (k > 0) + backs[k] = leave[order[k]].DistanceTo(centers[order[k - 1]]); + } + if (to >= count) + legs[count] = Tail(leave[order[count - 1]]); + } } // A reversal breaks a prerequisite only when both parts lie inside the reversed span. @@ -288,22 +326,30 @@ internal static class CuttingPartOrder // Moves a run of one to three parts to a later or earlier gap when that shortens the path. private static bool OrOpt(int[] order, IReadOnlyList centers, IReadOnlyList exits, Vector start, IReadOnlyList> prerequisites, int[] position, CancellationToken token, - Vector? endpoint = null) + Vector? endpoint, int indexedParts) { var improved = false; var count = order.Length; + // legs[gap] is the route's leg across that gap, Gap(gap - 1, gap); at[part] is its position. + var legs = new double[count + 1]; + var at = new int[count]; + var gaps = new List(count + 1); + var near = count < System.Math.Max(2, indexedParts) ? null : Index(exits, count); + var reach = near == null ? 0 : Reach(); + var far = new List(); + Measure(); for (var length = 1; length <= 3; length++) for (var i = 0; i + length <= count; i++) { token.ThrowIfCancellationRequested(); var last = i + length - 1; - var removal = Gap(i - 1, i) + Gap(last, last + 1) - Gap(i - 1, last + 1); + var removal = legs[i] + legs[last + 1] - Gap(i - 1, last + 1); // Insert between order[gap - 1] and order[gap], outside the run. - for (var gap = 0; gap <= count; gap++) + foreach (var gap in Gaps(i, last, removal)) { if (gap >= i && gap <= last + 1) continue; - var insertion = Gap(gap - 1, i) + Gap(last, gap) - Gap(gap - 1, gap); + var insertion = Gap(gap - 1, i) + Gap(last, gap) - legs[gap]; if (insertion >= removal - Epsilon) continue; var candidate = Move(order, i, length, gap); @@ -311,11 +357,67 @@ internal static class CuttingPartOrder continue; Array.Copy(candidate, order, count); improved = true; + Measure(); break; } } return improved; + void Measure() + { + for (var gap = 0; gap <= count; gap++) + legs[gap] = Gap(gap - 1, gap); + for (var k = 0; k < count; k++) + at[order[k]] = k; + far.Clear(); + for (var gap = 1; gap < count && near != null; gap++) + if (!(legs[gap] <= reach)) + far.Add(gap); + } + + // Every gap, ascending, where moving order[i..last] could shorten the route by more than + // Epsilon. On a large route that skips each gap whose leg is at most `reach` and whose + // first point lies too far from the run: from a, through the run's first point f and last + // point l, to b, the triangle inequality gives insertion >= 2|af| - 2|ab| - |fl|, so + // insertion < removal needs |af| < |ab| + (removal + |fl|) / 2. The start and end gaps and + // every longer leg are always tried; the order and the first gap taken are unchanged. + List Gaps(int i, int last, double removal) + { + gaps.Clear(); + var f = centers[order[i]]; + var radius = reach + (removal + f.DistanceTo(exits[order[last]])) / 2 + IndexSlack; + var query = new Extent(f.X, f.Y, f.X, f.Y); + if (near == null || !query.IsWellConditioned || !double.IsFinite(radius)) + { + for (var gap = 0; gap <= count; gap++) + gaps.Add(gap); + return gaps; + } + gaps.Add(0); + gaps.Add(count); + gaps.AddRange(far); + foreach (var part in near.Near(query, System.Math.Max(0, radius))) + gaps.Add(at[part] + 1); + gaps.Sort(); + var unique = 0; + for (var k = 0; k < gaps.Count; k++) + if (k == 0 || gaps[k] != gaps[k - 1]) + gaps[unique++] = gaps[k]; + gaps.RemoveRange(unique, gaps.Count - unique); + return gaps; + } + + // A leg length most legs are within, so few gaps are always tried yet the search radius + // stays small. + double Reach() + { + var lengths = new double[count - 1]; + for (var gap = 1; gap < count; gap++) + lengths[gap - 1] = Gap(gap - 1, gap); + Array.Sort(lengths); + return lengths[(int)(lengths.Length * ReachQuantile)]; + } + // Path length between order[a] and order[b] (a == -1 is the start; b == count is the open // end — the fixed endpoint when one was supplied, so the terminal edge is in every delta). double Gap(int a, int b) @@ -329,6 +431,10 @@ internal static class CuttingPartOrder } } + // The parts' exits in a grid, for finding the gaps that start near a point. + private static ExtentGrid Index(IReadOnlyList exits, int count) => + new ExtentGrid(Enumerable.Range(0, count).Select(p => new Extent(exits[p].X, exits[p].Y, exits[p].X, exits[p].Y)).ToArray()); + private static int[] Move(int[] order, int start, int length, int gap) { var run = order.Skip(start).Take(length).ToArray(); diff --git a/OpenNest.Tests/CuttingPlanning/CuttingPartOrderTests.cs b/OpenNest.Tests/CuttingPlanning/CuttingPartOrderTests.cs index 97efb6f6..d934a2eb 100644 --- a/OpenNest.Tests/CuttingPlanning/CuttingPartOrderTests.cs +++ b/OpenNest.Tests/CuttingPlanning/CuttingPartOrderTests.cs @@ -148,6 +148,37 @@ public class CuttingPartOrderTests NoPrerequisites(5), CancellationToken.None, visits: new IReadOnlyList[5])); } + [Theory] + [InlineData(1, false, false, false)] + [InlineData(2, true, false, false)] + [InlineData(3, true, true, false)] + [InlineData(4, true, true, true)] + [InlineData(5, false, true, true)] + public void Plan_IndexedOrOpt_GivesTheFullScansTour(int seed, bool scattered, bool constrained, bool farExits) + { + // Rows of parts like a filled plate, or parts scattered at random, some left from a far + // point as cut-offs are, some only after others, toward an endpoint or an open end. + var random = new Random(seed); + const int count = 300; + var centers = Enumerable.Range(0, count).Select(k => scattered + ? new Vector(random.NextDouble() * 60, random.NextDouble() * 40) + : new Vector(k % 20 * 3 + random.NextDouble() * 0.2, k / 20 * 3 + random.NextDouble() * 0.2)).ToArray(); + var exits = centers.Select(c => farExits && random.Next(10) == 0 + ? new Vector(c.X + random.NextDouble() * 20 - 10, c.Y + random.NextDouble() * 20 - 10) : c).ToArray(); + var prerequisites = NoPrerequisites(count); + if (constrained) + for (var k = 1; k < count; k += 7) + prerequisites[k] = [random.Next(k)]; + Vector? endpoint = seed % 2 == 0 ? new Vector(30, -5) : null; + + var full = CuttingPartOrder.Plan(centers, new Vector(-1, -1), prerequisites, CancellationToken.None, endpoint, + exits, indexedParts: int.MaxValue); + var indexed = CuttingPartOrder.Plan(centers, new Vector(-1, -1), prerequisites, CancellationToken.None, endpoint, + exits, indexedParts: 2); + + Assert.Equal(full, indexed); + } + private static int[] Plan(Vector[] centers, IReadOnlyCollection[] prerequisites) => CuttingPartOrder.Plan(centers, Vector.Zero, prerequisites, CancellationToken.None);