diff --git a/OpenNest.Engine.Tests/NestingEngines/IrregularSearchUntilCancelledTests.cs b/OpenNest.Engine.Tests/NestingEngines/IrregularSearchUntilCancelledTests.cs index f3e8d023..42dac8d2 100644 --- a/OpenNest.Engine.Tests/NestingEngines/IrregularSearchUntilCancelledTests.cs +++ b/OpenNest.Engine.Tests/NestingEngines/IrregularSearchUntilCancelledTests.cs @@ -25,14 +25,34 @@ public class IrregularSearchUntilCancelledTests { public List Plans { get; } = new(); + /// Every plan reported, improved or alternative, in order. + public List All { get; } = new(); + public void Report(NestJobProgress value) { if (value.Stage == NestJobStage.PlanImproved) Plans.Add(value.Plan!); + if (value.Stage is NestJobStage.PlanImproved or NestJobStage.PlanAlternative) + All.Add(value.Plan!); also?.Invoke(value); } } + /// Whether appears in in order. + private static bool InOrder(IEnumerable expected, IEnumerable reported) + { + using var next = reported.GetEnumerator(); + foreach (var plan in expected) + { + var found = false; + while (!found && next.MoveNext()) + found = Placements(next.Current).SequenceEqual(Placements(plan)); + if (!found) + return false; + } + return true; + } + private static List<(string, int, double, double, double)> Placements(NestJobResult result) => result.Plates.SelectMany(p => p.Placements.Select(q => (q.PartId, q.InstanceIndex, q.X, q.Y, q.Rotation))) .ToList(); @@ -47,6 +67,57 @@ public class IrregularSearchUntilCancelledTests Assert.Equal(Placements(plain), Placements(flagged)); } + [Fact] + public void ASolveThatCanEndUnlimitedReportsNoQuickPlan() + { + // The quick plan belongs to a solve that ends only at its limit: without the option, or + // without a token that can cancel it, the plans reported are the usual ones. + var plain = new Recorder(); + var plainResult = new IrregularNestingEngine().Solve(MixedJob(false), plain); + var quick = new IrregularNestingEngine().QuickPlanForTesting(MixedJob(false)); + Assert.DoesNotContain(plain.All, p => Placements(p).SequenceEqual(Placements(quick))); + + using var cancel = new CancellationTokenSource(); + var cancellable = new Recorder(); + var flagged = new Recorder(); + var cancellableResult = new IrregularNestingEngine().Solve(MixedJob(false), cancellable, cancel.Token); + var flaggedResult = new IrregularNestingEngine().Solve(MixedJob(true), flagged); + + foreach (var (recorder, result) in new[] { (cancellable, cancellableResult), (flagged, flaggedResult) }) + { + Assert.Equal(Placements(plainResult), Placements(result)); + Assert.Equal(plain.All.Select(Placements), recorder.All.Select(Placements)); + } + } + + [Fact] + public void ATimeLimitedSolveReportsAQuickPlanFirst() + { + // The first variant without Lattice blocks, reported before the normal search finishes its + // first sheet: stopped there, the solve has the quick plan, a valid layout, to return. + var job = MixedJob(true); + var quickSheets = 0; + var quick = new IrregularNestingEngine { SheetPacked = () => quickSheets++ }.QuickPlanForTesting(job); + using var cancel = new CancellationTokenSource(); + var sheets = 0; + var engine = new IrregularNestingEngine + { + SheetPacked = () => + { + if (++sheets > quickSheets) + cancel.Cancel(); + }, + }; + var recorder = new Recorder(); + + Assert.ThrowsAny(() => engine.Solve(job, recorder, cancel.Token)); + + var plan = Assert.Single(recorder.Plans); + Assert.Equal(Placements(quick), Placements(plan)); + Assert.NotEmpty(Placements(plan)); + LayoutAssert.Valid(MixedJob(false), plan); + } + [Fact] public void KeepsSearchingAfterTheNormalSearchUntilCancelled() { @@ -58,6 +129,10 @@ public class IrregularSearchUntilCancelledTests var plainResult = new IrregularNestingEngine { GroupLikeParts = false }.Solve(MixedJob(false, Ells), plain); var normalSheets = 0; new IrregularNestingEngine { GroupLikeParts = false, SheetPacked = () => normalSheets++ }.Solve(MixedJob(false, Ells)); + // A time-limited solve packs its quick plan before the normal search. + var quickSheets = 0; + var quick = new IrregularNestingEngine { GroupLikeParts = false, SheetPacked = () => quickSheets++ } + .QuickPlanForTesting(MixedJob(false, Ells)); var extendedSheets = 0; var extendedTailBudgets = new List(); @@ -65,16 +140,17 @@ public class IrregularSearchUntilCancelledTests var engine = new IrregularNestingEngine { GroupLikeParts = false, - // The normal search packs exactly normalSheets sheets; later ones are extended. + // The quick plan and the normal search pack exactly quickSheets + normalSheets sheets; + // later ones are extended. TailReplanning = budget => { - if (extendedSheets > normalSheets) + if (extendedSheets > quickSheets + normalSheets) extendedTailBudgets.Add(budget); }, SheetPacked = () => { // Let the extended search pack several more whole plans, then stop it. - if (++extendedSheets >= normalSheets * 12) + if (++extendedSheets >= quickSheets + normalSheets * 12) cancel.Cancel(); }, }; @@ -82,15 +158,17 @@ public class IrregularSearchUntilCancelledTests Assert.ThrowsAny(() => engine.Solve(MixedJob(true, Ells), extended, cancel.Token)); - Assert.True(extendedSheets >= normalSheets * 12); - // The normal search runs first, unchanged; the extended search improves on it and - // re-plans the tails of its plans. - Assert.True(extended.Plans.Count > plain.Plans.Count); + Assert.True(extendedSheets >= quickSheets + normalSheets * 12); + // The quick plan comes first. The normal search then runs unchanged, each of its plans + // reported (as an alternative while it does not beat the quick plan); the extended + // search improves on it and re-plans the tails of its plans. + Assert.Equal(Placements(quick), Placements(extended.Plans[0])); + Assert.True(InOrder(plain.Plans, extended.All.Skip(1))); + Assert.Contains(extended.Plans.Skip(1), + p => !plain.Plans.Any(q => Placements(q).SequenceEqual(Placements(p)))); // Each improvement gets a tail re-plan with its own fresh budget. Assert.NotEmpty(extendedTailBudgets); Assert.All(extendedTailBudgets, b => Assert.Equal(2 * new IrregularNestingEngine().WorkBudget, b)); - for (var i = 0; i < plain.Plans.Count; i++) - Assert.Equal(Placements(plain.Plans[i]), Placements(extended.Plans[i])); var job = MixedJob(false, Ells); var last = CandidateScore.Of(job, extended.Plans[^1], 0); Assert.False(CandidateScore.Of(job, plainResult, 0).IsBetterThan(last)); diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs index df1490eb..da7dfb09 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs @@ -23,7 +23,8 @@ namespace OpenNest.Engine.NestingEngines.Irregular; /// With , a cancellable token and a progress /// listener, the search then keeps decoding the variants with seeded per-type weights on the /// placement rule, reporting each better plan, until cancelled (not for one-type jobs, where -/// the weights change nothing). +/// the weights change nothing). Such a solve first reports a quick plan, the first variant +/// without Lattice blocks, metered apart so the search after it is unchanged. /// /// Fully deterministic: no clocks or randomness influence any decision. The weights come from /// fixed seeds 1, 2, 3, ..., so an extended search depends only on how far it got. @@ -117,6 +118,40 @@ public sealed class IrregularNestingEngine : INestingEngine || (type.Part.Quantity > 2 && type.Orientations.Count > 0) ? type.Part.Quantity : 0; } + // More searching can only end in cancellation, so it needs a listener for its plans, and + // it needs demand and two or more types, or every weighted decode repeats a variant. + var searchOn = job.Options.SearchUntilCancelled && token.CanBeCanceled && progress != null + && types.Count > 1 && demand.Any(d => d > 0); + + // A solve that ends only at its limit reports a quick plan first: the first variant without + // Lattice blocks, whose preparation takes most of the first decode's time on big jobs. It is + // metered apart, so the search below runs as without it. Until a plan of that search beats + // it, that search's plans are reported as alternatives, so no worse plan follows it. Without + // a type of three or more copies no block is ever prepared, and the quick plan would only + // repeat the first variant. + Plan? quick = null; + if (searchOn && demand.Any(d => d > 2)) + { + quick = solver.QuickPlan(demand); + if (quick.Sheets.Count > 0) + ReportPlan(job, types, quick, progress, token); + else + quick = null; + } + void Improved(Plan plan) + { + if (quick != null) + { + if (!plan.IsBetterThan(quick)) + { + ReportAlternative(job, types, plan, progress, token); + return; + } + quick = null; + } + ReportPlan(job, types, plan, progress, token); + } + Plan? best = null; foreach (var (axis, beta) in Variants) { @@ -128,7 +163,7 @@ public sealed class IrregularNestingEngine : INestingEngine if (best == null || plan.IsBetterThan(best)) { best = plan; - ReportPlan(job, types, best, progress, token); + Improved(best); } else ReportAlternative(job, types, plan, progress, token); @@ -139,7 +174,7 @@ public sealed class IrregularNestingEngine : INestingEngine // The last sheets hold the leftovers, which is where waste concentrates; re-plan them. var improved = solver.ImproveTail(best!, WorkBudget * 2); if (!ReferenceEquals(improved, best)) - ReportPlan(job, types, improved, progress, token); + Improved(improved); // Like parts grouped, the groups' stragglers filling the gaps after them. These run last, on // their own budget, so the search above is the same with or without them; a grouped plan @@ -159,10 +194,10 @@ public sealed class IrregularNestingEngine : INestingEngine ReportAlternative(job, types, plan, progress, token); continue; } - ReportPlan(job, types, plan, progress, token); + Improved(plan); improved = solver.ImproveTail(plan, solver.Work.Value + WorkBudget * 2); if (!ReferenceEquals(improved, plan)) - ReportPlan(job, types, improved, progress, token); + Improved(improved); } // Then full-height strips: each like-part group as a band of its Lattice pattern, or strip by // strip with the largest part first and the rest in its gaps; per sheet the better wins. @@ -176,10 +211,10 @@ public sealed class IrregularNestingEngine : INestingEngine ReportAlternatives(job, types, solver.Alternatives, progress, token); if (plan.IsBetterThan(improved)) { - ReportPlan(job, types, plan, progress, token); + Improved(plan); improved = solver.ImproveTail(plan, solver.Work.Value + WorkBudget * 2); if (!ReferenceEquals(improved, plan)) - ReportPlan(job, types, improved, progress, token); + Improved(improved); } else ReportAlternative(job, types, plan, progress, token); @@ -192,14 +227,11 @@ public sealed class IrregularNestingEngine : INestingEngine if (!ReferenceEquals(reduced, improved)) { improved = reduced; - ReportPlan(job, types, improved, progress, token); + Improved(improved); } } - // More searching can only end in cancellation, so it needs a listener for its plans, and - // it needs demand and two or more types, or every weighted decode repeats a variant. - if (job.Options.SearchUntilCancelled && token.CanBeCanceled && progress != null - && types.Count > 1 && demand.Any(d => d > 0)) - SearchUntilCancelled(job, types, solver, demand, improved, groups, progress, token); + if (searchOn) + SearchUntilCancelled(job, types, solver, demand, improved, groups, Improved, token); return BuildResult(job, types, improved, progress, token); } @@ -218,7 +250,8 @@ public sealed class IrregularNestingEngine : INestingEngine /// /// Decodes seed after seed, cycling the variants and grouped variants, and re-plans the tail of each plan that - /// beats the best so far; ends only when the token is cancelled. + /// beats the best so far, passing each to ; ends only when the token + /// is cancelled. /// private void SearchUntilCancelled( NestJob job, @@ -227,7 +260,7 @@ public sealed class IrregularNestingEngine : INestingEngine int[] demand, Plan best, bool groups, - IProgress? progress, + Action report, CancellationToken token ) { @@ -243,10 +276,10 @@ public sealed class IrregularNestingEngine : INestingEngine if (!plan.IsBetterThan(best)) continue; // Report before the tail re-plan, which the limit may cut short. - ReportPlan(job, types, plan, progress, token); + report(plan); best = solver.ImproveTail(plan, solver.Work.Value + WorkBudget * 2); if (!ReferenceEquals(best, plan)) - ReportPlan(job, types, best, progress, token); + report(best); } } @@ -311,6 +344,14 @@ public sealed class IrregularNestingEngine : INestingEngine return BuildResult(job, types, solver.Plan(demand, axis, beta, weights), null, default); } + /// The quick plan a time-limited solve reports first, whole demand placeable; for tests. + internal NestJobResult QuickPlanForTesting(NestJob job) + { + var types = PartCatalog.Build(job); + using var solver = new Solver(job, types, null, default, WorkBudget, DrawingFor, SheetPacked, BatchSelected, TailReplaced); + return BuildResult(job, types, solver.QuickPlan(types.Select(t => t.Part.Quantity).ToArray()), null, default); + } + /// Shared state for one solve: job, catalog, NFP caches, effort meter. private sealed class Solver( NestJob job, @@ -350,7 +391,32 @@ public sealed class IrregularNestingEngine : INestingEngine return found; } - public WorkCounter Work { get; } = new(); + public WorkCounter Work { get; private set; } = new(); + + /// Whether the decode under way is 's, which offers no blocks. + private bool quick; + + /// + /// The first variant decoded without Lattice blocks, on a work meter of its own, so the + /// search after it runs as without it: what it adds to the shared caches (no-fit polygons, + /// pairs, clamps, boundaries) depends only on the job, never on when it was built. + /// + public Plan QuickPlan(int[] demand) + { + var meter = Work; + Work = new WorkCounter(); + quick = true; + try + { + return Plan(demand, Variants[0].Axis, Variants[0].Beta); + } + finally + { + Work = meter; + quick = false; + Alternatives = Array.Empty(); + } + } private double Penalty => NestJobCost.UnplacedPartPenalty(job); @@ -688,7 +754,7 @@ public sealed class IrregularNestingEngine : INestingEngine // fill there and gave no denser groups. A banded fill's bands are Fill patterns // already; its gap fill takes singles and pairs. FrontierPacker Packer(IReadOnlyList? ranks, double? reach) => new(types, CacheFor(stock), - PairsFor(stock), stock, axis, beta, Work, grouped || banded ? null : BlocksFor(stock), ClampsFor(stock), BoundaryFor(stock), + PairsFor(stock), stock, axis, beta, Work, grouped || banded || quick ? null : BlocksFor(stock), ClampsFor(stock), BoundaryFor(stock), weights, ranks, reach); var fill = banded ? Banded(stock, remaining, weights, Packer) diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index f8db31e1..443524c4 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 (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 | +| 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 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 | | 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 | @@ -85,7 +85,8 @@ proposals with no committed counts, all come before the plate commits, and the l returned layout. Reporting never changes the search: layouts are identical with or without a progress sink. -- Irregular reports when a strategy variant, a grouped variant or a tail re-plan beats its best plan so far. +- Irregular reports when a strategy variant, a grouped variant or a tail re-plan beats its best plan so far; + under a time limit it reports a quick plan before them (see [time limits](#time-limits)). - Rectangles makes one sheet-by-sheet run, so it reports the finished job as its one plan. - Circles reports when a stock-preference run or a tail re-plan beats its best result so far. - Default scores each candidate plan as it ranks results (valid, fewest unplaced, lowest cost, @@ -126,6 +127,19 @@ candidates, and other engines ignore it; Irregular also ignores it when the toke cancelled, nobody listens for progress, or the job has a single part type. Default runs Irregular last for this reason. +Under those same conditions, where the solve can end only at the limit, Irregular first decodes +its first variant once without Lattice blocks and reports that quick plan, then runs its normal +search. Preparing blocks for each stock trial of the first sheet takes most of the first decode's +time on a big job: on a job of 260 parts of 7 types over 9 stock sizes, Default showed Irregular's +first plan after about 29 s; the quick plan comes after about 5 s and costs the normal search +about 2 to 3 s. The quick decode spends its own work meter and shares only caches that depend on +the job alone (no-fit polygons, pairs, clamps), so the normal search makes the same decisions as +without it. Until a plan of the normal search beats the quick plan, its plans are reported as +alternatives, so a worse plan never follows it. The quick plan is never a result of its own: at +the limit the best reported plan wins, which is the quick plan only when nothing reported later +beats it, and a solve that can finish on its own never makes one, so unlimited results are +unchanged. + Desktop, Console and MCP do not apply a limit yet; Console can solve a job twice (with and without cutouts), so a limit there needs one deadline shared across both solves.