diff --git a/OpenNest.Engine.Tests/NestingEngines/DeadlineNestingEngineTests.cs b/OpenNest.Engine.Tests/NestingEngines/DeadlineNestingEngineTests.cs new file mode 100644 index 00000000..fc93aa99 --- /dev/null +++ b/OpenNest.Engine.Tests/NestingEngines/DeadlineNestingEngineTests.cs @@ -0,0 +1,274 @@ +using OpenNest.Engine.Jobs; +using OpenNest.Engine.NestingEngines; +using OpenNest.Engine.NestingEngines.Default; +using static OpenNest.Engine.Tests.NestingEngines.JobBuilder; +using static OpenNest.Engine.Tests.NestingEngines.Shapes; + +namespace OpenNest.Engine.Tests.NestingEngines; + +public class DeadlineNestingEngineTests +{ + // Two 4x4 squares on 10x10 sheets with no spacing. + private static NestJob SquaresJob() => + Job([Part("p", Rectangle(4, 4), 2, RotationPolicy.Fixed(0))], [Stock("s", 10, 10)]); + + private static NestJobResult Layout(NestJob job, params (double X, double Y)[][] sheets) + { + var builder = new NestJobResultBuilder(job); + foreach (var sheet in sheets) + builder.AddSheet(job.Plates[0], sheet.Select(p => ("p", p.X, p.Y, 0.0))); + return builder.Build( + builder.IsComplete ? NestJobStopReason.Completed : NestJobStopReason.NoPlacementFound + ); + } + + private static NestJobResult OneSheet(NestJob job) => Layout(job, [(0, 0), (5, 0)]); + + private static NestJobResult TwoSheets(NestJob job) => Layout(job, [(0, 0)], [(0, 0)]); + + private static NestJobResult Overlapping(NestJob job) => Layout(job, [(0, 0), (1, 0)]); + + private sealed class Stub( + Func?, CancellationToken, NestJobResult> solve + ) : INestingEngine + { + public NestJobResult Solve( + NestJob job, + IProgress? progress = null, + CancellationToken token = default + ) => solve(job, progress, token); + } + + private sealed class Recorder : IProgress + { + public List Reports { get; } = new(); + + public void Report(NestJobProgress value) => Reports.Add(value); + } + + private static void Plan(IProgress? progress, NestJobResult plan) => + progress?.Report(new NestJobProgress(NestJobStage.PlanImproved, "", -1, 0, 0, Plan: plan)); + + /// Reports the given plans, then waits for cancellation like a long search. + private static Stub ReportsThenRunsUntilCancelled(params Func[] plans) => + new((job, progress, token) => + { + foreach (var plan in plans) + Plan(progress, plan(job)); + token.WaitHandle.WaitOne(TimeSpan.FromSeconds(30)); + token.ThrowIfCancellationRequested(); + throw new InvalidOperationException("the limit never cancelled the search"); + }); + + private static readonly TimeSpan Short = TimeSpan.FromMilliseconds(200); + + [Fact] + public void AnEngineThatFinishesInTimeKeepsItsResult() + { + var job = SquaresJob(); + var result = TwoSheets(job); + var progress = new Recorder(); + + var solved = new DeadlineNestingEngine( + new Stub((_, p, _) => + { + Plan(p, OneSheet(job)); + return result; + }), + TimeSpan.FromMinutes(1) + ).Solve(job, progress); + + Assert.Same(result, solved); + var commits = progress.Reports.Where(r => r.Stage == NestJobStage.PlateCommitted).ToList(); + Assert.Equal(2, commits.Count); + Assert.Equal(2, commits[^1].CommittedParts); + } + + [Fact] + public void AtTheLimitTheBestValidPlanIsReturnedAndCommitted() + { + var job = SquaresJob(); + NestJobResult? cheap = null; + var progress = new Recorder(); + + var solved = new DeadlineNestingEngine( + ReportsThenRunsUntilCancelled(TwoSheets, j => cheap = OneSheet(j), TwoSheets), + Short + ).Solve(job, progress); + + Assert.Same(cheap, solved); + var commits = progress.Reports.Where(r => r.Stage == NestJobStage.PlateCommitted).ToList(); + Assert.Single(commits); + Assert.Equal(2, commits[0].CommittedParts); + // The later, worse plan is not shown after the better one. + var shown = progress.Reports.Where(r => r.Stage == NestJobStage.PlanImproved).ToList(); + Assert.Equal(2, shown.Count); + Assert.Same(cheap, shown[^1].Plan); + } + + [Fact] + public void AnInvalidPlanIsNeverReturned() + { + var job = SquaresJob(); + Assert.NotEmpty(NestLayoutCheck.Violations(job, Overlapping(job))); + + var error = Assert.Throws(() => + new DeadlineNestingEngine(ReportsThenRunsUntilCancelled(Overlapping), Short).Solve(job) + ); + + Assert.Contains("No valid layout", error.Message); + } + + [Fact] + public void AValidPlanBeatsAnEarlierInvalidOne() + { + var job = SquaresJob(); + NestJobResult? valid = null; + + var solved = new DeadlineNestingEngine( + ReportsThenRunsUntilCancelled(Overlapping, j => valid = TwoSheets(j)), + Short + ).Solve(job); + + Assert.Same(valid, solved); + } + + [Fact] + public void WithNoPlanTheLimitIsATimeout() + { + var job = SquaresJob(); + + Assert.Throws(() => + new DeadlineNestingEngine(ReportsThenRunsUntilCancelled(), Short).Solve(job) + ); + } + + [Fact] + public void TheCallersCancellationIsNeverTurnedIntoAResult() + { + var job = SquaresJob(); + using var caller = new CancellationTokenSource(Short); + + Assert.ThrowsAny(() => + new DeadlineNestingEngine(ReportsThenRunsUntilCancelled(OneSheet), TimeSpan.FromMinutes(1)) + .Solve(job, null, caller.Token) + ); + } + + [Fact] + public void TheCallersCancellationIsNeverReportedAsATimeout() + { + var job = SquaresJob(); + using var caller = new CancellationTokenSource(Short); + + Assert.ThrowsAny(() => + new DeadlineNestingEngine(ReportsThenRunsUntilCancelled(), TimeSpan.FromMinutes(1)) + .Solve(job, null, caller.Token) + ); + } + + [Fact] + public void TheEnginesOwnCommitsAreNotForwarded() + { + var job = SquaresJob(); + var result = OneSheet(job); + var progress = new Recorder(); + + new DeadlineNestingEngine( + new Stub((_, p, _) => + { + p?.Report(new NestJobProgress(NestJobStage.PlateCommitted, "s", 0, 1, 2)); + return result; + }), + TimeSpan.FromMinutes(1) + ).Solve(job, progress); + + Assert.Single(progress.Reports, r => r.Stage == NestJobStage.PlateCommitted); + } + + [Fact] + public void ALimitMustFitACancellationTimer() + { + var engine = new Stub((_, _, _) => null!); + foreach (var bad in new[] { TimeSpan.Zero, TimeSpan.FromSeconds(-1), TimeSpan.FromDays(50) }) + Assert.Throws(() => new DeadlineNestingEngine(engine, bad)); + Assert.Equal( + DeadlineNestingEngine.MaxLimit, + new DeadlineNestingEngine(engine, DeadlineNestingEngine.MaxLimit).Limit + ); + Assert.Throws(() => new DeadlineNestingEngine(null!, Short)); + } + + [Fact] + public void ATiedLaterPlanReplacesTheEarlierOne() + { + // Engines report only plans they rank higher, so a tie follows the engine's judgment. + var job = SquaresJob(); + NestJobResult? later = null; + var progress = new Recorder(); + + var solved = new DeadlineNestingEngine( + ReportsThenRunsUntilCancelled(OneSheet, j => later = Layout(j, [(6, 0), (6, 4)])), + Short + ).Solve(job, progress); + + Assert.Same(later, solved); + Assert.Same(later, progress.Reports.Last(r => r.Stage == NestJobStage.PlanImproved).Plan); + } + + [Fact] + public void AResultReturnedAfterTheLimitIsTheEnginesOwn() + { + var job = SquaresJob(); + var result = TwoSheets(job); + + var solved = new DeadlineNestingEngine( + new Stub((j, p, token) => + { + Plan(p, OneSheet(j)); + token.WaitHandle.WaitOne(TimeSpan.FromSeconds(30)); + return result; + }), + Short + ).Solve(job); + + Assert.Same(result, solved); + } + + [Fact] + public void OtherProgressIsForwarded() + { + var job = SquaresJob(); + var progress = new Recorder(); + var stage = new NestJobProgress(NestJobStage.EvaluatingCandidate, "s", 0, 0, 2); + + new DeadlineNestingEngine( + new Stub((j, p, _) => + { + p?.Report(stage); + return OneSheet(j); + }), + TimeSpan.FromMinutes(1) + ).Solve(job, progress); + + Assert.Same(stage, progress.Reports[0]); + } + + [Fact] + public void DefaultUnderALimitReturnsTheFasterCandidatesResult() + { + // The slow candidate is first in tie-break order but runs second, so the limit finds + // the quick candidate's layout already reported. + var job = SquaresJob(); + NestJobResult? quick = null; + var slow = ReportsThenRunsUntilCancelled(); + var fast = new Stub((j, _, _) => quick = TwoSheets(j)); + + var solved = new DeadlineNestingEngine( + new DefaultNestingEngine(new Func[] { () => slow, () => fast }, new[] { 1, 0 }), + Short + ).Solve(job); + + Assert.Same(quick, solved); + } +} diff --git a/OpenNest.Engine.Tests/NestingEngines/DefaultNestingEngineTests.cs b/OpenNest.Engine.Tests/NestingEngines/DefaultNestingEngineTests.cs index 61001bbe..3a5a3d02 100644 --- a/OpenNest.Engine.Tests/NestingEngines/DefaultNestingEngineTests.cs +++ b/OpenNest.Engine.Tests/NestingEngines/DefaultNestingEngineTests.cs @@ -33,6 +33,62 @@ public class DefaultNestingEngineTests 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() + { + // 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 + // order Irregular, Rectangles, Circles. + Assert.Equal(new[] { 1, 0, 2 }, new DefaultNestingEngine().RunOrder); + } + + [Fact] + public void DefaultsRunOrderNeverChangesTheChoice() + { + // Equal layouts keep tie-break (candidate) order whichever candidate runs first. + var job = SquaresJob(); + var first = OneSheet(job); + var second = OneSheet(job); + Func[] candidates = + [ + () => new Stub((_, _, _) => first), + () => new Stub((_, _, _) => second), + ]; + + Assert.Same(first, new DefaultNestingEngine(candidates, new[] { 0, 1 }).Solve(job)); + Assert.Same(first, new DefaultNestingEngine(candidates, new[] { 1, 0 }).Solve(job)); + } + + [Fact] + public void DefaultRejectsARunOrderThatIsNotAPermutation() + { + Func[] candidates = + [ + () => new Stub((_, _, _) => null!), + () => new Stub((_, _, _) => null!), + ]; + + Assert.Throws(() => new DefaultNestingEngine(candidates, new[] { 0, 0 })); + Assert.Throws(() => new DefaultNestingEngine(candidates, new[] { 0 })); + Assert.Throws(() => new DefaultNestingEngine(candidates, new[] { 0, 2 })); + } + + [Fact] + public void WhenEveryCandidateThrowsTheFirstInTieBreakOrderIsRethrown() + { + Func[] candidates = + [ + () => new Stub((_, _, _) => throw new InvalidOperationException("first")), + () => new Stub((_, _, _) => throw new InvalidOperationException("second")), + ]; + + var error = Assert.Throws(() => + new DefaultNestingEngine(candidates, new[] { 1, 0 }).Solve(SquaresJob()) + ); + + Assert.Equal("first", error.Message); + } + 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/NestingEngines/DeadlineNestingEngine.cs b/OpenNest.Engine/NestingEngines/DeadlineNestingEngine.cs new file mode 100644 index 00000000..e41a472d --- /dev/null +++ b/OpenNest.Engine/NestingEngines/DeadlineNestingEngine.cs @@ -0,0 +1,114 @@ +#nullable enable +using System; +using System.Threading; +using OpenNest.Engine.Jobs; + +namespace OpenNest.Engine.NestingEngines; + +/// +/// Runs another engine under a wall-clock limit. When the engine finishes in time its result +/// is returned unchanged. When the limit cancels it, the best whole-job plan it reported +/// () is returned instead, provided that plan passes +/// ; plans are ranked like ranks +/// 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. +/// +/// +/// The engine's plate commits are not forwarded: the returned result's commits are reported +/// once it is known. Plans are forwarded only when they beat every plan shown so far. A +/// limited solve depends on the clock, so it is not reproducible like an unlimited one, and +/// the engine may overrun the limit by however long it takes to observe cancellation. Plans +/// are expected from the solve thread, as the built-in engines report them. +/// +public sealed class DeadlineNestingEngine : INestingEngine +{ + /// The longest limit a cancellation timer accepts. + public static readonly TimeSpan MaxLimit = TimeSpan.FromMilliseconds(uint.MaxValue - 1.0); + + private readonly INestingEngine inner; + + public DeadlineNestingEngine(INestingEngine inner, TimeSpan limit) + { + ArgumentNullException.ThrowIfNull(inner); + if (limit <= TimeSpan.Zero || limit > MaxLimit) + throw new ArgumentOutOfRangeException( + nameof(limit), + $"The time limit must be positive and at most {MaxLimit}." + ); + this.inner = inner; + Limit = limit; + } + + public TimeSpan Limit { get; } + + public NestJobResult Solve( + NestJob job, + IProgress? progress = null, + CancellationToken token = default + ) + { + ArgumentNullException.ThrowIfNull(job); + token.ThrowIfCancellationRequested(); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); + deadline.CancelAfter(Limit); + var plans = new BestPlan(job, progress); + + NestJobResult result; + try + { + result = inner.Solve(job, plans, deadline.Token); + } + catch (OperationCanceledException) + when (!token.IsCancellationRequested && deadline.IsCancellationRequested) + { + if (plans.Best is not { Valid: true } best) + throw new TimeoutException( + $"No valid layout was found within the {Limit.TotalSeconds:0.###} s time limit." + ); + result = best.Result; + } + + token.ThrowIfCancellationRequested(); + if (result == null) + throw new InvalidOperationException("The engine returned no result."); + CandidateProgress.ReportCommits(result, progress); + return result; + } + + /// Keeps the best reported plan and forwards everything but plate commits. + private sealed class BestPlan(NestJob job, IProgress? inner) + : IProgress + { + public CandidateScore? Best { get; private set; } + + public void Report(NestJobProgress value) + { + if (value == null || value.Stage == NestJobStage.PlateCommitted) + return; + if (value.Stage != NestJobStage.PlanImproved) + { + inner?.Report(value); + return; + } + if (value.Plan == null) + return; + + CandidateScore plan; + try + { + plan = CandidateScore.Of(job, value.Plan, 0); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // A plan that cannot be scored is never kept or shown. + return; + } + if (Best != null && Best.IsBetterThan(plan)) + return; + Best = plan; + inner?.Report(value); + } + } +} diff --git a/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs b/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs index 0c79da12..a539821c 100644 --- a/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs @@ -22,37 +22,76 @@ namespace OpenNest.Engine.NestingEngines.Default; /// cheap, valid fallback for the rest. Circles bids only when every part is round, and otherwise /// returns everything unplaced at once. /// A candidate that throws or returns no result is skipped; when every candidate throws, the -/// first exception is rethrown. Cancellation stops the search. Candidates' plate commits are not forwarded; the chosen -/// result's commits are reported once it is selected. +/// exception of the first in tie-break order is rethrown. Cancellation stops the search. +/// Candidates' plate commits are not forwarded; the chosen result's commits are reported once it +/// is selected. /// /// Candidates' whole-job plans () are scored the same way /// and reported only when one beats every plan reported so far, so a later candidate never shows a /// 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 +/// 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. +/// /// Deterministic: candidates run one after another and the choice uses no clock. /// public sealed class DefaultNestingEngine : INestingEngine { private readonly IReadOnlyList> candidates; + private readonly IReadOnlyList runOrder; public DefaultNestingEngine() - : this(new Func[] - { - () => new IrregularNestingEngine(), () => new RectanglesNestingEngine(), () => new CirclesNestingEngine(), - }) + : this( + new Func[] + { + () => new IrregularNestingEngine(), + () => new RectanglesNestingEngine(), + () => new CirclesNestingEngine(), + }, + new[] { 1, 0, 2 }) { } - /// Test seam: candidate engines in tie-break order. + /// Test seam: candidate engines in tie-break order, run in that order. internal DefaultNestingEngine(IReadOnlyList> candidates) + : this(candidates, Enumerable.Range(0, candidates?.Count ?? 0).ToArray()) + { + } + + /// 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. + internal DefaultNestingEngine( + IReadOnlyList> candidates, + IReadOnlyList runOrder + ) { ArgumentNullException.ThrowIfNull(candidates); + ArgumentNullException.ThrowIfNull(runOrder); if (candidates.Count == 0) - throw new ArgumentException("At least one candidate engine is required.", nameof(candidates)); + throw new ArgumentException( + "At least one candidate engine is required.", + nameof(candidates) + ); + if ( + runOrder.Count != candidates.Count + || runOrder.Distinct().Count() != candidates.Count + || runOrder.Any(i => i < 0 || i >= candidates.Count) + ) + throw new ArgumentException( + "The run order must list every candidate index once.", + nameof(runOrder) + ); this.candidates = candidates; + this.runOrder = runOrder; } + /// Candidate indexes in the order they run. + internal IReadOnlyList RunOrder => runOrder; + public NestJobResult Solve( NestJob job, IProgress? progress = null, @@ -64,8 +103,9 @@ public sealed class DefaultNestingEngine : INestingEngine var forward = progress == null ? null : new PlanFilter(job, progress, token); CandidateScore? best = null; ExceptionDispatchInfo? firstFailure = null; + var firstFailureOrder = int.MaxValue; - for (var order = 0; order < candidates.Count; order++) + foreach (var order in runOrder) { token.ThrowIfCancellationRequested(); NestJobResult? result; @@ -78,7 +118,11 @@ public sealed class DefaultNestingEngine : INestingEngine catch (Exception ex) { // A canceled solve is rethrown by the token checks around each candidate. - firstFailure ??= ExceptionDispatchInfo.Capture(ex); + if (order < firstFailureOrder) + { + firstFailure = ExceptionDispatchInfo.Capture(ex); + firstFailureOrder = order; + } continue; } if (result == null) diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index 6c0fec28..0410abae 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -11,7 +11,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 earlier engine | +| 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) | | 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 | @@ -20,7 +20,10 @@ in `OpenNest.Engine/NestingEngines//`, its tests in `OpenNest.Engine.Tests 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. A candidate that throws is skipped. Default routes the whole job: +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: 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. @@ -49,6 +52,18 @@ progress sink. Plug-ins may report plans the same way; FlatBar and the fixed-strategy engines do not. +### Time limits + +`DeadlineNestingEngine` wraps any engine with a wall-clock limit. An engine that finishes in time +keeps its result, as does one that ignores cancellation and returns a result late. At the limit the search is cancelled and the best reported plan that passes the +layout check is returned instead (ranked like Default ranks candidates, a tie going to the later +plan), so the result may leave parts unplaced; with no valid plan the solve fails with a +`TimeoutException`. The caller's own cancellation still cancels. A limited solve depends on the +clock, so it is not reproducible, and it can overrun the limit by however long the engine takes to +notice cancellation. A limit can be any positive time up to about 49.7 days (the cancellation timer's range). +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. + Interactive Fill shows its rectangle best-fit (box packing) layout before the best-fit pair phase, whose first computation for a drawing can take a minute, so **Accept** is available at once. The box layout is only a fallback: the strategies still run in their usual order and a