Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add CIR-T5 restricted contour snap candidate analyzer

Yuechen Li5628c682eb43
diff --git a/Aetheris.Kernel.Firmament.Tests/RestrictedContourSnapAnalyzerTests.cs b/Aetheris.Kernel.Firmament.Tests/RestrictedContourSnapAnalyzerTests.cs
new file mode 100644
index 00000000..ae72b884
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/RestrictedContourSnapAnalyzerTests.cs
@@ -0,0 +1,79 @@
+using Aetheris.Kernel.Core.Cir;
+using Aetheris.Kernel.Firmament.Execution;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class RestrictedContourSnapAnalyzerTests
+{
+ [Fact]
+ public void Snap_BoxFaceVsCylinder_ProducesCircleCandidate()
+ {
+ var stitched = BuildStitched(new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirCylinderNode(2, 20)), 65);
+ var result = RestrictedContourSnapAnalyzer.Analyze(stitched, new RestrictedContourSnapOptions(0.06d, 0.02d, 8));
+ var candidate = Assert.Single(result.Candidates.Where(c => c.Kind == RestrictedContourSnapKind.Circle && c.Status == RestrictedContourSnapStatus.Candidate));
+ var p = Assert.IsType<CircleSnapParameters2D>(candidate.Parameters);
+ Assert.True(double.IsFinite(p.CenterU) && double.IsFinite(p.CenterV) && double.IsFinite(p.Radius));
+ Assert.True(candidate.MaxError <= 0.06d);
+ Assert.False(result.ExactTrimAccepted);
+ }
+
+ [Fact]
+ public void Snap_BoxFaceVsSphere_ProducesCircleCandidate()
+ {
+ var stitched = BuildStitched(new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirSphereNode(6)), 65);
+ var result = RestrictedContourSnapAnalyzer.Analyze(stitched, new RestrictedContourSnapOptions(0.06d, 0.02d, 8));
+ Assert.Contains(result.Candidates, c => c.Kind == RestrictedContourSnapKind.Circle && c.Status == RestrictedContourSnapStatus.Candidate);
+ }
+
+ [Fact]
+ public void Snap_BoxFaceVsTorus_RejectsOrDefersNonCircularCandidate()
+ {
+ var stitched = BuildStitched(new CirSubtractNode(new CirBoxNode(12, 12, 12), new CirTorusNode(4, 1)), 65);
+ var result = RestrictedContourSnapAnalyzer.Analyze(stitched, new RestrictedContourSnapOptions(0.01d, 0.01d, 8));
+ var circles = result.Candidates.Where(c => c.Kind == RestrictedContourSnapKind.Circle).ToArray();
+ Assert.True(circles.Length == 0 || circles.All(c => c.Status != RestrictedContourSnapStatus.Candidate || c.Diagnostics.Contains("snap-candidate-only:not-exact-trim")));
+ Assert.False(result.ExactTrimAccepted);
+ Assert.False(result.BRepTopologyImplemented);
+ Assert.False(result.StepExportImplemented);
+ }
+
+ [Fact]
+ public void Snap_OpenBoundaryChain_LineCandidateOrDeferred()
+ {
+ 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 extraction = new SurfaceTrimContourExtractionResult(true, RestrictedFieldContourExtractionMethod.MarchingSquares, 2, [segA, segB], []);
+ var stitched = SurfaceTrimContourStitcher.Stitch(extraction);
+ var result = RestrictedContourSnapAnalyzer.Analyze(stitched, new RestrictedContourSnapOptions(0.02d, 0.05d, 3));
+ Assert.Contains(result.Candidates, c => c.Kind == RestrictedContourSnapKind.Line && (c.Status == RestrictedContourSnapStatus.Candidate || c.Status == RestrictedContourSnapStatus.Deferred));
+ }
+
+ [Fact]
+ public void Snap_DeterministicResults()
+ {
+ var stitched = BuildStitched(new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirSphereNode(6)), 65);
+ var options = new RestrictedContourSnapOptions(0.06d, 0.02d, 8);
+ var a = RestrictedContourSnapAnalyzer.Analyze(stitched, options);
+ var b = RestrictedContourSnapAnalyzer.Analyze(stitched, options);
+ Assert.Equal(a.Candidates.Select(c => (c.ChainId, c.Kind, c.Status, c.MaxError, c.MeanError, c.SampleCount)), b.Candidates.Select(c => (c.ChainId, c.Kind, c.Status, c.MaxError, c.MeanError, c.SampleCount)));
+ }
+
+ [Fact]
+ public void Snap_TooFewPoints_Rejected()
+ {
+ var seg = new SurfaceTrimContourSegment2D(0, 0, new(0.1d, 0.1d), new(0.2d, 0.2d), RestrictedFieldCellClassification.Mixed, []);
+ var extraction = new SurfaceTrimContourExtractionResult(true, RestrictedFieldContourExtractionMethod.MarchingSquares, 1, [seg], []);
+ var stitched = SurfaceTrimContourStitcher.Stitch(extraction);
+ var result = RestrictedContourSnapAnalyzer.Analyze(stitched, new RestrictedContourSnapOptions(0.01d, 0.01d, 5));
+ Assert.Contains(result.Candidates, c => c.Status == RestrictedContourSnapStatus.Rejected && c.Diagnostics.Any(d => d.StartsWith("snap-rejected-too-few-points:")));
+ }
+
+ 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/RestrictedContourSnapAnalyzer.cs b/Aetheris.Kernel.Firmament/Execution/RestrictedContourSnapAnalyzer.cs
new file mode 100644
index 00000000..2e1c01ff
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Execution/RestrictedContourSnapAnalyzer.cs
@@ -0,0 +1,170 @@
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Numerics;
+
+namespace Aetheris.Kernel.Firmament.Execution;
+
+internal enum RestrictedContourSnapKind
+{
+ Line,
+ Circle,
+ EllipseDeferred,
+ BSplineDeferred,
+ Unsupported,
+}
+
+internal enum RestrictedContourSnapStatus
+{
+ Candidate,
+ Rejected,
+ Deferred,
+ Unsupported,
+}
+
+internal sealed record LineSnapParameters2D(double PointU, double PointV, double DirectionU, double DirectionV);
+
+internal sealed record CircleSnapParameters2D(double CenterU, double CenterV, double Radius);
+
+internal sealed record RestrictedContourSnapCandidate(
+ int ChainId,
+ RestrictedContourSnapKind Kind,
+ RestrictedContourSnapStatus Status,
+ object? Parameters,
+ double MaxError,
+ double MeanError,
+ int SampleCount,
+ IReadOnlyList<string> Diagnostics);
+
+internal sealed record RestrictedContourSnapOptions(double MaxCircleError, double MaxLineError, int MinPointCount)
+{
+ internal static RestrictedContourSnapOptions ConservativeDefaults { get; } = new(0.02d, 0.01d, 8);
+}
+
+internal sealed record RestrictedContourSnapAnalysisResult(
+ bool Success,
+ IReadOnlyList<RestrictedContourSnapCandidate> Candidates,
+ IReadOnlyList<string> Diagnostics,
+ int AcceptedCount = 0,
+ bool ExactTrimAccepted = false,
+ bool BRepTopologyImplemented = false,
+ bool StepExportImplemented = false);
+
+internal static class RestrictedContourSnapAnalyzer
+{
+ internal static RestrictedContourSnapAnalysisResult Analyze(SurfaceTrimContourStitchResult stitchResult, RestrictedContourSnapOptions? options = null)
+ {
+ ArgumentNullException.ThrowIfNull(stitchResult);
+ var opts = options ?? RestrictedContourSnapOptions.ConservativeDefaults;
+ var diagnostics = new List<string>
+ {
+ "snap-analysis-started",
+ $"snap-chain-count:{stitchResult.Chains.Count}",
+ $"snap-option-max-circle-error:{opts.MaxCircleError:R}",
+ $"snap-option-max-line-error:{opts.MaxLineError:R}",
+ $"snap-option-min-point-count:{opts.MinPointCount}",
+ };
+
+ var candidates = new List<RestrictedContourSnapCandidate>();
+
+ foreach (var chain in stitchResult.Chains.OrderBy(c => c.ChainId))
+ {
+ if (chain.Points.Count < opts.MinPointCount)
+ {
+ candidates.Add(new RestrictedContourSnapCandidate(
+ chain.ChainId,
+ chain.Closed ? RestrictedContourSnapKind.Circle : RestrictedContourSnapKind.Line,
+ RestrictedContourSnapStatus.Rejected,
+ null,
+ double.PositiveInfinity,
+ double.PositiveInfinity,
+ chain.Points.Count,
+ [$"snap-rejected-too-few-points:{chain.Points.Count}"]));
+ continue;
+ }
+
+ if (chain.Closed || chain.Status == SurfaceTrimContourChainStatus.ClosedLoop)
+ {
+ candidates.Add(FitCircle(chain, opts));
+ candidates.Add(new RestrictedContourSnapCandidate(chain.ChainId, RestrictedContourSnapKind.BSplineDeferred, RestrictedContourSnapStatus.Deferred, null, double.NaN, double.NaN, chain.Points.Count, ["snap-bspline-deferred:candidate-only-milestone"]));
+ }
+ else if (chain.Status is SurfaceTrimContourChainStatus.OpenChain or SurfaceTrimContourChainStatus.BoundaryTouching)
+ {
+ candidates.Add(FitLine(chain, opts));
+ candidates.Add(new RestrictedContourSnapCandidate(chain.ChainId, RestrictedContourSnapKind.EllipseDeferred, RestrictedContourSnapStatus.Deferred, null, double.NaN, double.NaN, chain.Points.Count, ["snap-ellipse-deferred:out-of-scope"]));
+ }
+ else
+ {
+ candidates.Add(new RestrictedContourSnapCandidate(chain.ChainId, RestrictedContourSnapKind.Unsupported, RestrictedContourSnapStatus.Unsupported, null, double.NaN, double.NaN, chain.Points.Count, [$"snap-chain-status-unsupported:{chain.Status}"]));
+ }
+ }
+
+ diagnostics.Add($"snap-candidate-count:{candidates.Count}");
+ diagnostics.Add($"snap-circle-candidate-count:{candidates.Count(c => c.Kind == RestrictedContourSnapKind.Circle && c.Status == RestrictedContourSnapStatus.Candidate)}");
+ diagnostics.Add($"snap-line-candidate-count:{candidates.Count(c => c.Kind == RestrictedContourSnapKind.Line && c.Status == RestrictedContourSnapStatus.Candidate)}");
+ diagnostics.Add("snap-exact-trim-not-accepted");
+ diagnostics.Add("snap-brep-topology-not-implemented");
+ diagnostics.Add("snap-step-export-not-implemented");
+
+ return new RestrictedContourSnapAnalysisResult(stitchResult.Success, candidates, diagnostics);
+ }
+
+ private static RestrictedContourSnapCandidate FitCircle(SurfaceTrimContourChain2D chain, RestrictedContourSnapOptions options)
+ {
+ var pts = chain.Points.Select(p => (u: p.U, v: p.V)).ToArray();
+ var centerU = pts.Average(p => p.u);
+ var centerV = pts.Average(p => p.v);
+ var radii = pts.Select(p => double.Sqrt((p.u - centerU) * (p.u - centerU) + (p.v - centerV) * (p.v - centerV))).ToArray();
+ var radius = radii.Average();
+ var errors = radii.Select(r => double.Abs(r - radius)).ToArray();
+ var maxError = errors.Max();
+ var meanError = errors.Average();
+ var status = maxError <= options.MaxCircleError ? RestrictedContourSnapStatus.Candidate : RestrictedContourSnapStatus.Rejected;
+ var diag = new List<string>
+ {
+ "snap-circle-fit:centroid-mean-radius",
+ $"snap-circle-max-error:{maxError:R}",
+ $"snap-circle-mean-error:{meanError:R}",
+ $"snap-circle-threshold:{options.MaxCircleError:R}",
+ status == RestrictedContourSnapStatus.Candidate ? "snap-circle-candidate-produced" : "snap-circle-candidate-rejected:high-radial-error",
+ "snap-candidate-only:not-exact-trim"
+ };
+
+ return new RestrictedContourSnapCandidate(chain.ChainId, RestrictedContourSnapKind.Circle, status, new CircleSnapParameters2D(centerU, centerV, radius), maxError, meanError, pts.Length, diag);
+ }
+
+ private static RestrictedContourSnapCandidate FitLine(SurfaceTrimContourChain2D chain, RestrictedContourSnapOptions options)
+ {
+ var pts = chain.Points.Select(p => (u: p.U, v: p.V)).ToArray();
+ var first = pts.First();
+ var last = pts.Last();
+ var du = last.u - first.u;
+ var dv = last.v - first.v;
+ var length = double.Sqrt((du * du) + (dv * dv));
+ if (ToleranceMath.AlmostZero(length, ToleranceContext.Default))
+ {
+ return new RestrictedContourSnapCandidate(chain.ChainId, RestrictedContourSnapKind.Line, RestrictedContourSnapStatus.Rejected, null, double.PositiveInfinity, double.PositiveInfinity, pts.Length, ["snap-line-candidate-rejected:degenerate-direction"]);
+ }
+
+ var dirU = du / length;
+ var dirV = dv / length;
+ var errors = pts.Select(p => double.Abs(((p.u - first.u) * (-dirV)) + ((p.v - first.v) * dirU))).ToArray();
+ var maxError = errors.Max();
+ var meanError = errors.Average();
+ var status = maxError <= options.MaxLineError ? RestrictedContourSnapStatus.Candidate : RestrictedContourSnapStatus.Deferred;
+ return new RestrictedContourSnapCandidate(
+ chain.ChainId,
+ RestrictedContourSnapKind.Line,
+ status,
+ new LineSnapParameters2D(first.u, first.v, dirU, dirV),
+ maxError,
+ meanError,
+ pts.Length,
+ [
+ "snap-line-fit:endpoint-direction",
+ $"snap-line-max-error:{maxError:R}",
+ $"snap-line-mean-error:{meanError:R}",
+ $"snap-line-threshold:{options.MaxLineError:R}",
+ status == RestrictedContourSnapStatus.Candidate ? "snap-line-candidate-produced" : "snap-line-candidate-deferred:high-perpendicular-error",
+ "snap-candidate-only:not-exact-trim"
+ ]);
+ }
+}
diff --git a/docs/cir-t5-analytic-snap-candidates.md b/docs/cir-t5-analytic-snap-candidates.md
new file mode 100644
index 00000000..e048d5dd
--- /dev/null
+++ b/docs/cir-t5-analytic-snap-candidates.md
@@ -0,0 +1,94 @@
+# CIR-T5 — bounded analytic snap candidates for stitched restricted-field contours
+
+## Purpose
+
+CIR-T5 introduces deterministic **candidate-only** analytic snap analysis on stitched contour chains from CIR-T4.
+
+Input: `SurfaceTrimContourStitchResult` with `SurfaceTrimContourChain2D` chains.
+Output: `RestrictedContourSnapAnalysisResult` with `RestrictedContourSnapCandidate` entries for line/circle fitting attempts and deferred/unsupported placeholders.
+
+## Candidate-only policy
+
+This milestone does **not**:
+
+- accept exact trim curves,
+- emit BRep topology,
+- enable STEP exact export,
+- alter Boolean behavior or materialization routing.
+
+The result object hard-codes this milestone boundary via:
+
+- `AcceptedCount = 0`
+- `ExactTrimAccepted = false`
+- `BRepTopologyImplemented = false`
+- `StepExportImplemented = false`
+
+## Fitting policy
+
+### Circle fitting (closed chains)
+
+- Closed-loop chains are fit in UV space.
+- Fit method for T5 is bounded and stable: centroid + mean radius.
+- Errors are radial residuals.
+- Candidate emitted when `max radial error <= MaxCircleError`, otherwise rejected.
+
+### Line fitting (open/boundary chains)
+
+- Open/boundary chains are fit in UV space using first/last endpoint direction.
+- Errors are perpendicular distances to the line.
+- Candidate emitted when `max perpendicular error <= MaxLineError`, otherwise deferred.
+
+### Deferred/unsupported categories
+
+T5 surfaces explicit out-of-scope states:
+
+- `EllipseDeferred`
+- `BSplineDeferred`
+- `Unsupported`
+
+## Tolerance/error options
+
+`RestrictedContourSnapOptions`:
+
+- `MaxCircleError`
+- `MaxLineError`
+- `MinPointCount`
+
+Conservative defaults are provided and diagnostics always echo selected option values.
+
+## Torus/non-circular policy
+
+Torus contours are treated exactly like any stitched chain in this milestone:
+
+- if circular under chosen tolerances, a candidate may be emitted,
+- otherwise rejected/deferred with high-error diagnostics.
+
+No torus exactness claims are made in T5.
+
+## Diagnostics
+
+T5 diagnostics include:
+
+- analysis start + chain count,
+- option echoing,
+- per-fit method and error metrics,
+- candidate produced/rejected/deferred status,
+- explicit exact-trim/topology/export-not-implemented markers.
+
+## JudgmentEngine usage decision
+
+T5 intentionally emits all evaluated candidates and does not choose a winner among competing strategies.
+
+Because there is no bounded runtime strategy selection in this milestone, `JudgmentEngine` is intentionally **not** used yet.
+
+## SEM-A0 guardrails
+
+SEM-A0 guardrails remain preserved:
+
+- no generated topology naming,
+- no selector-provenance changes,
+- no user-facing topology identity additions.
+
+## Recommended CIR-T6 next step
+
+CIR-T6 should add bounded candidate ranking/selection (likely via `JudgmentEngine`) and acceptance gate wiring, while still separating candidate generation from final exact trim/BRep/STEP realization until explicitly enabled.