Files
OpenNest/OpenNest.Engine/NestingEngines/NestTrace.cs
T
ajandClaude Sonnet 5.5 e54a9456f4 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>
2026-11-28 14:44:05 -05:00

207 lines
7.3 KiB
C#

#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.
}
}
}
}