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 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-21 19:21:09 -05:00
1 parent f28fb5adb6
commit aea032a24d
5 files changed
+209 -11

No files matched your search

+29 -6
View File
@@ -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
/// <param name="minDimension">Rectangles narrower than this in either axis are dropped.</param>
/// <param name="divisions">Even subdivisions of the region's bounds per axis, which bound the
/// staircase loss along slanted edges.</param>
/// <param name="largest">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.</param>
/// <param name="token">Checked throughout; the search is long for a region with many edges.</param>
/// <returns>Rectangles not contained in another result, largest area first.</returns>
public static List<Box> InRegion(PathsD region, double minDimension = 0, int divisions = 64)
public static List<Box> 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);
}
/// <summary>
@@ -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<double> GridLines(IEnumerable<double> vertices, double min, double max, int divisions)
@@ -206,7 +219,8 @@ public static class MaximalRectangles
return true;
}
private static List<Box> MergeCells(IReadOnlyList<double> xs, IReadOnlyList<double> ys, bool[,] empty)
private static List<Box> MergeCells(IReadOnlyList<double> xs, IReadOnlyList<double> 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<Box> RemoveDominated(List<Box> boxes)
/// <summary>
/// The boxes not within a larger one, largest first. Stops at the first box smaller than the
/// result at rank <paramref name="largest"/>: boxes are taken in order, each against the
/// results before it, so the results kept up to there are those of the full pass.
/// </summary>
private static List<Box> RemoveDominated(List<Box> boxes, int largest, CancellationToken token)
{
boxes.Sort((a, b) => b.Area().CompareTo(a.Area()));
var results = new List<Box>();
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)
@@ -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;
/// <summary>
/// Irregular under <see cref="DeadlineNestingEngine"/>: 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.
/// </summary>
public class IrregularDeadlineTests
{
/// <summary>A gear: <paramref name="teeth"/> square teeth on a disc, with four square holes.</summary>
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));
}
/// <summary>A bar with a serrated long edge (<paramref name="teeth"/> teeth) and four square holes.</summary>
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);
}
/// <summary>
/// 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.
/// </summary>
[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<Placed>();
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<int, IReadOnlyList<PairPose>>();
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<OperationCanceledException>(() => packer.Fill(new[] { 400 }, cancel.Token, seated));
Assert.True(watch.Elapsed < limit + TimeSpan.FromSeconds(2), $"Took {watch.Elapsed.TotalSeconds:0.0} s.");
}
}
@@ -201,13 +201,16 @@ internal sealed class BlockCatalog : IDisposable
/// <summary>
/// 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.
/// </summary>
internal static IReadOnlyList<Box> Rectangles(Box work, IReadOnlyList<Placed> placed, double spacing) =>
MaximalRectangles.InRegion(FreeRegion(work, placed, spacing)).OrderByDescending(b => b.Area())
internal static IReadOnlyList<Box> Rectangles(Box work, IReadOnlyList<Placed> 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> placed, double spacing)
private static PathsD FreeRegion(Box work, IReadOnlyList<Placed> 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 },
@@ -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)
@@ -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<PathD> { 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<OperationCanceledException>(() =>
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) =>