From 63bcd89d35c3154c72b1fa15b434a40788830f1c Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sat, 31 Oct 2026 11:35:35 -0400 Subject: [PATCH] feat(engine): Irregular searches until a time limit Under a time limit, Irregular often finished in about a second and left the rest unused: on the converted Nestbolt b-jakobs1 job it used five sheets where four fit. NestJobOptions.SearchUntilCancelled asks an engine to keep searching after its normal search until the token is cancelled. DeadlineNestingEngine sets it. Irregular then re-runs its six variants with seeded per-type weights on its placement rule (seeds 1, 2, 3, ..., each weight within e^+-0.4), reports each plan that beats its best, then re-plans that plan's tail and reports any gain. It skips this when the token cannot be cancelled, nobody listens for progress, nothing is placeable, or the job has one part type, so unlimited solves are unchanged. Default now runs Irregular last (Rectangles, Circles, Irregular) so Circles still runs, and chooses only after every candidate has run, in tie-break order, so the run order never changes the choice. Unlimited choices match the old run order {Rectangles, Irregular, Circles} except when three candidates are near-tied within the 1e-9 comparison tolerance without being transitively ordered (only on all-round jobs, where Circles bids). b-jakobs1 on one CPU, 10 s limit: 5 sheets (4.500) -> 4 (3.751). --- .../DefaultNestingEngineTests.cs | 34 ++- .../IrregularSearchUntilCancelledTests.cs | 236 ++++++++++++++++++ OpenNest.Engine/Jobs/NestJobOptions.cs | 18 +- .../NestingEngines/DeadlineNestingEngine.cs | 6 +- .../Default/DefaultNestingEngine.cs | 24 +- .../Irregular/FrontierPacker.cs | 18 +- .../Irregular/IrregularNestingEngine.cs | 85 ++++++- docs/nesting-engines.md | 21 +- 8 files changed, 412 insertions(+), 30 deletions(-) create mode 100644 OpenNest.Engine.Tests/NestingEngines/IrregularSearchUntilCancelledTests.cs diff --git a/OpenNest.Engine.Tests/NestingEngines/DefaultNestingEngineTests.cs b/OpenNest.Engine.Tests/NestingEngines/DefaultNestingEngineTests.cs index 3a5a3d02..3d255c9b 100644 --- a/OpenNest.Engine.Tests/NestingEngines/DefaultNestingEngineTests.cs +++ b/OpenNest.Engine.Tests/NestingEngines/DefaultNestingEngineTests.cs @@ -1,4 +1,5 @@ using OpenNest.Engine.Jobs; +using OpenNest.Engine.NestingEngines; using OpenNest.Engine.NestingEngines.Default; using OpenNest.Engine.NestingEngines.Irregular; using OpenNest.Engine.NestingEngines.Rectangles; @@ -30,16 +31,18 @@ public class DefaultNestingEngineTests // Only a 10 x 5 strip left below the parts. private static NestJobResult OneSheetHigher(NestJob job) => Layout(job, Sheet((0, 5), (5, 5))); private static NestJobResult TwoSheets(NestJob job) => Layout(job, Sheet((0, 0)), Sheet((0, 0))); + private static NestJobResult Raised(NestJob job, double y) => Layout(job, Sheet((0, y), (5, y))); private static NestJobResult Overlapping(NestJob job) => Layout(job, Sheet((0, 0), (1, 0))); private static NestJobResult OnePlaced(NestJob job) => Layout(job, Sheet((0, 0))); [Fact] - public void BuiltInDefaultRunsRectanglesBeforeIrregular() + public void BuiltInDefaultRunsIrregularLast() { // Rectangles is the cheap, always-valid fallback: under a limit it must have reported - // its plan before the slower Irregular search starts. Candidates stay in tie-break + // its plan before the slower Irregular search starts, and Irregular, which may search + // until cancelled, must not keep Circles from running. Candidates stay in tie-break // order Irregular, Rectangles, Circles. - Assert.Equal(new[] { 1, 0, 2 }, new DefaultNestingEngine().RunOrder); + Assert.Equal(new[] { 1, 2, 0 }, new DefaultNestingEngine().RunOrder); } [Fact] @@ -89,6 +92,31 @@ public class DefaultNestingEngineTests Assert.Equal("first", error.Message); } + [Fact] + public void NearTiesAreChosenInTieBreakOrderWhateverTheRunOrder() + { + // Offcuts within the comparison tolerance tie, so these three are not transitively + // ordered: neighbours tie, but the lowest layout beats the highest outright. Choosing + // in run order would then depend on the order; choosing in tie-break order must not. + var job = SquaresJob(); + var heights = new[] { 8e-9, 4e-9, 0 }; + var scores = heights.Select(y => CandidateScore.Of(job, Raised(job, y), 0)).ToArray(); + Assert.False(scores[0].IsBetterThan(scores[1]) || scores[1].IsBetterThan(scores[0])); + Assert.False(scores[1].IsBetterThan(scores[2]) || scores[2].IsBetterThan(scores[1])); + Assert.True(scores[2].IsBetterThan(scores[0])); + + var candidates = heights.Select(y => Returns(j => Raised(j, y))).ToArray(); + var orders = new[] + { + new[] { 0, 1, 2 }, new[] { 0, 2, 1 }, new[] { 1, 0, 2 }, + new[] { 1, 2, 0 }, new[] { 2, 0, 1 }, new[] { 2, 1, 0 }, + }; + var picks = orders + .Select(order => new DefaultNestingEngine(candidates, order).Solve(job).Plates[0].Placements[0].Y) + .ToList(); + Assert.All(picks, y => Assert.Equal(picks[0], y)); + } + private sealed class Stub(Func?, CancellationToken, NestJobResult> solve) : INestingEngine { public NestJobResult Solve(NestJob job, IProgress? progress = null, CancellationToken token = default) => diff --git a/OpenNest.Engine.Tests/NestingEngines/IrregularSearchUntilCancelledTests.cs b/OpenNest.Engine.Tests/NestingEngines/IrregularSearchUntilCancelledTests.cs new file mode 100644 index 00000000..1e80f4b6 --- /dev/null +++ b/OpenNest.Engine.Tests/NestingEngines/IrregularSearchUntilCancelledTests.cs @@ -0,0 +1,236 @@ +using OpenNest.Engine.Jobs; +using OpenNest.Engine.NestingEngines; +using OpenNest.Engine.NestingEngines.Default; +using OpenNest.Engine.NestingEngines.Irregular; +using static OpenNest.Engine.Tests.NestingEngines.JobBuilder; +using static OpenNest.Engine.Tests.NestingEngines.Shapes; + +namespace OpenNest.Engine.Tests.NestingEngines; + +/// +/// : Irregular keeps decoding seeded variants +/// after its normal search, reporting each better plan, until the token is cancelled. +/// +public class IrregularSearchUntilCancelledTests +{ + private static NestJob MixedJob(bool searchUntilCancelled) => + Job( + new[] { Part("disc", Disc(3), 10), Part("ell", LShape(12, 8, 4), 10), Part("tri", Triangle(9, 7), 8) }, + new[] { Stock("sheet", 40, 60, spacing: 0.5) }, + new NestJobOptions(searchUntilCancelled: searchUntilCancelled) + ); + + private sealed class Recorder(Action? also = null) : IProgress + { + public List Plans { get; } = new(); + + public void Report(NestJobProgress value) + { + if (value.Stage == NestJobStage.PlanImproved) + Plans.Add(value.Plan!); + also?.Invoke(value); + } + } + + 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(); + + [Fact] + public void WithoutACancellableTokenTheSearchEndsAsUsual() + { + var plain = new IrregularNestingEngine().Solve(MixedJob(false)); + // A listener alone does not start the extended search: it ends only by cancellation. + var flagged = new IrregularNestingEngine().Solve(MixedJob(true), new Recorder()); + + Assert.Equal(Placements(plain), Placements(flagged)); + } + + [Fact] + public void KeepsSearchingAfterTheNormalSearchUntilCancelled() + { + var plain = new Recorder(); + var plainResult = new IrregularNestingEngine().Solve(MixedJob(false), plain); + var normalSheets = 0; + new IrregularNestingEngine { SheetPacked = () => normalSheets++ }.Solve(MixedJob(false)); + + var extendedSheets = 0; + var extendedTailBudgets = new List(); + using var cancel = new CancellationTokenSource(); + var engine = new IrregularNestingEngine + { + // The normal search packs exactly normalSheets sheets; later ones are extended. + TailReplanning = budget => + { + if (extendedSheets > normalSheets) + extendedTailBudgets.Add(budget); + }, + SheetPacked = () => + { + // Let the extended search pack several more whole plans, then stop it. + if (++extendedSheets >= normalSheets * 12) + cancel.Cancel(); + }, + }; + var extended = new Recorder(); + + Assert.ThrowsAny(() => engine.Solve(MixedJob(true), 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); + // 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); + var last = CandidateScore.Of(job, extended.Plans[^1], 0); + Assert.False(CandidateScore.Of(job, plainResult, 0).IsBetterThan(last)); + foreach (var plan in extended.Plans) + LayoutAssert.Valid(job, plan); + // Each reported plan beats the one before it: no seed reports a worse plan. + for (var i = 1; i < extended.Plans.Count; i++) + Assert.True( + CandidateScore.Of(job, extended.Plans[i], 0) + .IsBetterThan(CandidateScore.Of(job, extended.Plans[i - 1], 0)), + $"plan {i} does not improve on plan {i - 1}"); + } + + [Fact] + public void SeedWeightsChangeTheLayout() + { + // The weights must reach the placement rule: some seed decodes differently. + var job = MixedJob(false); + var engine = new IrregularNestingEngine(); + var unweighted = Placements(engine.PlanForTesting(job, 0, null)); + Assert.Equal(unweighted, Placements(engine.PlanForTesting(job, 0, new[] { 1.0, 1.0, 1.0 }))); + Assert.Contains( + Enumerable.Range(1, 8), + seed => !Placements(engine.PlanForTesting(job, 0, IrregularNestingEngine.SeedWeights(seed, 3))) + .SequenceEqual(unweighted)); + } + + [Fact] + public void AJobWithNothingToPlaceDoesNotWaitForTheLimit() + { + // Oversize parts only: every decode places nothing, so more searching cannot help. + var job = Job( + new[] { Part("big", Rectangle(80, 80), 2), Part("bigger", Rectangle(90, 90), 2) }, + new[] { Stock("sheet", 40, 60) } + ); + var watch = System.Diagnostics.Stopwatch.StartNew(); + + var result = new DeadlineNestingEngine(new IrregularNestingEngine(), TimeSpan.FromSeconds(30)).Solve(job); + + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(10), $"took {watch.Elapsed}"); + Assert.Empty(result.Plates.SelectMany(p => p.Placements)); + } + + [Fact] + public void SeedWeightsAreFixedPerSeedAndBounded() + { + var first = IrregularNestingEngine.SeedWeights(7, 5); + Assert.Equal(first, IrregularNestingEngine.SeedWeights(7, 5)); + Assert.NotEqual(first, IrregularNestingEngine.SeedWeights(8, 5)); + Assert.All(first, w => Assert.InRange( + w, + System.Math.Exp(-IrregularNestingEngine.WeightSpread), + System.Math.Exp(IrregularNestingEngine.WeightSpread))); + } + + [Fact] + public void ATimeLimitAsksTheEngineToSearchUntilCancelled() + { + NestJob? seen = null; + var options = new NestJobOptions("Fill", maxPlates: 3, salvageRate: 0.25, minimumSalvageDimension: 1.5); + var plain = MixedJob(false); + var job = new NestJob(plain.Parts, plain.Plates, options); + var engine = new DeadlineNestingEngine( + new StubEngine((j, _, _) => + { + seen = j; + return new IrregularNestingEngine().Solve(job); + }), + TimeSpan.FromMinutes(1) + ); + + engine.Solve(job); + + Assert.NotNull(seen); + Assert.True(seen!.Options.SearchUntilCancelled); + // Everything else about the job is passed on unchanged, and the caller's job is untouched. + Assert.Equal(options.PlacementStrategy, seen.Options.PlacementStrategy); + Assert.Equal(3, seen.Options.MaxPlates); + Assert.Equal(0.25, seen.Options.SalvageRate); + Assert.Equal(1.5, seen.Options.MinimumSalvageDimension); + Assert.Equal(job.Parts, seen.Parts); + Assert.Equal(job.Plates, seen.Plates); + Assert.False(job.Options.SearchUntilCancelled); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AWeightAboveOneLowersThePlacementValue(bool fills) + { + // Lower value wins, in gap fills and in advance alike; weight one changes nothing. + double Value(double weight) => FrontierPacker.PlacementValue(fills, 2.5, 7.0, 1.0, weight); + Assert.Equal(fills ? -7.0 : 2.5 / 7.0, Value(1.0)); + Assert.True(Value(1.5) < Value(1.0)); + Assert.True(Value(1.0) < Value(1 / 1.5)); + } + + [Fact] + public void AHeavyWeightPlacesItsTypeFirst() + { + // A weight above one favors its type; swapping the weights swaps the first type placed + // and moves the favored type's parts earlier in placement order. + var job = MixedJob(false); + var engine = new IrregularNestingEngine(); + double MeanOrder(NestJobResult r, string id) + { + var order = r.Plates.SelectMany(p => p.Placements).Select((q, i) => (q.PartId, i)) + .Where(x => x.PartId == id).Select(x => (double)x.i).ToList(); + return order.Average(); + } + foreach (var (favored, weights) in new[] + { + ("disc", new[] { 50.0, 1, 1 }), ("ell", new[] { 1, 50.0, 1 }), ("tri", new[] { 1, 1, 50.0 }), + }) + { + var result = engine.PlanForTesting(job, 0, weights); + var light = engine.PlanForTesting(job, 0, weights.Select(w => 1 / w).ToArray()); + Assert.Equal(favored, result.Plates[0].Placements[0].PartId); + Assert.True(MeanOrder(result, favored) < MeanOrder(light, favored), favored); + } + } + + [Fact] + public void DefaultUnderATimeLimitReturnsAValidPlanNoWorseThanUnlimited() + { + // Irregular runs last under Default and searches until the limit; its plans compete + // with the Rectangles and Circles results already reported. The limit leaves a wide + // margin over the unlimited solve (well under a second here) so a slow machine passes. + var job = MixedJob(false); + var normal = new DefaultNestingEngine().Solve(job); + + var limited = new DeadlineNestingEngine(new DefaultNestingEngine(), TimeSpan.FromSeconds(5)) + .Solve(job); + + LayoutAssert.Valid(job, limited); + Assert.False(CandidateScore.Of(job, normal, 0).IsBetterThan(CandidateScore.Of(job, limited, 0))); + } + + private sealed class StubEngine( + Func?, CancellationToken, NestJobResult> solve + ) : INestingEngine + { + public NestJobResult Solve( + NestJob job, + IProgress? progress = null, + CancellationToken token = default + ) => solve(job, progress, token); + } +} diff --git a/OpenNest.Engine/Jobs/NestJobOptions.cs b/OpenNest.Engine/Jobs/NestJobOptions.cs index 82f4b78a..ee9cdfea 100644 --- a/OpenNest.Engine/Jobs/NestJobOptions.cs +++ b/OpenNest.Engine/Jobs/NestJobOptions.cs @@ -9,7 +9,8 @@ public sealed class NestJobOptions string placementStrategy = "Fill", int? maxPlates = null, double salvageRate = 0, - double minimumSalvageDimension = 0 + double minimumSalvageDimension = 0, + bool searchUntilCancelled = false ) { ArgumentException.ThrowIfNullOrWhiteSpace(placementStrategy); @@ -23,8 +24,23 @@ public sealed class NestJobOptions MaxPlates = maxPlates; SalvageRate = salvageRate; MinimumSalvageDimension = minimumSalvageDimension; + SearchUntilCancelled = searchUntilCancelled; } + /// + /// Asks engines that support it to keep searching after their normal search, reporting + /// each better plan () until the solve's token is + /// cancelled, which then ends the solve with . + /// Meant for a caller that keeps the best reported plan at a time limit, such as + /// . Ignored when the token cannot be + /// cancelled. Results then depend on how long the search ran. + /// + public bool SearchUntilCancelled { get; } + + /// A copy of these options with set. + public NestJobOptions WithSearchUntilCancelled(bool value) => + new(PlacementStrategy, MaxPlates, SalvageRate, MinimumSalvageDimension, value); + /// Fraction of eligible edge-offcut area credited by (0..1). public double SalvageRate { get; } diff --git a/OpenNest.Engine/NestingEngines/DeadlineNestingEngine.cs b/OpenNest.Engine/NestingEngines/DeadlineNestingEngine.cs index 92b53180..37df7c91 100644 --- a/OpenNest.Engine/NestingEngines/DeadlineNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/DeadlineNestingEngine.cs @@ -13,7 +13,9 @@ namespace OpenNest.Engine.NestingEngines; /// results, and a tie goes to the later plan, as engines report only plans they rank higher. /// With no valid plan by the limit, the solve fails with a . /// Cancellation by the caller's own token is never turned into a result. A result the engine -/// returns, even after the limit, is its own and is returned unchanged. +/// returns, even after the limit, is its own and is returned unchanged. The engine sees the +/// job with set, so an engine that supports +/// it keeps improving its plan until the limit. /// /// /// The engine's plate commits are not forwarded: the returned result's commits are reported @@ -54,6 +56,8 @@ public sealed class DeadlineNestingEngine : INestingEngine { ArgumentNullException.ThrowIfNull(job); token.ThrowIfCancellationRequested(); + // Engines that can keep searching until cancelled may use all the time. + job = new NestJob(job.Parts, job.Plates, job.Options.WithSearchUntilCancelled(true)); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); using var finished = new ManualResetEventSlim(); var clock = StartClock(deadline, finished); diff --git a/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs b/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs index a539821c..eda5c916 100644 --- a/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs @@ -31,10 +31,11 @@ namespace OpenNest.Engine.NestingEngines.Default; /// worse plan after a better one. A candidate result that beats them is reported too, and the /// chosen result is always the last plan reported. /// -/// Rectangles, the quick and always-valid fallback, runs first, then Irregular, then Circles, so +/// Rectangles, the quick and always-valid fallback, runs first, then Circles, then Irregular, so /// a caller that stops the search early, such as , already -/// holds a valid plan. Ties still break by candidate (tie-break) order, so for these three -/// candidates the run order does not change the choice. +/// holds a valid plan, and Irregular can search until cancelled +/// () last. The choice is made after all have +/// run, in candidate (tie-break) order, so the run order never changes it. /// /// Deterministic: candidates run one after another and the choice uses no clock. /// @@ -51,7 +52,7 @@ public sealed class DefaultNestingEngine : INestingEngine () => new RectanglesNestingEngine(), () => new CirclesNestingEngine(), }, - new[] { 1, 0, 2 }) + new[] { 1, 2, 0 }) { } @@ -62,8 +63,8 @@ public sealed class DefaultNestingEngine : INestingEngine } /// Test seam: candidate engines in tie-break order, and the order to run them in - /// (a permutation of their indexes). Cost comparison has a relative tolerance, so with three - /// or more near-tied candidates the run order can matter. + /// (a permutation of their indexes); the run order affects progress, never the choice. + /// internal DefaultNestingEngine( IReadOnlyList> candidates, IReadOnlyList runOrder @@ -101,7 +102,7 @@ public sealed class DefaultNestingEngine : INestingEngine ArgumentNullException.ThrowIfNull(job); token.ThrowIfCancellationRequested(); var forward = progress == null ? null : new PlanFilter(job, progress, token); - CandidateScore? best = null; + var scores = new CandidateScore?[candidates.Count]; ExceptionDispatchInfo? firstFailure = null; var firstFailureOrder = int.MaxValue; @@ -129,11 +130,16 @@ public sealed class DefaultNestingEngine : INestingEngine continue; var scored = CandidateScore.Of(job, result, order); - if (best == null || scored.IsBetterThan(best)) - best = scored; + scores[order] = scored; forward?.Offer(scored); } + // Choose in tie-break order, whatever order the candidates ran in. + CandidateScore? best = null; + foreach (var scored in scores) + if (scored != null && (best == null || scored.IsBetterThan(best))) + best = scored; + token.ThrowIfCancellationRequested(); if (best == null) { diff --git a/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs b/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs index a8ce75ba..bf1f71c4 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/FrontierPacker.cs @@ -63,6 +63,17 @@ internal sealed class FrontierPacker private readonly NestPlateStock stock; private readonly PackAxis axis; private readonly double beta; + private readonly IReadOnlyList? typeWeights; + + /// + /// The placement rule's value of a candidate; lower wins. Gap fill prefers bigger parts + /// (negated area); advance prefers least advance per area. A type weight above one favors + /// the type: a more negative gap-fill value, a smaller advance score. Weight one is exact. + /// + internal static double PlacementValue(bool fills, double advance, double area, double beta, double weight) => + fills + ? -area * weight + : advance / System.Math.Pow(System.Math.Max(area, 1e-12), beta) / weight; private readonly Box work; private readonly WorkCounter counter; private readonly BlockCatalog? blocks; @@ -81,7 +92,8 @@ internal sealed class FrontierPacker WorkCounter counter, BlockCatalog? blocks = null, ClampObstacles? clamps = null, - PackBoundary? boundary = null + PackBoundary? boundary = null, + IReadOnlyList? typeWeights = null ) { if (boundary != null && !ReferenceEquals(boundary.Nfps, nfps)) @@ -95,6 +107,7 @@ internal sealed class FrontierPacker this.stock = stock; this.axis = axis; this.beta = beta; + this.typeWeights = typeWeights; this.boundary = boundary; work = boundary?.Bounds ?? stock.WorkArea; } @@ -260,8 +273,7 @@ internal sealed class FrontierPacker if (priority > bestPriority) return; var fills = advance <= Tie; - // Gap fill prefers bigger parts (negated area); advance prefers least advance per area. - var value = fills ? -area : advance / System.Math.Pow(System.Math.Max(area, 1e-12), beta); + var value = PlacementValue(fills, advance, area, beta, typeWeights?[typeIndex] ?? 1.0); var better = bestParts == null || priority < bestPriority diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs index 29d5d952..d26038e9 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs @@ -20,7 +20,13 @@ namespace OpenNest.Engine.NestingEngines.Irregular; /// remaining demand at the best efficiency seen) is committed. A handful of deterministic /// strategy variants (front direction, area exponent) run whole-job, and the cheapest wins. /// -/// Fully deterministic: no clocks or randomness influence any decision. +/// 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). +/// +/// 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. /// public sealed class IrregularNestingEngine : INestingEngine { @@ -57,6 +63,8 @@ public sealed class IrregularNestingEngine : INestingEngine internal Action? SheetPacked { get; init; } internal Action? BatchSelected { get; init; } internal Action? TailReplaced { get; init; } + /// A tail re-plan starts, with the work it may still spend. + internal Action? TailReplanning { get; init; } public NestJobResult Solve( NestJob job, @@ -67,7 +75,8 @@ public sealed class IrregularNestingEngine : INestingEngine ArgumentNullException.ThrowIfNull(job); token.ThrowIfCancellationRequested(); var types = PartCatalog.Build(job); - using var solver = new Solver(job, types, progress, token, WorkBudget, DrawingFor, SheetPacked, BatchSelected, TailReplaced); + using var solver = new Solver(job, types, progress, token, WorkBudget, DrawingFor, SheetPacked, BatchSelected, TailReplaced, + TailReplanning); // Pair-only orientations may fit stock even when the sampled single poses do not. // Demand that neither a single nor a pair can fit is reported unplaced. @@ -102,9 +111,56 @@ public sealed class IrregularNestingEngine : INestingEngine var improved = solver.ImproveTail(best!, WorkBudget * 2); if (!ReferenceEquals(improved, best)) ReportPlan(job, types, improved, progress, token); + // 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, progress, token); return BuildResult(job, types, improved, progress, token); } + /// Spread of the seeded type weights: each is e^(±WeightSpread) at most. + internal const double WeightSpread = 0.4; + + /// The placement-rule weights for one seed, one per part type. + internal static double[] SeedWeights(int seed, int typeCount) + { + var random = new Random(seed); + var weights = new double[typeCount]; + for (var i = 0; i < weights.Length; i++) + weights[i] = System.Math.Exp(WeightSpread * (2 * random.NextDouble() - 1)); + return weights; + } + + /// + /// Decodes seed after seed, cycling the variants, and re-plans the tail of each plan that + /// beats the best so far; ends only when the token is cancelled. + /// + private void SearchUntilCancelled( + NestJob job, + IReadOnlyList types, + Solver solver, + int[] demand, + Plan best, + IProgress? progress, + CancellationToken token + ) + { + for (var seed = 1; ; seed = seed == int.MaxValue ? 1 : seed + 1) + { + token.ThrowIfCancellationRequested(); + var (axis, beta) = Variants[seed % Variants.Length]; + var plan = solver.Plan(demand, axis, beta, SeedWeights(seed, types.Count)); + if (!plan.IsBetterThan(best)) + continue; + // Report before the tail re-plan, which the limit may cut short. + ReportPlan(job, types, plan, progress, token); + best = solver.ImproveTail(plan, solver.Work.Value + WorkBudget * 2); + if (!ReferenceEquals(best, plan)) + ReportPlan(job, types, best, progress, token); + } + } + /// Reports a new best whole-job plan; reporting never changes the search. private static void ReportPlan(NestJob job, IReadOnlyList types, Plan plan, IProgress? progress, CancellationToken token) @@ -127,6 +183,17 @@ public sealed class IrregularNestingEngine : INestingEngine return BuildResult(job, types, solver.ImproveTail(plan, WorkBudget * 2), null, default); } + /// Decodes one variant with the given type weights, whole demand placeable; for + /// tests of the weighted placement rule only. + internal NestJobResult PlanForTesting(NestJob job, int variant, IReadOnlyList? weights) + { + var types = PartCatalog.Build(job); + using var solver = new Solver(job, types, null, default, WorkBudget, DrawingFor, SheetPacked, BatchSelected, TailReplaced); + var demand = types.Select(t => t.Part.Quantity).ToArray(); + var (axis, beta) = Variants[variant]; + return BuildResult(job, types, solver.Plan(demand, axis, beta, weights), null, default); + } + /// Shared state for one solve: job, catalog, NFP caches, effort meter. private sealed class Solver( NestJob job, @@ -137,7 +204,8 @@ public sealed class IrregularNestingEngine : INestingEngine Func drawingFor, Action? sheetPacked, Action? batchSelected, - Action? tailReplaced + Action? tailReplaced, + Action? tailReplanning = null ) : IDisposable { public void Dispose() @@ -166,9 +234,10 @@ public sealed class IrregularNestingEngine : INestingEngine private double Penalty => NestJobCost.UnplacedPartPenalty(job); - public Plan Plan(int[] demand, PackAxis axis, double beta) + public Plan Plan(int[] demand, PackAxis axis, double beta, IReadOnlyList? weights = null) { - var run = Decode(demand, axis, beta, new Dictionary(StringComparer.Ordinal), job.Options.MaxPlates, null); + var run = Decode(demand, axis, beta, new Dictionary(StringComparer.Ordinal), job.Options.MaxPlates, null, + weights); 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) @@ -184,6 +253,7 @@ public sealed class IrregularNestingEngine : INestingEngine /// public Plan ImproveTail(Plan plan, long budget) { + tailReplanning?.Invoke(budget - Work.Value); var sheets = plan.Sheets.ToList(); for (var k = 1; k <= System.Math.Min(MaxTail, sheets.Count); k++) { @@ -287,7 +357,8 @@ public sealed class IrregularNestingEngine : INestingEngine double beta, IReadOnlyDictionary usedBefore, int? sheetCap, - NestPlateStock? first + NestPlateStock? first, + IReadOnlyList? weights = null ) { var remaining = (int[])demand.Clone(); @@ -320,7 +391,7 @@ public sealed class IrregularNestingEngine : INestingEngine continue; progress?.Report(new NestJobProgress(NestJobStage.EvaluatingCandidate, stock.Id, sheets.Count, 0, 0)); var packer = new FrontierPacker(types, CacheFor(stock), PairsFor(stock), stock, axis, beta, Work, - BlocksFor(stock), ClampsFor(stock), BoundaryFor(stock)); + BlocksFor(stock), ClampsFor(stock), BoundaryFor(stock), weights); var fill = packer.Fill(remaining, token); sheetPacked?.Invoke(); if (fill.Parts.Count > 0) diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index 409baab4..5668b625 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -11,19 +11,19 @@ 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 (whichever runs first) | +| 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; 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 | +| 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; 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 | | Fill, Strip, Vertical Remnant, Horizontal Remnant | Single-strategy fills | The fixed placement strategies behind interactive fill; Fill is the multi-phase lattice fill (linear, pairs, rectangle best-fit, remainder). In whole jobs, all four place a plate with any fixed or bounded part rotation by the rotation-aware ordered placer instead | Neither Irregular nor Rectangles wins every job, even within its own lane, so Default runs both rather than choosing by part shape; Rectangles adds little time and is also the fallback when an -Irregular layout fails the check. Default runs Rectangles first, then Irregular, then Circles, so -a search stopped early already holds a valid plan; ties still go to the earlier engine in the -table order (Irregular, Rectangles, Circles), so the run order does not change the choice. A -candidate that throws is skipped. Default routes the whole job: +Irregular layout fails the check. Default runs Rectangles first, then Circles, then Irregular, so +a search stopped early already holds a valid plan and Irregular can keep searching last; it +chooses only after all have run, in table order (Irregular, Rectangles, Circles), so the run +order never changes the choice. A candidate that throws is skipped. Default routes the whole job: engines cannot share a sheet, so a job mixing plain and irregular parts goes to both engines whole. Circles is a third candidate that bids only on round jobs (see below), so a job mixing round and other parts goes to Irregular and Rectangles. @@ -63,6 +63,15 @@ clock, so it is not reproducible, and it can overrun the limit by however long t notice cancellation. A limit can be any positive time up to about 49.7 days. A best-fit pair search running when the limit hits cannot be interrupted: Irregular stops waiting for it, and it finishes in the background and fills the shared pool, so a later job of the same parts skips it; until then it still uses CPU. +The limited engine sees the job with `NestJobOptions.SearchUntilCancelled` set. Irregular then +keeps going after its normal search: it re-runs its six variants with seeded per-type weights on +its placement rule (seeds 1, 2, 3, ...; each weight within e^±0.4), re-plans the tail of any plan +that beats its best, and reports it, until the limit cancels it. On the converted Nestbolt +b-jakobs1 job this took 5 sheets down to 4 within 10 s. Default passes the option to its +candidates, and other engines ignore it; Irregular also ignores it when the token cannot be +cancelled, nobody listens for progress, or the job has a single part type. Default runs Irregular last for this +reason. + 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.