From 7964785af56cec997a85a8b18fa1ff36c3f3d622 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sat, 21 Nov 2026 13:19:42 -0500 Subject: [PATCH] feat(rectangles): also nest large parts first and fill their gaps Sheet-by-sheet look-ahead cost picks the densest sheet, and a sheet of small parts packs densest. On a braze casing mixing 35x57 to 65x89 plates with 5x28 angles and 9x4 tabs, sheet 1 took 109 small parts and the plates followed one or two to a sheet with empty strips beside them: 28 sheets, 220,032 sq in. Rectangles now also runs the job large parts first, splitting types at the widest drops in box area: the large types nest alone, each of their sheets is repacked with every waiting small part (keeping all its large parts), and leftovers get new sheets. The cheapest whole job wins; ties keep the cost-first run. The braze casing takes 27 sheets and 203,616 sq in, every sheet but the last a plate with small parts in its gaps. Problem-nest corpus (auto-nest): all saved layouts unchanged. Co-Authored-By: Claude Opus 5.5 --- .../RectanglesLargeFirstTests.cs | 60 ++++++++++++ .../Rectangles/RectanglesNestingEngine.cs | 91 ++++++++++++++++++- .../NestingEngines/SheetByStock.cs | 10 +- docs/nesting-engines.md | 20 +++- 4 files changed, 178 insertions(+), 3 deletions(-) create mode 100644 OpenNest.Engine.Tests/NestingEngines/RectanglesLargeFirstTests.cs diff --git a/OpenNest.Engine.Tests/NestingEngines/RectanglesLargeFirstTests.cs b/OpenNest.Engine.Tests/NestingEngines/RectanglesLargeFirstTests.cs new file mode 100644 index 00000000..913f9fa1 --- /dev/null +++ b/OpenNest.Engine.Tests/NestingEngines/RectanglesLargeFirstTests.cs @@ -0,0 +1,60 @@ +using System.Linq; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.NestingEngines.Rectangles; +using static OpenNest.Engine.Tests.NestingEngines.JobBuilder; +using static OpenNest.Engine.Tests.NestingEngines.Shapes; + +namespace OpenNest.Engine.Tests.NestingEngines; + +/// +/// A job mixing large plates with small parts: cost alone picks the densest sheet first, a sheet of +/// small parts, and leaves the large plates' sheets nothing to fill their gaps with. The large-first +/// run nests the plates first and fills their gaps, so no sheet is spent on small parts alone. +/// +public class RectanglesLargeFirstTests +{ + private static NestJob BrazeCasing() => Job( + new[] + { + Part("side-a", Rectangle(56.93, 88.99), 3), + Part("side-b", Rectangle(58.7, 56.93), 2), + Part("angle", Rectangle(5.3, 28.28), 30), + Part("tab", Rectangle(9, 3.75), 40), + }, + new[] + { + Stock("60x120", 60, 120, spacing: 0.25), + Stock("72x144", 72, 144, spacing: 0.25), + }); + + private static readonly string[] Large = { "side-a", "side-b" }; + + [Fact] + public void CostAloneSpendsTheFirstSheetOnSmallParts() + { + var job = BrazeCasing(); + + var result = new RectanglesNestingEngine { LargeFirstRuns = false }.Solve(job); + + LayoutAssert.Valid(job, result); + Assert.DoesNotContain(result.Plates[0].Placements, p => Large.Contains(p.PartId)); + } + + [Fact] + public void SmallPartsFillTheLargePlatesSheets() + { + var job = BrazeCasing(); + + var result = new RectanglesNestingEngine().Solve(job); + var costFirst = new RectanglesNestingEngine { LargeFirstRuns = false }.Solve(job); + + LayoutAssert.Valid(job, result); + Assert.Equal(NestJobStatus.Complete, result.Status); + Assert.True(NestJobCost.Evaluate(job, result) <= NestJobCost.Evaluate(job, costFirst)); + // Only the last sheet may hold small parts alone: those its predecessors had no room for. + Assert.All(result.Plates.Take(result.Plates.Count - 1), + sheet => Assert.Contains(sheet.Placements, p => Large.Contains(p.PartId))); + Assert.All(result.Plates.Take(result.Plates.Count - 1), + sheet => Assert.Contains(sheet.Placements, p => !Large.Contains(p.PartId))); + } +} diff --git a/OpenNest.Engine/NestingEngines/Rectangles/RectanglesNestingEngine.cs b/OpenNest.Engine/NestingEngines/Rectangles/RectanglesNestingEngine.cs index 76479a7e..d27b711d 100644 --- a/OpenNest.Engine/NestingEngines/Rectangles/RectanglesNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Rectangles/RectanglesNestingEngine.cs @@ -35,6 +35,8 @@ public sealed class RectanglesNestingEngine : INestingEngine // Instance-owned diagnostics; no process-global counters or mutable solver state. internal Action? SheetPacked { get; init; } internal Action? BatchSelected { get; init; } + /// Tests turn the large-first runs off to compare against the cost-first run alone. + internal bool LargeFirstRuns { get; init; } = true; public NestJobResult Solve( NestJob job, @@ -55,7 +57,22 @@ public sealed class RectanglesNestingEngine : INestingEngine var demand = types.Select(t => new SheetDemand(t.Index, t.Id, t.Priority, t.MaterialArea)).ToArray(); // One run makes one whole-job plan: report it, then its commits, as the other engines do. var forward = progress == null ? null : new CandidateProgress(progress); - var result = SheetByStock.Run(job, demand, remaining, Pack, forward, token, BatchSelected); + var result = SheetByStock.Run(job, demand, remaining.ToArray(), Pack, forward, token, BatchSelected); + // Sheet by sheet, cost picks the densest sheet, which on a job mixing large plates with + // small parts packs the small parts onto early sheets of their own and leaves the large + // plates' sheets nothing to fill their gaps. Large-first runs nest the large parts alone, + // fill each of their sheets' gaps with the small parts, and only then start new sheets for + // what is left. The cheapest whole job wins; ties keep the cost-first run. + var best = Score(result, 0); + var order = 1; + foreach (var split in LargeFirstRuns ? LargeSplits(types, remaining) : Enumerable.Empty()) + { + token.ThrowIfCancellationRequested(); + var scored = Score(LargeFirst(split), order++); + if (scored.IsBetterThan(best)) + best = scored; + } + result = best.Result; CandidateProgress.ReportPlan(result, progress); CandidateProgress.ReportCommits(result, progress, token); return result; @@ -85,10 +102,82 @@ public sealed class RectanglesNestingEngine : INestingEngine return plans; } + NestJobResult LargeFirst(double split) + { + var large = types.Select(t => t.BoxArea >= split).ToArray(); + var small = remaining.Select((r, i) => large[i] ? 0 : r).ToArray(); + var sheets = SheetByStock.Run(job, demand, remaining.Select((r, i) => large[i] ? r : 0).ToArray(), + Pack, forward, token); + var stocks = job.Plates.ToDictionary(p => p.Id, StringComparer.Ordinal); + var index = types.ToDictionary(t => t.Id, t => t.Index, StringComparer.Ordinal); + var filled = new List(sheets.Plates.Count); + foreach (var sheet in sheets.Plates) + { + token.ThrowIfCancellationRequested(); + var stock = stocks[sheet.StockId]; + var own = new int[types.Count]; + foreach (var p in sheet.Placements) + own[index[p.PartId]]++; + var poses = sheet.Placements.Select(p => (p.PartId, p.X, p.Y, p.Rotation)).ToArray(); + var layout = new SheetLayout(stock, poses, types.Sum(t => own[t.Index] * t.MaterialArea), null); + if (small.Any(r => r > 0)) + { + // Repack the sheet's own large parts with every small part still waiting; + // a plan counts only if it keeps all of the sheet's large parts. + var wanted = own.Select((n, i) => n + small[i]).ToArray(); + SheetPlan? fill = null; + foreach (var plan in PackAll(stock, wanted, null, null)) + { + var counts = new int[types.Count]; + foreach (var p in plan.Parts) + counts[p.Type.Index]++; + if (types.Any(t => large[t.Index] && counts[t.Index] < own[t.Index])) + continue; + if (fill == null || plan.MaterialArea > fill.MaterialArea) + fill = plan; + } + if (fill != null && fill.MaterialArea > layout.MaterialArea) + { + layout = Layout(fill); + foreach (var p in fill.Parts) + if (!large[p.Type.Index]) + small[p.Type.Index]--; + } + } + filled.Add(layout); + } + return SheetByStock.Run(job, demand, small, Pack, forward, token, prefix: filled); + } + + // Both runs come from the same validated box packer, so they rank on demand met, cost and + // offcut without a layout check. + CandidateScore Score(NestJobResult r, int at) + { + var unplaced = System.Math.Max(0, job.Parts.Sum(p => p.Quantity) - r.Plates.Sum(p => p.Placements.Count)); + return new CandidateScore(r, true, unplaced, NestJobCost.Evaluate(job, r), + NestJobCost.CompactnessOffcut(job, r), at, NestJobCost.UsesExplicitCosts(job)); + } + static SheetLayout Layout(SheetPlan plan) => new(plan.Stock, plan.Poses().ToArray(), plan.MaterialArea, plan.Envelope); } + /// Box-area thresholds splitting the job's types into large and small: below each of + /// the widest drops in box area (to half or less of the next larger type), at most + /// , widest first. + private static IEnumerable LargeSplits(IReadOnlyList types, int[] remaining) + { + var areas = types.Where(t => remaining[t.Index] > 0).Select(t => t.BoxArea) + .Distinct().OrderByDescending(a => a).ToArray(); + return Enumerable.Range(1, System.Math.Max(0, areas.Length - 1)) + .Where(i => areas[i] <= areas[i - 1] * 0.5) + .OrderBy(i => areas[i] / areas[i - 1]).ThenBy(i => i) + .Take(MaxLargeSplits) + .Select(i => areas[i - 1]); + } + + private const int MaxLargeSplits = 3; + private static bool FitsStock(NestPlateStock stock, BoxOrientation o) { if (stock.Outline != null) diff --git a/OpenNest.Engine/NestingEngines/SheetByStock.cs b/OpenNest.Engine/NestingEngines/SheetByStock.cs index 181f5597..0e3ba3d3 100644 --- a/OpenNest.Engine/NestingEngines/SheetByStock.cs +++ b/OpenNest.Engine/NestingEngines/SheetByStock.cs @@ -38,6 +38,8 @@ internal static class SheetByStock /// packer's completed search, not budget-limited output, so a repeat is safe. /// When set, only this stock is tried while it is available and /// takes a layout; the others are tried only once it cannot. + /// Sheets already chosen, committed first in order and counted against + /// stock and plate limits; must already exclude their parts. public static NestJobResult Run( NestJob job, IReadOnlyList types, @@ -46,12 +48,18 @@ internal static class SheetByStock IProgress? progress, CancellationToken token, Action? batchSelected = null, - NestPlateStock? preferred = null) + NestPlateStock? preferred = null, + IReadOnlyList? prefix = null) { var used = job.Plates.ToDictionary(s => s.Id, _ => 0, StringComparer.Ordinal); var parts = job.Parts.ToDictionary(p => p.Id, StringComparer.Ordinal); var priority = types.ToDictionary(t => t.Id, t => t.Priority, StringComparer.Ordinal); var result = new NestJobResultBuilder(job, progress); + foreach (var sheet in prefix ?? Array.Empty()) + { + result.AddSheet(sheet.Stock, sheet.Poses); + used[sheet.Stock.Id]++; + } NestJobStopReason reason; while (true) diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index e7e727ac..11347b81 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -12,7 +12,7 @@ in `OpenNest.Engine/NestingEngines//`, its tests in `OpenNest.Engine.Tests | Engine | Best for | Method | |---|---|---| | Default | Any job; used when no engine is named | Runs Irregular, Rectangles and Circles, checks each layout with the layout check and keeps the best: valid first, then fewest unplaced parts, then lowest salvage-credited cost, then the largest compactness offcut; remaining ties keep the engine listed first here | -| Rectangles | Plain and near-rectangular plates | Each part packed as the box of its material at its minimum-area rotation, using a maximal-rectangles free list; the sheet that finishes the job is also squeezed into a shorter or narrower bin; stock chosen sheet by sheet by salvage-credited look-ahead cost | +| Rectangles | Plain and near-rectangular plates | Each part packed as the box of its material at its minimum-area rotation, using a maximal-rectangles free list; the sheet that finishes the job is also squeezed into a shorter or narrower bin; stock chosen sheet by sheet by salvage-credited look-ahead cost, and the whole job also run large parts first with the small parts filling their sheets' gaps | | Circles | Round parts: blanks, washers, flanges, gears by their tip circle | Each part packed as its minimum enclosing circle at centers tangent to two of walls, placed discs and clamp keep-outs, with hexagonal and square lattice seeds; bids only when every part is round; stock chosen as Rectangles does, plus whole-job runs preferring each stock and a tail re-plan | | Irregular | Irregular profiles | No-fit-polygon frontier packing with gap filling and best-fit pairs, six whole-job strategy variants (each also keeping a stock that finished the job when the per-sheet estimate passed it over for a plan that ended up dearer) and a tail re-plan, then grouped variants that pack like parts together, then a banded variant that packs each sheet in full-height strips, each group as its Lattice band or each strip from the largest parts down, then a sheet-reduction pass that packs edge parts first and turns a key part by its contacts, then a squeeze that packs the last sheet again, largest part first, in ever shorter strips; under a time limit it first reports a quick plan without Lattice blocks, and after its search keeps trying seeded variants until the limit | | FlatBar | Flat bar: parts about as wide as the bar | Each stock read as a bar and cut in one row: the CutList cut-list packer and a best-fill search on part lengths less their self-nesting gain, then a slide-left pass that nests shaped ends and refills freed length; stock chosen bar by bar by whole-plan cost | @@ -64,6 +64,24 @@ Rectangles places irregular parts validly, but only as their bounding boxes; it notch or hole. Box sides account for how the layout check flattens arcs, so round-edged parts stay valid at box contact. +#### Large parts first + +Picking each sheet by its look-ahead cost favors the densest sheet, and a sheet of small parts +packs densest. On a job mixing large plates with small parts that spends the first sheets on the +small parts alone and leaves each large plate a sheet with an empty strip beside it. On one real +job (a braze casing in 3/16 steel: 35 x 57 to 65 x 89 side and cover plates, 5 x 28 angles and +9 x 4 tabs, 219 parts on five stock sizes) sheet 1 held 109 small parts and the plates followed +one or two to a sheet, 28 sheets and 220,032 sq in in all. + +So Rectangles also runs the job large parts first. The part types are split at a wide drop in box +area (to half or less of the next larger type; the three widest drops are each tried). The large +types nest alone, sheet by sheet as usual; then each of their sheets, in order, is packed again with +its own large parts and every small part still waiting, keeping the packing that places the most +material without dropping one of its large parts; whatever small parts are left get new sheets of +their own. The cheapest whole job wins (then the larger compactness offcut); a tie keeps the +cost-first run. The braze casing now takes 27 sheets and 203,616 sq in, every sheet but the last +holding a plate with small parts in its gaps. + #### Squeezing the last sheet The fit rules pack into the whole sheet, so when the last sheet has room to spare they spread the