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