From aea032a24d15bfecfda89a6e5994e4ee6e69281b Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sat, 21 Nov 2026 19:21:07 -0500 Subject: [PATCH] fix(irregular): stop at the deadline while preparing Lattice blocks Irregular overran DeadlineNestingEngine's 30 s limit by up to 50x in the ML flag-sweep pilot (1,537 s on a 450-per-sheet part). Stack samples put every second of the overrun in BlockCatalog.Rectangles: after a sheet fill places a Lattice block of hundreds of detailed parts, the next block preparation builds the free region one Clipper difference per part and then sorts out every maximal rectangle with a quadratic dominance pass, and neither checked the token. It shows only once best fits are cached (a warm app, worker or sweep process), which is when the fill gets there within the limit. MaximalRectangles.InRegion now takes a token and a `largest` count: it stops dominance checks past that rank, keeping every result tied in area with the last, so its results are exactly the full search's down to that area and Rectangles' top two are unchanged. The free region checks the token per part. Layouts do not change; the reproducing job's whole solve now takes 34 s instead of over 1,000. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Core/Geometry/MaximalRectangles.cs | 35 ++++- .../NestingEngines/IrregularDeadlineTests.cs | 135 ++++++++++++++++++ .../NestingEngines/Irregular/BlockCatalog.cs | 12 +- .../Irregular/FrontierPacker.cs | 2 +- .../Geometry/MaximalRectanglesTests.cs | 36 +++++ 5 files changed, 209 insertions(+), 11 deletions(-) create mode 100644 OpenNest.Engine.Tests/NestingEngines/IrregularDeadlineTests.cs diff --git a/OpenNest.Core/Geometry/MaximalRectangles.cs b/OpenNest.Core/Geometry/MaximalRectangles.cs index e03fe5d9..a8f3253f 100644 --- a/OpenNest.Core/Geometry/MaximalRectangles.cs +++ b/OpenNest.Core/Geometry/MaximalRectangles.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using Clipper2Lib; namespace OpenNest.Geometry; @@ -29,11 +30,20 @@ public static class MaximalRectangles /// Rectangles narrower than this in either axis are dropped. /// Even subdivisions of the region's bounds per axis, which bound the /// staircase loss along slanted edges. + /// Results wanted: the search stops once it has this many, keeping + /// every further result as large as the last of them, so the results returned are exactly + /// those of the full search whose area is at least the area of its result at that rank. + /// A region with many edges can have very many candidate rectangles, and ruling out the + /// dominated ones costs time quadratic in them, so ask only for what is used. + /// Checked throughout; the search is long for a region with many edges. /// Rectangles not contained in another result, largest area first. - public static List InRegion(PathsD region, double minDimension = 0, int divisions = 64) + public static List InRegion(PathsD region, double minDimension = 0, int divisions = 64, + int largest = int.MaxValue, CancellationToken token = default) { ArgumentNullException.ThrowIfNull(region); ArgumentOutOfRangeException.ThrowIfLessThan(divisions, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(largest, 1); + token.ThrowIfCancellationRequested(); var paths = region.Where(path => path.Count >= 3).ToList(); if (paths.Count == 0) @@ -52,6 +62,7 @@ public static class MaximalRectangles var crossed = new bool[rows, cols]; foreach (var path in paths) { + token.ThrowIfCancellationRequested(); var previous = path[^1]; foreach (var current in path) { @@ -67,6 +78,7 @@ public static class MaximalRectangles // Even-odd scan along the row's center line. No vertex lies on it, and an edge that // meets it strictly inside a cell has already marked that cell crossed, so each // uncrossed cell is on the same side as its center. + token.ThrowIfCancellationRequested(); var y = (ys[r] + ys[r + 1]) / 2; crossings.Clear(); foreach (var path in paths) @@ -91,7 +103,8 @@ public static class MaximalRectangles } } - return FromGrid(xs, ys, empty, minDimension); + var merged = MergeCells(xs, ys, empty, token); + return RemoveDominated(FilterBySize(merged, minDimension), largest, token); } /// @@ -111,9 +124,9 @@ public static class MaximalRectangles double minDimension = 0 ) { - var merged = MergeCells(xs, ys, empty); + var merged = MergeCells(xs, ys, empty, default); var sized = FilterBySize(merged, minDimension); - return RemoveDominated(sized); + return RemoveDominated(sized, int.MaxValue, default); } private static List GridLines(IEnumerable vertices, double min, double max, int divisions) @@ -206,7 +219,8 @@ public static class MaximalRectangles return true; } - private static List MergeCells(IReadOnlyList xs, IReadOnlyList ys, bool[,] empty) + private static List MergeCells(IReadOnlyList xs, IReadOnlyList ys, bool[,] empty, + CancellationToken token) { var rows = empty.GetLength(0); var cols = empty.GetLength(1); @@ -222,6 +236,7 @@ public static class MaximalRectangles for (var r = 0; r < rows; r++) { + token.ThrowIfCancellationRequested(); var stack = new Stack<(int startCol, int h)>(); for (var c = 0; c <= cols; c++) @@ -268,13 +283,21 @@ public static class MaximalRectangles return result; } - private static List RemoveDominated(List boxes) + /// + /// The boxes not within a larger one, largest first. Stops at the first box smaller than the + /// result at rank : boxes are taken in order, each against the + /// results before it, so the results kept up to there are those of the full pass. + /// + private static List RemoveDominated(List boxes, int largest, CancellationToken token) { boxes.Sort((a, b) => b.Area().CompareTo(a.Area())); var results = new List(); foreach (var box in boxes) { + if (results.Count >= largest && box.Area() < results[largest - 1].Area()) + break; + token.ThrowIfCancellationRequested(); var dominated = false; foreach (var larger in results) diff --git a/OpenNest.Engine.Tests/NestingEngines/IrregularDeadlineTests.cs b/OpenNest.Engine.Tests/NestingEngines/IrregularDeadlineTests.cs new file mode 100644 index 00000000..f81bcd5f --- /dev/null +++ b/OpenNest.Engine.Tests/NestingEngines/IrregularDeadlineTests.cs @@ -0,0 +1,135 @@ +using System.Diagnostics; +using OpenNest.CNC; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.NestingEngines; +using OpenNest.Engine.NestingEngines.Irregular; +using OpenNest.Geometry; +using static OpenNest.Engine.Tests.NestingEngines.JobBuilder; + +namespace OpenNest.Engine.Tests.NestingEngines; + +/// +/// Irregular under : it stops soon after the limit. A dense +/// sheet of detailed parts once held it in the free-rectangle search for Lattice blocks, which +/// neither checked the token nor scaled, for many minutes past a 30 s limit. +/// +public class IrregularDeadlineTests +{ + /// A gear: square teeth on a disc, with four square holes. + private static Program Gear(double radius, int teeth) + { + var program = new Program(); + var outline = new List<(double X, double Y)>(); + var root = radius * 0.85; + for (var i = 0; i < teeth; i++) + { + var a = 2 * System.Math.PI * i / teeth; + var step = 2 * System.Math.PI / teeth / 4; + outline.Add(Polar(root, a)); + outline.Add(Polar(radius, a + step)); + outline.Add(Polar(radius, a + 2 * step)); + outline.Add(Polar(root, a + 3 * step)); + } + Contour(program, outline); + var hole = radius * 0.15; + foreach (var (cx, cy) in new[] { (0.4, 0.0), (-0.4, 0.0), (0.0, 0.4), (0.0, -0.4) }) + { + var x = radius + cx * radius; + var y = radius + cy * radius; + Contour(program, new[] { (x - hole, y - hole), (x - hole, y + hole), (x + hole, y + hole), (x + hole, y - hole) }); + } + return program; + + (double X, double Y) Polar(double r, double angle) => + (radius + r * System.Math.Cos(angle), radius + r * System.Math.Sin(angle)); + } + + private static void Contour(Program program, IReadOnlyList<(double X, double Y)> points) + { + program.Codes.Add(new RapidMove(points[0].X, points[0].Y)); + foreach (var (x, y) in points.Skip(1)) + program.Codes.Add(new LinearMove(x, y)); + program.Codes.Add(new LinearMove(points[0].X, points[0].Y)); + } + + /// A bar with a serrated long edge ( teeth) and four square holes. + private static Program Serrated(double length, double width, int teeth) + { + var program = new Program(); + var outline = new List<(double X, double Y)> { (0, 0), (length, 0), (length, width) }; + var pitch = length / teeth; + for (var i = teeth - 1; i >= 0; i--) + { + outline.Add((i * pitch + pitch * 0.75, width)); + outline.Add((i * pitch + pitch * 0.5, width - pitch * 0.4)); + outline.Add((i * pitch + pitch * 0.25, width)); + } + outline.Add((0, width)); + Contour(program, outline); + var hole = width * 0.12; + foreach (var fx in new[] { 0.15, 0.4, 0.6, 0.85 }) + { + var x = fx * length; + var y = width * 0.4; + Contour(program, new[] { (x - hole, y - hole), (x - hole, y + hole), (x + hole, y + hole), (x + hole, y - hole) }); + } + return program; + } + + [Fact] + public void StopsSoonAfterTheLimitOnADenseJobOfDetailedParts() + { + // About 450 bars a sheet; a sheet and a half of them. + var part = Part("bar", Serrated(5, 1.75, 24), 680, RotationPolicy.Automatic); + var stock = Stock("sheet", 60, 120, spacing: 0.25, edge: new Spacing(0.25, 0.75, 0.25, 0.25)); + var job = Job(new[] { part }, new[] { stock }); + + var limit = TimeSpan.FromSeconds(3); + var engine = new DeadlineNestingEngine(new IrregularNestingEngine(), limit); + var watch = Stopwatch.StartNew(); + NestJobResult? result = null; + try + { + result = engine.Solve(job); + } + catch (TimeoutException) + { + // No valid plan by the limit is an answer too; the point is how soon it comes. + } + watch.Stop(); + + Assert.True(watch.Elapsed < limit + TimeSpan.FromSeconds(3), + $"The solve took {watch.Elapsed.TotalSeconds:0.0} s against a {limit.TotalSeconds:0} s limit."); + if (result != null) + LayoutAssert.Valid(job, result); + } + + /// + /// The frame that held a 30 s solve for over 1,000 s in the flag sweep: a sheet fill offering + /// Lattice blocks looks for the free rectangles beside hundreds of detailed parts already on + /// the sheet. Uncancelled, the free region alone takes about 20 s here. + /// + [Fact] + public void BlockPreparationBesideACrowdedSheetStopsWhenCancelled() + { + var stock = Stock("sheet", 60, 120, spacing: 0.25); + var job = Job(new[] { Part("gear", Gear(1.25, 24), 400, RotationPolicy.Fixed(0)) }, new[] { stock }); + var types = PartCatalog.Build(job); + var orientation = types[0].Orientations[0]; + var seated = new List(); + for (var x = 0.0; x + 2.75 <= 120; x += 2.75) + for (var y = 0.0; y + 2.75 <= 50; y += 2.75) + seated.Add(new Placed(orientation, x, y)); + var pairs = new Dictionary>(); + using var blocks = new BlockCatalog(0.25, types, pairs, new WorkCounter(), long.MaxValue); + var packer = new FrontierPacker(types, new NoFitCache(0.25), pairs, stock, PackAxis.X, 1, + new WorkCounter(), blocks); + // Seating the parts takes under a second; the limit falls in the block preparation after it. + var limit = TimeSpan.FromSeconds(2); + using var cancel = new CancellationTokenSource(limit); + var watch = Stopwatch.StartNew(); + + Assert.ThrowsAny(() => packer.Fill(new[] { 400 }, cancel.Token, seated)); + Assert.True(watch.Elapsed < limit + TimeSpan.FromSeconds(2), $"Took {watch.Elapsed.TotalSeconds:0.0} s."); + } +} diff --git a/OpenNest.Engine/NestingEngines/Irregular/BlockCatalog.cs b/OpenNest.Engine/NestingEngines/Irregular/BlockCatalog.cs index f7bc19d1..836918a8 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/BlockCatalog.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/BlockCatalog.cs @@ -201,13 +201,16 @@ internal sealed class BlockCatalog : IDisposable /// /// The free rectangles of a work area blocks are offered: the largest clear of the parts - /// placed, their spacing included. + /// placed, their spacing included. Only the largest are searched for: on a sheet of many + /// detailed parts, sorting out every maximal rectangle takes minutes. /// - internal static IReadOnlyList Rectangles(Box work, IReadOnlyList placed, double spacing) => - MaximalRectangles.InRegion(FreeRegion(work, placed, spacing)).OrderByDescending(b => b.Area()) + internal static IReadOnlyList Rectangles(Box work, IReadOnlyList placed, double spacing, + CancellationToken token = default) => + MaximalRectangles.InRegion(FreeRegion(work, placed, spacing, token), largest: MaxRectangles, token: token) + .OrderByDescending(b => b.Area()) .ThenBy(b => b.Left).ThenBy(b => b.Bottom).ThenBy(b => b.Length).Take(MaxRectangles).ToArray(); - private static PathsD FreeRegion(Box work, IReadOnlyList placed, double spacing) + private static PathsD FreeRegion(Box work, IReadOnlyList placed, double spacing, CancellationToken token) { var free = new PathsD { new PathD { @@ -216,6 +219,7 @@ internal sealed class BlockCatalog : IDisposable } }; foreach (var part in placed) { + token.ThrowIfCancellationRequested(); // Physical occupied material, not a reference-point region for any moving part. // The catalog currently prepares solid outlines; future profile preparation owns holes. var blocked = Clipper.InflatePaths(new PathsD { part.Orientation.Outline }, diff --git a/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs b/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs index f9123207..bfb16d7f 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs @@ -336,7 +336,7 @@ internal sealed class FrontierPacker if (blocks == null || sheet.BlockPreparations++ >= MaxBlockPreparations) return; var left = sheet.Left; - var rectangles = BlockCatalog.Rectangles(work, sheet.Placed, stock.PartSpacing); + var rectangles = BlockCatalog.Rectangles(work, sheet.Placed, stock.PartSpacing, sheet.Token); foreach (var type in types.Where(t => left[t.Index] >= MinBlockCopies) .OrderByDescending(t => t.Area * left[t.Index]).ThenBy(t => t.Index).Take(MaxBlockTypes)) foreach (var rectangle in rectangles) diff --git a/OpenNest.Tests/Geometry/MaximalRectanglesTests.cs b/OpenNest.Tests/Geometry/MaximalRectanglesTests.cs index e2904132..3f6ff035 100644 --- a/OpenNest.Tests/Geometry/MaximalRectanglesTests.cs +++ b/OpenNest.Tests/Geometry/MaximalRectanglesTests.cs @@ -104,6 +104,42 @@ public class MaximalRectanglesTests Assert.Empty(MaximalRectangles.InRegion(new PathsD())); } + [Fact] + public void InRegion_Largest_KeepsTheFullSearchsResultsDownToThatRank() + { + // A sheet with holes punched in a staggered grid: many maximal rectangles, with ties. + var paths = new List { Rect(0, 0, 60, 40) }; + for (var x = 3; x < 57; x += 7) + for (var y = 3 + x % 3; y < 36; y += 6) + { + var hole = Rect(x, y, x + 2.5, y + 1.5 + x % 2); + hole.Reverse(); + paths.Add(hole); + } + var region = Region(paths.ToArray()); + + var full = MaximalRectangles.InRegion(region); + foreach (var largest in new[] { 1, 2, 5, 20 }) + { + var cut = full[largest - 1].Area(); + var expected = full.Where(b => b.Area() >= cut).ToList(); + var result = MaximalRectangles.InRegion(region, largest: largest); + + Assert.Equal(expected.Count, result.Count); + Assert.All(expected, box => Assert.Contains(result, r => Matches(r, box.Left, box.Bottom, box.Length, box.Width))); + } + } + + [Fact] + public void InRegion_CancelledToken_Throws() + { + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + + Assert.ThrowsAny(() => + MaximalRectangles.InRegion(Region(Rect(0, 0, 10, 10)), token: cancelled.Token)); + } + private static PathsD Region(params PathD[] paths) => new(paths); private static PathD Rect(double left, double bottom, double right, double top) =>