From fcfb3e6c1b380129a38794fd1b93ff9d134d73e5 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sun, 15 Nov 2026 22:50:50 -0500 Subject: [PATCH] feat(auto-nest): offer each sheet size that finishes the job as its own layout Irregular picks each sheet's stock on an estimate of what the leftovers will cost, so a size that took every remaining part could lose the pick to a plan that ended up dearer, and its trial sheet was thrown away. Each pass now keeps those finished plans: one that beats the pass's own plan replaces it, and the rest are reported as alternatives (at most six a pass). No extra sheets are packed. The progress window's layout families now include the sheet sizes, so a one-sheet 60 x 120 layout is offered beside a one-sheet 48 x 144 best instead of being dropped as a near copy. With 48 x 96, 48 x 144 and 60 x 120 offered, the seven sample parts (130 copies) still take one 48 x 144 sheet and now end at 130.7" instead of 136.6"; the tutorial and synthetic nests are unchanged. Co-Authored-By: Claude Fable 5.2 --- .../Forms/NestLayoutChoicesTests.cs | 19 +++++ OpenNest.Desktop/Forms/NestLayoutChoices.cs | 16 +++- .../IrregularPassedOverStockTests.cs | 78 +++++++++++++++++++ .../Irregular/IrregularNestingEngine.cs | 64 ++++++++++++++- docs/automatic-nesting.md | 2 +- docs/nesting-engines.md | 6 +- 6 files changed, 176 insertions(+), 9 deletions(-) create mode 100644 OpenNest.Engine.Tests/NestingEngines/IrregularPassedOverStockTests.cs diff --git a/OpenNest.Desktop.Tests/Forms/NestLayoutChoicesTests.cs b/OpenNest.Desktop.Tests/Forms/NestLayoutChoicesTests.cs index 6757cc81..5666a967 100644 --- a/OpenNest.Desktop.Tests/Forms/NestLayoutChoicesTests.cs +++ b/OpenNest.Desktop.Tests/Forms/NestLayoutChoicesTests.cs @@ -123,6 +123,25 @@ public class NestLayoutChoicesTests Assert.Equal(new[] { best, fullerRow }, choices.Top); } + [Fact] + public void AnotherSheetSize_IsAFamilyOfItsOwn() + { + var stock = Stock(); + var wider = new NestPlateStock("wide", new Size(60, 120), quantity: null, partSpacing: 0.25, quadrant: 1); + var sameSizeOtherRow = new NestPlateStock("drop", new Size(48, 96), quantity: null, partSpacing: 0.25, quadrant: 1); + var choices = new NestLayoutChoices(); + var best = Layout(Sheet(stock, (0, 0), (0, 28), (10, 0))); + var onWider = Layout(Sheet(wider, (0, 0), (0, 28), (10, 0))); + + choices.Add(best, best: true); + // Same count and direction as the best, but on a different size: a real alternative. + Assert.True(choices.Add(onWider, best: false)); + // The size is what counts, not the stock row it came from. + Assert.False(choices.Add(Layout(Sheet(sameSizeOtherRow, (0, 0), (0, 28), (10, 0))), best: false)); + + Assert.Equal(new[] { best, onWider }, choices.Top); + } + [Fact] public void TheListIsCappedBestFirstThenByPartsPlaced() { diff --git a/OpenNest.Desktop/Forms/NestLayoutChoices.cs b/OpenNest.Desktop/Forms/NestLayoutChoices.cs index 86550a18..85e0e6ea 100644 --- a/OpenNest.Desktop/Forms/NestLayoutChoices.cs +++ b/OpenNest.Desktop/Forms/NestLayoutChoices.cs @@ -107,10 +107,18 @@ namespace OpenNest.Forms } /// - /// Layouts alike enough that only the better one is offered: the same number of sheets, - /// leaving the free strip the same way. + /// Layouts alike enough that only the better one is offered: the same number of sheets + /// of the same sizes, leaving the free strip the same way. /// - internal (int Sheets, bool? AlongLength) Family => (SheetCount, Remnant?.AlongLength); + internal (int Sheets, string Sizes, bool? AlongLength) Family => (SheetCount, sizes ??= SizeKey(), Remnant?.AlongLength); + + private string sizes; + + /// The sheet sizes with their counts, in a fixed order: "1x48x144" or "1x48x96|1x60x120". + private string SizeKey() => string.Join("|", Sheets + .GroupBy(s => FormattableString.Invariant($"{s.Stock.Size.Width:R}x{s.Stock.Size.Length:R}"), StringComparer.Ordinal) + .Select(g => FormattableString.Invariant($"{g.Sum(s => s.Quantity)}x{g.Key}")) + .OrderBy(k => k, StringComparer.Ordinal)); /// True when both place the same parts at the same poses on the same stock. public bool SameLayoutAs(NestLayoutChoice other) @@ -153,7 +161,7 @@ namespace OpenNest.Forms /// /// The layouts a run offers: the engine's best first, then the best layout of every other - /// family (sheet count and free-strip direction), so the list holds real alternatives rather + /// family (sheet count, sheet sizes and free-strip direction), so the list holds real alternatives rather /// than near copies of the best. Not thread-safe: use it from one thread. /// internal sealed class NestLayoutChoices diff --git a/OpenNest.Engine.Tests/NestingEngines/IrregularPassedOverStockTests.cs b/OpenNest.Engine.Tests/NestingEngines/IrregularPassedOverStockTests.cs new file mode 100644 index 00000000..1d14a375 --- /dev/null +++ b/OpenNest.Engine.Tests/NestingEngines/IrregularPassedOverStockTests.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.NestingEngines.Irregular; +using static OpenNest.Engine.Tests.NestingEngines.JobBuilder; +using static OpenNest.Engine.Tests.NestingEngines.Shapes; + +namespace OpenNest.Engine.Tests.NestingEngines; + +/// +/// A stock that takes the whole job on one sheet but loses the decode's per-sheet pick is still +/// a complete plan: it competes with the decode's own plan and is reported. +/// +public class IrregularPassedOverStockTests +{ + // Five 10 x 10 squares. "small" holds four, so the look-ahead rates it 441 + 100 * (441 / 400), + // about 551, under the strip's 572; the fifth square then needs a second small sheet (882). + private static NestJob UnderestimatedLeftovers() => Job( + new[] { Part("square", Rectangle(10, 10), 5) }, + new[] { Stock("small", 21, 21, spacing: 0.25), Stock("strip", 11, 52, spacing: 0.25) } + ); + + [Fact] + public void APassKeepsTheStockThatFinishedTheJob_WhenItsOwnPlanEndsUpDearer() + { + var job = UnderestimatedLeftovers(); + + var result = new IrregularNestingEngine().PlanForTesting(job, 0, null); + + LayoutAssert.Valid(job, result); + var sheet = Assert.Single(result.Plates); + Assert.Equal("strip", sheet.StockId); + Assert.Equal(5, sheet.Placements.Count); + } + + [Fact] + public void TheDearerStockThatAlsoFinishesTheJob_IsReportedAsAnAlternative() + { + var job = Job( + new[] { Part("square", Rectangle(10, 10), 4) }, + new[] { Stock("big", 60, 120, spacing: 0.25), Stock("small", 25, 25, spacing: 0.25) } + ); + var reports = new List(); + + var result = new IrregularNestingEngine().Solve(job, new Inline(reports.Add)); + + Assert.Equal("small", Assert.Single(result.Plates).StockId); + var onBig = reports.Where(r => r.Stage == NestJobStage.PlanAlternative) + .Select(r => r.Plan!) + .Where(p => p.Plates.Count == 1 && p.Plates[0].StockId == "big") + .ToList(); + Assert.NotEmpty(onBig); + Assert.All(onBig, plan => + { + LayoutAssert.Valid(job, plan); + Assert.Equal(4, plan.Plates[0].Placements.Count); + }); + } + + [Fact] + public void ReportingNeverChangesTheLayout() + { + var job = UnderestimatedLeftovers(); + + var silent = new IrregularNestingEngine().Solve(job); + var reported = new IrregularNestingEngine().Solve(job, new Inline(_ => { })); + + Assert.Equal( + silent.Plates.Select(p => (p.StockId, string.Join(";", p.Placements.Select(q => $"{q.X:R},{q.Y:R},{q.Rotation:R}")))), + reported.Plates.Select(p => (p.StockId, string.Join(";", p.Placements.Select(q => $"{q.X:R},{q.Y:R},{q.Rotation:R}"))))); + } + + private sealed class Inline(Action report) : IProgress + { + public void Report(NestJobProgress value) => report(value); + } +} diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs index b05ee34a..df1490eb 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs @@ -124,6 +124,7 @@ public sealed class IrregularNestingEngine : INestingEngine if (best != null && solver.Work.Value >= WorkBudget) break; var plan = solver.Plan(demand, axis, beta); + ReportAlternatives(job, types, solver.Alternatives, progress, token); if (best == null || plan.IsBetterThan(best)) { best = plan; @@ -152,6 +153,7 @@ public sealed class IrregularNestingEngine : INestingEngine if (solver.Work.Value >= WorkBudget) break; var plan = solver.Plan(demand, axis, 1.0, grouped: true); + ReportAlternatives(job, types, solver.Alternatives, progress, token); if (!plan.IsBetterThan(improved)) { ReportAlternative(job, types, plan, progress, token); @@ -171,6 +173,7 @@ public sealed class IrregularNestingEngine : INestingEngine { token.ThrowIfCancellationRequested(); var plan = solver.Plan(demand, PackAxis.X, 1.0, banded: true); + ReportAlternatives(job, types, solver.Alternatives, progress, token); if (plan.IsBetterThan(improved)) { ReportPlan(job, types, plan, progress, token); @@ -266,6 +269,14 @@ public sealed class IrregularNestingEngine : INestingEngine CandidateProgress.ReportAlternative(BuildResult(job, types, plan, null, token), progress); } + /// Reports the complete plans a pass found beside the one it returned. + private static void ReportAlternatives(NestJob job, IReadOnlyList types, IReadOnlyList plans, + IProgress? progress, CancellationToken token) + { + foreach (var plan in plans) + ReportAlternative(job, types, plan, progress, token); + } + /// Exercises the production physical-tail lifecycle from a test-owned incumbent. /// This does not alter normal Solve or expose a public packing API. internal NestJobResult ImproveTailForTesting(NestJob job, IReadOnlyList physicalPlan) @@ -363,8 +374,40 @@ public sealed class IrregularNestingEngine : INestingEngine bool banded = false) { groupedBudget = Work.Value + workBudget; + var finishers = new List(); var run = Decode(demand, axis, beta, new Dictionary(StringComparer.Ordinal), job.Options.MaxPlates, null, - weights, grouped, banded); + weights, grouped, banded, finishers); + // The decode picks each sheet's stock on an estimate of what the leftovers will cost, + // so a stock that finished the job outright can lose the pick to a plan that ends up + // dearer. Each such finished plan competes with the decode's own; a tie keeps the decode. + var decoded = ToPlan(run); + var best = decoded; + var plans = new List { decoded }; + foreach (var finisher in finishers) + { + var plan = ToPlan(finisher); + plans.Add(plan); + if (plan.IsBetterThan(best)) + best = plan; + } + plans.Remove(best); + plans.Sort((a, b) => a.IsBetterThan(b) ? -1 : b.IsBetterThan(a) ? 1 : 0); + Alternatives = plans.Take(MaxAlternatives).ToList(); + return best; + } + + /// Most plans one call keeps beside the one it returns. + private const int MaxAlternatives = 6; + + /// + /// The complete plans the last call found beside the one it returned, + /// best first: the job finished on another stock at some sheet, or the decode's own plan + /// when one of those beat it. + /// + public IReadOnlyList Alternatives { get; private set; } = Array.Empty(); + + private Plan ToPlan(Run run) + { var unplaced = types.Sum(t => t.Part.Quantity) - run.Sheets.Sum(s => s.Parts.Count); var reason = run.Reason; if (unplaced > 0 && reason == NestJobStopReason.Completed) @@ -595,6 +638,9 @@ public sealed class IrregularNestingEngine : INestingEngine /// Greedy sheet-by-sheet decode. seeds finite-stock /// accounting, bounds the sheets this run may add, and /// , when set, forces the stock of the first sheet. + /// , when set, receives every complete run the decode passed + /// over: the sheets chosen so far plus a trial sheet that took all the remaining parts + /// but was not the sheet chosen. Collecting them never changes the decode. /// private Run Decode( int[] demand, @@ -605,7 +651,8 @@ public sealed class IrregularNestingEngine : INestingEngine NestPlateStock? first, IReadOnlyList? weights = null, bool grouped = false, - bool banded = false + bool banded = false, + List? finishers = null ) { var remaining = (int[])demand.Clone(); @@ -673,6 +720,19 @@ public sealed class IrregularNestingEngine : INestingEngine .ThenBy(t => t.order) .First(); + if (finishers != null) + { + var left = remaining.Sum(); + for (var i = 0; i < trials.Count; i++) + { + if (i == chosen.order || trials[i].Fill.Parts.Count != left) + continue; + // Each run owns its sheets' part lists, as the chosen copies below do. + var finished = sheets.Select(s => s with { Parts = s.Parts.ToList() }).Append(trials[i].Fill).ToList(); + finishers.Add(new Run(finished, NestJobCost.RequireFinite(net + trials[i].Net), NestJobStopReason.Completed)); + } + } + var outstanding = types.ToDictionary(t => t.Part.Id, t => remaining[t.Index], StringComparer.Ordinal); var counts = chosen.Fill.Parts.GroupBy(p => types[p.Orientation.TypeIndex].Part.Id, StringComparer.Ordinal) .ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal); diff --git a/docs/automatic-nesting.md b/docs/automatic-nesting.md index 5f386c0b..4dcfea11 100644 --- a/docs/automatic-nesting.md +++ b/docs/automatic-nesting.md @@ -28,7 +28,7 @@ Auto Nest starts on empty/new sheets and does not change existing populated plat Progress is owned and modal so the input drawings cannot be edited while a worker uses them. Stop or closing progress cancels and discards the whole proposal. The dialog waits for the worker to finish. **Use This Layout** (below) is the only way to end the search early with something to keep, and what it keeps is validated like any result. A plug-in that ignores the cancellation token cannot commit its late result. -Auto Nest never draws its parts on the plate view before they are kept: its result is a set of sheets, possibly of several sizes, not parts on the current plate. Ghost (preview) parts on the plate view mean only "what this plate gets if you accept now", and stay with interactive Fill and the remnant tools. Instead the progress window shows **Top layouts**: up to three whole-job layouts as cards, the engine's best so far first. A card draws every sheet of its layout side by side at one scale, identical sheets once with their count, each captioned with size, part count, utilization and its free strip, which is also dimensioned on the sheet: the distance from the parts to the right edge when they were packed in vertical strips, or to the top for horizontal strips (the left edge or the bottom in the quadrants whose origin is on the other side; whichever strip has more area is the one shown, and an outlined sheet shows none). The card's title line totals the layout and gives the last sheet's free strip, the usable drop. An engine reports a plan with `NestJobStage.PlanImproved` and `NestJobProgress.Plan`; `NestPipeline` adds `PlanSheets`, parts on detached drawings built from the job geometry, so nothing touches the caller's drawings or quantities. The plan is unvalidated and may be replaced. An engine may also report plans that lost to its best (`NestJobStage.PlanAlternative`); the window keeps the best layout of each family (sheet count and free-strip direction) other than the best's, so the cards are real alternatives, such as the same job packed toward the left edge and toward the bottom, not near copies. Default, Irregular, Rectangles and Circles report plans (see [nesting engines](nesting-engines.md#best-plan-so-far)); FlatBar, the fixed-strategy engines and plug-ins that report none show the strip empty until the review. +Auto Nest never draws its parts on the plate view before they are kept: its result is a set of sheets, possibly of several sizes, not parts on the current plate. Ghost (preview) parts on the plate view mean only "what this plate gets if you accept now", and stay with interactive Fill and the remnant tools. Instead the progress window shows **Top layouts**: up to three whole-job layouts as cards, the engine's best so far first. A card draws every sheet of its layout side by side at one scale, identical sheets once with their count, each captioned with size, part count, utilization and its free strip, which is also dimensioned on the sheet: the distance from the parts to the right edge when they were packed in vertical strips, or to the top for horizontal strips (the left edge or the bottom in the quadrants whose origin is on the other side; whichever strip has more area is the one shown, and an outlined sheet shows none). The card's title line totals the layout and gives the last sheet's free strip, the usable drop. An engine reports a plan with `NestJobStage.PlanImproved` and `NestJobProgress.Plan`; `NestPipeline` adds `PlanSheets`, parts on detached drawings built from the job geometry, so nothing touches the caller's drawings or quantities. The plan is unvalidated and may be replaced. An engine may also report plans that lost to its best (`NestJobStage.PlanAlternative`); the window keeps the best layout of each family (sheet count, sheet sizes and free-strip direction) other than the best's, so the cards are real alternatives, such as the same job on one 60 x 120 sheet instead of one 48 x 144, or packed toward the left edge and toward the bottom, not near copies. The alternatives are ordered by parts placed, then fewer sheets, less sheet area and the larger free strip. Default, Irregular, Rectangles and Circles report plans (see [nesting engines](nesting-engines.md#best-plan-so-far)); FlatBar, the fixed-strategy engines and plug-ins that report none show the strip empty until the review. Any card can be used. Click a card to select it (the best stays selected until you do) and choose **Use This Layout**, or double-click the card: during the search this stops it; when the search finishes with more than one layout the window stays open, titled **Nesting Finished**, until a layout is used or **Discard** drops them all. A search that ends with a single layout goes straight to the review, as do Make Nests runs, which always take the engine's result. The layout used goes through the same validation and binding as the engine's result (`NestJobProgress.AcceptPlan`), so a layout that breaks a rule shows the validation report below; last-resort clamp removal applies only to the engine's own result. diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index afe6bdd0..2bf0b1b9 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -14,7 +14,7 @@ in `OpenNest.Engine/NestingEngines//`, its tests in `OpenNest.Engine.Tests | 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 | | 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 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; under a time limit it keeps trying seeded variants until the limit | +| 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; under a time limit it 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 | | Lattice, Strip, Vertical Remnant, Horizontal Remnant | Many copies of a few parts | The fixed placement strategies behind interactive fill; Lattice is the multi-phase lattice fill (linear, pairs, rectangle best-fit, remainder; the pairs phase fills the strip its grid leaves with rows of pairs when they hold more than single parts, and also tiles herringbone pairs: the part turned so a hull edge lies along a sheet axis, nested into its own row, with every other row reversed), and the remnant strategies run it ranked to keep the largest drop. In whole jobs, all four place a plate with any fixed or bounded part rotation by the rotation-aware ordered placer instead | @@ -100,7 +100,9 @@ An engine may also report a complete plan that lost to its best as `NestJobStage another layout the desktop may offer beside the best (see [automatic nesting](automatic-nesting.md)). Alternatives are optional, unranked and unvalidated, never the engine's result, and reporting them never changes the search. Irregular reports the strategy, grouped and banded variants that -did not beat its best (not the seeded decodes of a search until cancelled); Default and a +did not beat its best (not the seeded decodes of a search until cancelled), and with several stock +sizes the plans each of those passes found on a stock other than the one it chose: the sheets +chosen so far plus a trial sheet that took every remaining part (at most six a pass). Default and a time-limited solve report a valid plan or candidate result that did not beat the one shown. The nest server's worker drops them.