mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-03 16:49:25 -05:00
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:
1 parent
bf9b0df816
commit
e54a9456f4
11 files changed
+642
-10
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user