mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-05 05:59:25 -05:00
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>
152 lines
7.6 KiB
C#
152 lines
7.6 KiB
C#
#nullable enable
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading;
|
|
using OpenNest.CNC.CuttingPlanning;
|
|
using OpenNest.Geometry;
|
|
|
|
namespace OpenNest.Engine.CuttingPlanning;
|
|
|
|
/// <summary>The three verdicts a candidate entry can receive from the shared lead validator.</summary>
|
|
public enum ContourFeasibilityStatus
|
|
{
|
|
/// <summary>Every emitted lead of this contour is complete AND clear.</summary>
|
|
Clear,
|
|
|
|
/// <summary>A complete check found a lead contact/overlap — the reason is preserved.</summary>
|
|
Blocked,
|
|
|
|
/// <summary>The check could not complete (incomplete material, malformed emission) — never clear.</summary>
|
|
Incomplete,
|
|
}
|
|
|
|
/// <summary>Verdict for one candidate entry. Complete/blocked/incomplete stay distinct.</summary>
|
|
public sealed record ContourFeasibilityVerdict(ContourFeasibilityStatus Status, string? Reason)
|
|
{
|
|
public bool IsClear => Status == ContourFeasibilityStatus.Clear;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Feasibility adapter over the EXISTING <see cref="LeadPathValidator"/>: emits one owned
|
|
/// candidate contour through the S06 diagnostic seam, reads it at the placement position,
|
|
/// and certifies the emitted lead-in and lead-out against ALL placed material. It is not a
|
|
/// new collision implementation and not a plan approval: a Clear verdict certifies this
|
|
/// contour's emitted leads only — NoLeadIn is supported, and the complete plan must
|
|
/// still pass rapid travel and contour-accounting checks. A
|
|
/// candidate rejected here is not proven infeasible by anything else: this adapter only
|
|
/// reports what the validator reported.
|
|
/// One instance is one captured planning attempt: verdicts cache per exact choice and node
|
|
/// context for the instance's lifetime — settings and placement are fixed per instance —
|
|
/// and nothing is cached across instances or statically. Evaluation is lazy: only the
|
|
/// choice handed to <see cref="Check"/> is ever emitted or validated, and
|
|
/// <see cref="EvaluationCount"/> counts validator executions (not cache hits) for cost tests.
|
|
/// </summary>
|
|
public sealed class ContourEntryFeasibility
|
|
{
|
|
private readonly PreparedContours prepared;
|
|
private readonly Vector location;
|
|
private readonly LeadMaterialSnapshot ownMaterial;
|
|
private readonly IReadOnlyList<LeadMaterialSnapshot> materials;
|
|
private readonly Dictionary<Key, ContourFeasibilityVerdict> cache = new();
|
|
private readonly LeadContactMemo? leadContacts;
|
|
|
|
public ContourEntryFeasibility(PreparedContours prepared, Vector location,
|
|
LeadMaterialSnapshot ownMaterial, IReadOnlyList<LeadMaterialSnapshot> otherMaterials)
|
|
: this(prepared, location, ownMaterial, otherMaterials, null)
|
|
{
|
|
}
|
|
|
|
/// <param name="leadContacts">Shares exact lead/material results with the caller's search.</param>
|
|
internal ContourEntryFeasibility(PreparedContours prepared, Vector location,
|
|
LeadMaterialSnapshot ownMaterial, IReadOnlyList<LeadMaterialSnapshot> otherMaterials,
|
|
LeadContactMemo? leadContacts)
|
|
{
|
|
this.leadContacts = leadContacts;
|
|
this.prepared = prepared ?? throw new ArgumentException("Prepared contours are required.", nameof(prepared));
|
|
this.ownMaterial = ownMaterial ?? throw new ArgumentException("Own material snapshot is required.", nameof(ownMaterial));
|
|
if (otherMaterials == null)
|
|
throw new ArgumentException("Placed-material snapshots are required.", nameof(otherMaterials));
|
|
this.location = location;
|
|
if (otherMaterials is LeadMaterialSet set)
|
|
{
|
|
if (set.HasNull)
|
|
throw new ArgumentException("Placed-material snapshots must not be null.", nameof(otherMaterials));
|
|
// Already immutable and shared by the search's adapters. The validator passes over the
|
|
// own material by reference and visits the others in their order, as in the copy below.
|
|
materials = set;
|
|
return;
|
|
}
|
|
// Immutable copy; the validator's own-material-first convention is preserved.
|
|
var all = new List<LeadMaterialSnapshot> { this.ownMaterial };
|
|
foreach (var material in otherMaterials)
|
|
{
|
|
if (material == null)
|
|
throw new ArgumentException("Placed-material snapshots must not be null.", nameof(otherMaterials));
|
|
if (!ReferenceEquals(material, this.ownMaterial))
|
|
all.Add(material);
|
|
}
|
|
materials = all.ToArray();
|
|
}
|
|
|
|
/// <summary>Validator executions performed (cache misses only) during this attempt.</summary>
|
|
public int EvaluationCount { get; private set; }
|
|
|
|
/// <summary>
|
|
/// The verdict for one owned candidate. Same choice + node context within this attempt
|
|
/// is answered from cache. Cancellation propagates; a malformed emission is an
|
|
/// Incomplete verdict with the emission's own reason, never a crash and never Clear.
|
|
/// </summary>
|
|
public ContourFeasibilityVerdict Check(ContourChoice choice, string nodeContext = "",
|
|
CancellationToken token = default)
|
|
{
|
|
token.ThrowIfCancellationRequested();
|
|
if (choice == null)
|
|
throw new ArgumentException("A contour choice is required.", nameof(choice));
|
|
// Ownership is an input boundary, not part of a memoized geometric verdict.
|
|
// Reject before lookup so neither a warm hit nor a foreign first call can
|
|
// substitute for the isolated emitter's owned-choice check.
|
|
if (!ReferenceEquals(choice.Owner, prepared))
|
|
return new(ContourFeasibilityStatus.Incomplete, "Foreign contour choice.");
|
|
// A drawing pin's entry is a fixed emission, accepted as given: it is never filtered
|
|
// out here. The emitted program's checks report its violations as warnings.
|
|
// A forged ordinal falls through to the probe, which refuses it as Incomplete.
|
|
if (choice.ContourOrdinal >= 0 && choice.ContourOrdinal < prepared.Count
|
|
&& prepared.PinnedEntry(choice.ContourOrdinal) == choice)
|
|
return new(ContourFeasibilityStatus.Clear, null);
|
|
var key = new Key(choice.ContourOrdinal, choice.EntityOrdinal,
|
|
choice.Point.X, choice.Point.Y, choice.Pierce?.X, choice.Pierce?.Y, nodeContext ?? string.Empty);
|
|
if (cache.TryGetValue(key, out var known))
|
|
return known;
|
|
var verdict = Probe(choice, token);
|
|
cache[key] = verdict;
|
|
EvaluationCount++;
|
|
return verdict;
|
|
}
|
|
|
|
private ContourFeasibilityVerdict Probe(ContourChoice choice, CancellationToken token)
|
|
{
|
|
try
|
|
{
|
|
var program = prepared.EmitCandidateForValidation(choice);
|
|
var execution = ExecutionMotionReader.Read(program, location, null, token);
|
|
var result = leadContacts == null
|
|
? LeadPathValidator.Check(execution, ownMaterial, materials, prepared.PierceZoneRadius, token)
|
|
: LeadPathValidator.Check(execution, ownMaterial, materials, leadContacts, token,
|
|
prepared.PierceZoneRadius);
|
|
if (!result.IsComplete)
|
|
return new(ContourFeasibilityStatus.Incomplete, result.Reason);
|
|
return result.IsClear
|
|
? new(ContourFeasibilityStatus.Clear, null)
|
|
: new(ContourFeasibilityStatus.Blocked, result.Reason);
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or NotSupportedException)
|
|
{
|
|
// Malformed emission or foreign choice: refused, reason preserved, never cached as clear.
|
|
return new(ContourFeasibilityStatus.Incomplete, ex.Message);
|
|
}
|
|
}
|
|
|
|
private readonly record struct Key(int ContourOrdinal, int EntityOrdinal, double X, double Y,
|
|
double? PierceX, double? PierceY, string NodeContext);
|
|
}
|