Files
OpenNest/OpenNest.Tests/CuttingPlanning/ExtentGridTests.cs
T
ajandClaude Opus 5.5 b97929a53d perf(planner): skip far parts on large plates without changing the plan
The 5k-washers corpus plate planned in about 90 s alone and timed out at the
corpus's 120 s limit whenever anything else ran, making the corpus fragile.
Profiling showed nearly all of it was linear scans over every part, repeated
per candidate: each lead check walked all 5,742 materials (and first re-tested
that all were complete), each rapid walked every completed contour, each
expansion rebuilt a HashSet of every cut part, each checker copy regrew its
obstacle list, and the nested-part search tested all 33 million part pairs.

A uniform grid over extents (ExtentGrid) now leaves out only parts whose
extents lie beyond the margin the existing skip tests use, and the rest are
visited in their original order, so every check returns exactly what the full
scan returned (same findings, same first obstacle, same budget charges):
- LeadPathValidator visits only materials not clear of the lead's queries or
  its midpoint's row, through a shared LeadMaterialSet built once per walk and
  replay; ContourEntryFeasibility reuses that set instead of copying it per part.
- ReleasedContourState keeps a read-only obstacle prefix with a grid, shared by
  copies, so copies stay cheap and rapids test only nearby contours.
- The search keeps one ordinal flag array per order instead of a HashSet per call.
- CuttingDependencyGraph tests each part only against hosts whose bounds can hold it.

Plate 1 alone: 93.3 s -> 12.3 s (capture 2.7 -> 1.2 s, plan 90.6 -> 11.1 s),
with the identical plan digest and 86,245 expansions; plate 2 also plans
identically. The problem-nest corpus (part-order,entries) gives every plate the
same outcome and expansion count as master, and the Collision kernel and every
tolerance are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:58:28 -05:00

127 lines
6.0 KiB
C#

