diff --git a/OpenNest.Engine.Tests/NestingEngines/NestTraceTests.cs b/OpenNest.Engine.Tests/NestingEngines/NestTraceTests.cs new file mode 100644 index 00000000..cb14706e --- /dev/null +++ b/OpenNest.Engine.Tests/NestingEngines/NestTraceTests.cs @@ -0,0 +1,98 @@ +#nullable enable +using System.Text.Json; +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 sealed class NestTraceTests : IDisposable +{ + private readonly string directory = Path.Combine(Path.GetTempPath(), "opennest-trace-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(directory)) + Directory.Delete(directory, recursive: true); + } + + // Two part types of very different size, three of each, on one of two stocks. + private static NestJob MixedJob() => Job( + [ + Part("large", LShape(20, 20, 6), 3, RotationPolicy.Automatic), + Part("small", Triangle(5, 4), 6, RotationPolicy.Automatic), + ], + [Stock("s48", 48, 48, spacing: 0.25), Stock("s60", 48, 60, spacing: 0.25)]); + + private List Events() => + File.ReadAllLines(Assert.Single(Directory.GetFiles(directory, "*.jsonl"))) + .Select(line => JsonDocument.Parse(line).RootElement) + .ToList(); + + private static string Name(JsonElement e) => e.GetProperty("event").GetString()!; + + [Fact] + public void TracingLogsEveryCandidateAndNeverChangesTheResult() + { + var job = MixedJob(); + var plain = new DefaultNestingEngine { TraceDirectory = null }.Solve(job); + + var traced = new DefaultNestingEngine { TraceDirectory = directory }.Solve(job); + + Assert.True(CandidateProgress.SameLayout(plain, traced)); + var events = Events(); + Assert.Equal("job", Name(events[0])); + Assert.Equal(4, events.Count(e => Name(e) == "candidate.finished")); + foreach (var name in new[] + { + "default.chosen", "irregular.start", "irregular.decode", "irregular.pass", + "rectangles.run", "raster.variant", "circles.noBid", + }) + Assert.Contains(events, e => Name(e) == name); + Assert.DoesNotContain(events, e => Name(e) == "solve.aborted"); + Assert.Contains("Chosen: ", File.ReadAllText(Assert.Single(Directory.GetFiles(directory, "*.summary.txt")))); + Assert.Null(NestTrace.Current); + } + + [Fact] + public void ACanceledSolveLeavesItsLog() + { + var job = MixedJob(); + using var canceled = new CancellationTokenSource(); + var engine = new DefaultNestingEngine(new Func[] { () => new Canceling(canceled) }) + { + TraceDirectory = directory, + }; + + Assert.Throws(() => engine.Solve(job, token: canceled.Token)); + + Assert.Equal("solve.aborted", Name(Events()[^1])); + Assert.Null(NestTrace.Current); + } + + [Fact] + public void AnUnwritableDirectoryStillSolves() + { + Directory.CreateDirectory(directory); + var file = Path.Combine(directory, "taken"); + File.WriteAllText(file, ""); + var job = MixedJob(); + + var result = new DefaultNestingEngine { TraceDirectory = file }.Solve(job); + + Assert.NotEmpty(result.Plates); + } + + private sealed class Canceling(CancellationTokenSource source) : INestingEngine + { + public NestJobResult Solve(NestJob job, IProgress? progress = null, + CancellationToken token = default) + { + source.Cancel(); + token.ThrowIfCancellationRequested(); + throw new InvalidOperationException("Not canceled."); + } + } +} diff --git a/OpenNest.Engine/NestingEngines/Circles/CirclesNestingEngine.cs b/OpenNest.Engine/NestingEngines/Circles/CirclesNestingEngine.cs index daacb278..cb67f9fe 100644 --- a/OpenNest.Engine/NestingEngines/Circles/CirclesNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Circles/CirclesNestingEngine.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading; using OpenNest.Engine.CirclePacking; @@ -61,7 +62,11 @@ public sealed class CirclesNestingEngine : INestingEngine var rotations = part.Rotation.EnumerateAngles(maxSamples: 1); var item = geometry == null ? null : Item.Create(geometry); if (item != null && item.FillRatio < MinFillRatio) + { + NestTrace.Current?.Write("circles.noBid", + new { part = part.Id, fillRatio = item.FillRatio, required = MinFillRatio }); return new NestJobResultBuilder(job, progress).Build(NestJobStopReason.NoPlacementFound); + } // Unreadable parts keep a placeholder so type indices match requirement order. types.Add(new DiscType(i, part, item ?? new Item(), rotations.Count > 0 ? rotations[0] : 0, geometry?.MaterialArea ?? 0)); @@ -79,9 +84,20 @@ public sealed class CirclesNestingEngine : INestingEngine foreach (var preferred in runs) { token.ThrowIfCancellationRequested(); + var timer = Stopwatch.StartNew(); var result = SheetByStock.Run(job, demand, remaining.ToArray(), Pack, forward, token, preferred: preferred); var scored = CandidateScore.Of(job, result, run++); + NestTrace.Current?.Write("circles.run", new + { + run = scored.Order, + preferredStock = preferred?.Id, + ms = timer.ElapsedMilliseconds, + valid = scored.Valid, + unplaced = scored.Unplaced, + cost = scored.Cost, + sheets = scored.Result.Plates.Count, + }); if (best == null || scored.IsBetterThan(best)) { best = scored; @@ -127,6 +143,8 @@ public sealed class CirclesNestingEngine : INestingEngine if (scored.IsBetterThan(chosen)) { chosen = scored; + NestTrace.Current?.Write("circles.tailImproved", + new { tail, stock = stock.Id, unplaced = chosen.Unplaced, cost = chosen.Cost }); CandidateProgress.ReportPlan(chosen.Result, progress); } } diff --git a/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs b/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs index c2f28e9a..ac2781f7 100644 --- a/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Default/DefaultNestingEngine.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading; @@ -41,6 +42,9 @@ namespace OpenNest.Engine.NestingEngines.Default; /// 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. +/// +/// Setting the OPENNEST_NEST_LOG environment variable to a directory writes a +/// of each solve there; it changes nothing about the result. /// public sealed class DefaultNestingEngine : INestingEngine { @@ -97,6 +101,10 @@ public sealed class DefaultNestingEngine : INestingEngine /// Candidate indexes in the order they run. internal IReadOnlyList RunOrder => runOrder; + /// Where each solve's goes; null writes none. + internal string? TraceDirectory { get; init; } = + Environment.GetEnvironmentVariable(NestTrace.DirectoryVariable); + public NestJobResult Solve( NestJob job, IProgress? progress = null, @@ -105,6 +113,8 @@ public sealed class DefaultNestingEngine : INestingEngine { ArgumentNullException.ThrowIfNull(job); token.ThrowIfCancellationRequested(); + using var trace = NestTrace.Start(TraceDirectory, job); + var names = new string[candidates.Count]; var forward = progress == null ? null : new PlanFilter(job, progress, token); var scores = new CandidateScore?[candidates.Count]; ExceptionDispatchInfo? firstFailure = null; @@ -116,12 +126,19 @@ public sealed class DefaultNestingEngine : INestingEngine NestJobResult? result; if (forward != null) forward.Order = order; + var timer = Stopwatch.StartNew(); try { - result = candidates[order]().Solve(job, forward, token); + var engine = candidates[order](); + names[order] = engine.GetType().Name; + trace?.Write("candidate.start", new { engine = names[order], order }); + result = engine.Solve(job, forward, token); } catch (Exception ex) { + trace?.Write("candidate.failed", + new { engine = names[order], order, ms = timer.ElapsedMilliseconds, error = ex.ToString() }); + trace?.Summarize($"{names[order]}: failed after {timer.ElapsedMilliseconds} ms: {ex.Message}"); // A canceled solve is rethrown by the token checks around each candidate. if (order < firstFailureOrder) { @@ -131,10 +148,16 @@ public sealed class DefaultNestingEngine : INestingEngine continue; } if (result == null) + { + trace?.Write("candidate.noResult", new { engine = names[order], order, ms = timer.ElapsedMilliseconds }); continue; + } + var solved = timer.ElapsedMilliseconds; var scored = CandidateScore.Of(job, result, order); scores[order] = scored; + if (trace != null) + TraceCandidate(trace, job, names[order], scored, solved, timer.ElapsedMilliseconds - solved); forward?.Offer(scored); } @@ -153,9 +176,67 @@ public sealed class DefaultNestingEngine : INestingEngine forward?.Finish(best); CandidateProgress.ReportCommits(best.Result, progress); + if (trace != null) + TraceChoice(trace, names, scores, best); return best.Result; } + private static void TraceCandidate(NestTrace trace, NestJob job, string engine, CandidateScore score, + long solveMs, long scoreMs) + { + var utilization = score.Valid ? trace.Utilization(score.Result) : 0; + trace.Write("candidate.finished", new + { + engine, + order = score.Order, + solveMs, + scoreMs, + valid = score.Valid, + violations = score.Valid ? null : NestLayoutCheck.Violations(job, score.Result).Take(20).ToArray(), + unplaced = score.Unplaced, + cost = score.Cost, + offcut = score.Offcut, + utilization, + stopReason = score.Result.StopReason, + sheets = score.Valid ? trace.Sheets(score.Result) : null, + }); + trace.Summarize($"{engine}: {solveMs} ms, {(score.Valid ? "valid" : "INVALID")}, " + + $"{score.Result.Plates.Count} sheet(s), {score.Unplaced} unplaced, cost {score.Cost:0.##}, " + + $"utilization {utilization:P1}"); + } + + private static void TraceChoice(NestTrace trace, string[] names, CandidateScore?[] scores, CandidateScore best) + { + CandidateScore? second = null; + foreach (var scored in scores) + if (scored != null && !ReferenceEquals(scored, best) && (second == null || scored.IsBetterThan(second))) + second = scored; + var priced = second != null && best.Valid && second.Valid; + var costMargin = priced ? second!.Cost - best.Cost : (double?)null; + var offcutMargin = priced ? best.Offcut - second!.Offcut : (double?)null; + // Costs this close tie, as CandidateScore ranks them. + var costDecides = priced && System.Math.Abs(second!.Cost - best.Cost) + > 1e-9 * System.Math.Max(1, System.Math.Abs(best.Cost)); + // Given the runner-up's place in the tie-break order, the best still wins only on its score. + var reason = second == null ? "only result" + : best.Valid != second.Valid ? "only valid layout" + : best.Unplaced != second.Unplaced ? "fewer unplaced" + : costDecides ? "lower cost" + : (best with { Order = second.Order }).IsBetterThan(second) ? "same cost, larger offcut" + : "tie, candidate order"; + var runnerUp = second == null ? null : names[second.Order]; + trace.Write("default.chosen", new + { + engine = names[best.Order], + reason, + runnerUp, + costMargin, + offcutMargin, + }); + trace.Summarize($"Chosen: {names[best.Order]} ({reason}{(runnerUp == null ? "" : $" over {runnerUp}")})"); + trace.Complete(); + } + /// /// Forwards candidate progress except plate commits, and replaces candidates' raw plan reports /// with Default's own best plan so far by . @@ -203,6 +284,14 @@ public sealed class DefaultNestingEngine : INestingEngine return; } shown = plan; + NestTrace.Current?.Write("default.betterPlan", new + { + order = plan.Order, + valid = plan.Valid, + unplaced = plan.Unplaced, + cost = plan.Cost, + sheets = plan.Result.Plates.Count, + }); CandidateProgress.ReportPlan(plan.Result, inner); } diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Improvements.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Improvements.cs index 6fd80b62..97f5da57 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Improvements.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Improvements.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using OpenNest.Engine.Jobs; @@ -28,6 +29,9 @@ public sealed partial class IrregularNestingEngine public Plan ImproveTail(Plan plan, long budget) { engine.TailReplanning?.Invoke(budget - Work.Value); + var timer = Stopwatch.StartNew(); + var (workBefore, trialsBefore, costBefore) = (Work.Value, stockTrials, plan.Cost); + var replaced = new List(); var sheets = plan.Sheets.ToList(); for (var k = 1; k <= System.Math.Min(MaxTail, sheets.Count); k++) { @@ -42,7 +46,18 @@ public sealed partial class IrregularNestingEngine sheets = prefix.Concat(replan.Sheets).ToList(); plan = plan with { Sheets = sheets.ToList(), Cost = plan.Cost - (tailNet - replan.Net) }; engine.TailReplaced?.Invoke(k); + replaced.Add(k); } + NestTrace.Current?.Write("irregular.tailReplan", new + { + ms = timer.ElapsedMilliseconds, + budget = budget - workBefore, + work = Work.Value - workBefore, + stockTrials = stockTrials - trialsBefore, + tailsReplaced = replaced, + costBefore, + cost = plan.Cost, + }); return plan; } @@ -105,17 +120,26 @@ public sealed partial class IrregularNestingEngine { var stock = plan.Sheets[0].Stock; if (stock.Outline != null || plan.Sheets.Any(s => !ReferenceEquals(s.Stock, stock))) + { + Skip("ReduceSheets", "outlined or mixed stock"); return null; + } var instances = plan.Sheets.SelectMany(s => s.Parts).Select(p => p.Orientation.TypeIndex) .OrderByDescending(t => types[t].Area).ThenBy(t => t).ToList(); var target = plan.Sheets.Count - 1; var room = stock.WorkArea.Length * stock.WorkArea.Width; if (instances.Count > MaxReduceParts || instances.Sum(t => types[t].Area) > target * room) + { + Skip("ReduceSheets", instances.Count > MaxReduceParts + ? $"{instances.Count} parts, more than the {MaxReduceParts} it tries" + : $"part area does not fit {target} sheet(s)"); return null; + } foreach (var bins in Splits(instances, target)) { var sheets = PackEdgeFirst(stock, bins); + NestTrace.Current?.Write("irregular.reduceSplit", new { sheets = target, packed = sheets != null }); if (sheets == null) continue; var candidate = PlanOf(job, sheets, NestJobCost.RequireFinite(sheets.Sum(s => NetCost(job.Options, s))), 0, @@ -218,6 +242,8 @@ public sealed partial class IrregularNestingEngine if (fill != null && fill.Parts.Count != last.Parts.Count) fill = null; tailBands[key] = fill; + NestTrace.Current?.Write("irregular.bandLastSheet", + new { parts = last.Parts.Count, bandedWhole = fill != null }); } if (fill == null) return plan; @@ -251,13 +277,18 @@ public sealed partial class IrregularNestingEngine var last = plan.Sheets[^1]; var stock = last.Stock; if (stock.Outline != null || last.Parts.Count < 2 || last.Parts.Count > OrderedSqueeze.MaxParts) + { + Skip("SqueezeLastSheet", + $"outlined stock, or {last.Parts.Count} part(s) outside 2..{OrderedSqueeze.MaxParts}"); return plan; + } var best = plan; foreach (var axis in SqueezeAxes(job, stock)) { token.ThrowIfCancellationRequested(); var fill = new OrderedSqueeze(types, CacheFor(stock), stock, ClampsFor(stock), Work, SqueezeOrientations) .Fill(last.Parts, axis, token); + NestTrace.Current?.Write("irregular.squeeze", new { axis, packed = fill != null }); if (fill == null) continue; var sheets = plan.Sheets.Take(plan.Sheets.Count - 1).Append(fill).ToList(); diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Plan.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Plan.cs index 858ac9fd..471ea9d6 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Plan.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Plan.cs @@ -50,7 +50,7 @@ public sealed partial class IrregularNestingEngine private sealed record Plan(IReadOnlyList Sheets, double Cost, int Unplaced, NestJobStopReason Reason, bool Priced, NestJobOptions Options) { - private double Offcut => Sheets.Sum(s => IrregularNestingEngine.Offcut(Options, s)); + public double Offcut => Sheets.Sum(s => IrregularNestingEngine.Offcut(Options, s)); public bool IsBetterThan(Plan other) { diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Solver.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Solver.cs index 6388360c..4451e35c 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Solver.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.Solver.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading; using OpenNest.Engine.Jobs; @@ -32,6 +33,9 @@ public sealed partial class IrregularNestingEngine private readonly Dictionary blocks = new(); private readonly IReadOnlyDictionary parts = job.Parts.ToDictionary(p => p.Id, StringComparer.Ordinal); + /// Sheets packed on trial so far, for . + private long stockTrials; + /// Work at which the current grouped plan stops starting new fills. private long groupedBudget; @@ -142,6 +146,9 @@ public sealed partial class IrregularNestingEngine { groupedBudget = Work.Value + workBudget; var finishers = new List(); + var timer = Stopwatch.StartNew(); + var workBefore = Work.Value; + var trialsBefore = stockTrials; var run = Decode(demand, strategy, new Dictionary(StringComparer.Ordinal), job.Options.MaxPlates, null, finishers); // The decode picks each sheet's stock on an estimate of what the leftovers will cost, @@ -160,6 +167,29 @@ public sealed partial class IrregularNestingEngine plans.Remove(best); plans.Sort((a, b) => a.IsBetterThan(b) ? -1 : b.IsBetterThan(a) ? 1 : 0); Alternatives = plans.Take(MaxAlternatives).ToList(); + NestTrace.Current?.Write("irregular.decode", new + { + axis = strategy.Axis, + beta = strategy.Beta, + rule = strategy.Rule, + weighted = strategy.Weights != null, + largeFirst = strategy.Ranks != null, + quick, + apart, + ms = timer.ElapsedMilliseconds, + work = Work.Value - workBefore, + stockTrials = stockTrials - trialsBefore, + cost = best.Cost, + unplaced = best.Unplaced, + stopReason = best.Reason, + finisherWon = !ReferenceEquals(best, decoded), + sheets = best.Sheets.Select(s => new + { + stock = s.Stock.Id, + parts = s.Parts.Count, + utilization = NestTrace.Share(s.PartArea, s.Stock.Area), + }), + }); return best; } @@ -263,6 +293,7 @@ public sealed partial class IrregularNestingEngine continue; progress?.Report(new NestJobProgress(NestJobStage.EvaluatingCandidate, stock.Id, sheetIndex, 0, 0)); var fill = FillSheet(stock, strategy, remaining); + stockTrials++; engine.SheetPacked?.Invoke(); if (fill.Parts.Count > 0) trials.Add(new Trial(fill, NetCost(job.Options, fill))); diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs index 56ca8b41..3512bfd3 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; @@ -187,6 +188,19 @@ public sealed partial class IrregularNestingEngine : INestingEngine var untilCancelled = job.Options.SearchUntilCancelled && token.CanBeCanceled && progress != null && types.Count > 1 && demand.Any(d => d > 0); + NestTrace.Current?.Write("irregular.start", new + { + workBudget = WorkBudget, + untilCancelled, + types = types.Select(t => new + { + t.Part.Id, + orientations = t.Orientations.Count, + demand = t.Part.Quantity, + placeable = demand[t.Index], + }), + }); + // 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. The search's plans are reported as @@ -195,9 +209,9 @@ public sealed partial class IrregularNestingEngine : INestingEngine // Without a type of three or more copies no block is ever prepared, and the quick plan would // only repeat the first variant. if (untilCancelled && demand.Any(d => d > 2)) - search.QuickPlan(); + search.Traced("QuickPlan", search.QuickPlan); - search.StrategyVariants(); + search.Traced("StrategyVariants", search.StrategyVariants); // Then the large parts first: each sheet packs the large types before any small one, so the // small parts fill the large parts' gaps instead of spending the first, densest sheets on @@ -205,7 +219,7 @@ public sealed partial class IrregularNestingEngine : INestingEngine // preparing no Lattice blocks, so the passes after it run as without it; it only changes // them by beating the best plan, which they must then beat. if (LargeFirst) - search.LargeFirstVariants(); + search.Traced("LargeFirstVariants", search.LargeFirstVariants); // 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 @@ -213,28 +227,33 @@ public sealed partial class IrregularNestingEngine : INestingEngine // budget is spent. var groups = GroupLikeParts && GroupedFill.Applies(types, demand); if (groups) - search.GroupedVariants(); + search.Traced("GroupedVariants", search.GroupedVariants); + else + Skip("GroupedVariants", "no group of like parts to pack together, or grouping is off"); // 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. if (BandLikeParts && groups) - search.BandedVariant(); + search.Traced("BandedVariant", search.BandedVariant); // Then try to drop a sheet: split the parts over one sheet fewer and pack each sheet edge // first, the key part turned by its contacts. Replaces the result only by beating it. if (ReduceSheets) - search.ReduceSheets(); + search.Traced("ReduceSheets", search.ReduceSheets); // Last, shorten the last sheet: its parts packed again in a given order, largest first, // inside ever shorter strips. Replaces the result only by beating it. if (SqueezeLastSheet) - search.SqueezeLastSheet(); + search.Traced("SqueezeLastSheet", search.SqueezeLastSheet); if (untilCancelled) - search.SeededVariants(groups); + search.Traced("SeededVariants", () => search.SeededVariants(groups)); return BuildResult(job, types, search.Result, progress, token); } + private static void Skip(string pass, string reason) => + NestTrace.Current?.Write("irregular.skip", new { pass, reason }); + /// /// One solve's passes, in the order runs them. Each keeps the best plan so /// far and reports what it finds; reporting never changes the search. @@ -267,6 +286,44 @@ public sealed partial class IrregularNestingEngine : INestingEngine private long WorkBudget => engine.WorkBudget; + /// Runs one pass, logging what it cost and whether it changed the result. + public void Traced(string name, Action pass) + { + if (NestTrace.Current is not { } trace) + { + pass(); + return; + } + + var before = shown ?? best; + var work = solver.Work.Value; + var timer = Stopwatch.StartNew(); + trace.Write("irregular.passStart", new { pass = name }); + pass(); + var after = shown ?? best; + var improved = !ReferenceEquals(before, after); + trace.Write("irregular.pass", new + { + pass = name, + ms = timer.ElapsedMilliseconds, + // The main meter only: passes that run apart report their work per decode. + work = solver.Work.Value - work, + workTotal = solver.Work.Value, + improved, + costBefore = before?.Cost, + cost = after?.Cost, + offcutBefore = before?.Offcut, + offcut = after?.Offcut, + sheetsBefore = before?.Sheets.Count, + sheets = after?.Sheets.Count, + unplaced = after?.Unplaced, + }); + trace.Summarize($" Irregular {name}: {timer.ElapsedMilliseconds} ms, " + + (after == null ? "no plan yet" + : $"{(improved ? "new plan" : "unchanged")}, {after.Sheets.Count} sheet(s), cost {after.Cost:0.##}, " + + $"offcut {after.Offcut:0.##}")); + } + /// Reports the first variant decoded without Lattice blocks; it never becomes the best. public void QuickPlan() { @@ -286,7 +343,10 @@ public sealed partial class IrregularNestingEngine : INestingEngine { token.ThrowIfCancellationRequested(); if (leader != null && solver.Work.Value >= WorkBudget) + { + Skip("StrategyVariants", $"work budget spent before {axis} beta {beta} and later variants"); break; + } var plan = solver.Plan(demand, new Strategy(axis, beta)); ReportAlternatives(); if (leader == null || plan.IsBetterThan(leader)) @@ -313,7 +373,10 @@ public sealed partial class IrregularNestingEngine : INestingEngine { token.ThrowIfCancellationRequested(); if (solver.Work.Value >= WorkBudget) + { + Skip("GroupedVariants", $"work budget spent before the {axis} variant"); break; + } Offer(solver.Plan(demand, Strategy.Grouped(axis))); } } @@ -327,7 +390,10 @@ public sealed partial class IrregularNestingEngine : INestingEngine { if (job.Parts.Select(p => p.Priority).Distinct().Count() != 1 || solver.Work.Value >= BandedWorkLimit * WorkBudget) + { + Skip("BandedVariant", "mixed priorities or banded work limit spent"); return; + } token.ThrowIfCancellationRequested(); Offer(solver.Plan(demand, Strategy.Banded), banded: true); } @@ -342,6 +408,8 @@ public sealed partial class IrregularNestingEngine : INestingEngine var splits = LargeFirstRanks(types, demand).ToList(); if (splits.Count > 0) solver.Apart(() => LargeFirstSplits(splits)); + else + Skip("LargeFirstVariants", "no large/small split in this job"); } private bool LargeFirstSplits(IReadOnlyList splits) @@ -354,7 +422,10 @@ public sealed partial class IrregularNestingEngine : INestingEngine { token.ThrowIfCancellationRequested(); if (!first && solver.Work.Value >= limit) + { + Skip("LargeFirstVariants", $"split budget spent before {axis} beta {beta} and later variants"); break; + } first = false; Offer(solver.Plan(demand, new Strategy(axis, beta, Ranks: ranks))); } diff --git a/OpenNest.Engine/NestingEngines/NestTrace.cs b/OpenNest.Engine/NestingEngines/NestTrace.cs new file mode 100644 index 00000000..6f3aadcb --- /dev/null +++ b/OpenNest.Engine/NestingEngines/NestTrace.cs @@ -0,0 +1,206 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using System.Threading; +using OpenNest.Engine.Jobs; + +namespace OpenNest.Engine.NestingEngines; + +/// +/// Opt-in log of one Default solve, for finding where the engines can improve: a JSON Lines file +/// of events and a short text summary. Default starts it when names +/// a directory; the candidate engines write to when there is one. Lines are +/// flushed as written, so a stopped or crashed solve still leaves its log. It only observes: its +/// clock decides nothing, and a failure to write is ignored rather than failing the solve. +/// +internal sealed class NestTrace : IDisposable +{ + /// Environment variable naming the directory that turns the log on. + public const string DirectoryVariable = "OPENNEST_NEST_LOG"; + + private static readonly AsyncLocal current = new(); + private static int sequence; + + private static readonly JsonSerializerOptions Json = new() + { + NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() }, + }; + + private readonly object sync = new(); + private readonly Stopwatch clock = Stopwatch.StartNew(); + private readonly StreamWriter writer; + private readonly StringBuilder summary = new(); + private readonly Dictionary areas; + private bool completed; + private bool closed; + + private NestTrace(string path, StreamWriter writer, NestJob job) + { + EventsPath = path; + this.writer = writer; + areas = job.Parts.ToDictionary(p => p.Id, + p => JobPartGeometry.TryRead(p.Geometry)?.MaterialArea ?? 0, StringComparer.Ordinal); + } + + /// The log of the solve under way on this execution context, or null when off. + public static NestTrace? Current => current.Value; + + public string EventsPath { get; } + public string SummaryPath => Path.ChangeExtension(EventsPath, ".summary.txt"); + + /// + /// Starts a log in and makes it until + /// disposed; null when the directory is blank or cannot be written, or a log is already open. + /// + public static NestTrace? Start(string? directory, NestJob job) + { + if (string.IsNullOrWhiteSpace(directory) || current.Value != null) + return null; + try + { + Directory.CreateDirectory(directory); + var name = $"nest-{DateTime.Now:yyyyMMdd-HHmmss-fff}-{Environment.ProcessId}-" + + $"{Interlocked.Increment(ref sequence)}.jsonl"; + var path = Path.Combine(directory, name); + var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.Read); + var trace = new NestTrace(path, new StreamWriter(stream) { AutoFlush = true }, job); + current.Value = trace; + trace.WriteJob(job); + return trace; + } + catch (Exception) + { + return null; + } + } + + /// Writes one event: its name, the milliseconds since the solve started and the + /// properties of . + public void Write(string name, object? data = null) + { + try + { + var line = new JsonObject { ["t"] = clock.ElapsedMilliseconds, ["event"] = name }; + if (data != null && JsonSerializer.SerializeToNode(data, Json) is JsonObject fields) + foreach (var (key, value) in fields.ToList()) + { + fields.Remove(key); + line[key] = value; + } + var text = line.ToJsonString(Json); + lock (sync) + if (!closed) + writer.WriteLine(text); + } + catch (Exception) + { + // A log that cannot be written must not change what the solve does. + } + } + + /// Adds a line to the text summary. + public void Summarize(string line) + { + lock (sync) + summary.AppendLine(line); + } + + /// Marks the solve as having returned a result. + public void Complete() => completed = true; + + /// Each sheet's stock, part count and share of its area that is part material. + public object[] Sheets(NestJobResult result) => + result.Plates.Select(sheet => (object)new + { + stock = sheet.StockId, + parts = sheet.Placements.Count, + utilization = Share(PlacedArea(sheet), sheet.Stock.Area), + }).ToArray(); + + /// Part material over sheet area, across all of a result's sheets. + public double Utilization(NestJobResult result) => + Share(result.Plates.Sum(PlacedArea), result.Plates.Sum(p => p.Stock.Area)); + + public static double Share(double part, double whole) => whole > 0 ? System.Math.Round(part / whole, 4) : 0; + + private double PlacedArea(NestJobPlateResult sheet) => + sheet.Placements.Sum(p => areas.GetValueOrDefault(p.PartId)); + + private void WriteJob(NestJob job) + { + var quantity = job.Parts.Sum(p => p.Quantity); + var area = job.Parts.Sum(p => areas[p.Id] * p.Quantity); + Write("job", new + { + options = new + { + job.Options.MaxPlates, + job.Options.SalvageRate, + job.Options.MinimumSalvageDimension, + job.Options.SearchUntilCancelled, + job.Options.OffcutCut, + }, + totalQuantity = quantity, + totalPartArea = area, + parts = job.Parts.Select(p => + { + var box = JobPartGeometry.TryRead(p.Geometry)?.Bounds; + return new + { + p.Id, + p.Quantity, + p.Priority, + rotation = p.Rotation.Kind, + area = areas[p.Id], + length = box?.Length, + width = box?.Width, + }; + }), + stocks = job.Plates.Select(s => new + { + s.Id, + s.Size.Length, + s.Size.Width, + s.Quantity, + s.PartSpacing, + s.Cost, + outlined = s.Outline != null, + clampZones = s.ClampZones.Count, + }), + }); + Summarize($"Job: {job.Parts.Count} part type(s), {quantity} part(s), part area {area:0.##}, " + + $"{job.Plates.Count} stock size(s)"); + } + + public void Dispose() + { + current.Value = null; + if (!completed) + { + Write("solve.aborted"); + Summarize("Aborted: canceled or failed before a result was chosen."); + } + lock (sync) + { + closed = true; + try + { + writer.Dispose(); + File.WriteAllText(SummaryPath, summary.ToString()); + } + catch (Exception) + { + // As in Write. + } + } + } +} diff --git a/OpenNest.Engine/NestingEngines/Raster/RasterNestingEngine.cs b/OpenNest.Engine/NestingEngines/Raster/RasterNestingEngine.cs index bfb87aad..82fa556a 100644 --- a/OpenNest.Engine/NestingEngines/Raster/RasterNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Raster/RasterNestingEngine.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -60,15 +61,19 @@ public sealed class RasterNestingEngine : INestingEngine // Only the first run reports its stock trials, so the host hears from one thread; commits // belong to the result finally chosen. var forward = progress == null ? null : new CandidateProgress(progress); + var trace = NestTrace.Current; + var elapsed = new long[results.Length]; try { Parallel.For(0, results.Length, new ParallelOptions { CancellationToken = token }, i => { + var timer = Stopwatch.StartNew(); results[i] = i < variants.Count ? SheetByStock.Run(job, demand, remaining.ToArray(), (stock, left) => new[] { Fill(stock, variants[i], left) }, i == 0 ? forward : null, token) : SheetByStock.Run(job, demand, remaining.ToArray(), (stock, left) => variants.Select(v => Fill(stock, v, left)), null, token); + elapsed[i] = timer.ElapsedMilliseconds; }); } catch (AggregateException e) when (token.IsCancellationRequested @@ -81,6 +86,26 @@ public sealed class RasterNestingEngine : INestingEngine var ranked = results.Select((r, i) => Score(r, i)).ToList(); ranked.Sort((a, b) => a.IsBetterThan(b) ? -1 : b.IsBetterThan(a) ? 1 : 0); var best = ranked[0]; + if (trace != null) + foreach (var score in ranked) + { + var variant = score.Order < variants.Count ? variants[score.Order] : null; + trace.Write("raster.variant", new + { + variant = score.Order, + rotations = variant == null ? null + : variant.Kinds == RotationKinds.All ? "quarter, eighth and hull-aligned turns" + : variant.Kinds == RotationKinds.QuarterTurns ? "quarter turns" + : "quarter and hull-aligned turns", + policy = variant?.Policy.ToString() ?? "every variant each round", + order = variant == null ? (int?)null : score.Order % (2 + Shuffles), + // Variants run in parallel, so these times overlap. + ms = elapsed[score.Order], + unplaced = score.Unplaced, + cost = score.Cost, + sheets = score.Result.Plates.Count, + }); + } foreach (var candidate in ranked) { token.ThrowIfCancellationRequested(); @@ -89,7 +114,13 @@ public sealed class RasterNestingEngine : INestingEngine best = candidate; break; } + trace?.Write("raster.invalidVariant", new + { + variant = candidate.Order, + violations = NestLayoutCheck.Violations(job, candidate.Result).Take(5).ToArray(), + }); } + trace?.Write("raster.chosen", new { variant = best.Order }); CandidateProgress.ReportPlan(best.Result, progress); CandidateProgress.ReportCommits(best.Result, progress, token); return best.Result; diff --git a/OpenNest.Engine/NestingEngines/Rectangles/RectanglesNestingEngine.cs b/OpenNest.Engine/NestingEngines/Rectangles/RectanglesNestingEngine.cs index d27b711d..70f868ae 100644 --- a/OpenNest.Engine/NestingEngines/Rectangles/RectanglesNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Rectangles/RectanglesNestingEngine.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading; using OpenNest.Engine.Jobs; @@ -55,6 +56,9 @@ public sealed class RectanglesNestingEngine : INestingEngine remaining[t.Index] = 0; var demand = types.Select(t => new SheetDemand(t.Index, t.Id, t.Priority, t.MaterialArea)).ToArray(); + var trace = NestTrace.Current; + var timer = Stopwatch.StartNew(); + var packs = 0; // One run makes one whole-job plan: report it, then its commits, as the other engines do. var forward = progress == null ? null : new CandidateProgress(progress); var result = SheetByStock.Run(job, demand, remaining.ToArray(), Pack, forward, token, BatchSelected); @@ -64,15 +68,18 @@ public sealed class RectanglesNestingEngine : INestingEngine // fill each of their sheets' gaps with the small parts, and only then start new sheets for // what is left. The cheapest whole job wins; ties keep the cost-first run. var best = Score(result, 0); + TraceRun(null, best); var order = 1; foreach (var split in LargeFirstRuns ? LargeSplits(types, remaining) : Enumerable.Empty()) { token.ThrowIfCancellationRequested(); var scored = Score(LargeFirst(split), order++); + TraceRun(split, scored); if (scored.IsBetterThan(best)) best = scored; } result = best.Result; + trace?.Write("rectangles.chosen", new { run = best.Order }); CandidateProgress.ReportPlan(result, progress); CandidateProgress.ReportCommits(result, progress, token); return result; @@ -97,11 +104,29 @@ public sealed class RectanglesNestingEngine : INestingEngine foreach (var rule in Rules) { plans.Add(SheetPacker.Pack(types, left, stock, rule, mode, token, width, height)); + packs++; SheetPacked?.Invoke(mode); } return plans; } + // Each run's time and sheet packings since the one before it. + void TraceRun(double? largeSplit, CandidateScore score) + { + trace?.Write("rectangles.run", new + { + run = score.Order, + largeSplit, + ms = timer.ElapsedMilliseconds, + packs, + unplaced = score.Unplaced, + cost = score.Cost, + sheets = trace.Sheets(score.Result), + }); + timer.Restart(); + packs = 0; + } + NestJobResult LargeFirst(double split) { var large = types.Select(t => t.BoxArea >= split).ToArray(); diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index 166933aa..f2c6cd96 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -944,6 +944,38 @@ it asked before. An engine or plug-in may return groups itself on `NestJobPlateR common lines. Benchmark a level with `--common-lines --kerf ` against `--common-lines off`, reporting placed parts and absolute nested area. +## Solve log + +To see where Default spends its time and what each part of it contributes, set +`OPENNEST_NEST_LOG` to a directory before starting any front end (desktop, console, MCP, benchmark +or server worker): + +```powershell +$env:OPENNEST_NEST_LOG = "$env:TEMP\nest-log"; dotnet run -c Release --project OpenNest.Benchmark -- --engines Default --parallel 1 +``` + +Each Default solve writes `nest-