feat: add NFP-based mixed-part autonesting
Implement geometry-aware nesting using No-Fit Polygons and simulated annealing optimization. Parts interlock based on true shape rather than bounding boxes, producing tighter layouts for mixed-part scenarios. New types in Core/Geometry: - ConvexDecomposition: ear-clipping triangulation for concave polygons - NoFitPolygon: Minkowski sum via convex decomposition + Clipper2 union - InnerFitPolygon: feasible region computation for plate placement New types in Engine: - NfpCache: caches NFPs keyed by (drawingId, rotation) pairs - BottomLeftFill: places parts using feasible regions from IFP - NFP union - INestOptimizer: abstraction for future GA/parallel upgrades - SimulatedAnnealing: optimizes part ordering and rotation Integration: - NestEngine.AutoNest(): new public entry point for mixed-part nesting - MainForm.RunAutoNest_Click: uses AutoNest instead of Pack - NestingTools.autonest_plate: new MCP tool for Claude Code integration - Drawing.Id: auto-incrementing identifier for NFP cache keys - Clipper2 NuGet added to OpenNest.Core for polygon boolean operations Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
121
OpenNest.Engine/BottomLeftFill.cs
Normal file
121
OpenNest.Engine/BottomLeftFill.cs
Normal file
@@ -0,0 +1,121 @@
|
||||
using System.Collections.Generic;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest
|
||||
{
|
||||
/// <summary>
|
||||
/// NFP-based Bottom-Left Fill (BLF) placement engine.
|
||||
/// Places parts one at a time using feasible regions computed from
|
||||
/// the Inner-Fit Polygon minus the union of No-Fit Polygons.
|
||||
/// </summary>
|
||||
public class BottomLeftFill
|
||||
{
|
||||
private readonly Box workArea;
|
||||
private readonly NfpCache nfpCache;
|
||||
|
||||
public BottomLeftFill(Box workArea, NfpCache nfpCache)
|
||||
{
|
||||
this.workArea = workArea;
|
||||
this.nfpCache = nfpCache;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Places parts according to the given sequence using NFP-based BLF.
|
||||
/// Each entry is (drawingId, rotation) determining what to place and how.
|
||||
/// Returns the list of successfully placed parts with their positions.
|
||||
/// </summary>
|
||||
public List<PlacedPart> Fill(List<(int drawingId, double rotation, Drawing drawing)> sequence)
|
||||
{
|
||||
var placedParts = new List<PlacedPart>();
|
||||
|
||||
foreach (var (drawingId, rotation, drawing) in sequence)
|
||||
{
|
||||
var polygon = nfpCache.GetPolygon(drawingId, rotation);
|
||||
|
||||
if (polygon == null || polygon.Vertices.Count < 3)
|
||||
continue;
|
||||
|
||||
// Compute IFP for this part inside the work area.
|
||||
var ifp = InnerFitPolygon.Compute(workArea, polygon);
|
||||
|
||||
if (ifp.Vertices.Count < 3)
|
||||
continue;
|
||||
|
||||
// Compute NFPs against all already-placed parts.
|
||||
var nfps = new Polygon[placedParts.Count];
|
||||
|
||||
for (var i = 0; i < placedParts.Count; i++)
|
||||
{
|
||||
var placed = placedParts[i];
|
||||
var nfp = nfpCache.Get(placed.DrawingId, placed.Rotation, drawingId, rotation);
|
||||
|
||||
// Translate NFP to the placed part's position.
|
||||
var translated = TranslatePolygon(nfp, placed.Position);
|
||||
nfps[i] = translated;
|
||||
}
|
||||
|
||||
// Compute feasible region and find bottom-left point.
|
||||
var feasible = InnerFitPolygon.ComputeFeasibleRegion(ifp, nfps);
|
||||
var point = InnerFitPolygon.FindBottomLeftPoint(feasible);
|
||||
|
||||
if (double.IsNaN(point.X))
|
||||
continue;
|
||||
|
||||
placedParts.Add(new PlacedPart
|
||||
{
|
||||
DrawingId = drawingId,
|
||||
Rotation = rotation,
|
||||
Position = point,
|
||||
Drawing = drawing
|
||||
});
|
||||
}
|
||||
|
||||
return placedParts;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts placed parts to OpenNest Part instances positioned on the plate.
|
||||
/// </summary>
|
||||
public static List<Part> ToNestParts(List<PlacedPart> placedParts)
|
||||
{
|
||||
var parts = new List<Part>(placedParts.Count);
|
||||
|
||||
foreach (var placed in placedParts)
|
||||
{
|
||||
var part = new Part(placed.Drawing);
|
||||
|
||||
if (placed.Rotation != 0)
|
||||
part.Rotate(placed.Rotation);
|
||||
|
||||
part.Location = placed.Position;
|
||||
parts.Add(part);
|
||||
}
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a translated copy of a polygon.
|
||||
/// </summary>
|
||||
private static Polygon TranslatePolygon(Polygon polygon, Vector offset)
|
||||
{
|
||||
var result = new Polygon();
|
||||
|
||||
foreach (var v in polygon.Vertices)
|
||||
result.Vertices.Add(new Vector(v.X + offset.X, v.Y + offset.Y));
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a part that has been placed by the BLF algorithm.
|
||||
/// </summary>
|
||||
public class PlacedPart
|
||||
{
|
||||
public int DrawingId { get; set; }
|
||||
public double Rotation { get; set; }
|
||||
public Vector Position { get; set; }
|
||||
public Drawing Drawing { get; set; }
|
||||
}
|
||||
}
|
||||
38
OpenNest.Engine/INestOptimizer.cs
Normal file
38
OpenNest.Engine/INestOptimizer.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest
|
||||
{
|
||||
/// <summary>
|
||||
/// Result of a nest optimization run.
|
||||
/// </summary>
|
||||
public class NestResult
|
||||
{
|
||||
/// <summary>
|
||||
/// The best sequence found: (drawingId, rotation, drawing) tuples in placement order.
|
||||
/// </summary>
|
||||
public List<(int drawingId, double rotation, Drawing drawing)> Sequence { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The score achieved by the best sequence.
|
||||
/// </summary>
|
||||
public FillScore Score { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Number of iterations performed.
|
||||
/// </summary>
|
||||
public int Iterations { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interface for nest optimization algorithms that search for the best
|
||||
/// part ordering and rotation to maximize plate utilization.
|
||||
/// </summary>
|
||||
public interface INestOptimizer
|
||||
{
|
||||
NestResult Optimize(List<NestItem> items, Box workArea, NfpCache cache,
|
||||
Dictionary<int, List<double>> candidateRotations,
|
||||
CancellationToken cancellation = default);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using OpenNest.Converters;
|
||||
using OpenNest.Engine.BestFit;
|
||||
using OpenNest.Geometry;
|
||||
using OpenNest.Math;
|
||||
@@ -533,5 +535,223 @@ namespace OpenNest
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mixed-part geometry-aware nesting using NFP-based collision avoidance
|
||||
/// and simulated annealing optimization.
|
||||
/// </summary>
|
||||
public List<Part> AutoNest(List<NestItem> items, CancellationToken cancellation = default)
|
||||
{
|
||||
return AutoNest(items, Plate, cancellation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mixed-part geometry-aware nesting using NFP-based collision avoidance
|
||||
/// and simulated annealing optimization.
|
||||
/// </summary>
|
||||
public static List<Part> AutoNest(List<NestItem> items, Plate plate,
|
||||
CancellationToken cancellation = default)
|
||||
{
|
||||
var workArea = plate.WorkArea();
|
||||
var halfSpacing = plate.PartSpacing / 2.0;
|
||||
var nfpCache = new NfpCache();
|
||||
var candidateRotations = new Dictionary<int, List<double>>();
|
||||
|
||||
// Extract perimeter polygons for each unique drawing.
|
||||
foreach (var item in items)
|
||||
{
|
||||
var drawing = item.Drawing;
|
||||
|
||||
if (candidateRotations.ContainsKey(drawing.Id))
|
||||
continue;
|
||||
|
||||
var perimeterPolygon = ExtractPerimeterPolygon(drawing, halfSpacing);
|
||||
|
||||
if (perimeterPolygon == null)
|
||||
{
|
||||
Debug.WriteLine($"[AutoNest] Skipping drawing '{drawing.Name}': no valid perimeter");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Compute candidate rotations for this drawing.
|
||||
var rotations = ComputeCandidateRotations(item, perimeterPolygon, workArea);
|
||||
candidateRotations[drawing.Id] = rotations;
|
||||
|
||||
// Register polygons at each candidate rotation.
|
||||
foreach (var rotation in rotations)
|
||||
{
|
||||
var rotatedPolygon = RotatePolygon(perimeterPolygon, rotation);
|
||||
nfpCache.RegisterPolygon(drawing.Id, rotation, rotatedPolygon);
|
||||
}
|
||||
}
|
||||
|
||||
if (candidateRotations.Count == 0)
|
||||
return new List<Part>();
|
||||
|
||||
// Pre-compute all NFPs.
|
||||
nfpCache.PreComputeAll();
|
||||
|
||||
Debug.WriteLine($"[AutoNest] NFP cache: {nfpCache.Count} entries for {candidateRotations.Count} drawings");
|
||||
|
||||
// Run simulated annealing optimizer.
|
||||
var optimizer = new SimulatedAnnealing();
|
||||
var result = optimizer.Optimize(items, workArea, nfpCache, candidateRotations, cancellation);
|
||||
|
||||
if (result.Sequence == null || result.Sequence.Count == 0)
|
||||
return new List<Part>();
|
||||
|
||||
// Final BLF placement with the best solution.
|
||||
var blf = new BottomLeftFill(workArea, nfpCache);
|
||||
var placedParts = blf.Fill(result.Sequence);
|
||||
var parts = BottomLeftFill.ToNestParts(placedParts);
|
||||
|
||||
Debug.WriteLine($"[AutoNest] Result: {parts.Count} parts placed, {result.Iterations} SA iterations");
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the perimeter polygon from a drawing, inflated by half-spacing.
|
||||
/// </summary>
|
||||
private static Polygon ExtractPerimeterPolygon(Drawing drawing, double halfSpacing)
|
||||
{
|
||||
var entities = ConvertProgram.ToGeometry(drawing.Program)
|
||||
.Where(e => e.Layer != SpecialLayers.Rapid)
|
||||
.ToList();
|
||||
|
||||
if (entities.Count == 0)
|
||||
return null;
|
||||
|
||||
var definedShape = new DefinedShape(entities);
|
||||
var perimeter = definedShape.Perimeter;
|
||||
|
||||
if (perimeter == null)
|
||||
return null;
|
||||
|
||||
// Inflate by half-spacing if spacing is non-zero.
|
||||
Shape inflated;
|
||||
|
||||
if (halfSpacing > 0)
|
||||
{
|
||||
var offsetEntity = perimeter.OffsetEntity(halfSpacing, OffsetSide.Right);
|
||||
inflated = offsetEntity as Shape ?? perimeter;
|
||||
}
|
||||
else
|
||||
{
|
||||
inflated = perimeter;
|
||||
}
|
||||
|
||||
// Convert to polygon with circumscribed arcs for tight nesting.
|
||||
var polygon = inflated.ToPolygonWithTolerance(0.01, circumscribe: true);
|
||||
|
||||
if (polygon.Vertices.Count < 3)
|
||||
return null;
|
||||
|
||||
// Normalize: move reference point to origin.
|
||||
polygon.UpdateBounds();
|
||||
var bb = polygon.BoundingBox;
|
||||
polygon.Offset(-bb.Left, -bb.Bottom);
|
||||
|
||||
return polygon;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes candidate rotation angles for a drawing.
|
||||
/// </summary>
|
||||
private static List<double> ComputeCandidateRotations(NestItem item,
|
||||
Polygon perimeterPolygon, Box workArea)
|
||||
{
|
||||
var rotations = new List<double> { 0 };
|
||||
|
||||
// Add hull-edge angles from the polygon itself.
|
||||
var hullAngles = ComputeHullEdgeAngles(perimeterPolygon);
|
||||
|
||||
foreach (var angle in hullAngles)
|
||||
{
|
||||
if (!rotations.Any(r => r.IsEqualTo(angle)))
|
||||
rotations.Add(angle);
|
||||
}
|
||||
|
||||
// Add 90-degree rotation.
|
||||
if (!rotations.Any(r => r.IsEqualTo(Angle.HalfPI)))
|
||||
rotations.Add(Angle.HalfPI);
|
||||
|
||||
// For narrow work areas, add sweep angles.
|
||||
var partBounds = perimeterPolygon.BoundingBox;
|
||||
var partLongest = System.Math.Max(partBounds.Width, partBounds.Height);
|
||||
var workShort = System.Math.Min(workArea.Width, workArea.Height);
|
||||
|
||||
if (workShort < partLongest)
|
||||
{
|
||||
var step = Angle.ToRadians(5);
|
||||
|
||||
for (var a = 0.0; a < System.Math.PI; a += step)
|
||||
{
|
||||
if (!rotations.Any(r => r.IsEqualTo(a)))
|
||||
rotations.Add(a);
|
||||
}
|
||||
}
|
||||
|
||||
return rotations;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes convex hull edge angles from a polygon for candidate rotations.
|
||||
/// </summary>
|
||||
private static List<double> ComputeHullEdgeAngles(Polygon polygon)
|
||||
{
|
||||
var angles = new List<double>();
|
||||
|
||||
if (polygon.Vertices.Count < 3)
|
||||
return angles;
|
||||
|
||||
var hull = ConvexHull.Compute(polygon.Vertices);
|
||||
var verts = hull.Vertices;
|
||||
var n = hull.IsClosed() ? verts.Count - 1 : verts.Count;
|
||||
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var next = (i + 1) % n;
|
||||
var dx = verts[next].X - verts[i].X;
|
||||
var dy = verts[next].Y - verts[i].Y;
|
||||
|
||||
if (dx * dx + dy * dy < Tolerance.Epsilon)
|
||||
continue;
|
||||
|
||||
var angle = -System.Math.Atan2(dy, dx);
|
||||
|
||||
if (!angles.Any(a => a.IsEqualTo(angle)))
|
||||
angles.Add(angle);
|
||||
}
|
||||
|
||||
return angles;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a rotated copy of a polygon around the origin.
|
||||
/// </summary>
|
||||
private static Polygon RotatePolygon(Polygon polygon, double angle)
|
||||
{
|
||||
if (angle.IsEqualTo(0))
|
||||
return polygon;
|
||||
|
||||
var result = new Polygon();
|
||||
var cos = System.Math.Cos(angle);
|
||||
var sin = System.Math.Sin(angle);
|
||||
|
||||
foreach (var v in polygon.Vertices)
|
||||
{
|
||||
result.Vertices.Add(new Vector(
|
||||
v.X * cos - v.Y * sin,
|
||||
v.X * sin + v.Y * cos));
|
||||
}
|
||||
|
||||
// Re-normalize to origin.
|
||||
result.UpdateBounds();
|
||||
var bb = result.BoundingBox;
|
||||
result.Offset(-bb.Left, -bb.Bottom);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
138
OpenNest.Engine/NfpCache.cs
Normal file
138
OpenNest.Engine/NfpCache.cs
Normal file
@@ -0,0 +1,138 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest
|
||||
{
|
||||
/// <summary>
|
||||
/// Caches computed No-Fit Polygons keyed by (DrawingA.Id, RotationA, DrawingB.Id, RotationB).
|
||||
/// NFPs are computed on first access and stored for reuse during optimization.
|
||||
/// Thread-safe for concurrent reads after pre-computation.
|
||||
/// </summary>
|
||||
public class NfpCache
|
||||
{
|
||||
private readonly Dictionary<NfpKey, Polygon> cache = new Dictionary<NfpKey, Polygon>();
|
||||
private readonly Dictionary<int, Dictionary<double, Polygon>> polygonCache
|
||||
= new Dictionary<int, Dictionary<double, Polygon>>();
|
||||
|
||||
/// <summary>
|
||||
/// Registers a pre-computed polygon for a drawing at a specific rotation.
|
||||
/// Call this during initialization before computing NFPs.
|
||||
/// </summary>
|
||||
public void RegisterPolygon(int drawingId, double rotation, Polygon polygon)
|
||||
{
|
||||
if (!polygonCache.TryGetValue(drawingId, out var rotations))
|
||||
{
|
||||
rotations = new Dictionary<double, Polygon>();
|
||||
polygonCache[drawingId] = rotations;
|
||||
}
|
||||
|
||||
rotations[rotation] = polygon;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the polygon for a drawing at a specific rotation.
|
||||
/// </summary>
|
||||
public Polygon GetPolygon(int drawingId, double rotation)
|
||||
{
|
||||
if (polygonCache.TryGetValue(drawingId, out var rotations))
|
||||
{
|
||||
if (rotations.TryGetValue(rotation, out var polygon))
|
||||
return polygon;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or computes the NFP between two drawings at their respective rotations.
|
||||
/// The NFP is computed from the stationary polygon (drawingA at rotationA) and
|
||||
/// the orbiting polygon (drawingB at rotationB).
|
||||
/// </summary>
|
||||
public Polygon Get(int drawingIdA, double rotationA, int drawingIdB, double rotationB)
|
||||
{
|
||||
var key = new NfpKey(drawingIdA, rotationA, drawingIdB, rotationB);
|
||||
|
||||
if (cache.TryGetValue(key, out var nfp))
|
||||
return nfp;
|
||||
|
||||
var polyA = GetPolygon(drawingIdA, rotationA);
|
||||
var polyB = GetPolygon(drawingIdB, rotationB);
|
||||
|
||||
if (polyA == null || polyB == null)
|
||||
return new Polygon();
|
||||
|
||||
nfp = NoFitPolygon.Compute(polyA, polyB);
|
||||
cache[key] = nfp;
|
||||
return nfp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pre-computes all NFPs for every combination of registered polygons.
|
||||
/// Call after all polygons are registered to front-load computation.
|
||||
/// </summary>
|
||||
public void PreComputeAll()
|
||||
{
|
||||
var entries = new List<(int drawingId, double rotation)>();
|
||||
|
||||
foreach (var kvp in polygonCache)
|
||||
{
|
||||
foreach (var rot in kvp.Value)
|
||||
entries.Add((kvp.Key, rot.Key));
|
||||
}
|
||||
|
||||
for (var i = 0; i < entries.Count; i++)
|
||||
{
|
||||
for (var j = 0; j < entries.Count; j++)
|
||||
{
|
||||
Get(entries[i].drawingId, entries[i].rotation,
|
||||
entries[j].drawingId, entries[j].rotation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Number of cached NFP entries.
|
||||
/// </summary>
|
||||
public int Count => cache.Count;
|
||||
|
||||
private readonly struct NfpKey : IEquatable<NfpKey>
|
||||
{
|
||||
public readonly int DrawingIdA;
|
||||
public readonly double RotationA;
|
||||
public readonly int DrawingIdB;
|
||||
public readonly double RotationB;
|
||||
|
||||
public NfpKey(int drawingIdA, double rotationA, int drawingIdB, double rotationB)
|
||||
{
|
||||
DrawingIdA = drawingIdA;
|
||||
RotationA = rotationA;
|
||||
DrawingIdB = drawingIdB;
|
||||
RotationB = rotationB;
|
||||
}
|
||||
|
||||
public bool Equals(NfpKey other)
|
||||
{
|
||||
return DrawingIdA == other.DrawingIdA
|
||||
&& RotationA == other.RotationA
|
||||
&& DrawingIdB == other.DrawingIdB
|
||||
&& RotationB == other.RotationB;
|
||||
}
|
||||
|
||||
public override bool Equals(object obj) => obj is NfpKey key && Equals(key);
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
unchecked
|
||||
{
|
||||
var hash = 17;
|
||||
hash = hash * 31 + DrawingIdA;
|
||||
hash = hash * 31 + RotationA.GetHashCode();
|
||||
hash = hash * 31 + DrawingIdB;
|
||||
hash = hash * 31 + RotationB.GetHashCode();
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
269
OpenNest.Engine/SimulatedAnnealing.cs
Normal file
269
OpenNest.Engine/SimulatedAnnealing.cs
Normal file
@@ -0,0 +1,269 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest
|
||||
{
|
||||
/// <summary>
|
||||
/// Simulated annealing optimizer for NFP-based nesting.
|
||||
/// Searches for the best part ordering and rotation to maximize plate utilization.
|
||||
/// </summary>
|
||||
public class SimulatedAnnealing : INestOptimizer
|
||||
{
|
||||
private const double DefaultCoolingRate = 0.997;
|
||||
private const double DefaultMinTemperature = 0.01;
|
||||
private const int DefaultMaxNoImprovement = 2000;
|
||||
|
||||
public NestResult Optimize(List<NestItem> items, Box workArea, NfpCache cache,
|
||||
Dictionary<int, List<double>> candidateRotations,
|
||||
CancellationToken cancellation = default)
|
||||
{
|
||||
var random = new Random();
|
||||
|
||||
// Build initial sequence: expand NestItems into individual (drawingId, rotation, drawing) entries,
|
||||
// sorted by area descending.
|
||||
var sequence = BuildInitialSequence(items, candidateRotations);
|
||||
|
||||
if (sequence.Count == 0)
|
||||
return new NestResult { Sequence = sequence, Score = default, Iterations = 0 };
|
||||
|
||||
// Evaluate initial solution.
|
||||
var blf = new BottomLeftFill(workArea, cache);
|
||||
var bestPlaced = blf.Fill(sequence);
|
||||
var bestScore = FillScore.Compute(BottomLeftFill.ToNestParts(bestPlaced), workArea);
|
||||
var bestSequence = new List<(int, double, Drawing)>(sequence);
|
||||
|
||||
var currentSequence = new List<(int, double, Drawing)>(sequence);
|
||||
var currentScore = bestScore;
|
||||
|
||||
// Calibrate initial temperature so ~80% of worse moves are accepted.
|
||||
var initialTemp = CalibrateTemperature(currentSequence, workArea, cache,
|
||||
candidateRotations, random);
|
||||
var temperature = initialTemp;
|
||||
var noImprovement = 0;
|
||||
var iteration = 0;
|
||||
|
||||
Debug.WriteLine($"[SA] Initial: {bestScore.Count} parts, density={bestScore.Density:P1}, temp={initialTemp:F2}");
|
||||
|
||||
while (temperature > DefaultMinTemperature
|
||||
&& noImprovement < DefaultMaxNoImprovement
|
||||
&& !cancellation.IsCancellationRequested)
|
||||
{
|
||||
iteration++;
|
||||
|
||||
var candidate = new List<(int drawingId, double rotation, Drawing drawing)>(currentSequence);
|
||||
Mutate(candidate, candidateRotations, random);
|
||||
|
||||
var candidatePlaced = blf.Fill(candidate);
|
||||
var candidateScore = FillScore.Compute(BottomLeftFill.ToNestParts(candidatePlaced), workArea);
|
||||
|
||||
var delta = candidateScore.CompareTo(currentScore);
|
||||
|
||||
if (delta > 0)
|
||||
{
|
||||
// Better solution — always accept.
|
||||
currentSequence = candidate;
|
||||
currentScore = candidateScore;
|
||||
|
||||
if (currentScore > bestScore)
|
||||
{
|
||||
bestScore = currentScore;
|
||||
bestSequence = new List<(int, double, Drawing)>(currentSequence);
|
||||
noImprovement = 0;
|
||||
|
||||
Debug.WriteLine($"[SA] New best at iter {iteration}: {bestScore.Count} parts, density={bestScore.Density:P1}");
|
||||
}
|
||||
else
|
||||
{
|
||||
noImprovement++;
|
||||
}
|
||||
}
|
||||
else if (delta < 0)
|
||||
{
|
||||
// Worse solution — accept with probability based on temperature.
|
||||
var scoreDiff = ScoreDifference(currentScore, candidateScore);
|
||||
var acceptProb = System.Math.Exp(-scoreDiff / temperature);
|
||||
|
||||
if (random.NextDouble() < acceptProb)
|
||||
{
|
||||
currentSequence = candidate;
|
||||
currentScore = candidateScore;
|
||||
}
|
||||
|
||||
noImprovement++;
|
||||
}
|
||||
else
|
||||
{
|
||||
noImprovement++;
|
||||
}
|
||||
|
||||
temperature *= DefaultCoolingRate;
|
||||
}
|
||||
|
||||
Debug.WriteLine($"[SA] Done: {iteration} iters, best={bestScore.Count} parts, density={bestScore.Density:P1}");
|
||||
|
||||
return new NestResult
|
||||
{
|
||||
Sequence = bestSequence,
|
||||
Score = bestScore,
|
||||
Iterations = iteration
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the initial placement sequence sorted by drawing area descending.
|
||||
/// Each NestItem is expanded by its quantity.
|
||||
/// </summary>
|
||||
private static List<(int drawingId, double rotation, Drawing drawing)> BuildInitialSequence(
|
||||
List<NestItem> items, Dictionary<int, List<double>> candidateRotations)
|
||||
{
|
||||
var sequence = new List<(int drawingId, double rotation, Drawing drawing)>();
|
||||
|
||||
// Sort items by area descending.
|
||||
var sorted = items.OrderByDescending(i => i.Drawing.Area).ToList();
|
||||
|
||||
foreach (var item in sorted)
|
||||
{
|
||||
var qty = item.Quantity > 0 ? item.Quantity : 1;
|
||||
var rotation = 0.0;
|
||||
|
||||
if (candidateRotations.TryGetValue(item.Drawing.Id, out var rotations) && rotations.Count > 0)
|
||||
rotation = rotations[0];
|
||||
|
||||
for (var i = 0; i < qty; i++)
|
||||
sequence.Add((item.Drawing.Id, rotation, item.Drawing));
|
||||
}
|
||||
|
||||
return sequence;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a random mutation to the sequence.
|
||||
/// </summary>
|
||||
private static void Mutate(List<(int drawingId, double rotation, Drawing drawing)> sequence,
|
||||
Dictionary<int, List<double>> candidateRotations, Random random)
|
||||
{
|
||||
if (sequence.Count < 2)
|
||||
return;
|
||||
|
||||
var op = random.Next(3);
|
||||
|
||||
switch (op)
|
||||
{
|
||||
case 0: // Swap
|
||||
MutateSwap(sequence, random);
|
||||
break;
|
||||
case 1: // Rotate
|
||||
MutateRotate(sequence, candidateRotations, random);
|
||||
break;
|
||||
case 2: // Segment reverse
|
||||
MutateReverse(sequence, random);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Swaps two random parts in the sequence.
|
||||
/// </summary>
|
||||
private static void MutateSwap(List<(int, double, Drawing)> sequence, Random random)
|
||||
{
|
||||
var i = random.Next(sequence.Count);
|
||||
var j = random.Next(sequence.Count);
|
||||
|
||||
while (j == i && sequence.Count > 1)
|
||||
j = random.Next(sequence.Count);
|
||||
|
||||
(sequence[i], sequence[j]) = (sequence[j], sequence[i]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes a random part's rotation to another candidate angle.
|
||||
/// </summary>
|
||||
private static void MutateRotate(List<(int drawingId, double rotation, Drawing drawing)> sequence,
|
||||
Dictionary<int, List<double>> candidateRotations, Random random)
|
||||
{
|
||||
var idx = random.Next(sequence.Count);
|
||||
var entry = sequence[idx];
|
||||
|
||||
if (!candidateRotations.TryGetValue(entry.drawingId, out var rotations) || rotations.Count <= 1)
|
||||
return;
|
||||
|
||||
var newRotation = rotations[random.Next(rotations.Count)];
|
||||
sequence[idx] = (entry.drawingId, newRotation, entry.drawing);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reverses a random contiguous subsequence.
|
||||
/// </summary>
|
||||
private static void MutateReverse(List<(int, double, Drawing)> sequence, Random random)
|
||||
{
|
||||
var i = random.Next(sequence.Count);
|
||||
var j = random.Next(sequence.Count);
|
||||
|
||||
if (i > j)
|
||||
(i, j) = (j, i);
|
||||
|
||||
while (i < j)
|
||||
{
|
||||
(sequence[i], sequence[j]) = (sequence[j], sequence[i]);
|
||||
i++;
|
||||
j--;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calibrates the initial temperature by sampling random mutations and
|
||||
/// measuring score differences. Sets temperature so ~80% of worse moves
|
||||
/// are accepted initially.
|
||||
/// </summary>
|
||||
private static double CalibrateTemperature(
|
||||
List<(int drawingId, double rotation, Drawing drawing)> sequence,
|
||||
Box workArea, NfpCache cache,
|
||||
Dictionary<int, List<double>> candidateRotations, Random random)
|
||||
{
|
||||
const int samples = 20;
|
||||
var deltas = new List<double>();
|
||||
var blf = new BottomLeftFill(workArea, cache);
|
||||
|
||||
var basePlaced = blf.Fill(sequence);
|
||||
var baseScore = FillScore.Compute(BottomLeftFill.ToNestParts(basePlaced), workArea);
|
||||
|
||||
for (var i = 0; i < samples; i++)
|
||||
{
|
||||
var candidate = new List<(int, double, Drawing)>(sequence);
|
||||
Mutate(candidate, candidateRotations, random);
|
||||
|
||||
var placed = blf.Fill(candidate);
|
||||
var score = FillScore.Compute(BottomLeftFill.ToNestParts(placed), workArea);
|
||||
|
||||
var diff = ScoreDifference(baseScore, score);
|
||||
|
||||
if (diff > 0)
|
||||
deltas.Add(diff);
|
||||
}
|
||||
|
||||
if (deltas.Count == 0)
|
||||
return 1.0;
|
||||
|
||||
// T = -avgDelta / ln(0.8) ≈ avgDelta * 4.48
|
||||
var avgDelta = deltas.Average();
|
||||
return -avgDelta / System.Math.Log(0.8);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes a numeric difference between two scores for SA acceptance probability.
|
||||
/// Uses a weighted combination of count and density.
|
||||
/// </summary>
|
||||
private static double ScoreDifference(FillScore better, FillScore worse)
|
||||
{
|
||||
// Weight count heavily (each part is worth 10 density points).
|
||||
var countDiff = better.Count - worse.Count;
|
||||
var densityDiff = better.Density - worse.Density;
|
||||
|
||||
return countDiff * 10.0 + densityDiff;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user