using OpenNest.CNC;
using OpenNest.CNC.CuttingPlanning;
using OpenNest.Diagnostics;
using OpenNest.Geometry;
using Extent = OpenNest.Diagnostics.PostVerificationGeometry.Extent;
namespace OpenNest.Tests.CuttingPlanning;
/// <summary>
/// Large plates skip far parts through <see cref="ExtentGrid"/>: the lead check, the rapid check
/// and the nested-part search. Each must give exactly what testing every part gives.
/// </summary>
public class ExtentGridTests
{
[Fact]
public void Near_LeavesOutOnlyExtentsBeyondTheMargin()
{
var random = new Random(7);
var extents = Enumerable.Range(0, 500).Select(i => i % 97 == 0
? new Extent(double.NaN, 0, 1, 1) // Not well conditioned: always returned.
: Box(random, 100)).ToArray();
var grid = new ExtentGrid(extents);
for (var trial = 0; trial < 500; trial++)
{
var query = Box(random, 110);
var margin = random.NextDouble() * (trial % 3);
var near = grid.Near(query, margin);
Assert.Equal(near.Distinct().Order(), near);
for (var i = 0; i < extents.Length; i++)
if (!near.Contains(i))
Assert.True(extents[i].IsWellConditioned && Apart(extents[i], query, margin), $"Extent {i} left out.");
var rows = grid.InRows(query.MinY, query.MaxY, margin);
for (var i = 0; i < extents.Length; i++)
if (!rows.Contains(i))
Assert.True(extents[i].IsWellConditioned
&& (extents[i].MaxY + margin < query.MinY || query.MaxY + margin < extents[i].MinY), $"Row {i} left out.");
}
}
[Fact]
public void Near_EmptyOrDegenerateGrids()
{
Assert.Empty(new ExtentGrid([]).Near(new Extent(0, 0, 1, 1), 0));
var line = new ExtentGrid([new Extent(2, 0, 2, 5), new Extent(2, 7, 2, 9)]);
Assert.Equal([0, 1], line.Near(new Extent(2, 4, 2, 8), 0));
Assert.Empty(line.Near(new Extent(4, 0, 5, 9), 0.5));
}
[Theory]
[InlineData(0)]
[InlineData(0.3)]
public void LeadCheck_AgreesWithTheFullScan(double pierceRadius)
{
// 900 squares, so the set's grid has many cells; leads of random length and direction
// enter squares across the grid, some reaching their neighbors.
var squares = new List<(double X, double Y, LeadMaterialSnapshot Material)>();
for (var row = 0; row < 30; row++)
for (var column = 0; column < 30; column++)
{
var (x, y) = (column * 1.5, row * 1.5);
squares.Add((x, y, LeadMaterialSnapshot.Capture(LeadPathValidationTests.Rectangle(x, y, x + 1, y + 1), Vector.Zero)));
}
var all = squares.Select(s => s.Material).ToArray();
var set = new LeadMaterialSet(all);
var random = new Random(11);
var outcomes = new HashSet<bool>();
for (var trial = 0; trial < 400; trial++)
{
var (x, y, target) = squares[random.Next(squares.Count)];
var angle = System.Math.PI / 2 + random.NextDouble() * System.Math.PI;
var length = 0.1 + random.NextDouble() * 2;
var program = new Program();
program.MoveTo(x + length * System.Math.Cos(angle), y + 0.5 + length * System.Math.Sin(angle));
program.Codes.Add(new LinearMove(x, y + 0.5) { Layer = LayerType.Leadin });
program.LineTo(x, y + 1); program.LineTo(x + 1, y + 1); program.LineTo(x + 1, y);
program.LineTo(x, y); program.LineTo(x, y + 0.5);
var execution = ExecutionMotionReader.Read(program, Vector.Zero, null, default);
var full = LeadPathValidator.Check(execution, target, all, pierceRadius);
var indexed = LeadPathValidator.Check(execution, target, set, pierceRadius);
Assert.Equal(full, indexed);
outcomes.Add(full.IsClear);
}
Assert.Equal([false, true], outcomes.Order());
}
[Fact]
public void RapidCheck_FindsTheSameCrossingsInObstacleOrder_InCopiesToo()
{
// 400 cut squares put most obstacles in the shared grid; copies taken along the way
// must judge rapids just as a state that checked everything itself.
var state = new ReleasedContourState(reportMissingLeadIns: false);
ReleasedContourState copy = null;
var part = 0;
for (var row = 0; row < 20; row++)
for (var column = 0; column < 20; column++)
{
var (x, y) = (column * 2.0, row * 2.0);
var square = ExecutionMotionReader.Read(LeadPathValidationTests.Rectangle(x, y, x + 1, y + 1), Vector.Zero, null, default);
part++;
// A short rapid in from the gap below-left, so every square checks one.
var arrival = new Vector(x - 0.5, y - 0.5);
Assert.Empty(state.Check(square, arrival, part));
if (part == 250)
copy = state.Copy();
else if (part > 250)
Assert.Empty(copy.Check(square, arrival, part));
}
// Up column 0 from below the sheet to a square above it: it crosses parts 1, 21, ..., 381.
var probe = ExecutionMotionReader.Read(LeadPathValidationTests.Rectangle(0.5, 45, 1, 46), Vector.Zero, null, default);
var expected = Enumerable.Range(0, 20).Select(r => r * 20 + 1).ToArray();
Assert.Equal(expected, state.Check(probe, new Vector(0.5, -1), 401).Select(f => f.OtherPartNumber ?? 0));
Assert.Equal(expected, copy.Check(probe, new Vector(0.5, -1), 401).Select(f => f.OtherPartNumber ?? 0));
}
private static Extent Box(Random random, double size)
{
var (x, y) = (random.NextDouble() * size, random.NextDouble() * size);
return new Extent(x, y, x + random.NextDouble() * 5, y + random.NextDouble() * 5);
}
private static bool Apart(Extent a, Extent b, double margin) =>
a.MaxX + margin < b.MinX || b.MaxX + margin < a.MinX || a.MaxY + margin < b.MinY || b.MaxY + margin < a.MinY;
}