feat(engine): add an opt-in solve log to the Default nesting engine

Set OPENNEST_NEST_LOG to a directory to write one JSON Lines file of
events and a text summary per Default solve: each candidate engine's
result, time and passes, and why the winning layout was chosen. It only
observes, so layouts are the same with it on or off.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Sonnet 5.5 committed 2026-11-28 14:44:05 -05:00
1 parent bf9b0df816
commit e54a9456f4
11 files changed
+642 -10

No files matched your search

@@ -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<JsonElement> 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<INestingEngine>[] { () => new Canceling(canceled) })
{
TraceDirectory = directory,
};
Assert.Throws<OperationCanceledException>(() => 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<NestJobProgress>? progress = null,
CancellationToken token = default)
{
source.Cancel();
token.ThrowIfCancellationRequested();
throw new InvalidOperationException("Not canceled.");
}
}
}
@@ -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);
}
}
@@ -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 <c>OPENNEST_NEST_LOG</c> environment variable to a directory writes a
/// <see cref="NestTrace"/> of each solve there; it changes nothing about the result.
/// </summary>
public sealed class DefaultNestingEngine : INestingEngine
{
@@ -97,6 +101,10 @@ public sealed class DefaultNestingEngine : INestingEngine
/// <summary>Candidate indexes in the order they run.</summary>
internal IReadOnlyList<int> RunOrder => runOrder;
/// <summary>Where each solve's <see cref="NestTrace"/> goes; null writes none.</summary>
internal string? TraceDirectory { get; init; } =
Environment.GetEnvironmentVariable(NestTrace.DirectoryVariable);
public NestJobResult Solve(
NestJob job,
IProgress<NestJobProgress>? 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();
}
/// <summary>
/// Forwards candidate progress except plate commits, and replaces candidates' raw plan reports
/// with Default's own best plan so far by <see cref="CandidateScore"/>.
@@ -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);
}
@@ -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<int>();
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();
@@ -50,7 +50,7 @@ public sealed partial class IrregularNestingEngine
private sealed record Plan(IReadOnlyList<SheetFill> 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)
{
@@ -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<double, BlockCatalog> blocks = new();
private readonly IReadOnlyDictionary<string, NestJobPart> parts = job.Parts.ToDictionary(p => p.Id, StringComparer.Ordinal);
/// <summary>Sheets packed on trial so far, for <see cref="NestTrace"/>.</summary>
private long stockTrials;
/// <summary>Work at which the current grouped plan stops starting new fills.</summary>
private long groupedBudget;
@@ -142,6 +146,9 @@ public sealed partial class IrregularNestingEngine
{
groupedBudget = Work.Value + workBudget;
var finishers = new List<Run>();
var timer = Stopwatch.StartNew();
var workBefore = Work.Value;
var trialsBefore = stockTrials;
var run = Decode(demand, strategy, new Dictionary<string, int>(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)));
@@ -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 });
/// <summary>
/// One solve's passes, in the order <see cref="Solve"/> 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;
/// <summary>Runs one pass, logging what it cost and whether it changed the result.</summary>
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.##}"));
}
/// <summary>Reports the first variant decoded without Lattice blocks; it never becomes the best.</summary>
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<int[]> 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)));
}
+206
View File
@@ -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;
/// <summary>
/// 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 <see cref="DirectoryVariable"/> names
/// a directory; the candidate engines write to <see cref="Current"/> 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.
/// </summary>
internal sealed class NestTrace : IDisposable
{
/// <summary>Environment variable naming the directory that turns the log on.</summary>
public const string DirectoryVariable = "OPENNEST_NEST_LOG";
private static readonly AsyncLocal<NestTrace?> 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<string, double> 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);
}
/// <summary>The log of the solve under way on this execution context, or null when off.</summary>
public static NestTrace? Current => current.Value;
public string EventsPath { get; }
public string SummaryPath => Path.ChangeExtension(EventsPath, ".summary.txt");
/// <summary>
/// Starts a log in <paramref name="directory"/> and makes it <see cref="Current"/> until
/// disposed; null when the directory is blank or cannot be written, or a log is already open.
/// </summary>
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;
}
}
/// <summary>Writes one event: its name, the milliseconds since the solve started and the
/// properties of <paramref name="data"/>.</summary>
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.
}
}
/// <summary>Adds a line to the text summary.</summary>
public void Summarize(string line)
{
lock (sync)
summary.AppendLine(line);
}
/// <summary>Marks the solve as having returned a result.</summary>
public void Complete() => completed = true;
/// <summary>Each sheet's stock, part count and share of its area that is part material.</summary>
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();
/// <summary>Part material over sheet area, across all of a result's sheets.</summary>
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.
}
}
}
}
@@ -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;
@@ -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<double>())
{
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();
+32
View File
@@ -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 <level> --kerf <k>` 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 -- <jobs> --engines Default --parallel 1
```
Each Default solve writes `nest-<time>-<pid>-<n>.jsonl`, one event per line with `t`
(milliseconds since the solve started) and `event`, and a `.summary.txt` beside it. One Auto Nest
may solve more than once (trials by the pipeline), so it may write several. Only Default starts a
log: an engine chosen by name writes none. Utilization is part material over whole-sheet area.
| Event | What it records |
|---|---|
| `job` | Options, parts (quantity, area, size) and stocks |
| `candidate.start`, `candidate.finished`, `candidate.failed`, `candidate.noResult` | Each engine's time, validity and violations, unplaced parts, cost, per-sheet utilization |
| `default.betterPlan`, `default.chosen` | When the best plan improved; the winner, why, and its cost margin over the runner-up |
| `irregular.start`, `irregular.passStart`, `irregular.pass`, `irregular.skip` | Orientations per part type; each pass's time, work and whether it changed the plan; what was skipped and why |
| `irregular.decode` | Each whole-job decode: strategy, time, work, sheet trials, cost and per-sheet utilization |
| `irregular.tailReplan`, `irregular.reduceSplit`, `irregular.bandLastSheet`, `irregular.squeeze` | Whether each improvement attempt packed and what it saved |
| `rectangles.run`, `rectangles.chosen` | The cost-first and large-first runs |
| `raster.variant`, `raster.invalidVariant`, `raster.chosen` | All decode variants, best first |
| `circles.noBid`, `circles.run`, `circles.tailImproved` | Why Circles did not bid, or its runs |
| `solve.aborted` | Last line of a solve that was canceled or failed |
Lines are written as they happen, so a search stopped at a time limit keeps its log. The log only
observes; the variable never changes a layout. Logging adds scoring and file work, so take
benchmark timings without it.
## Changing an engine
Use the [engine benchmarking guide](performance/engine-benchmarking.md) for the command, candidate-sheet controls, and comparison procedure.