Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add CIR-T6 snap selection gate with analytic candidate routing
Yuechen Li35d555197544
diff --git a/Aetheris.Kernel.Firmament.Tests/RestrictedContourSnapSelectionTests.cs b/Aetheris.Kernel.Firmament.Tests/RestrictedContourSnapSelectionTests.csnew file mode 100644index 00000000..5b8aeb2c--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/RestrictedContourSnapSelectionTests.cs@@ -0,0 +1,103 @@+using Aetheris.Kernel.Core.Cir;+using Aetheris.Kernel.Firmament.Execution;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class RestrictedContourSnapSelectionTests+{+ [Fact]+ public void SnapSelection_BoxFaceVsCylinder_SelectsCircleCandidate()+ {+ var stitched = BuildStitched(new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirCylinderNode(2, 20)), 65);+ var options = new RestrictedContourSnapOptions(0.06d, 0.02d, 8);+ var analysis = RestrictedContourSnapAnalyzer.Analyze(stitched, options);+ var selected = RestrictedContourSnapSelector.Select(stitched, analysis, options);++ Assert.Equal(RestrictedContourSnapRouteKind.AnalyticCircle, selected.SelectedRoute);+ Assert.True(selected.AcceptedAnalyticCandidate);+ Assert.Equal(RestrictedContourExportCapability.ElementaryCurveCandidate, selected.ExportCapability);+ Assert.False(selected.BRepTopologyImplemented);+ Assert.False(selected.StepExportImplemented);+ }++ [Fact]+ public void SnapSelection_BoxFaceVsSphere_SelectsCircleCandidate()+ {+ var stitched = BuildStitched(new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirSphereNode(6)), 65);+ var options = new RestrictedContourSnapOptions(0.06d, 0.02d, 8);+ var selected = RestrictedContourSnapSelector.Select(stitched, RestrictedContourSnapAnalyzer.Analyze(stitched, options), options);+ Assert.Equal(RestrictedContourSnapRouteKind.AnalyticCircle, selected.SelectedRoute);+ Assert.True(selected.AcceptedAnalyticCandidate);+ }++ [Fact]+ public void SnapSelection_OpenBoundaryLine_SelectsLineOrDefersPrecisely()+ {+ var segA = new SurfaceTrimContourSegment2D(0, 0, new(0d, 0.25d), new(0.2d, 0.3d), RestrictedFieldCellClassification.Mixed, []);+ var segB = new SurfaceTrimContourSegment2D(1, 0, new(0.2d, 0.3d), new(0.4d, 0.35d), RestrictedFieldCellClassification.Mixed, []);+ var stitched = SurfaceTrimContourStitcher.Stitch(new SurfaceTrimContourExtractionResult(true, RestrictedFieldContourExtractionMethod.MarchingSquares, 2, [segA, segB], []));+ var options = new RestrictedContourSnapOptions(0.02d, 0.05d, 3);+ var selected = RestrictedContourSnapSelector.Select(stitched, RestrictedContourSnapAnalyzer.Analyze(stitched, options), options);++ Assert.True(selected.SelectedRoute is RestrictedContourSnapRouteKind.AnalyticLine or RestrictedContourSnapRouteKind.NumericalOnly);+ if (selected.SelectedRoute != RestrictedContourSnapRouteKind.AnalyticLine)+ {+ Assert.Contains(selected.Diagnostics, d => d.Contains("numerical-only", StringComparison.Ordinal));+ }+ }++ [Fact]+ public void SnapSelection_Torus_DoesNotClaimGenericExactness()+ {+ var stitched = BuildStitched(new CirSubtractNode(new CirBoxNode(12, 12, 12), new CirTorusNode(4, 1)), 65);+ var options = new RestrictedContourSnapOptions(0.01d, 0.01d, 8);+ var selected = RestrictedContourSnapSelector.Select(stitched, RestrictedContourSnapAnalyzer.Analyze(stitched, options), options);+ Assert.Contains(selected.Diagnostics, d => d == "snap-selection-torus-generic-exactness-not-implied");+ Assert.False(selected.BRepTopologyImplemented);+ Assert.False(selected.StepExportImplemented);+ }++ [Fact]+ public void SnapSelection_RejectedHighError_FallsBackNumericalOnlyOrDeferred()+ {+ var candidate = new RestrictedContourSnapCandidate(0, RestrictedContourSnapKind.Circle, RestrictedContourSnapStatus.Rejected, null, 0.2d, 0.1d, 10, ["high-error"]);+ var chain = new SurfaceTrimContourChain2D(0, SurfaceTrimContourChainStatus.ClosedLoop, [new SurfaceTrimContourChainPoint2D(0,0,0,"A"), new SurfaceTrimContourChainPoint2D(1,1,0,"B")], [0], true, false, [], "k");+ var stitched = new SurfaceTrimContourStitchResult(true, [chain], 1, 0, 0, 0, 0, []);+ var analysis = new RestrictedContourSnapAnalysisResult(true, [candidate], []);+ var selected = RestrictedContourSnapSelector.Select(stitched, analysis, new RestrictedContourSnapOptions(0.01d, 0.01d, 2));+ Assert.Equal(RestrictedContourSnapRouteKind.NumericalOnly, selected.SelectedRoute);+ Assert.False(selected.AcceptedAnalyticCandidate);+ }++ [Fact]+ public void SnapSelection_DeterministicTieBreak()+ {+ var chain = new SurfaceTrimContourChain2D(0, SurfaceTrimContourChainStatus.ClosedLoop, [new SurfaceTrimContourChainPoint2D(0,0,0,"A"), new SurfaceTrimContourChainPoint2D(1,0,0,"B"), new SurfaceTrimContourChainPoint2D(0,0,0,"A")], [0], true, false, [], "k");+ var stitched = new SurfaceTrimContourStitchResult(true, [chain], 1, 0, 0, 0, 0, []);+ var circle = new RestrictedContourSnapCandidate(0, RestrictedContourSnapKind.Circle, RestrictedContourSnapStatus.Candidate, new CircleSnapParameters2D(0,0,1), 0.001d, 0.001d, 9, []);+ var line = new RestrictedContourSnapCandidate(0, RestrictedContourSnapKind.Line, RestrictedContourSnapStatus.Candidate, new LineSnapParameters2D(0,0,1,0), 0.001d, 0.001d, 9, []);+ var analysis = new RestrictedContourSnapAnalysisResult(true, [circle, line], []);+ var selected = RestrictedContourSnapSelector.Select(stitched, analysis, new RestrictedContourSnapOptions(0.01d, 0.01d, 8));+ Assert.Equal(RestrictedContourSnapRouteKind.AnalyticCircle, selected.SelectedRoute);+ }++ [Fact]+ public void SnapSelection_CandidateTracesIncludeRejectedReasons()+ {+ var chain = new SurfaceTrimContourChain2D(0, SurfaceTrimContourChainStatus.OpenChain, [new SurfaceTrimContourChainPoint2D(0,0,0,"A"), new SurfaceTrimContourChainPoint2D(0.1,0.3,0,"B")], [0], false, false, [], "k");+ var stitched = new SurfaceTrimContourStitchResult(true, [chain], 0, 1, 0, 0, 0, []);+ var circle = new RestrictedContourSnapCandidate(0, RestrictedContourSnapKind.Circle, RestrictedContourSnapStatus.Rejected, null, 0.2d, 0.1d, 2, ["bad-circle"]);+ var analysis = new RestrictedContourSnapAnalysisResult(true, [circle], []);+ var selected = RestrictedContourSnapSelector.Select(stitched, analysis, new RestrictedContourSnapOptions(0.01d, 0.01d, 2));+ Assert.Contains(selected.CandidateTraces, t => !t.Admissible && !string.IsNullOrWhiteSpace(t.RejectionReason));+ }++ private static SurfaceTrimContourStitchResult BuildStitched(CirSubtractNode root, int resolution)+ {+ var source = Assert.Single(SourceSurfaceExtractor.Extract(root.Left).Descriptors.Where(d => d.ParameterPayloadReference == "top"));+ var field = SurfaceRestrictedFieldFactory.ForSubtractSource(root, source, SubtractOperandSide.Left);+ var grid = RestrictedFieldGridSampler.Sample(field, new RestrictedFieldGridOptions(resolution, resolution));+ var extraction = RestrictedFieldMarchingSquaresExtractor.Extract(grid, field.Parameterization);+ return SurfaceTrimContourStitcher.Stitch(extraction);+ }+}diff --git a/Aetheris.Kernel.Firmament/Execution/RestrictedContourSnapSelector.cs b/Aetheris.Kernel.Firmament/Execution/RestrictedContourSnapSelector.csnew file mode 100644index 00000000..06a00f4b--- /dev/null+++ b/Aetheris.Kernel.Firmament/Execution/RestrictedContourSnapSelector.cs@@ -0,0 +1,258 @@+using Aetheris.Kernel.Core.Judgment;++namespace Aetheris.Kernel.Firmament.Execution;++internal enum RestrictedContourSnapRouteKind+{+ AnalyticCircle,+ AnalyticLine,+ NumericalOnly,+ Deferred,+ Unsupported,+}++internal enum RestrictedContourExportCapability+{+ ElementaryCurveCandidate,+ NumericalOnlyNotExportable,+ Deferred,+ Unsupported,+}++internal sealed record RestrictedContourSnapSelectionCandidate(+ RestrictedContourSnapRouteKind RouteKind,+ RestrictedContourSnapKind CandidateKind,+ bool Admissible,+ double Score,+ string RejectionReason,+ IReadOnlyList<string> Diagnostics);++internal sealed record RestrictedContourSnapSelectionResult(+ bool Success,+ RestrictedContourSnapRouteKind SelectedRoute,+ RestrictedContourSnapCandidate? SelectedCandidate,+ bool AcceptedAnalyticCandidate,+ RestrictedContourExportCapability ExportCapability,+ IReadOnlyList<RestrictedContourSnapSelectionCandidate> CandidateTraces,+ IReadOnlyList<string> Diagnostics,+ bool BRepTopologyImplemented = false,+ bool StepExportImplemented = false);++internal static class RestrictedContourSnapSelector+{+ private sealed record SelectionContext(+ SurfaceTrimContourChain2D Chain,+ IReadOnlyList<RestrictedContourSnapCandidate> Candidates,+ RestrictedContourSnapOptions Options,+ bool PreferCircle,+ bool PreferLine);++ private static readonly JudgmentEngine<SelectionContext> Engine = new();++ internal static RestrictedContourSnapSelectionResult Select(+ SurfaceTrimContourStitchResult stitchResult,+ RestrictedContourSnapAnalysisResult analysis,+ RestrictedContourSnapOptions? options = null)+ {+ ArgumentNullException.ThrowIfNull(stitchResult);+ ArgumentNullException.ThrowIfNull(analysis);+ var opts = options ?? RestrictedContourSnapOptions.ConservativeDefaults;++ var traces = new List<RestrictedContourSnapSelectionCandidate>();+ var diagnostics = new List<string>+ {+ "snap-selection-started",+ $"snap-selection-chain-count:{stitchResult.Chains.Count}",+ $"snap-selection-candidate-count:{analysis.Candidates.Count}",+ };++ var selected = new List<(SurfaceTrimContourChain2D Chain, RestrictedContourSnapCandidate Candidate, RestrictedContourSnapRouteKind Route, double Score)>();+ foreach (var chain in stitchResult.Chains.OrderBy(c => c.ChainId))+ {+ var chainCandidates = analysis.Candidates.Where(c => c.ChainId == chain.ChainId).ToArray();+ if (chainCandidates.Length == 0)+ {+ diagnostics.Add($"snap-selection-chain-no-candidates:{chain.ChainId}");+ continue;+ }++ var ctx = new SelectionContext(+ chain,+ chainCandidates,+ opts,+ chain.Status == SurfaceTrimContourChainStatus.ClosedLoop || chain.Closed,+ chain.Status is SurfaceTrimContourChainStatus.OpenChain or SurfaceTrimContourChainStatus.BoundaryTouching || chain.BoundaryTouching);++ var judgmentCandidates = BuildJudgmentCandidates(chainCandidates, ctx);+ var eval = Engine.Evaluate(ctx, judgmentCandidates);+ foreach (var jc in judgmentCandidates)+ {+ var admissible = jc.IsAdmissible(ctx);+ var score = admissible ? jc.Score(ctx) : double.NegativeInfinity;+ var rejection = admissible ? string.Empty : jc.RejectionReason?.Invoke(ctx) ?? "candidate-not-admissible";+ traces.Add(new RestrictedContourSnapSelectionCandidate(+ ParseRoute(jc.Name),+ ParseKind(jc.Name),+ admissible,+ score,+ rejection,+ chainCandidates.Where(c => KindName(c.Kind) == KindName(ParseKind(jc.Name))).SelectMany(c => c.Diagnostics).ToArray()));+ }++ if (!eval.IsSuccess)+ {+ diagnostics.Add($"snap-selection-chain-no-admissible-analytic:{chain.ChainId}");+ diagnostics.AddRange(eval.Rejections.Select(r => $"snap-selection-rejection:{chain.ChainId}:{r.CandidateName}:{r.Reason}"));+ continue;+ }++ var sel = eval.Selection!.Value;+ var picked = chainCandidates.First(c => RouteFromKind(c.Kind) == ParseRoute(sel.Candidate.Name));+ selected.Add((chain, picked, ParseRoute(sel.Candidate.Name), sel.Score));+ }++ if (selected.Count == 0)+ {+ var route = stitchResult.Chains.Count == 0 ? RestrictedContourSnapRouteKind.Unsupported : RestrictedContourSnapRouteKind.NumericalOnly;+ diagnostics.Add(route == RestrictedContourSnapRouteKind.Unsupported+ ? "snap-selection-unsupported:no-chains"+ : "snap-selection-numerical-only:analytic-rejected-or-deferred");+ diagnostics.Add("snap-selection-not-exact-trim");+ diagnostics.Add("snap-selection-brep-topology-not-implemented");+ diagnostics.Add("snap-selection-step-export-not-implemented");+ diagnostics.Add("snap-selection-torus-generic-exactness-not-implied");+ return new RestrictedContourSnapSelectionResult(+ analysis.Success,+ route,+ null,+ false,+ route == RestrictedContourSnapRouteKind.Unsupported ? RestrictedContourExportCapability.Unsupported : RestrictedContourExportCapability.NumericalOnlyNotExportable,+ traces,+ diagnostics);+ }++ var best = selected+ .OrderByDescending(s => s.Score)+ .ThenBy(s => s.Route)+ .ThenBy(s => s.Chain.ChainId)+ .First();++ diagnostics.Add($"snap-selection-route:{best.Route}");+ diagnostics.Add("snap-selection-accepted-internal-analytic-candidate");+ diagnostics.Add("snap-selection-not-exact-trim");+ diagnostics.Add("snap-selection-brep-topology-not-implemented");+ diagnostics.Add("snap-selection-step-export-not-implemented");+ if (best.Route == RestrictedContourSnapRouteKind.AnalyticCircle)+ {+ diagnostics.Add("snap-selection-torus-generic-exactness-not-implied");+ }++ return new RestrictedContourSnapSelectionResult(+ analysis.Success,+ best.Route,+ best.Candidate,+ true,+ RestrictedContourExportCapability.ElementaryCurveCandidate,+ traces,+ diagnostics);+ }++ private static IReadOnlyList<JudgmentCandidate<SelectionContext>> BuildJudgmentCandidates(IReadOnlyList<RestrictedContourSnapCandidate> chainCandidates, SelectionContext context)+ {+ var list = new List<JudgmentCandidate<SelectionContext>>();+ if (chainCandidates.Any(c => c.Kind == RestrictedContourSnapKind.Circle))+ {+ list.Add(new JudgmentCandidate<SelectionContext>(+ "AnalyticCircle:Circle",+ IsAdmissibleCircle,+ ScoreCircle,+ CircleRejection,+ TieBreakerPriority: context.PreferCircle ? 0 : 1));+ }++ if (chainCandidates.Any(c => c.Kind == RestrictedContourSnapKind.Line))+ {+ list.Add(new JudgmentCandidate<SelectionContext>(+ "AnalyticLine:Line",+ IsAdmissibleLine,+ ScoreLine,+ LineRejection,+ TieBreakerPriority: context.PreferLine ? 0 : 1));+ }++ return list;+ }++ private static bool IsAdmissibleCircle(SelectionContext ctx)+ {+ var candidate = ctx.Candidates.FirstOrDefault(c => c.Kind == RestrictedContourSnapKind.Circle);+ return candidate is not null+ && candidate.Status == RestrictedContourSnapStatus.Candidate+ && candidate.SampleCount >= ctx.Options.MinPointCount+ && candidate.MaxError <= ctx.Options.MaxCircleError+ && (ctx.Chain.Closed || ctx.Chain.Status == SurfaceTrimContourChainStatus.ClosedLoop);+ }++ private static bool IsAdmissibleLine(SelectionContext ctx)+ {+ var candidate = ctx.Candidates.FirstOrDefault(c => c.Kind == RestrictedContourSnapKind.Line);+ return candidate is not null+ && candidate.Status == RestrictedContourSnapStatus.Candidate+ && candidate.SampleCount >= ctx.Options.MinPointCount+ && candidate.MaxError <= ctx.Options.MaxLineError+ && (ctx.Chain.Status is SurfaceTrimContourChainStatus.OpenChain or SurfaceTrimContourChainStatus.BoundaryTouching || ctx.Chain.BoundaryTouching);+ }++ private static double ScoreCircle(SelectionContext ctx)+ {+ var candidate = ctx.Candidates.First(c => c.Kind == RestrictedContourSnapKind.Circle);+ var score = 1000d - (candidate.MaxError * 1000d) - (candidate.MeanError * 100d);+ if (ctx.PreferCircle) score += 10d;+ return score;+ }++ private static double ScoreLine(SelectionContext ctx)+ {+ var candidate = ctx.Candidates.First(c => c.Kind == RestrictedContourSnapKind.Line);+ var score = 1000d - (candidate.MaxError * 1000d) - (candidate.MeanError * 100d);+ if (ctx.PreferLine) score += 10d;+ return score;+ }++ private static string CircleRejection(SelectionContext ctx)+ {+ var c = ctx.Candidates.FirstOrDefault(x => x.Kind == RestrictedContourSnapKind.Circle);+ if (c is null) return "circle-candidate-missing";+ if (c.Status != RestrictedContourSnapStatus.Candidate) return $"circle-status:{c.Status}";+ if (c.SampleCount < ctx.Options.MinPointCount) return $"circle-sample-count-below-min:{c.SampleCount}";+ if (c.MaxError > ctx.Options.MaxCircleError) return $"circle-max-error-exceeds-threshold:{c.MaxError:R}";+ return "circle-chain-not-closed";+ }++ private static string LineRejection(SelectionContext ctx)+ {+ var c = ctx.Candidates.FirstOrDefault(x => x.Kind == RestrictedContourSnapKind.Line);+ if (c is null) return "line-candidate-missing";+ if (c.Status != RestrictedContourSnapStatus.Candidate) return $"line-status:{c.Status}";+ if (c.SampleCount < ctx.Options.MinPointCount) return $"line-sample-count-below-min:{c.SampleCount}";+ if (c.MaxError > ctx.Options.MaxLineError) return $"line-max-error-exceeds-threshold:{c.MaxError:R}";+ return "line-chain-not-open-or-boundary";+ }++ private static RestrictedContourSnapRouteKind RouteFromKind(RestrictedContourSnapKind kind) => kind switch+ {+ RestrictedContourSnapKind.Circle => RestrictedContourSnapRouteKind.AnalyticCircle,+ RestrictedContourSnapKind.Line => RestrictedContourSnapRouteKind.AnalyticLine,+ _ => RestrictedContourSnapRouteKind.Deferred,+ };++ private static RestrictedContourSnapRouteKind ParseRoute(string name) => name.StartsWith("AnalyticCircle", StringComparison.Ordinal)+ ? RestrictedContourSnapRouteKind.AnalyticCircle+ : RestrictedContourSnapRouteKind.AnalyticLine;++ private static RestrictedContourSnapKind ParseKind(string name) => name.EndsWith(":Circle", StringComparison.Ordinal)+ ? RestrictedContourSnapKind.Circle+ : RestrictedContourSnapKind.Line;++ private static string KindName(RestrictedContourSnapKind kind) => kind.ToString();+}diff --git a/docs/cir-t6-snap-selection-gate.md b/docs/cir-t6-snap-selection-gate.mdnew file mode 100644index 00000000..e792c15d--- /dev/null+++ b/docs/cir-t6-snap-selection-gate.md@@ -0,0 +1,69 @@+# CIR-T6 — Snap Candidate Ranking/Selection + Analytic Acceptance Gate++## Purpose++CIR-T6 adds deterministic bounded selection over CIR-T5 snap candidates. It chooses internal analytic trim candidates (circle/line) only when admissible, otherwise falls back to numerical-only/deferred routes.++This milestone is **selection and gate only**:+- no BRep topology emission,+- no STEP export behavior change,+- no final trim-curve representation integration.++## Candidate routes++- `AnalyticCircle`+- `AnalyticLine`+- `NumericalOnly`+- `Deferred`+- `Unsupported`++Export capability is classified separately:+- `ElementaryCurveCandidate`+- `NumericalOnlyNotExportable`+- `Deferred`+- `Unsupported`++`ElementaryCurveCandidate` means compatibility with future elementary-curve export wiring, not actual export in CIR-T6.++## JudgmentEngine usage decision++CIR-T6 is a bounded competing-strategy problem (line vs circle vs fallback), so `JudgmentEngine` is used to make admissibility, scoring, rejection reasons, and deterministic tie-breaking explicit.++## Admissibility and scoring++Per chain:+- Circle is admissible when candidate kind/status/sample-count/error and closed-loop suitability pass.+- Line is admissible when candidate kind/status/sample-count/error and open/boundary suitability pass.++Ranking:+- lower error yields higher score,+- circle gets preference on closed loops,+- line gets preference on open/boundary chains,+- deterministic tie-break follows JudgmentEngine ordering.++## Fallback behavior++If no analytic candidate is admissible and numerical contour data exists, route is `NumericalOnly` with diagnostics indicating analytic rejection/defer and non-exportable status.++If no chain/candidate data exists, route is `Unsupported`.++## Torus policy++Torus contours may still produce a candidate circle in special geometry cases. CIR-T6 diagnostics explicitly state that generic torus exactness/boolean support is not implied.++## Non-goals++- ellipse acceptance+- BSpline fitting+- BRep topology+- STEP export+- torus quartic/exact recognition+- boolean behavior changes++## SEM-A0 status++SEM-A0 guardrails remain preserved: CIR-T6 introduces routing/diagnostics only, without generated topology naming or provenance model expansion.++## Next step (T7)++Integrate selected analytic candidates into trim-curve representation routing (CURVE track) while preserving the same acceptance/export separation and guardrails.