Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Expose continuum tools through the CLI

Yuechen Li78e06802d0e5
diff --git a/.gitignore b/.gitignore
index eb71a6df..ddf7fece 100644
--- a/.gitignore
+++ b/.gitignore
@@ -118,6 +118,10 @@ artifacts/release/*
!docs/release/2.0.0-preview.1-notes.md
!docs/release/2.0.0-preview.1-release.md
!docs/release/preview1-baseline-stabilization-x1.md
+!docs/release/PAT-DOGFOOD-X0.md
+!docs/release/PAT-DOGFOOD-X0.evidence.json
+!docs/release/DCSD-DOGFOOD-X0.md
+!docs/release/DCSD-DOGFOOD-X0.evidence.json
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
diff --git a/Aetheris.CLI.Tests/ContinuumToolsCliTests.cs b/Aetheris.CLI.Tests/ContinuumToolsCliTests.cs
new file mode 100644
index 00000000..b2561373
--- /dev/null
+++ b/Aetheris.CLI.Tests/ContinuumToolsCliTests.cs
@@ -0,0 +1,45 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class ContinuumToolsCliTests
+{
+ [Fact]
+ public void HelpIsDiscoverableForEveryBoundedSubcommand()
+ {
+ foreach(var command in new[]{"pat-query","contour","make-fixtures"})
+ {
+ var stdout=new StringWriter();var stderr=new StringWriter();
+ Assert.Equal(0,CliRunner.Run(["continuum",command,"--help"],stdout,stderr));
+ Assert.Contains("Usage: aetheris continuum",stdout.ToString());Assert.Equal(string.Empty,stderr.ToString());
+ }
+ }
+
+ [Fact]
+ public void GeneratedFixturesRunThroughPatAndContourCommands()
+ {
+ var root=Path.Combine(Path.GetTempPath(),"aetheris-continuum-cli-"+Guid.NewGuid().ToString("N"));
+ try
+ {
+ AssertRun(["continuum","make-fixtures","--out-dir",root]);
+ var patOutput=Path.Combine(root,"results.json");
+ AssertRun(["continuum","pat-query",Path.Combine(root,"sphere-point-tori.json"),Path.Combine(root,"sphere-queries.json"),"--out",patOutput]);
+ var mesh=Path.Combine(root,"box.obj");var report=Path.Combine(root,"box-report.json");
+ AssertRun(["continuum","contour",Path.Combine(root,"sharp-box-grid.json"),"--out",mesh,"--report",report]);
+ Assert.True(File.Exists(patOutput));Assert.True(File.Exists(mesh));Assert.True(File.Exists(report));
+ using var json=JsonDocument.Parse(File.ReadAllText(report));
+ Assert.Equal(0,json.RootElement.GetProperty("diagnostics").GetProperty("boundaryEdges").GetInt32());
+ Assert.Equal(0,json.RootElement.GetProperty("diagnostics").GetProperty("nonManifoldEdges").GetInt32());
+ }
+ finally
+ {
+ if(Directory.Exists(root))Directory.Delete(root,true);
+ }
+ }
+
+ private static void AssertRun(string[] args)
+ {
+ var stdout=new StringWriter();var stderr=new StringWriter();var exit=CliRunner.Run(args,stdout,stderr);
+ Assert.True(exit==0,$"Exit {exit}. stderr: {stderr} stdout: {stdout}");
+ }
+}
diff --git a/Aetheris.CLI/Aetheris.CLI.csproj b/Aetheris.CLI/Aetheris.CLI.csproj
index b42486df..550cfe08 100644
--- a/Aetheris.CLI/Aetheris.CLI.csproj
+++ b/Aetheris.CLI/Aetheris.CLI.csproj
@@ -31,6 +31,7 @@
<ProjectReference Include="..\Aetheris.PlasticShell\Aetheris.PlasticShell.csproj" />
<ProjectReference Include="..\Aetheris.Sculpture\Aetheris.Sculpture.csproj" />
<ProjectReference Include="..\Aetheris.Drawing\Aetheris.Drawing.csproj" />
+ <ProjectReference Include="..\Aetheris.Continuum\Aetheris.Continuum.csproj" />
</ItemGroup>
<ItemGroup>
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 02619d0d..ce30a5f1 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -238,6 +238,7 @@ public static class CliRunner
"section-chain" => RunSectionChain(args.Skip(1).ToArray(), stdout, stderr),
"wireframe" => RunWireframe(args.Skip(1).ToArray(), stdout, stderr),
"reconstruct" => ReconstructionCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
+ "continuum" => ContinuumToolsCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
_ => UnknownCommand(args[0], stderr)
};
}
@@ -4813,6 +4814,7 @@ Model CanonicalPanel {
stdout.WriteLine(" wireframe Render a deterministic trim-aware SVG preview from a STEP BRep.");
stdout.WriteLine(" verify Build/reimport and verify a model.");
stdout.WriteLine(" reconstruct Experimentally reconstruct a structured mesh from triangle PLY input.");
+ stdout.WriteLine(" continuum Run bounded point-torus queries or sharp sampled-grid contouring.");
stdout.WriteLine();
stdout.WriteLine("Global options:");
stdout.WriteLine(" -h, --help Show help.");
@@ -4832,6 +4834,7 @@ Model CanonicalPanel {
stdout.WriteLine(" aetheris section-chain build flagship --json");
stdout.WriteLine(" aetheris wireframe model.step --out model.wireframe.svg --view iso --density 8");
stdout.WriteLine(" aetheris reconstruct mesh scan.ply --mode fast --out scan-remesh.obj --report scan-report.json");
+ stdout.WriteLine(" aetheris continuum --help");
stdout.WriteLine();
stdout.WriteLine("Run 'aetheris <command> --help' for command-specific usage.");
}
diff --git a/Aetheris.CLI/ContinuumToolsCli.cs b/Aetheris.CLI/ContinuumToolsCli.cs
new file mode 100644
index 00000000..ccd9fe30
--- /dev/null
+++ b/Aetheris.CLI/ContinuumToolsCli.cs
@@ -0,0 +1,90 @@
+using System.Text.Json;
+using Aetheris.Continuum.Reconstruction;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.CLI;
+
+internal static class ContinuumToolsCli
+{
+ private const string Usage = "Usage: aetheris continuum <pat-query|contour|make-fixtures> [options]";
+
+ public static int Run(string[] args, TextWriter stdout, TextWriter stderr, JsonSerializerOptions jsonOptions)
+ {
+ if (args.Length == 0 || args[0] is "-h" or "--help") { WriteHelp(stdout); return args.Length == 0 ? 1 : 0; }
+ return args[0] switch
+ {
+ "pat-query" => RunPat(args[1..],stdout,stderr,jsonOptions),
+ "contour" => RunContour(args[1..],stdout,stderr,jsonOptions),
+ "make-fixtures" => MakeFixtures(args[1..],stdout,stderr,jsonOptions),
+ _ => Fail($"Unknown continuum command '{args[0]}'.",stderr)
+ };
+ }
+
+ private static int RunPat(string[] args, TextWriter stdout, TextWriter stderr, JsonSerializerOptions jsonOptions)
+ {
+ if(args.Length>0&&args[0] is "-h" or "--help"){stdout.WriteLine("Usage: aetheris continuum pat-query <field.json> <queries.json> [--out <results.json>]");return 0;}
+ if(args.Length<2){stderr.WriteLine("Usage: aetheris continuum pat-query <field.json> <queries.json> [--out <results.json>]");return 1;}
+ var output=Option(args,"--out");
+ using var fieldStream=File.OpenRead(args[0]); var field=ContinuumInterchange.ReadPointTorusField(fieldStream);
+ var arrays=JsonSerializer.Deserialize<double[][]>(File.ReadAllText(args[1]),ContinuumInterchange.JsonOptions)??throw new InvalidDataException("Query JSON is empty.");
+ var queries=arrays.Select((q,i)=>q.Length==3?new Point3D(q[0],q[1],q[2]):throw new InvalidDataException($"Query {i} must have three coordinates.")).ToArray();
+ var evaluations=field.EvaluateBatch(queries);
+ var result=new { schema="aetheris.point-torus-query-results.v1", approximate=true, authority="reconstruction/query evidence only", field.Provenance,
+ queries=queries.Select((q,i)=>new { point=new[]{q.X,q.Y,q.Z}, evaluations[i].ValueMm, evaluations[i].Qualification, evaluations[i].IsSigned,
+ evaluations[i].NeighborsUsed,evaluations[i].NearestSourceDistanceMm,evaluations[i].Reason }) };
+ var text=JsonSerializer.Serialize(result,jsonOptions); if(output is null)stdout.WriteLine(text);else{WriteFile(output,text);stdout.WriteLine(JsonSerializer.Serialize(new{output=Path.GetFullPath(output),queryCount=queries.Length},jsonOptions));}
+ return 0;
+ }
+
+ private static int RunContour(string[] args, TextWriter stdout, TextWriter stderr, JsonSerializerOptions jsonOptions)
+ {
+ if(args.Length>0&&args[0] is "-h" or "--help"){stdout.WriteLine("Usage: aetheris continuum contour <grid.json> --out <mesh.obj> [--report <report.json>]");return 0;}
+ if(args.Length<1){stderr.WriteLine("Usage: aetheris continuum contour <grid.json> --out <mesh.obj> [--report <report.json>]");return 1;}
+ var output=Option(args,"--out"); if(output is null){stderr.WriteLine("contour requires --out <mesh.obj>.");return 1;}
+ var reportPath=Option(args,"--report"); using var stream=File.OpenRead(args[0]); var grid=ContinuumInterchange.ReadSdfGrid(stream,out var source);
+ var result=SharpDualContouring.Reconstruct(grid,source); Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!);
+ using(var writer=File.CreateText(output))ApproximateMeshObj.Write(result.Mesh,writer);
+ var report=new {schema="aetheris.sharp-dual-contour-result.v1",approximate=true,authority=result.Mesh.Provenance.Authority,input=Path.GetFullPath(args[0]),output=Path.GetFullPath(output),
+ vertices=result.Mesh.Vertices.Count,triangles=result.Mesh.Triangles.Count,result.Diagnostics,result.Statistics,result.Mesh.Provenance};
+ var text=JsonSerializer.Serialize(report,jsonOptions);if(reportPath is not null)WriteFile(reportPath,text);stdout.WriteLine(text);return 0;
+ }
+
+ private static int MakeFixtures(string[] args, TextWriter stdout, TextWriter stderr, JsonSerializerOptions jsonOptions)
+ {
+ if(args.Length>0&&args[0] is "-h" or "--help"){stdout.WriteLine("Usage: aetheris continuum make-fixtures --out-dir <directory>");return 0;}
+ var outDir=Option(args,"--out-dir");if(outDir is null){stderr.WriteLine("Usage: aetheris continuum make-fixtures --out-dir <directory>");return 1;}
+ Directory.CreateDirectory(outDir);
+ var axes=new[]{new[]{1d,0,0},new[]{-1d,0,0},new[]{0d,1,0},new[]{0d,-1,0},new[]{0d,0,1},new[]{0d,0,-1}};
+ var samples=axes.Select(p=>new PointTorusJsonSample(p.Select(v=>v*10d).ToArray(),p,p.Select(_=>0d).ToArray(),new[]{0d,0d,1d},0d,10d)).ToArray();
+ var pat=new PointTorusJsonDocument(ContinuumInterchange.PointTorusSchema,"exact 10 mm sphere fixture","checked-in deterministic fixture generator",null,null,6,4d,
+ PointTorusSignCapability.SignedClosedOriented,samples,new(){["truth"]="length(q)-10 mm"});
+ WriteFile(Path.Combine(outDir,"sphere-point-tori.json"),JsonSerializer.Serialize(pat,jsonOptions));
+ WriteFile(Path.Combine(outDir,"sphere-queries.json"),JsonSerializer.Serialize(new[]{new[]{0d,0d,0d},new[]{10d,0d,0d},new[]{12d,0d,0d},new[]{0d,9d,0d}},jsonOptions));
+ const int n=25; const double spacing=1d; var origin=new[]{-12.25d,-12.25d,-12.25d};var values=new double[n*n*n];var cursor=0;
+ for(var z=0;z<n;z++)for(var y=0;y<n;y++)for(var x=0;x<n;x++)
+ {
+ var px=origin[0]+x*spacing;var py=origin[1]+y*spacing;var pz=origin[2]+z*spacing;
+ values[cursor++]=BoxSdf(px,py,pz,8d,6d,5d);
+ }
+ var grid=new SampledSdfGridJsonDocument(ContinuumInterchange.SdfGridSchema,n,n,n,origin,new[]{spacing,spacing,spacing},values,"exact axis-aligned box half extents 8,6,5 mm");
+ WriteFile(Path.Combine(outDir,"sharp-box-grid.json"),JsonSerializer.Serialize(grid,jsonOptions));
+ stdout.WriteLine(JsonSerializer.Serialize(new {outDir=Path.GetFullPath(outDir),files=new[]{"sphere-point-tori.json","sphere-queries.json","sharp-box-grid.json"}},jsonOptions));return 0;
+ }
+
+ private static double BoxSdf(double x,double y,double z,double hx,double hy,double hz)
+ {
+ var qx=Math.Abs(x)-hx;var qy=Math.Abs(y)-hy;var qz=Math.Abs(z)-hz;
+ var outside=Math.Sqrt(Math.Max(qx,0)*Math.Max(qx,0)+Math.Max(qy,0)*Math.Max(qy,0)+Math.Max(qz,0)*Math.Max(qz,0));
+ return outside+Math.Min(Math.Max(qx,Math.Max(qy,qz)),0d);
+ }
+ private static string? Option(string[] args,string name){var i=Array.IndexOf(args,name);return i>=0&&i+1<args.Length?args[i+1]:null;}
+ private static void WriteFile(string path,string text){var full=Path.GetFullPath(path);Directory.CreateDirectory(Path.GetDirectoryName(full)!);File.WriteAllText(full,text);}
+ private static int Fail(string message,TextWriter stderr){stderr.WriteLine(message);stderr.WriteLine(Usage);return 1;}
+ private static void WriteHelp(TextWriter output)
+ {
+ output.WriteLine("Bounded approximate utilities for geometry decompilation assistance; never canonical CAD authority.");output.WriteLine();output.WriteLine(Usage);
+ output.WriteLine(" pat-query <field.json> <queries.json> [--out <results.json>] Evaluate imported precomputed local tori.");
+ output.WriteLine(" contour <grid.json> --out <mesh.obj> [--report <report.json>] Reconstruct an approximate explicit mesh.");
+ output.WriteLine(" make-fixtures --out-dir <directory> Generate deterministic sphere and sharp-box evidence inputs.");
+ }
+}
diff --git a/Aetheris.Continuum.Tests/Reconstruction/PointTorusFieldTests.cs b/Aetheris.Continuum.Tests/Reconstruction/PointTorusFieldTests.cs
new file mode 100644
index 00000000..0f683324
--- /dev/null
+++ b/Aetheris.Continuum.Tests/Reconstruction/PointTorusFieldTests.cs
@@ -0,0 +1,36 @@
+using Aetheris.Continuum.Reconstruction;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Continuum.Tests.Reconstruction;
+
+public sealed class PointTorusFieldTests
+{
+ [Fact]
+ public void DegenerateTorusEvaluatesSphereAndQualifiesNearSource()
+ {
+ var samples=Axes().Select(axis=>new PointTorusSample(new(axis.X*10,axis.Y*10,axis.Z*10),axis,Point3D.Origin,new(0,0,1),0,10)).ToArray();
+ var field=new PointTorusField(samples,new(6,3,PointTorusSignCapability.SignedClosedOriented),new("sphere","test",null,null));
+ var surface=field.Evaluate(new(10,0,0));var outside=field.Evaluate(new(12,0,0));
+ Assert.Equal(PointTorusQualification.Qualified,surface.Qualification);
+ Assert.Equal(0,surface.ValueMm,10);Assert.Equal(2,outside.ValueMm,10);Assert.True(outside.IsSigned);
+ }
+
+ [Fact]
+ public void OpenSurfaceNeverAdvertisesSign()
+ {
+ var sample=new PointTorusSample(new(10,0,0),new(1,0,0),Point3D.Origin,new(0,0,1),0,10);
+ var field=new PointTorusField(new[]{sample},new(1,5,PointTorusSignCapability.UnsignedOnlyOpenSurface),new("open","test",null,null));
+ var result=field.Evaluate(new(9,0,0));
+ Assert.Equal(PointTorusQualification.UnsignedOnly,result.Qualification);Assert.False(result.IsSigned);Assert.Equal(1,result.ValueMm,10);
+ }
+
+ [Fact]
+ public void FarQueryIsOutsideDeclaredBand()
+ {
+ var sample=new PointTorusSample(new(10,0,0),new(1,0,0),Point3D.Origin,new(0,0,1),0,10);
+ var field=new PointTorusField(new[]{sample},new(1,2),new("sphere","test",null,null));
+ Assert.Equal(PointTorusQualification.OutsideValidityBand,field.Evaluate(Point3D.Origin).Qualification);
+ }
+
+ private static Vector3D[] Axes()=>new[]{new Vector3D(1,0,0),new(-1,0,0),new(0,1,0),new(0,-1,0),new(0,0,1),new(0,0,-1)};
+}
diff --git a/Aetheris.Continuum.Tests/Reconstruction/SharpDualContouringTests.cs b/Aetheris.Continuum.Tests/Reconstruction/SharpDualContouringTests.cs
new file mode 100644
index 00000000..6463448d
--- /dev/null
+++ b/Aetheris.Continuum.Tests/Reconstruction/SharpDualContouringTests.cs
@@ -0,0 +1,48 @@
+using Aetheris.Continuum.Reconstruction;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Continuum.Tests.Reconstruction;
+
+public sealed class SharpDualContouringTests
+{
+ [Fact]
+ public void SharpBoxProducesDeterministicClosedApproximateMesh()
+ {
+ var grid=BoxGrid(25,1,new(-12.25,-12.25,-12.25),new(8,6,5));
+ var first=SharpDualContouring.Reconstruct(grid);var second=SharpDualContouring.Reconstruct(grid);
+ Assert.NotEmpty(first.Mesh.Vertices);Assert.NotEmpty(first.Mesh.Triangles);
+ Assert.Equal(0,first.Diagnostics.BoundaryEdges);Assert.Equal(0,first.Diagnostics.NonManifoldEdges);Assert.Equal(1,first.Diagnostics.Components);
+ Assert.Equal(first.Mesh.Vertices,second.Mesh.Vertices);Assert.Equal(first.Mesh.Triangles,second.Mesh.Triangles);
+ Assert.Contains(first.Mesh.Vertices,v=>Math.Abs(v.X-8)<.25&&Math.Abs(v.Y-6)<.25&&Math.Abs(v.Z-5)<.25);
+ var rms=Math.Sqrt(first.Mesh.Vertices.Average(v=>Math.Pow(BoxDistance(v,new(8,6,5)),2)));
+ Assert.True(rms<.1,$"Expected sharp QEF vertices close to exact box; RMS was {rms:G6} mm.");
+ Assert.Contains("not BRep",first.Mesh.Provenance.Authority,StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void DiagnosticsAlwaysExposeTopologyFailures()
+ {
+ var mesh=new ApproximateSurfaceMesh(new[]{new Point3D(0,0,0),new(1,0,0),new(0,1,0),new(0,-1,0),new(0,0,1)},
+ new[]{new MeshTriangle(0,1,2),new MeshTriangle(0,1,3),new MeshTriangle(0,1,4),new MeshTriangle(0,1,2)},new("test","test","approximate"));
+ var diagnostics=SharpDualContouring.Diagnose(mesh);
+ Assert.True(diagnostics.NonManifoldEdges>0);Assert.True(diagnostics.DuplicateFaces>0);Assert.True(diagnostics.BoundaryEdges>0);
+ }
+
+ private static SampledSdfGrid BoxGrid(int n,double spacing,Point3D origin,Vector3D h)
+ {
+ var values=new double[n*n*n];var i=0;
+ for(var z=0;z<n;z++)for(var y=0;y<n;y++)for(var x=0;x<n;x++)
+ {
+ var px=origin.X+x*spacing;var py=origin.Y+y*spacing;var pz=origin.Z+z*spacing;
+ var qx=Math.Abs(px)-h.X;var qy=Math.Abs(py)-h.Y;var qz=Math.Abs(pz)-h.Z;
+ values[i++]=Math.Sqrt(Math.Pow(Math.Max(qx,0),2)+Math.Pow(Math.Max(qy,0),2)+Math.Pow(Math.Max(qz,0),2))+Math.Min(Math.Max(qx,Math.Max(qy,qz)),0);
+ }
+ return new(n,n,n,origin,new(spacing,spacing,spacing),values);
+ }
+
+ private static double BoxDistance(Point3D p,Vector3D h)
+ {
+ var qx=Math.Abs(p.X)-h.X;var qy=Math.Abs(p.Y)-h.Y;var qz=Math.Abs(p.Z)-h.Z;
+ return Math.Sqrt(Math.Pow(Math.Max(qx,0),2)+Math.Pow(Math.Max(qy,0),2)+Math.Pow(Math.Max(qz,0),2))+Math.Min(Math.Max(qx,Math.Max(qy,qz)),0);
+ }
+}
diff --git a/Aetheris.Continuum/README.md b/Aetheris.Continuum/README.md
new file mode 100644
index 00000000..4cb19bae
--- /dev/null
+++ b/Aetheris.Continuum/README.md
@@ -0,0 +1,30 @@
+# Aetheris.Continuum bounded reconstruction utilities
+
+`Aetheris.Continuum.Reconstruction` contains two deliberately small geometry-decompilation aids:
+
+- `PointTorusField` evaluates precomputed local analytic tori imported from an external fitter. It follows the query representation and 32-neighbor exponential blend observed in Feng et al., *Points as Tori: Fast Pointwise Signed Distance for Point Clouds* (SIGGRAPH 2026). The learned Flax model and its weights are not included. [Project](https://nzfeng.github.io/research/PointsAsTori/index.html) · [code](https://github.com/nzfeng/points-as-tori)
+- `SharpDualContouring` converts a regular sampled signed-distance grid into an approximate explicit triangle mesh with sign-changing-edge Hermite constraints, finite-difference normals, per-cell QEF placement, and deterministic dual connectivity. It is a clean-room bounded implementation informed by Carrera et al., *Dual Contouring of Signed Distance Data*. [code](https://github.com/xianacarrera/dual-contouring-of-signed-distance-data)
+
+## Authority warning
+
+Both outputs are approximate, source-derived evidence for reconstruction, scan comparison, fitting, and geometry decompilation. They are not BRep, CIR topology, Firmament feature history, manufacturing geometry, or semantic authority. A mesh extracted here requires a separate explicit reconstruction/admission step before it can participate in stronger lanes.
+
+PAT sign is qualified only for closed, globally oriented, locally single-sheet input and only inside the declared near-source validity band. Open, unoriented, thin, and multi-sheet inputs return unsigned values. Callers must inspect both `Qualification` and `IsSigned`: a query can be outside the validity band and also unsigned. Callers receive `PointTorusEvaluation`; there is intentionally no naked-double query API.
+
+The contourer always reports boundary edges, nonmanifold edges, connected components, duplicate faces, and duplicate vertices. It does not repair them. These counters do not test self-intersection, consistent orientation, degenerate triangles, or source-distance fitness; downstream admission must add whichever checks its authority requires.
+
+## Minimal CLI workflow
+
+```powershell
+dotnet run --project Aetheris.CLI -- continuum make-fixtures --out-dir artifacts/local/continuum-tools-x1
+dotnet run --project Aetheris.CLI -- continuum pat-query artifacts/local/continuum-tools-x1/sphere-point-tori.json artifacts/local/continuum-tools-x1/sphere-queries.json --out artifacts/local/continuum-tools-x1/sphere-results.json
+dotnet run --project Aetheris.CLI -- continuum contour artifacts/local/continuum-tools-x1/sharp-box-grid.json --out artifacts/local/continuum-tools-x1/sharp-box.obj --report artifacts/local/continuum-tools-x1/sharp-box-report.json
+```
+
+The interchange formats are intentionally boring JSON (`aetheris.point-torus-field.v1`, `aetheris.sampled-sdf-grid.v1`) and OBJ. Coordinates, radii, spacing, distances, and validity bands use millimetres. Grid values are flattened with X varying fastest, then Y, then Z: `values[(z * sizeY * sizeX) + (y * sizeX) + x]`. Query input is a JSON array of `[x,y,z]` millimetre triples. `make-fixtures` generates complete deterministic examples under ignored local artifacts.
+
+The public upstream PAT path used 32 neighbors; `NeighborCount` remains explicit and may be smaller for tiny fixtures. The blend is the observed upstream exponential kernel with `shift = 0.5 * max(neighbor distance)` and `lambda = 64 / shift`.
+
+## Licensing and provenance
+
+The PAT upstream repository is MIT, but its pretrained weight file has no separately stated grant; this module redistributes neither code nor weights. The DCSD repository contains an MIT text whose copyright notice names Nick Sharp rather than the paper authors, while the paper PDF is CC BY-NC-ND; this implementation therefore copies no upstream source. Preserve upstream/model hashes in `PointTorusProvenance` when importing real fitted parameters.
diff --git a/Aetheris.Continuum/Reconstruction/ContinuumInterchange.cs b/Aetheris.Continuum/Reconstruction/ContinuumInterchange.cs
new file mode 100644
index 00000000..992a7ea1
--- /dev/null
+++ b/Aetheris.Continuum/Reconstruction/ContinuumInterchange.cs
@@ -0,0 +1,54 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Continuum.Reconstruction;
+
+public sealed record PointTorusJsonSample(double[] SourcePoint, double[] SourceNormal, double[] Center, double[] Axis, double MajorRadius, double SignedMinorRadius);
+public sealed record PointTorusJsonDocument(
+ string Schema,
+ string Source,
+ string ParameterProducer,
+ string? ModelRevision,
+ string? ModelHash,
+ int NeighborCount,
+ double ValidityBandMm,
+ PointTorusSignCapability SignCapability,
+ PointTorusJsonSample[] Samples,
+ Dictionary<string,string>? Properties = null);
+
+public sealed record SampledSdfGridJsonDocument(string Schema, int SizeX, int SizeY, int SizeZ, double[] Origin, double[] Spacing, double[] Values, string Source);
+
+public static class ContinuumInterchange
+{
+ public const string PointTorusSchema = "aetheris.point-torus-field.v1";
+ public const string SdfGridSchema = "aetheris.sampled-sdf-grid.v1";
+ public static readonly JsonSerializerOptions JsonOptions = CreateOptions();
+
+ public static PointTorusField ReadPointTorusField(Stream stream)
+ {
+ var document = JsonSerializer.Deserialize<PointTorusJsonDocument>(stream, JsonOptions) ?? throw new InvalidDataException("Point-torus JSON is empty.");
+ if (document.Schema != PointTorusSchema) throw new InvalidDataException($"Expected schema '{PointTorusSchema}'.");
+ var samples = document.Samples.Select((s,i) => new PointTorusSample(Point(s.SourcePoint,$"samples[{i}].sourcePoint"), Vector(s.SourceNormal,$"samples[{i}].sourceNormal"),
+ Point(s.Center,$"samples[{i}].center"), Vector(s.Axis,$"samples[{i}].axis"), s.MajorRadius, s.SignedMinorRadius));
+ return new(samples, new(document.NeighborCount, document.ValidityBandMm, document.SignCapability),
+ new(document.Source, document.ParameterProducer, document.ModelRevision, document.ModelHash, document.Properties));
+ }
+
+ public static SampledSdfGrid ReadSdfGrid(Stream stream, out string source)
+ {
+ var document = JsonSerializer.Deserialize<SampledSdfGridJsonDocument>(stream, JsonOptions) ?? throw new InvalidDataException("SDF grid JSON is empty.");
+ if (document.Schema != SdfGridSchema) throw new InvalidDataException($"Expected schema '{SdfGridSchema}'.");
+ source = document.Source;
+ return new(document.SizeX,document.SizeY,document.SizeZ,Point(document.Origin,"origin"),Vector(document.Spacing,"spacing"),document.Values);
+ }
+
+ private static Point3D Point(double[] values,string name){Require3(values,name);return new(values[0],values[1],values[2]);}
+ private static Vector3D Vector(double[] values,string name){Require3(values,name);return new(values[0],values[1],values[2]);}
+ private static void Require3(double[]? values,string name){if(values is null||values.Length!=3||values.Any(v=>!double.IsFinite(v)))throw new InvalidDataException($"'{name}' must contain three finite numbers.");}
+ private static JsonSerializerOptions CreateOptions()
+ {
+ var options=new JsonSerializerOptions{PropertyNamingPolicy=JsonNamingPolicy.CamelCase,PropertyNameCaseInsensitive=true,WriteIndented=true};
+ options.Converters.Add(new JsonStringEnumConverter()); return options;
+ }
+}
diff --git a/Aetheris.Continuum/Reconstruction/PointTorusField.cs b/Aetheris.Continuum/Reconstruction/PointTorusField.cs
new file mode 100644
index 00000000..49f5a6da
--- /dev/null
+++ b/Aetheris.Continuum/Reconstruction/PointTorusField.cs
@@ -0,0 +1,210 @@
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Continuum.Reconstruction;
+
+public enum PointTorusSignCapability
+{
+ SignedClosedOriented,
+ UnsignedOnlyOpenSurface,
+ UnsignedOnlyUnoriented,
+ UnsignedOnlyMultiSheet
+}
+
+public enum PointTorusQualification
+{
+ Qualified,
+ UnsignedOnly,
+ OutsideValidityBand,
+ InsufficientNeighborhood
+}
+
+public sealed record PointTorusProvenance(
+ string Source,
+ string ParameterProducer,
+ string? ModelRevision,
+ string? ModelHash,
+ IReadOnlyDictionary<string, string>? Properties = null);
+
+public sealed record PointTorusFieldSettings(
+ int NeighborCount = 32,
+ double ValidityBandMm = 5d,
+ PointTorusSignCapability SignCapability = PointTorusSignCapability.SignedClosedOriented)
+{
+ public void Validate(int sampleCount)
+ {
+ if (NeighborCount < 1 || NeighborCount > sampleCount)
+ throw new ArgumentOutOfRangeException(nameof(NeighborCount), "Neighbor count must be within the imported sample count.");
+ if (!double.IsFinite(ValidityBandMm) || ValidityBandMm <= 0d)
+ throw new ArgumentOutOfRangeException(nameof(ValidityBandMm), "Validity band must be finite and positive.");
+ }
+}
+
+/// <summary>One precomputed local analytic torus. Learned fitting is deliberately outside this assembly.</summary>
+public sealed record PointTorusSample(
+ Point3D SourcePoint,
+ Vector3D SourceNormal,
+ Point3D Center,
+ Vector3D Axis,
+ double MajorRadius,
+ double SignedMinorRadius);
+
+public readonly record struct PointTorusEvaluation(
+ double ValueMm,
+ PointTorusQualification Qualification,
+ bool IsSigned,
+ int NeighborsUsed,
+ double NearestSourceDistanceMm,
+ string Reason);
+
+/// <summary>
+/// Source-derived approximate field using precomputed Points-as-Tori local parameters.
+/// This is reconstruction/query evidence, never BRep, topology, or manufacturing authority.
+/// </summary>
+public sealed class PointTorusField
+{
+ private readonly PointTorusSample[] _samples;
+ private readonly KdIndex _index;
+
+ public PointTorusField(IEnumerable<PointTorusSample> samples, PointTorusFieldSettings settings, PointTorusProvenance provenance)
+ {
+ ArgumentNullException.ThrowIfNull(samples);
+ ArgumentNullException.ThrowIfNull(settings);
+ ArgumentNullException.ThrowIfNull(provenance);
+ _samples = samples.ToArray();
+ if (_samples.Length == 0) throw new ArgumentException("At least one local torus is required.", nameof(samples));
+ settings.Validate(_samples.Length);
+ for (var i = 0; i < _samples.Length; i++) Validate(_samples[i], i);
+ Settings = settings;
+ Provenance = provenance;
+ _index = new KdIndex(_samples.Select(static s => s.SourcePoint).ToArray());
+ }
+
+ public IReadOnlyList<PointTorusSample> Samples => _samples;
+ public PointTorusFieldSettings Settings { get; }
+ public PointTorusProvenance Provenance { get; }
+ public string Acceleration => "deterministic-kd-tree";
+
+ public PointTorusEvaluation Evaluate(Point3D query)
+ {
+ var neighbors = _index.Nearest(query, Settings.NeighborCount);
+ if (neighbors.Length == 0)
+ return new(double.NaN, PointTorusQualification.InsufficientNeighborhood, false, 0, double.PositiveInfinity, "No local torus was available.");
+
+ var maxDistance = Math.Sqrt(neighbors[^1].DistanceSquared);
+ var nearest = Math.Sqrt(neighbors[0].DistanceSquared);
+ var shift = 0.5d * maxDistance;
+ var weighted = 0d;
+ var weightSum = 0d;
+ var signed = Settings.SignCapability == PointTorusSignCapability.SignedClosedOriented;
+ foreach (var neighbor in neighbors)
+ {
+ var distance = Math.Sqrt(neighbor.DistanceSquared);
+ var weight = shift <= 1e-15 ? 1d : Math.Exp((-64d / shift) * (distance - shift));
+ var local = EvaluateTorus(_samples[neighbor.Index], query);
+ weighted += weight * (signed ? local : Math.Abs(local));
+ weightSum += weight;
+ }
+
+ var value = weighted / weightSum;
+ if (nearest > Settings.ValidityBandMm)
+ return new(value, PointTorusQualification.OutsideValidityBand, signed, neighbors.Length, nearest,
+ $"Nearest source sample is {nearest:G6} mm away, outside the {Settings.ValidityBandMm:G6} mm validity band." +
+ (signed ? string.Empty : $" {SignReason(Settings.SignCapability)}"));
+ if (!signed)
+ return new(value, PointTorusQualification.UnsignedOnly, false, neighbors.Length, nearest, SignReason(Settings.SignCapability));
+ return new(value, PointTorusQualification.Qualified, true, neighbors.Length, nearest, "Closed, globally oriented source within the declared validity band.");
+ }
+
+ public PointTorusEvaluation[] EvaluateBatch(IEnumerable<Point3D> queries)
+ {
+ ArgumentNullException.ThrowIfNull(queries);
+ return queries.Select(Evaluate).ToArray();
+ }
+
+ public static double EvaluateTorus(PointTorusSample torus, Point3D query)
+ {
+ var delta = query - torus.Center;
+ var axis = torus.Axis;
+ var axial = delta.Dot(axis);
+ var radial = delta.Cross(axis).Length;
+ var tubeDistance = Math.Sqrt(((radial - torus.MajorRadius) * (radial - torus.MajorRadius)) + (axial * axial));
+ return Math.Sign(torus.SignedMinorRadius) * (tubeDistance - Math.Abs(torus.SignedMinorRadius));
+ }
+
+ private static void Validate(PointTorusSample sample, int index)
+ {
+ static bool FinitePoint(Point3D p) => double.IsFinite(p.X) && double.IsFinite(p.Y) && double.IsFinite(p.Z);
+ static bool FiniteVector(Vector3D v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z);
+ if (!FinitePoint(sample.SourcePoint) || !FiniteVector(sample.SourceNormal) || !FinitePoint(sample.Center) || !FiniteVector(sample.Axis) ||
+ !double.IsFinite(sample.MajorRadius) || !double.IsFinite(sample.SignedMinorRadius))
+ throw new ArgumentException($"Local torus {index} contains a non-finite value.");
+ if (Math.Abs(sample.Axis.Length - 1d) > 1e-8)
+ throw new ArgumentException($"Local torus {index} axis must be unit length.");
+ if (sample.MajorRadius < 0d || Math.Abs(sample.SignedMinorRadius) <= 1e-15)
+ throw new ArgumentException($"Local torus {index} radii are invalid.");
+ }
+
+ private static string SignReason(PointTorusSignCapability capability) => capability switch
+ {
+ PointTorusSignCapability.UnsignedOnlyOpenSurface => "Open source surfaces do not define authoritative inside/outside.",
+ PointTorusSignCapability.UnsignedOnlyUnoriented => "Globally consistent oriented normals are required for sign.",
+ PointTorusSignCapability.UnsignedOnlyMultiSheet => "Thin or locally multi-sheet neighborhoods are restricted to unsigned residuals.",
+ _ => "Sign is not qualified."
+ };
+
+ private readonly record struct Neighbor(int Index, double DistanceSquared);
+
+ private sealed class KdIndex
+ {
+ private readonly Point3D[] _points;
+ private readonly Node? _root;
+
+ public KdIndex(Point3D[] points)
+ {
+ _points = points;
+ _root = Build(Enumerable.Range(0, points.Length).ToArray(), 0);
+ }
+
+ public Neighbor[] Nearest(Point3D query, int count)
+ {
+ var heap = new PriorityQueue<Neighbor, double>();
+ Search(_root, query, count, heap);
+ return heap.UnorderedItems.Select(static x => x.Element).OrderBy(static x => x.DistanceSquared).ThenBy(static x => x.Index).ToArray();
+ }
+
+ private Node? Build(int[] indices, int depth)
+ {
+ if (indices.Length == 0) return null;
+ var axis = depth % 3;
+ Array.Sort(indices, (a, b) => Coordinate(_points[a], axis).CompareTo(Coordinate(_points[b], axis)) is var c && c != 0 ? c : a.CompareTo(b));
+ var middle = indices.Length / 2;
+ return new(indices[middle], axis,
+ Build(indices[..middle], depth + 1),
+ Build(indices[(middle + 1)..], depth + 1));
+ }
+
+ private void Search(Node? node, Point3D query, int count, PriorityQueue<Neighbor, double> heap)
+ {
+ if (node is null) return;
+ var point = _points[node.Index];
+ var d = query - point;
+ var distanceSquared = d.LengthSquared;
+ if (heap.Count < count) heap.Enqueue(new(node.Index, distanceSquared), -distanceSquared);
+ else if (heap.TryPeek(out _, out var worstPriority) && distanceSquared < -worstPriority)
+ {
+ heap.Dequeue();
+ heap.Enqueue(new(node.Index, distanceSquared), -distanceSquared);
+ }
+
+ var delta = Coordinate(query, node.Axis) - Coordinate(point, node.Axis);
+ var near = delta <= 0d ? node.Left : node.Right;
+ var far = delta <= 0d ? node.Right : node.Left;
+ Search(near, query, count, heap);
+ var worst = heap.Count < count || !heap.TryPeek(out _, out var p) ? double.PositiveInfinity : -p;
+ if ((delta * delta) <= worst) Search(far, query, count, heap);
+ }
+
+ private static double Coordinate(Point3D p, int axis) => axis == 0 ? p.X : axis == 1 ? p.Y : p.Z;
+ private sealed record Node(int Index, int Axis, Node? Left, Node? Right);
+ }
+}
diff --git a/Aetheris.Continuum/Reconstruction/SharpDualContouring.cs b/Aetheris.Continuum/Reconstruction/SharpDualContouring.cs
new file mode 100644
index 00000000..1eec3080
--- /dev/null
+++ b/Aetheris.Continuum/Reconstruction/SharpDualContouring.cs
@@ -0,0 +1,210 @@
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Continuum.Reconstruction;
+
+public sealed class SampledSdfGrid
+{
+ public SampledSdfGrid(int sizeX, int sizeY, int sizeZ, Point3D origin, Vector3D spacing, IReadOnlyList<double> values)
+ {
+ if (sizeX < 2 || sizeY < 2 || sizeZ < 2) throw new ArgumentOutOfRangeException(nameof(sizeX), "Grid dimensions must each be at least two.");
+ if (spacing.X <= 0d || spacing.Y <= 0d || spacing.Z <= 0d) throw new ArgumentOutOfRangeException(nameof(spacing), "Grid spacing must be positive.");
+ if (values.Count != checked(sizeX * sizeY * sizeZ)) throw new ArgumentException("Grid value count does not match dimensions.", nameof(values));
+ if (values.Any(static v => !double.IsFinite(v))) throw new ArgumentException("Grid contains a non-finite sample.", nameof(values));
+ SizeX = sizeX; SizeY = sizeY; SizeZ = sizeZ; Origin = origin; Spacing = spacing; Values = values.ToArray();
+ }
+
+ public int SizeX { get; }
+ public int SizeY { get; }
+ public int SizeZ { get; }
+ public Point3D Origin { get; }
+ public Vector3D Spacing { get; }
+ public IReadOnlyList<double> Values { get; }
+ public double this[int x, int y, int z] => Values[(z * SizeY * SizeX) + (y * SizeX) + x];
+ public Point3D Point(int x, int y, int z) => new(Origin.X + (x * Spacing.X), Origin.Y + (y * Spacing.Y), Origin.Z + (z * Spacing.Z));
+}
+
+public sealed record ApproximateMeshProvenance(string Source, string Algorithm, string Authority, IReadOnlyDictionary<string, string>? Properties = null);
+public readonly record struct MeshTriangle(int A, int B, int C);
+public sealed record ApproximateSurfaceMesh(IReadOnlyList<Point3D> Vertices, IReadOnlyList<MeshTriangle> Triangles, ApproximateMeshProvenance Provenance);
+public sealed record MeshTopologyDiagnostics(int BoundaryEdges, int NonManifoldEdges, int Components, int DuplicateFaces, int DuplicateVertices);
+public sealed record SharpDualContourStatistics(int ActiveCells, int HermiteConstraints, double ElapsedMilliseconds);
+public sealed record SharpDualContourResult(ApproximateSurfaceMesh Mesh, MeshTopologyDiagnostics Diagnostics, SharpDualContourStatistics Statistics);
+
+/// <summary>Clean-room bounded sharp dual contouring of a regular sampled SDF grid.</summary>
+public static class SharpDualContouring
+{
+ private static readonly (int A, int B)[] CellEdges =
+ {
+ (0,1),(2,3),(4,5),(6,7), (0,2),(1,3),(4,6),(5,7), (0,4),(1,5),(2,6),(3,7)
+ };
+ private static readonly (int X, int Y, int Z)[] Corners =
+ {
+ (0,0,0),(1,0,0),(0,1,0),(1,1,0),(0,0,1),(1,0,1),(0,1,1),(1,1,1)
+ };
+
+ public static SharpDualContourResult Reconstruct(SampledSdfGrid grid, string source = "sampled-sdf-grid")
+ {
+ ArgumentNullException.ThrowIfNull(grid);
+ var started = System.Diagnostics.Stopwatch.StartNew();
+ var vertices = new List<Point3D>();
+ var cellVertices = new Dictionary<(int X, int Y, int Z), int>();
+ var constraintCount = 0;
+ for (var z = 0; z < grid.SizeZ - 1; z++)
+ for (var y = 0; y < grid.SizeY - 1; y++)
+ for (var x = 0; x < grid.SizeX - 1; x++)
+ {
+ var values = new double[8];
+ var negative = 0;
+ for (var c = 0; c < 8; c++)
+ {
+ var o = Corners[c]; values[c] = grid[x + o.X, y + o.Y, z + o.Z];
+ if (values[c] < 0d) negative++;
+ }
+ if (negative is 0 or 8) continue;
+
+ var constraints = new List<(Point3D Point, Vector3D Normal)>(12);
+ foreach (var (a, b) in CellEdges)
+ {
+ if ((values[a] < 0d) == (values[b] < 0d)) continue;
+ var oa = Corners[a]; var ob = Corners[b];
+ var pa = grid.Point(x + oa.X, y + oa.Y, z + oa.Z);
+ var pb = grid.Point(x + ob.X, y + ob.Y, z + ob.Z);
+ var t = values[a] / (values[a] - values[b]);
+ var p = Lerp(pa, pb, t);
+ var normal = Gradient(grid, p);
+ if (normal.TryNormalize(out var unit)) constraints.Add((p, unit));
+ }
+ if (constraints.Count == 0) continue;
+ constraintCount += constraints.Count;
+ var min = grid.Point(x, y, z); var max = grid.Point(x + 1, y + 1, z + 1);
+ var vertex = SolveQef(constraints, min, max);
+ cellVertices[(x, y, z)] = vertices.Count;
+ vertices.Add(vertex);
+ }
+
+ var triangles = new List<MeshTriangle>();
+ AddXEdgeFaces(grid, cellVertices, triangles);
+ AddYEdgeFaces(grid, cellVertices, triangles);
+ AddZEdgeFaces(grid, cellVertices, triangles);
+ var provenance = new ApproximateMeshProvenance(source, "clean-room-bounded-sharp-dual-contouring",
+ "Approximate reconstruction evidence only; not BRep, topology, feature, or manufacturing authority.",
+ new Dictionary<string, string> { ["grid"] = $"{grid.SizeX}x{grid.SizeY}x{grid.SizeZ}", ["placement"] = "Hermite QEF constrained to source cell" });
+ var mesh = new ApproximateSurfaceMesh(vertices, triangles, provenance);
+ var diagnostics = Diagnose(mesh);
+ started.Stop();
+ return new(mesh, diagnostics, new(cellVertices.Count, constraintCount, started.Elapsed.TotalMilliseconds));
+ }
+
+ private static void AddXEdgeFaces(SampledSdfGrid g, Dictionary<(int,int,int),int> cells, List<MeshTriangle> triangles)
+ {
+ for (var z=1; z<g.SizeZ-1; z++) for (var y=1; y<g.SizeY-1; y++) for (var x=0; x<g.SizeX-1; x++)
+ AddFaceIfCrossing(g[x,y,z], g[x+1,y,z], cells, triangles, (x,y-1,z-1),(x,y,z-1),(x,y,z),(x,y-1,z));
+ }
+ private static void AddYEdgeFaces(SampledSdfGrid g, Dictionary<(int,int,int),int> cells, List<MeshTriangle> triangles)
+ {
+ for (var z=1; z<g.SizeZ-1; z++) for (var y=0; y<g.SizeY-1; y++) for (var x=1; x<g.SizeX-1; x++)
+ AddFaceIfCrossing(g[x,y,z], g[x,y+1,z], cells, triangles, (x-1,y,z-1),(x-1,y,z),(x,y,z),(x,y,z-1));
+ }
+ private static void AddZEdgeFaces(SampledSdfGrid g, Dictionary<(int,int,int),int> cells, List<MeshTriangle> triangles)
+ {
+ for (var z=0; z<g.SizeZ-1; z++) for (var y=1; y<g.SizeY-1; y++) for (var x=1; x<g.SizeX-1; x++)
+ AddFaceIfCrossing(g[x,y,z], g[x,y,z+1], cells, triangles, (x-1,y-1,z),(x,y-1,z),(x,y,z),(x-1,y,z));
+ }
+
+ private static void AddFaceIfCrossing(double a, double b, Dictionary<(int,int,int),int> cells, List<MeshTriangle> triangles,
+ (int,int,int) c0, (int,int,int) c1, (int,int,int) c2, (int,int,int) c3)
+ {
+ if ((a < 0d) == (b < 0d) || !cells.TryGetValue(c0,out var i0) || !cells.TryGetValue(c1,out var i1) ||
+ !cells.TryGetValue(c2,out var i2) || !cells.TryGetValue(c3,out var i3)) return;
+ if (a < 0d)
+ {
+ triangles.Add(new(i0,i1,i2)); triangles.Add(new(i0,i2,i3));
+ }
+ else
+ {
+ triangles.Add(new(i0,i2,i1)); triangles.Add(new(i0,i3,i2));
+ }
+ }
+
+ private static Point3D SolveQef(IReadOnlyList<(Point3D Point, Vector3D Normal)> constraints, Point3D min, Point3D max)
+ {
+ var centroid = new Point3D(constraints.Average(c=>c.Point.X), constraints.Average(c=>c.Point.Y), constraints.Average(c=>c.Point.Z));
+ var a00=0d; var a01=0d; var a02=0d; var a11=0d; var a12=0d; var a22=0d; var b0=0d; var b1=0d; var b2=0d;
+ foreach (var (p,n) in constraints)
+ {
+ var d=(n.X*p.X)+(n.Y*p.Y)+(n.Z*p.Z);
+ a00+=n.X*n.X; a01+=n.X*n.Y; a02+=n.X*n.Z; a11+=n.Y*n.Y; a12+=n.Y*n.Z; a22+=n.Z*n.Z;
+ b0+=n.X*d; b1+=n.Y*d; b2+=n.Z*d;
+ }
+ var regularization = Math.Max(1e-10, constraints.Count * 1e-9);
+ a00+=regularization; a11+=regularization; a22+=regularization;
+ b0+=regularization*centroid.X; b1+=regularization*centroid.Y; b2+=regularization*centroid.Z;
+ var solved = SolveSymmetric(a00,a01,a02,a11,a12,a22,b0,b1,b2, out var x, out var y, out var z);
+ if (!solved) return centroid;
+ return new(Math.Clamp(x,min.X,max.X), Math.Clamp(y,min.Y,max.Y), Math.Clamp(z,min.Z,max.Z));
+ }
+
+ private static bool SolveSymmetric(double a00,double a01,double a02,double a11,double a12,double a22,double b0,double b1,double b2,
+ out double x,out double y,out double z)
+ {
+ var m = new[,] {{a00,a01,a02,b0},{a01,a11,a12,b1},{a02,a12,a22,b2}};
+ for (var col=0; col<3; col++)
+ {
+ var pivot=col; for(var r=col+1;r<3;r++) if(Math.Abs(m[r,col])>Math.Abs(m[pivot,col])) pivot=r;
+ if(Math.Abs(m[pivot,col])<1e-14){x=y=z=0d;return false;}
+ if(pivot!=col) for(var c=col;c<4;c++) (m[col,c],m[pivot,c])=(m[pivot,c],m[col,c]);
+ var scale=m[col,col]; for(var c=col;c<4;c++) m[col,c]/=scale;
+ for(var r=0;r<3;r++) if(r!=col){var factor=m[r,col];for(var c=col;c<4;c++)m[r,c]-=factor*m[col,c];}
+ }
+ x=m[0,3];y=m[1,3];z=m[2,3];return double.IsFinite(x)&&double.IsFinite(y)&&double.IsFinite(z);
+ }
+
+ private static Vector3D Gradient(SampledSdfGrid grid, Point3D p)
+ {
+ var ex=grid.Spacing.X*.25d; var ey=grid.Spacing.Y*.25d; var ez=grid.Spacing.Z*.25d;
+ return new((Sample(grid,new(p.X+ex,p.Y,p.Z))-Sample(grid,new(p.X-ex,p.Y,p.Z)))/(2d*ex),
+ (Sample(grid,new(p.X,p.Y+ey,p.Z))-Sample(grid,new(p.X,p.Y-ey,p.Z)))/(2d*ey),
+ (Sample(grid,new(p.X,p.Y,p.Z+ez))-Sample(grid,new(p.X,p.Y,p.Z-ez)))/(2d*ez));
+ }
+
+ private static double Sample(SampledSdfGrid g, Point3D p)
+ {
+ var fx=Math.Clamp((p.X-g.Origin.X)/g.Spacing.X,0d,g.SizeX-1d); var x=Math.Min((int)Math.Floor(fx),g.SizeX-2); var tx=fx-x;
+ var fy=Math.Clamp((p.Y-g.Origin.Y)/g.Spacing.Y,0d,g.SizeY-1d); var y=Math.Min((int)Math.Floor(fy),g.SizeY-2); var ty=fy-y;
+ var fz=Math.Clamp((p.Z-g.Origin.Z)/g.Spacing.Z,0d,g.SizeZ-1d); var z=Math.Min((int)Math.Floor(fz),g.SizeZ-2); var tz=fz-z;
+ double L(double a,double b,double t)=>a+((b-a)*t);
+ var z0=L(L(g[x,y,z],g[x+1,y,z],tx),L(g[x,y+1,z],g[x+1,y+1,z],tx),ty);
+ var z1=L(L(g[x,y,z+1],g[x+1,y,z+1],tx),L(g[x,y+1,z+1],g[x+1,y+1,z+1],tx),ty);
+ return L(z0,z1,tz);
+ }
+
+ private static Point3D Lerp(Point3D a, Point3D b, double t) => new(a.X+((b.X-a.X)*t),a.Y+((b.Y-a.Y)*t),a.Z+((b.Z-a.Z)*t));
+
+ public static MeshTopologyDiagnostics Diagnose(ApproximateSurfaceMesh mesh)
+ {
+ var edges=new Dictionary<(int,int),int>(); var faces=new HashSet<(int,int,int)>(); var duplicateFaces=0;
+ var adjacency=Enumerable.Range(0,mesh.Vertices.Count).Select(_=>new List<int>()).ToArray();
+ foreach(var t in mesh.Triangles)
+ {
+ var key=Sort3(t.A,t.B,t.C); if(!faces.Add(key)) duplicateFaces++;
+ AddEdge(t.A,t.B);AddEdge(t.B,t.C);AddEdge(t.C,t.A);
+ }
+ void AddEdge(int a,int b){if(a>b)(a,b)=(b,a);edges[(a,b)]=edges.GetValueOrDefault((a,b))+1;adjacency[a].Add(b);adjacency[b].Add(a);}
+ var components=0; var visited=new bool[mesh.Vertices.Count];
+ for(var i=0;i<visited.Length;i++) if(!visited[i]){components++;var q=new Queue<int>();q.Enqueue(i);visited[i]=true;while(q.Count>0){foreach(var n in adjacency[q.Dequeue()])if(!visited[n]){visited[n]=true;q.Enqueue(n);}}}
+ var duplicateVertices=mesh.Vertices.Count-mesh.Vertices.Distinct().Count();
+ return new(edges.Count(e=>e.Value==1),edges.Count(e=>e.Value>2),components,duplicateFaces,duplicateVertices);
+ }
+
+ private static (int,int,int) Sort3(int a,int b,int c){if(a>b)(a,b)=(b,a);if(b>c)(b,c)=(c,b);if(a>b)(a,b)=(b,a);return(a,b,c);}
+}
+
+public static class ApproximateMeshObj
+{
+ public static void Write(ApproximateSurfaceMesh mesh, TextWriter writer)
+ {
+ writer.WriteLine("# Aetheris approximate reconstruction; not canonical CAD authority");
+ foreach(var v in mesh.Vertices) writer.WriteLine(FormattableString.Invariant($"v {v.X:R} {v.Y:R} {v.Z:R}"));
+ foreach(var t in mesh.Triangles) writer.WriteLine($"f {t.A+1} {t.B+1} {t.C+1}");
+ }
+}
diff --git a/docs/release/CONTINUUM-TOOLS-X1.md b/docs/release/CONTINUUM-TOOLS-X1.md
new file mode 100644
index 00000000..674f2575
--- /dev/null
+++ b/docs/release/CONTINUUM-TOOLS-X1.md
@@ -0,0 +1,108 @@
+# CONTINUUM-TOOLS-X1 — bounded implicit reconstruction utilities
+
+Date: 2026-09-17
+Verdict: **Accepted**
+
+## Executive result
+
+Aetheris now has two small, real, agent-usable decompilation utilities in `Aetheris.Continuum.Reconstruction`:
+
+1. `PointTorusField`: a deterministic KD-tree-backed consumer of externally precomputed PAT local torus parameters, using the observed upstream analytic formula and exponential neighbor blend. Every query reports its qualification, signed capability, neighbor count, nearest-source distance, and reason.
+2. `SharpDualContouring`: a clean-room regular-grid SDF to approximate explicit mesh path using sign-changing primal edges, finite-difference Hermite normals, constrained per-cell QEF placement, deterministic connectivity, OBJ export, provenance, and unconditional topology diagnostics.
+
+This is not a general reconstruction framework, plugin model, strategy registry, hybrid PAT/DCSD system, or production BRep path. Learned PAT inference remains external. The contourer is the useful sharp QEF/dual-connectivity core, not a claim to reproduce the paper's slow iterative sphere optimizer.
+
+## Evidence
+
+The actual CLI workflow generated and consumed its own versioned JSON under `artifacts/local/continuum-tools-x1`.
+
+| Case | Result |
+|---|---:|
+| PAT exact 10 mm sphere | exact values at all four probes (`-10`, `0`, `2`, `-1` mm) |
+| PAT near-source probes | `Qualified`, signed |
+| PAT center probe | correct value but `OutsideValidityBand` rather than silently authoritative |
+| Sharp box grid | 25 x 25 x 25 nodes, offset from the zero set |
+| Sharp-box output | 946 vertices, 1,888 triangles |
+| Sharp-box forward vertex RMS / max | 0.040 / 0.190 mm |
+| Sharp-box topology | 0 boundary, 0 nonmanifold, 1 component, 0 duplicate faces/vertices |
+| Contour kernel time | 25.0 ms on this run |
+
+The earlier exact-box dogfood measured Marching Cubes at 0.1700 mm RMS on a 32³ grid and the published DCSD optimizer at 0.0201 mm in 96.3 s, with 6 nonmanifold edges. X1 is not an apples-to-apples resolution comparison, but it establishes the intended trade: materially sharper placement than the measured MC reference, about four orders of magnitude less contour time than the upstream optimizer, and clean topology on the bounded box. The focused test also requires a recovered positive corner within 0.25 mm per coordinate and vertex RMS below 0.1 mm.
+
+## PAT boundary
+
+The imported representation is exactly the post-inference analytic boundary needed by Aetheris: source point and normal, torus center and unit axis, nonnegative major radius, and signed nonzero minor radius. `PointTorusProvenance` records source, parameter producer, model revision/hash, and arbitrary properties. The model still predicts six local fundamental-form coefficients externally; this library neither embeds nor replaces it.
+
+The field has no naked `double Evaluate(...)`. Results distinguish `Qualified`, `UnsignedOnly`, `OutsideValidityBand`, and `InsufficientNeighborhood`. Sign is available only when metadata declares closed, globally oriented, single-sheet input. Open, unoriented, and thin/multi-sheet inputs evaluate an unsigned residual and explain why. The validity band is explicit and based on nearest source-sample distance.
+
+This is an admission contract, not automatic geometric proof. A producer that falsely labels a bad cloud closed/oriented can still produce wrong answers. X0's measured failures remain governing evidence: sharp box 5.04% sign error, 0.5 mm plate 16.44%, bent `ProfileDelta` sheet 13.37%, and open slab 32.4%.
+
+## DCSD-derived boundary
+
+The implemented core accepts only a finite regular scalar grid with negative-inside convention. It builds one vertex per active dual cell and faces around sign-changing primal edges. It always emits:
+
+- boundary-edge count;
+- nonmanifold-edge count;
+- connected-component count;
+- duplicate-face and duplicate-vertex counts;
+- active-cell, Hermite-constraint, and elapsed-time statistics;
+- approximate provenance and an authority warning.
+
+There is no automatic repair, adaptive octree, feature semantics, or direct BRep conversion. Boundary-touching surfaces may be open because the input must pad a closed zero set. Thin features below grid support can disappear or join. Finite-difference normals limit corner accuracy; this bounded box reached 0.040 mm RMS but a 0.190 mm maximum at corner-influenced cells.
+
+## CLI and agent workflow
+
+```powershell
+dotnet run --project Aetheris.CLI -- continuum make-fixtures --out-dir artifacts/local/continuum-tools-x1
+dotnet run --project Aetheris.CLI -- continuum pat-query artifacts/local/continuum-tools-x1/sphere-point-tori.json artifacts/local/continuum-tools-x1/sphere-queries.json --out artifacts/local/continuum-tools-x1/sphere-results.json
+dotnet run --project Aetheris.CLI -- continuum contour artifacts/local/continuum-tools-x1/sharp-box-grid.json --out artifacts/local/continuum-tools-x1/sharp-box.obj --report artifacts/local/continuum-tools-x1/sharp-box-report.json
+```
+
+Inputs/outputs use versioned JSON and OBJ. Generated bulk artifacts remain ignored. The fixture recipe is under `fixtures/Experiments/ContinuumToolsX1/`.
+
+## Size and complexity
+
+The implementation is intentionally compact:
+
+| Unit | Lines |
+|---|---:|
+| PAT field, qualification, deterministic KD tree | 210 |
+| Sampled grid, QEF contouring, diagnostics, OBJ | 210 |
+| JSON interchange | 54 |
+| CLI commands and deterministic fixtures | 90 |
+| Total production code | 564 |
+
+There is no registry, provider abstraction, generic optimizer, hidden repair pass, or second geometry authority.
+
+## Credit and license posture
+
+PAT is credited to Feng et al., *Points as Tori: Fast Pointwise Signed Distance for Point Clouds* (SIGGRAPH 2026), with project and repository links in `Aetheris.Continuum/README.md`. PAT code is MIT; weights remain external because no separate weight license was found.
+
+The contouring work credits Carrera et al., *Dual Contouring of Signed Distance Data*. Because upstream code provenance is ambiguous (MIT text naming Nick Sharp; paper PDF CC BY-NC-ND), X1 is clean-room and copies no upstream code or data.
+
+## Authority and next boundary
+
+Correct placement:
+
+```text
+ImportedPointCloud + external fitted parameters -> PointTorusField -> qualified residual/query evidence
+SampledSdfGrid -> SharpDualContouring -> ApproximateSurfaceMesh + diagnostics
+either result -> explicit decompilation/reconstruction admission -> stronger geometry, if separately justified
+```
+
+Neither path writes CIR topology or creates canonical BRep/Firmament/manufacturing intent. The smallest later experiment would use these tools in one explicit scan-to-CAD decompilation witness and require topology/qualification admission before downstream use; no hybrid field is justified here.
+
+## Verification
+
+- `dotnet build Aetheris.slnx`: succeeded, 0 errors; seven pre-existing WebAssembly/trimming/platform warnings
+- `Aetheris.Continuum.Tests`: 153/153 passed
+- focused `Aetheris.Continuum.Tests.Reconstruction`: 5/5 passed
+- focused `ContinuumToolsCliTests`: 2/2 passed
+- real CLI fixture generation, PAT query, contour, JSON report, and OBJ output
+- fresh-agent PAT, DCSD, and decompilation workflow checks
+
+## Fresh-agent results
+
+Three agents started from the READMEs rather than implementation knowledge. All reproduced the workflow without edits. PAT returned the four exact values and the expected three qualified/one outside-band classifications. The contour agent independently parsed 946 OBJ vertices and 1,888 valid-index triangles, reproduced the five topology counters, and measured bounds at the intended box extents. The workflow agent passed the five focused tests and correctly kept model inference, grid construction, repair, semantic recovery, and stronger authority external.
+
+Their friction findings were addressed in-place: every subcommand now has direct `--help`; PAT file-output mode prints a success summary; the README specifies millimetres, x-fastest flattening, query shape, configurable neighbor count, and independent qualification/sign checks. The report also states that the required topology counters are not self-intersection, orientation, degeneracy, or source-fit admission.
diff --git a/docs/release/DCSD-DOGFOOD-X0.evidence.json b/docs/release/DCSD-DOGFOOD-X0.evidence.json
new file mode 100644
index 00000000..fe67499f
--- /dev/null
+++ b/docs/release/DCSD-DOGFOOD-X0.evidence.json
@@ -0,0 +1,90 @@
+{
+ "schema": "aetheris.dcsd-dogfood-x0.compact.v1",
+ "upstream": {
+ "repository": "https://github.com/xianacarrera/dual-contouring-of-signed-distance-data",
+ "revision": "fa1962cd5825cfc9bb698569714f579e1d75a4e8",
+ "nativeModuleSha256": "765A67BC0BC2393163873B4E2B58876142EEF2499DDDFCEE134A7C059871C79F",
+ "codeLicenseFile": "MIT text; copyright notice says Nick Sharp (2019), so provenance needs legal confirmation",
+ "learnedModel": null
+ },
+ "seed": 20260917,
+ "units": "mm",
+ "normalization": "longest source bbox dimension mapped to 1.0 before the fixed-weight optimizer; output transformed back to mm",
+ "grid": { "paddingFraction": 0.08, "layout": "regular full grid", "sign": "negative inside", "exactZeroPolicy": "strict sign change; grid-aligned exact zeros alone do not activate a cell" },
+ "publishedProfile": { "outerIterations": 100, "innerIterations": 100, "hermiteUpdate": true, "mu": 0.1, "dcWeight": 0.02, "sphereWeight": 1.0, "svdThreshold": 0.01, "blendWeights": [0.2, 0.2, 0.2] },
+ "authorDemo": {
+ "input": "upstream/data/cube.obj",
+ "cells": 32,
+ "dcsdSeconds": 40.0024,
+ "dcsdVertices": 3878,
+ "dcsdTrianglesAfterQuadSplit": 7756,
+ "errorUnits": "normalized longest-bbox units",
+ "rotationSeed": 919993,
+ "dcsdRms": 0.01528,
+ "marchingCubesSeconds": 0.00623,
+ "visual": "artifacts/local/dcsd-x0/demo/author-cube.png"
+ },
+ "benchmarkRotation": { "generator": "NumPy default_rng PCG64", "seed": 919993 },
+ "primary": [
+ { "fixture": "sphere", "cells": 32, "voxel": 0.54196, "method": "MarchingCubes", "seconds": 0.0070, "rms": 0.00804, "p95": 0.01145, "max": 0.01411, "nonmanifoldEdges": 0 },
+ { "fixture": "sphere", "cells": 32, "voxel": 0.54196, "method": "DCSD", "seconds": 79.3490, "rms": 0.00242, "p95": 0.00460, "max": 0.01012, "nonmanifoldEdges": 0 },
+ { "fixture": "sharp_box", "cells": 32, "voxel": 3.52975, "method": "MarchingCubes", "seconds": 0.0068, "rms": 0.17003, "p95": 0.42487, "max": 1.49898, "nonmanifoldEdges": 0 },
+ { "fixture": "sharp_box", "cells": 32, "voxel": 3.52975, "method": "DCSD", "seconds": 96.2720, "rms": 0.02015, "p95": 0.02800, "max": 0.75531, "nonmanifoldEdges": 6 },
+ { "fixture": "sharp_box", "cells": 64, "voxel": 1.76488, "method": "MarchingCubes", "seconds": 0.0519, "rms": 0.06282, "p95": 0.09308, "max": 0.66674, "nonmanifoldEdges": 0 },
+ { "fixture": "sharp_box", "cells": 64, "voxel": 1.76488, "method": "DCSD", "seconds": 619.5276, "rms": 0.00994, "p95": 0.00950, "max": 0.50864, "nonmanifoldEdges": 12 },
+ { "fixture": "thin_plate_0.5mm", "cells": 32, "voxel": 1.77753, "method": "MarchingCubes", "seconds": 0.0064, "rms": 0.13225, "p95": 0.23444, "max": 0.24999, "components": 13, "nonmanifoldEdges": 0 },
+ { "fixture": "thin_plate_0.5mm", "cells": 32, "voxel": 1.77753, "method": "DCSD", "seconds": 141.8875, "rms": 0.11606, "p95": 0.23058, "max": 0.84998, "components": 1, "nonmanifoldEdges": 162 },
+ { "fixture": "bent_sheet_profile_delta", "cells": 32, "voxel": 4.20534, "method": "MarchingCubes", "seconds": 0.0067, "rms": 0.91113, "p95": 1.42699, "max": 2.33314, "components": 8, "nonmanifoldEdges": 0 },
+ { "fixture": "bent_sheet_profile_delta", "cells": 32, "voxel": 4.20534, "method": "DCSD", "seconds": 173.0698, "rms": 0.90178, "p95": 1.44770, "max": 3.46214, "components": 4, "nonmanifoldEdges": 318 }
+ ],
+ "sharpWedgeScreening": {
+ "source": "fixtures/Experiments/DCSDDogfoodX0/sharp-wedge-prism.firmament",
+ "field": "exact analytic signed distance to the closed triangular prism",
+ "cells": 32,
+ "voxel": 2.31788,
+ "profile": "10x20 screening",
+ "marchingCubes": { "seconds": 0.00636, "rms": 0.13587, "p95": 0.34546, "max": 1.07219, "components": 1, "nonmanifoldEdges": 0 },
+ "dcsd": { "seconds": 4.42075, "rms": 0.05336, "p95": 0.03039, "max": 1.11736, "components": 1, "nonmanifoldEdges": 9 },
+ "raw": "artifacts/local/dcsd-x0/benchmark/sharp-wedge-prism-screen.json"
+ },
+ "sharpBoxFeatures": {
+ "32": {
+ "marchingCubes": { "edgeRms": 1.63191, "edgeP95": 2.71510, "cornerRms": 2.11742, "cornerMax": 2.98231, "meanDihedralAbsErrorDegrees": 38.537 },
+ "dcsd": { "edgeRms": 1.11271, "edgeP95": 1.30689, "cornerRms": 0.02157, "cornerMax": 0.03629, "meanDihedralAbsErrorDegrees": 19.113, "planeResidualRms": 0.01092 }
+ },
+ "64": {
+ "marchingCubes": { "edgeRms": 0.82995, "edgeP95": 1.36665, "cornerRms": 1.20737, "cornerMax": 1.41485, "meanDihedralAbsErrorDegrees": 37.545 },
+ "dcsd": { "edgeRms": 0.92004, "edgeP95": 0.74538, "cornerRms": 0.01052, "cornerMax": 0.01519, "meanDihedralAbsErrorDegrees": 18.578, "planeResidualRms": 0.00398 }
+ },
+ "protocol": "candidate adjacency edges with unsigned normal angle >30 degrees; midpoint-to-nearest exact box segment; exact-corner-to-nearest reconstructed vertex"
+ },
+ "thinSweepScreening": [
+ { "thickness": 10.0, "cells": 32, "voxel": 1.84, "dcsdRms": 0.01, "dcsdComponents": 1 },
+ { "thickness": 3.0, "cells": 32, "voxel": 1.79, "dcsdRms": 0.02, "dcsdComponents": 1 },
+ { "thickness": 1.0, "cells": 32, "voxel": 1.78, "dcsdRms": 0.21, "dcsdComponents": 1 },
+ { "thickness": 0.5, "cells": 32, "voxel": 1.78, "dcsdRms": 0.11, "dcsdComponents": 1 },
+ { "thickness": 0.25, "cells": 32, "voxel": 1.78, "dcsdRms": 0.07, "dcsdComponents": 41 },
+ { "thickness": 0.25, "cells": 64, "voxel": 0.89, "dcsdRms": 0.06, "dcsdComponents": 1 }
+ ],
+ "noiseScreening": [
+ { "noiseVoxels": 0.05, "marchingCubesRms": 0.19895, "dcsdRms": 0.08608, "dcsdNonmanifoldEdges": 4 },
+ { "noiseVoxels": 0.20, "marchingCubesRms": 0.45467, "dcsdRms": 0.38387, "dcsdNonmanifoldEdges": 24 },
+ { "quantization": "float16", "marchingCubesRms": 0.17005, "dcsdRms": 0.03118, "dcsdNonmanifoldEdges": 6 }
+ ],
+ "openSurface": { "field": "phi=z cannot encode the finite rectangle boundary", "dcsdBoundaryEdges": 192, "intendedFootprint": [40.0, 30.0], "reconstructedFootprint": [48.56384, 35.52896] },
+ "determinism": { "profile": "10x20", "facesEqual": true, "maxVertexDeltaMm": 0.0 },
+ "reconstructionSha256": {
+ "sphere32Published": "D52F36E3CCA22B8BDA84E1A7677C5DCB99E0049365ACB0123C734D44660EB73B",
+ "sharpBox32Published": "D7F5E40C4A62957F4DE1B163409578CB0A6F9F581087C1DAF258E3460F09652E",
+ "sharpBox64Published": "C141F4E998ECA0D1E8F010A2472AA79FCD362B3908B06D4F307B9329033EBA92",
+ "thinPlate32Published": "E21BFD78234D4C0CCA2CC94491D95E7AE8F4ED6B367F21F6927C92D3804CE891",
+ "bentSheet32Published": "470316AFEFE1819FC3D2D094301F05BBA8EEA29EA036A434CF799E440C07E64B"
+ },
+ "raw": {
+ "summary": "artifacts/local/dcsd-x0/benchmark/summary.json",
+ "metricsCsv": "artifacts/local/dcsd-x0/benchmark/metrics.csv",
+ "thinSweep": "artifacts/local/dcsd-x0/benchmark/thin-sweep.json",
+ "sharpFeatures": "artifacts/local/dcsd-x0/benchmark/sharp-feature-metrics.json",
+ "openSurface": "artifacts/local/dcsd-x0/benchmark/open-surface.json"
+ }
+}
diff --git a/docs/release/DCSD-DOGFOOD-X0.md b/docs/release/DCSD-DOGFOOD-X0.md
new file mode 100644
index 00000000..6af53955
--- /dev/null
+++ b/docs/release/DCSD-DOGFOOD-X0.md
@@ -0,0 +1,192 @@
+# DCSD-DOGFOOD-X0 — Dual Contouring sharp-feature recovery
+
+## Executive verdict
+
+**Verdict: Useful but bounded.** Dual Contouring of Signed Distance Data (DCSD) materially improves reconstruction of sharp geometry from a sampled SDF. On the exact 80 × 50 × 25 mm Aetheris box at 32³ cells, forward surface RMS fell from Marching Cubes' 0.1700 mm to 0.0201 mm. Exact-corner RMS fell from 2.117 mm to 0.0216 mm, and candidate sharp-edge p95 error fell from 2.715 mm to 1.307 mm. At 64³, DCSD reached 0.0099 mm forward RMS and 0.0105 mm corner RMS.
+
+That result does **not** qualify the output as CAD geometry. The published optimizer took 96.3 s at 32³ and 619.5 s at 64³ for the sharp box on this CPU, versus 6.8 ms and 51.9 ms for Marching Cubes. The triangulated DCSD box had 6 and 12 nonmanifold edges; its 32³ p99 aspect ratio was 403 and its smallest triangle angle was 0.002°. Thin and bent-sheet outputs were worse: the 0.5 mm plate had 162 nonmanifold edges, and the real ProfileDelta sheet had 318. The reconstruction is useful sharp-feature evidence, not a generally admissible downstream mesh.
+
+DCSD earns a place only as an external, experimental `SampledField -> ApproximateExplicitMesh` reconstruction candidate. It must not become BRep, Firmament, CIR topology, manufacturing, or feature-history authority. **Do not port it to .NET yet; wrap the pinned implementation first.**
+
+The PAT/DCSD complementarity hypothesis is plausible but not proven enough to start mesh stitching. DCSD owns the sharper zero-set candidate; PAT remains the useful fast pointwise field for smooth, oriented point clouds. A smallest follow-up should compare both methods from one identical sampled source and add a topology/manifold admissibility gate before any region-level Judgment Engine experiment.
+
+## Reproduction and licensing
+
+| Item | Recorded value |
+|---|---|
+| Repository | `xianacarrera/dual-contouring-of-signed-distance-data` |
+| Revision | `fa1962cd5825cfc9bb698569714f579e1d75a4e8` (2026-08-05) |
+| Platform | Windows build 26200, MSVC 2022/18, CMake 4.4.3, Ninja, Python 3.11 |
+| Hardware | AMD Ryzen 7 7700X, 8 cores / 16 logical processors, 31.1 GiB RAM; RTX 3070 present but reconstruction ran on CPU |
+| Native module hash | SHA-256 `765A67BC0BC2393163873B4E2B58876142EEF2499DDDFCEE134A7C059871C79F` |
+| Code license | Root `LICENSE` contains MIT terms, but the notice says `Copyright (c) 2019 Nick Sharp`, not the paper authors. Treat code provenance as unresolved until legal review. |
+| Paper license | The paper PDF is marked CC BY-NC-ND 4.0; that grant is distinct from source code. |
+| Model/weights | None. This method is not learned. |
+| Bundled sample data | No repository-wide sample-data grant was found. Several scripts refer to third-party model sources. Upstream data stays fetched under ignored `artifacts/local`; no sample is redistributed here. |
+| Dependencies | C++/Eigen/libigl/Polyscope/GLFW/OpenGL plus the repository submodules; Python uses NumPy, SciPy, gpytoolbox, libigl, Matplotlib, and trimesh. Subdependency licenses are mixed and must be audited before binary redistribution. |
+
+The upstream repository says it was tested on macOS. Reproduction required four compatibility changes in the ignored checkout:
+
+1. Add missing `<vector>` includes to `contouring.h` and `ui.h`.
+2. Exclude obsolete `sample_fun.cpp`; it defines a second `contouring()` and MSVC selected that placeholder, causing `Ours` to return an empty mesh.
+3. Change three OpenMP loop forms to MSVC-compatible indexed/signed loops.
+4. Disable OpenMP for the benchmark. Although the patched parallel build compiled, the 32³ demo exceeded three minutes instead of the serial path's approximately 82 seconds. The objective, weights, iterations, Hermite update, and connectivity were not changed.
+
+The C++ still initializes Polyscope/OpenGL even for headless Python calls. It does not show a window, but it is an unnecessary runtime/UI dependency for a future wrapper.
+
+### Author-data demo
+
+The demo consumes the repository's `data/cube.obj`, normalizes it, applies the authors' exact legacy-NumPy random rotation (seed `919993`) to avoid grid bias, samples a 33 × 33 × 33 node grid, supplies only scalar SDF values, and runs the published 100 outer / 100 inner iterations. DCSD produced 3,878 vertices and 3,878 quads (7,756 triangles after deterministic splitting) in 40.00 s. The qualified sampled-surface RMS was 0.0153 normalized longest-bbox units. Marching Cubes took 6.2 ms.
+
+Visual: `artifacts/local/dcsd-x0/demo/author-cube.png`.
+
+One important code-level boundary appeared immediately: active cells require both a strictly negative and a strictly positive corner. An axis-aligned cube whose zero set lands exactly on grid nodes can therefore produce no active cells. The authors rotate inputs to avoid this grid degeneracy; the Aetheris adapter does the same with seed `919993`.
+
+## Implementation observed
+
+The public path accepts a one-dimensional array of scalar samples `S`, regular-grid positions `GV`, three node resolutions, an iso value, and `ContouringOptions`. Negative means inside. It is a fixed, full regular grid; there is no adaptive octree path in the observed binding.
+
+For each cell containing strict positive and negative corner values, sign-changing primal edges generate Hermite positions by linear interpolation. Normals come from finite differences/trilinear differentiation of sampled `S`; X0 passes neither Aetheris normals nor the optional exact-SDF/gradient callback. This verifies the gradient-free path.
+
+Classic Dual Contouring averages constraints and solves a QEF. The paper's `Ours` path begins from Hermite centroids, assigns sampled-SDF spheres to cells/face intersections, and iterates vertex refinement. With `hermite_update=true`, later outer iterations update Hermite positions and normals from adjacent cell vertices. Per-cell inner minimization combines sphere constraints, a DC/QEF term, SVD thresholding, and regularization to the preceding vertex. Published settings used here are `mu=0.1`, `dc_weight=0.02`, `sphere_weight=1`, `svd_threshold=0.01`, three update weights of `0.2`, 100 outer iterations, and 100 inner iterations.
+
+Connectivity is built around sign-changing primal edges, joining their four incident dual cells. The C++ output is quads even though the Python docstring says triangles. The harness splits each quad along `(0,1,2)` and `(0,2,3)` only for Aetheris-style triangle validation. This split does not explain edges shared by more than two faces; the reported nonmanifold counts reflect upstream connectivity/duplicate incidence and need a focused audit.
+
+Boundary handling assumes a meaningful volumetric sign field and a padded closed zero set. A finite open surface cannot, in general, be recovered from `phi=z`: that field describes an unbounded plane and contains no finite patch boundary.
+
+## Deterministic Aetheris adapter
+
+`Aetheris.CLI mesh` exports the exact/qualified Firmament/BRep fixtures to ignored OBJ files. The SheetMetal witness uses the real authored `profile-delta-tab-family.firmament`, its `ProfileDelta` specialization, `aetheris build` to formed STEP, `sheetmetal inspect`, and then exact-BRep tessellation. DCSD is never fed PAT output.
+
+The adapter:
+
+1. Centers each source at its bounding-box center and divides by its longest dimension, matching upstream `normalize_points`. This normalization is mandatory because the optimizer uses fixed dimensionless weights.
+2. Applies one deterministic rotation to avoid grid-aligned exact-zero degeneracy.
+3. Pads every rotated bound by 8% of the normalized longest dimension.
+4. Samples analytic signed distance for sphere, cylinder, torus, sharp box, the exact triangular wedge prism, and plates. Other BRep fixtures use qualified signed triangle distance; those measurements inherit Aetheris tessellation error.
+5. Runs the standard sampled-SDF path with no exact gradient oracle.
+6. Transforms vertices back to millimetres and labels the result an approximate mesh.
+
+The full-grid input lower bound is 32 bytes/node (three float64 coordinates plus one float64 SDF): 1.15 MB at 33³ nodes, 8.79 MB at 65³, about 68.7 MB at 129³, and about 543 MB at 257³, before cells, sphere assignments, QEF state, mesh, and library overhead. For the bent sheet at 32³, grid creation took 0.00036 s and qualified SDF sampling 0.0830 s; reconstruction dominated at 173.1 s.
+
+Raw evidence lives under ignored `artifacts/local/dcsd-x0/benchmark`. The compact, reviewable evidence is in `DCSD-DOGFOOD-X0.evidence.json`.
+
+Visual evidence includes `sharp_box-comparison.png` (same-camera exact/MC/DCSD), `sharp-error-heatmap.png`, `sharp-corner-closeup.png`, `sdf-grid-slice.png`, `sharp-noise.png`, the sphere/thin-sheet/ProfileDelta comparisons, `thin-sweep.png`, `plots.png`, and the independent `sharp-wedge-prism-comparison.png`. These are generated artifacts and intentionally remain under `artifacts/local`.
+
+## Primary accuracy and performance
+
+The surface values below are one-way reconstructed-surface errors. `Sym RMS` adds the reverse sampled direction. Analytic fixtures use exact SDF in the forward direction; BRep fixtures use a deterministic dense-surface proxy and are labeled qualified rather than exact.
+
+| Fixture | Grid / voxel | Method | Time | RMS | p95 | max | Sym RMS | Topology finding |
+|---|---:|---|---:|---:|---:|---:|---:|---|
+| Sphere | 32³ / 0.542 mm | MC | 0.007 s | 0.0080 | 0.0114 | 0.0141 | 0.0860 | closed manifold |
+| Sphere | 32³ / 0.542 mm | DCSD | 79.35 s | **0.0024** | **0.0046** | **0.0101** | 0.0879 | closed manifold |
+| Sharp box | 32³ / 3.530 mm | MC | 0.007 s | 0.1700 | 0.4249 | 1.4990 | 0.3773 | closed manifold |
+| Sharp box | 32³ / 3.530 mm | DCSD | 96.27 s | **0.0201** | **0.0280** | **0.7553** | **0.3195** | 6 nonmanifold edges |
+| Sharp box | 64³ / 1.765 mm | MC | 0.052 s | 0.0628 | 0.0931 | 0.6667 | 0.3142 | closed manifold |
+| Sharp box | 64³ / 1.765 mm | DCSD | 619.53 s | **0.0099** | **0.0095** | **0.5086** | **0.3025** | 12 nonmanifold edges |
+| 0.5 mm plate | 32³ / 1.778 mm | MC | 0.006 s | 0.1322 | 0.2344 | **0.2500** | 0.4673 | 13 components |
+| 0.5 mm plate | 32³ / 1.778 mm | DCSD | 141.89 s | **0.1161** | **0.2306** | 0.8500 | **0.3013** | 1 component, 162 nonmanifold edges |
+| ProfileDelta bend | 32³ / 4.205 mm | MC | 0.007 s | 0.9111 | **1.4270** | **2.3331** | 1.1068 | 8 components |
+| ProfileDelta bend | 32³ / 4.205 mm | DCSD | 173.07 s | **0.9018** | 1.4477 | 3.4621 | **0.9118** | 4 components, 318 nonmanifold edges |
+
+Doubling the sharp-box resolution increased DCSD time 6.4×, from 96.3 s to 619.5 s. A 128³ published-profile run was not justified after this scaling; 256³ has 16.97 million nodes, a 543 MB input lower bound, and substantially larger optimizer state. These were deliberately omitted rather than presenting a machine-crashing benchmark as useful evidence.
+
+### Sharp-box features
+
+Candidate reconstructed feature edges are adjacency edges whose unsigned normal angle exceeds 30°. Their midpoints are measured against the nearest exact box segment. Corners are exact box corners measured to the nearest reconstructed vertex. This localized protocol is deterministic but correspondence-free; isolated false feature edges affect its max and RMS.
+
+| Grid | Method | edge RMS / p95 | corner RMS / max | mean absolute 90° dihedral error | face-interior plane RMS |
+|---|---|---:|---:|---:|---:|
+| 32³ | MC | 1.632 / 2.715 mm | 2.117 / 2.982 mm | 38.54° | numerical zero |
+| 32³ | DCSD | **1.113 / 1.307 mm** | **0.0216 / 0.0363 mm** | **19.11°** | 0.0109 mm |
+| 64³ | MC | **0.830 / 1.367 mm** | 1.207 / 1.415 mm | 37.54° | numerical zero |
+| 64³ | DCSD | 0.920 / **0.745 mm** | **0.0105 / 0.0152 mm** | **18.58°** | 0.0040 mm |
+
+DCSD decisively recovers corners and typical edge locations. Its mean dihedral estimate improves by roughly half but remains about 19° wrong, and its edge RMS at 64³ is slightly worse because false/outlier feature edges remain. The method preserves an excellent zero set while producing poor local triangles: at 32³, minimum angle was 0.002°, p99 aspect 403, and 5.06% of triangles had angle below 5°. Feature recovery and mesh admissibility are separate questions.
+
+### CAD feature screen
+
+The 10 outer / 20 inner screen is diagnostic, not the primary quality claim. At 32³ it produced: chamfered box 0.14 mm RMS, rounded rectangle prism 0.33 mm, through hole 0.78 mm, counterbore 0.71 mm, filleted box 0.92 mm, phone-like chassis 1.08 mm, and bent sheet 0.91 mm. All were one connected component except the bent sheet (four); every case except sphere had at least one nonmanifold edge. The screen confirms broad execution but does not establish chamfer width, bore diameter/depth, bend radius, or region-level normals to CAD tolerance.
+
+An additional exact Aetheris witness, `sharp-wedge-prism.firmament`, extrudes a 60 × 40 mm right-triangle section through 20 mm. Its benchmark path uses the exact analytic Euclidean SDF of that closed triangular prism, not tessellated-distance qualification. At 32³ (2.318 mm voxel, 10 × 20 screen), Marching Cubes produced 0.1359 mm forward RMS with a closed manifold mesh. DCSD improved forward RMS to 0.0534 mm and p95 to 0.0304 mm, but produced 9 nonmanifold edges. The wedge therefore broadens the sharp-feature evidence while independently repeating the zero-set/connectivity split seen on the box.
+
+## Thin, noisy, quantized, and open data
+
+The deterministic thin-plate screen varied exact thickness while preserving a 40 × 30 mm footprint.
+
+| Thickness | Grid / voxel | DCSD RMS | components | interpretation |
+|---:|---:|---:|---:|---|
+| 10 mm | 32³ / 1.84 mm | 0.01 mm | 1 | well resolved |
+| 3 mm | 32³ / 1.79 mm | 0.02 mm | 1 | useful geometry |
+| 1 mm | 32³ / 1.78 mm | 0.21 mm | 1 | below one voxel; thickness biased |
+| 0.5 mm | 32³ / 1.78 mm | 0.11 mm | 1 | connected but nonmanifold |
+| 0.25 mm | 32³ / 1.78 mm | 0.07 mm | 41 | topology lost |
+| 0.25 mm | 64³ / 0.89 mm | 0.06 mm | 1 | connected, still thickness-biased |
+
+Low pointwise distance does not prove wall preservation. For example, the 0.25 mm plate reconstructed with a 1.04 mm total z-span at 32³ and 0.80 mm at 64³. A useful wall needs multiple voxels across its thickness and an independent topology/thickness admission check.
+
+On the sharp box, direct SDF noise of 0.05 voxel gave DCSD 0.0861 mm RMS versus MC 0.1990 mm; 0.20 voxel gave 0.3839 versus 0.4547 mm. DCSD remained closer but gained 4 and 24 nonmanifold edges. Float16 round-trip SDF values yielded 0.0312 mm RMS versus MC's 0.1700 mm, again with 6 nonmanifold edges. Robust zero-set placement does not cure connectivity.
+
+For an intentional finite open rectangle, `phi=z` reconstructed an open grid-clipped plane with 192 boundary edges. The intended 40 × 30 mm footprint became 48.56 × 35.53 mm under DCSD because the scalar field contains no finite boundary. Signed volumetric DCSD is not an open-surface reconstruction method.
+
+## PAT comparison and complementarity
+
+The inputs differ: PAT receives an oriented point cloud and answers a reusable pointwise field; DCSD receives a dense sampled volumetric SDF and emits one explicit mesh. The numbers are therefore architectural evidence, not a controlled head-to-head accuracy leaderboard.
+
+| Regime | PAT X0 | DCSD X0 | Interpretation |
+|---|---|---|---|
+| Sphere | 0.0051 mm RMS, field queries ~180k/s | 0.0024 mm mesh RMS, 79 s reconstruction | both excellent; PAT supplies reusable queries, DCSD supplies an offline mesh |
+| Torus | 0.0196 mm RMS, 0.04% sign error | 64³ screen near 0.00 mm RMS | no evidence that DCSD damages smooth curvature, but comparison inputs differ |
+| Sharp box | 0.5736 mm RMS, 5.04% sign error; edge/corner rounding | 0.0201 mm RMS at 32³; 0.0216 mm corner RMS | DCSD clearly owns the sharper candidate |
+| 0.5 mm plate | 0.3129 mm RMS, 16.44% sign error | 0.1161 mm RMS but 162 nonmanifold edges | neither is occupancy/manufacturing authority |
+| Bent sheet | 1.6104 mm RMS, 13.37% sign error | 0.9018 mm RMS but 318 nonmanifold edges | DCSD is geometrically closer; neither output is admissible |
+| Phone chassis | 0.4115 mm PAT field RMS | 1.08 mm DCSD screening mesh RMS | PAT is preferable for the current smooth scan-query role |
+| Open | PAT sign failed (32.4%) | finite boundary is not encoded by volumetric sign | neither qualified |
+
+The simple claim “PAT wins smooth, DCSD wins sharp” is too coarse. DCSD is excellent on the exact sphere too, while PAT remains vastly more useful for pointwise query throughput after point-cloud preprocessing. Their strongest complement is representation and workflow, not merely curvature class.
+
+There is **maybe** enough evidence for `SDF-HYBRID-X0`, after one prerequisite: run both candidates from a common sampled source and reject nonmanifold/thin/open regions explicitly. A future `ReconstructionCandidate` Judgment Engine could consider PAT, DCSD, and a plane/MC baseline, with admissibility first (closedness, manifoldness, topology, bounded error) and utility second (smooth residual, sharp-feature location, normal consistency, triangle quality). X0 does not implement that selection or splice meshes.
+
+## Authority, port, and next decision
+
+Conceptual placement:
+
+```text
+SampledField + provenance
+ -> external DCSD reconstruction
+ -> ApproximateExplicitMesh
+ -> validation / region recognition / fitting
+ -> explicit admission step
+ -> canonical geometry only if independently reconstructed and admitted
+```
+
+The result carries source fixture/hash, grid frame and physical spacing, padding, normalization scale, upstream revision and binary hash, options, reconstruction hash, and validation metrics. It does not carry or recover analytic support ownership, topology intent, holes/chamfers/fillets as features, AIR, Firmament history, manufacturing semantics, or BRep authority. SDF-to-mesh is decompilation: many explicit surfaces can fit one sampled field.
+
+**Port decision: wrap first / not yet.** The C++ implementation is slow, entangled with Polyscope, and produces invalid connectivity in precisely the thin and mixed-CAD cases Aetheris cares about. A .NET port would freeze unclear behavior before it earns an admissible contract. The existing script is the correct X0 boundary.
+
+**Narrow next experiment:** `DCSD-CONNECTIVITY-X1`. Determine whether the nonmanifold incidences are an upstream connectivity defect, a quad-to-triangle interpretation issue, or an unavoidable sign-grid ambiguity; add a hard approximate-mesh admission gate. Only if the sharp witness remains strong and the mesh becomes valid should `SDF-HYBRID-X0` compare PAT/DCSD residuals region by region from identical evidence.
+
+## Reproduce
+
+```powershell
+pwsh -File tools/DCSDDogfoodX0/run.ps1 -Phase all
+```
+
+The command clones and pins upstream plus recursive submodules under `artifacts/local/dcsd-x0`, applies the documented Windows compatibility patch, validates the revision, creates the Python environment, builds the native binding, exports exact Aetheris fixtures (including the authored SheetMetal `ProfileDelta` part), runs the author-data demo, generates normalized exact/qualified SDF grids, reconstructs MC/DCSD meshes, executes the thin/noise/open/determinism tests, and writes CSV/JSON/plots/renders under ignored local artifacts. A complete run is CPU-heavy because the 64³ sharp box alone takes about ten minutes with published iterations.
+
+For a cheap independent re-analysis of already generated sharp-box outputs:
+
+```powershell
+pwsh -File tools/DCSDDogfoodX0/run.ps1 -Phase analyze
+```
+
+A fresh agent also reran the real 32³ published-profile adapter. It reproduced every geometric value above with byte-identical faces and `0.0 mm` maximum vertex delta; runtime varied from 96.3 s to 119.2 s. Its independent 64³ analysis confirmed the mixed edge result: DCSD improved edge p95 but had worse edge RMS and an 11.37 mm false-feature maximum. A second fresh agent added the exact authored wedge fixture without touching upstream and independently reproduced the better zero set plus nonmanifold-connectivity split. A third fresh reviewer rejected universal smooth/sharp authority and recommended connectivity/admissibility work before any hybrid implementation.
+
+Tracked evidence: `docs/release/DCSD-DOGFOOD-X0.evidence.json`.
+
+To export and run only the bounded wedge screen (without the full benchmark):
+
+```powershell
+pwsh -File tools/DCSDDogfoodX0/run.ps1 -Phase wedge
+```
diff --git a/docs/release/PAT-DOGFOOD-X0.evidence.json b/docs/release/PAT-DOGFOOD-X0.evidence.json
new file mode 100644
index 00000000..8dc060c7
--- /dev/null
+++ b/docs/release/PAT-DOGFOOD-X0.evidence.json
@@ -0,0 +1,45 @@
+{
+ "schema": "aetheris.pat-dogfood-x0.compact.v1",
+ "upstreamRevision": "253bf9fc5e79831a03f0486e0c42feeb67c1c546",
+ "modelSha256": "AAA2F3882C36AC32D57361377A73AC830C47D03D6167D51249127A6C40EF7FF9",
+ "seed": 20260917,
+ "units": "mm",
+ "queryNeighbors": 32,
+ "clean2048": [
+ {"fixture":"sphere","truth":"analytic","rms":0.0051,"p95":0.0090,"max":0.0172,"signErrorRate":0.0000,"zeroRms":0.0057,"baselineRms":0.0103,"precomputeSeconds":3.29},
+ {"fixture":"cylinder","truth":"analytic","rms":0.1996,"p95":0.5681,"max":0.9476,"signErrorRate":0.0150,"zeroRms":0.1600,"baselineRms":1.0845,"precomputeSeconds":2.22},
+ {"fixture":"torus","truth":"analytic","rms":0.0196,"p95":0.0372,"max":0.1080,"signErrorRate":0.0004,"zeroRms":0.0150,"baselineRms":0.0517,"precomputeSeconds":2.22},
+ {"fixture":"frustum","truth":"analytic","rms":0.2283,"p95":0.6459,"max":1.2756,"signErrorRate":0.0135,"zeroRms":0.0546,"zeroRootCount":115,"zeroProbeCount":128,"baselineRms":1.7830,"precomputeSeconds":2.31},
+ {"fixture":"slab","truth":"analytic","rms":0.1381,"p95":0.3258,"max":0.8764,"signErrorRate":0.0306,"zeroRms":0.3066,"baselineRms":1.5518,"precomputeSeconds":2.22},
+ {"fixture":"filleted_box","truth":"qualified-mesh","rms":0.7185,"p95":1.1183,"max":8.2177,"signErrorRate":0.0577,"zeroRms":0.4915,"baselineRms":2.4165,"precomputeSeconds":2.22},
+ {"fixture":"rounded_rectangle_prism","truth":"qualified-mesh","rms":0.1528,"p95":0.4099,"max":0.8805,"signErrorRate":0.0263,"zeroRms":0.2805,"baselineRms":0.7547,"precomputeSeconds":2.27},
+ {"fixture":"sharp_box","truth":"analytic","rms":0.5736,"p95":1.3367,"max":2.1009,"signErrorRate":0.0504,"zeroRms":0.4446,"baselineRms":2.1047,"precomputeSeconds":2.21},
+ {"fixture":"chamfered_box","truth":"qualified-mesh","rms":0.0639,"p95":0.1597,"max":0.3637,"signErrorRate":0.0301,"zeroRms":0.0568,"baselineRms":0.4496,"precomputeSeconds":2.22},
+ {"fixture":"through_hole","truth":"qualified-mesh","rms":0.9530,"p95":1.2365,"max":19.2282,"signErrorRate":0.0499,"zeroRms":0.4284,"baselineRms":2.2173,"precomputeSeconds":2.22},
+ {"fixture":"counterbore","truth":"qualified-mesh","rms":0.6337,"p95":1.0304,"max":13.0835,"signErrorRate":0.0496,"zeroRms":0.4388,"baselineRms":1.7753,"precomputeSeconds":2.22},
+ {"fixture":"thin_plate","truth":"analytic","rms":0.3129,"p95":0.5693,"max":1.1880,"signErrorRate":0.1644,"zeroRms":0.4090,"baselineRms":2.6613,"precomputeSeconds":2.21},
+ {"fixture":"bent_sheet_profile_delta","truth":"qualified-mesh","rms":1.6104,"p95":2.7820,"max":17.8555,"signErrorRate":0.1337,"zeroRms":4.2494,"baselineRms":12.6771,"precomputeSeconds":2.23},
+ {"fixture":"phone_like_chassis","truth":"qualified-mesh","rms":0.4115,"p95":0.9548,"max":2.3914,"signErrorRate":0.0300,"zeroRms":0.6991,"baselineRms":2.3416,"precomputeSeconds":2.29}
+ ],
+ "sphereRobustness": [
+ {"scenario":"position-noise","level":0.01,"rms":0.0058,"p95":0.0104,"signErrorRate":0.0000},
+ {"scenario":"position-noise","level":0.05,"rms":0.0205,"p95":0.0390,"signErrorRate":0.0000},
+ {"scenario":"position-noise","level":0.10,"rms":0.0390,"p95":0.0778,"signErrorRate":0.0272},
+ {"scenario":"position-noise","level":0.50,"rms":0.5859,"p95":0.7111,"signErrorRate":0.1502},
+ {"scenario":"normal-noise-deg","level":25.0,"rms":0.0803,"p95":0.1469,"signErrorRate":0.0110},
+ {"scenario":"normal-flips-fraction","level":0.05,"rms":0.1684,"p95":0.1535,"signErrorRate":0.0143},
+ {"scenario":"missing-cap-fraction","level":0.25,"rms":0.3544,"p95":0.8342,"signErrorRate":0.0521},
+ {"scenario":"random-missing-fraction","level":0.25,"rms":0.0055,"p95":0.0104,"signErrorRate":0.0000},
+ {"scenario":"nonuniform-density","level":1.0,"rms":0.0100,"p95":0.0170,"signErrorRate":0.0000}
+ ],
+ "queryPerformance": [
+ {"queries":1,"seconds":0.0000781,"queriesPerSecond":12804},
+ {"queries":1000,"seconds":0.007900,"queriesPerSecond":126577},
+ {"queries":100000,"seconds":0.5365,"queriesPerSecond":186403},
+ {"queries":1000000,"seconds":5.5440,"queriesPerSecond":180374}
+ ],
+ "sphereTracing": {"rays":961,"expectedHits":489,"missed":8,"falseHits":0,"meanHitSteps":13.70,"maxSteps":73},
+ "deterministicRepeatMaxDeltaMm": 0.0,
+ "rawEvidence": "artifacts/local/pat-x0/benchmark/query-evidence.csv",
+ "rawSummary": "artifacts/local/pat-x0/benchmark/summary.json"
+}
diff --git a/docs/release/PAT-DOGFOOD-X0.md b/docs/release/PAT-DOGFOOD-X0.md
new file mode 100644
index 00000000..7b1a6150
--- /dev/null
+++ b/docs/release/PAT-DOGFOOD-X0.md
@@ -0,0 +1,256 @@
+# PAT-DOGFOOD-X0 — Points-as-Tori reproduction and Aetheris fit test
+
+Date: 2026-09-17
+Verdict: **Useful but bounded**
+Reimplementation decision: **Not yet**
+
+## Executive verdict
+
+Points-as-Tori (PAT) earns a place as an experimental, source-derived point-cloud field for smooth, closed, consistently oriented data. It does not earn authority for exact CAD distance, topology, manufacturing intent, thin-sheet occupancy, or open-surface sign.
+
+The published pretrained model generalized extremely well to exact Aetheris spheres and tori. At 2,048 samples, the sphere had 0.0051 mm RMS distance error and no sign errors; the torus had 0.0196 mm RMS and a 0.04% sign-error rate. The analytic PAT query path sustained about 180k queries/s for 1M CPU queries after preprocessing in the final uncontended run (180k–213k/s across repeated runs).
+
+The limits are equally clear. A sharp box had 0.574 mm RMS error and 5.0% sign errors overall; its edge-near and corner-near RMS errors were 0.95 mm and 1.34 mm, respectively. The 0.5 mm plate had 16.4% sign errors. An actual Aetheris Sheet Metal `ProfileDelta` part had 1.61 mm RMS error, 13.4% sign errors, and only 4 of 128 surface-normal probes bracketed a usable zero crossing. An open slab had 32.4% sign errors. These are disqualifying for exact occupancy, cut-cell material authority, and manufacturing geometry.
+
+Recommended use:
+
+- reconstruction guidance and scan-to-CAD residuals for smooth closed data;
+- approximate visualization, surface extraction, and proximity hints with an explicit validity band;
+- an experimental Imported Geometry / Reconstruction lane, never canonical BRep or Firmament authority.
+
+Do not port the full stack into .NET yet. Keep the pinned upstream implementation external for one narrow follow-up that validates a real scan-to-CAD fitting residual and explores portable inference. If that succeeds, wrap pretrained inference first and consider porting only the analytic query core.
+
+## Reproduction basis and license audit
+
+| Item | Recorded value |
+|---|---|
+| Project | [Points as Tori project page](https://nzfeng.github.io/research/PointsAsTori/index.html) |
+| Repository | [nzfeng/points-as-tori](https://github.com/nzfeng/points-as-tori) |
+| Revision | `253bf9fc5e79831a03f0486e0c42feeb67c1c546` |
+| Paper | [ACM DOI 10.1145/3811385](https://doi.org/10.1145/3811385) |
+| Code license | Root repository license is MIT |
+| Model | `src/pointsastori/models/FundamentalFormPredictor.pkl`, 6,366,869 bytes |
+| Model SHA-256 | `AAA2F3882C36AC32D57361377A73AC830C47D03D6167D51249127A6C40EF7FF9` |
+| Weight license | No separate explicit license found; do not redistribute without clarification |
+| Sample/data license | No separate explicit license found; keep fetched samples local |
+| Native dependencies | C++17, nanobind, OpenMP, nanoflann; upstream also vendors/uses libigl and CGAL paths |
+| Python dependencies observed | Python 3.11, JAX 0.8.2, Flax 0.12.2, NumPy, trimesh and build dependencies |
+| Redistribution constraint | Treat weights and bundled samples as fetch-only, hash-pinned local artifacts. Review the selected libigl/CGAL build path before distributing a binary, because CGAL licensing depends on the packages used and may require GPL compliance or a commercial license. |
+| Runtime constraint | Learned precompute requires JAX/Flax. The packaged query extension is native C++/OpenMP. This Windows run used JAX CPU despite an installed RTX 3070. |
+
+The upstream repository, model, and samples are cloned under ignored `artifacts/local/pat-x0/upstream`; none are committed here.
+
+## Published demo reproduction
+
+The canonical `block.obj` demo was reproduced with the upstream sampler: 2,048 surface points, seed 42, center-and-scale normalization, and upstream mesh normals. The published interactive GUI evaluates all source points in a shader; the headless reproduction used the public Python `Shape3D.signed_distance` path with its default 32 nearest local tori.
+
+| Measurement | Result |
+|---|---:|
+| Sampling | 0.0044 s |
+| Model/precompute | 3.43 s |
+| Queries | 48,400 |
+| Query time | 0.289 s |
+| RMS against packaged mesh | 0.0177 normalized units |
+| p95 absolute error | 0.0310 normalized units |
+| Maximum absolute error | 0.0439 normalized units |
+| Sign-error rate | 0.44% |
+
+Visual proof is written to `artifacts/local/pat-x0/demo/author-demo.png`; machine-readable values are in `artifacts/local/pat-x0/demo/demo.json`.
+
+Two minimal Windows compatibility changes were required in the ignored upstream clone: add `<numeric>` in `shape_2d.cpp`, and use a signed OpenMP loop index in `shape_3d.cpp`. No algorithm, weights, network, or evaluation equation was changed.
+
+## Implementation observed
+
+PAT does not learn a global implicit field. For every source sample, the implementation builds a local 64-point neighborhood. It normalizes supplied normals, translates the center point to the origin, constructs a deterministic local orthonormal frame from the center normal, and divides coordinates by the median neighbor distance from the center. There is no epsilon guard on that median scale.
+
+The Flax predictor receives positions and normals as two `[batch, 64, 3]` tensors. Its transformer has a 128-wide embedding, eight attention heads, eight layers, a 512-wide MLP, and no dropout. It has 1,588,358 float32 parameters and emits `[batch, 6]`: six local quadratic/fundamental-form coefficients `(a00, a01, a10, a11, a02, a20)`. Those coefficients are converted to local curvature/principal-frame information and then to one analytic torus per source point. The network neither stores nor answers the global field.
+
+For a torus with center `c`, axis `u`, major radius `R`, and signed minor radius `r`, the local evaluator is:
+
+```text
+sign(r) * (sqrt((|cross(q - c, u)| - R)^2 + dot(q - c, u)^2) - |r|)
+```
+
+Query evaluation is fully analytic after preprocessing, plus nearest-neighbor lookup and blending; it does not invoke the network per query. The public 3D API uses a nanoflann index and 32 nearest source tori. For neighbor distances `d`, it uses an exponential kernel equivalent to `exp(-lambda * (d - shift))`, with `shift = 0.5 * max(d)` and `lambda = 64 / shift`, then normalizes the weights. The sign convention is negative inside for consistently outward-oriented input normals.
+
+This differs in detail from the paper's fixed-radius discussion and from the demo GUI's all-point shader path. Results in this report identify the actual public API path being measured.
+
+## Aetheris fixture and truth pipeline
+
+`Aetheris.CLI mesh` materializes exact Firmament/BRep fixtures through the production compiler and exports oriented `SurfaceMeshIR` OBJ meshes. Analytic truth is used for the sphere, cylinder, torus, slab/box, sharp box, and thin plate. Other BRep fixtures use a qualified triangle closest-point distance plus watertight inside/outside classification; their truth therefore inherits tessellation error and is labeled `qualified-mesh`, not exact analytic truth.
+
+The corpus includes sphere, cylinder, torus, capped frustum, slab, all-edge filleted box, rounded-rectangle prism, sharp box, chamfered box, through hole, counterbore, 0.5 mm thin plate, phone-like smooth chassis, and a real formed Sheet Metal part. The frustum is the existing canonical `fixtures/Canonical/Primitives/frustum.firmament`; its 20 mm bottom radius, 10 mm top radius, and 30 mm height drive a closed-form capped-frustum distance authority, and sampled points are lifted from tessellation onto the exact caps and conical side. The last fixture builds `fixtures/Canonical/SheetMetal/profile-delta-tab-family.firmament`, including its `Table`, immutable `with` specialization, typed `ProfileDelta`, exact blank, and 90-degree flange. The resulting formed STEP has 18 faces and tessellates to 860 triangles. This confirms the programmable profile path while exercising PAT on actual bent thin geometry.
+
+Sampling is deterministic with seed `20260917`. The harness supports area-weighted and uniform-triangle selection, position noise in millimeters, angular normal noise, local normal inversions, random removal, missing caps, nonuniform clustering, and deliberately open surfaces. No retraining or fine-tuning occurs.
+
+Queries cover on-surface, surface-near, inside, outside, far field, sharp edges, corners, hole/counterbore transitions, and thin-wall lines. Metrics use millimeters and exclude exact boundary points from sign classification.
+
+## Accuracy at 2,048 clean oriented samples
+
+| Fixture | Truth | RMS | p95 | Max | Sign error | Zero-set RMS | Plane baseline RMS |
+|---|---|---:|---:|---:|---:|---:|---:|
+| Sphere | analytic | 0.0051 | 0.0090 | 0.0172 | 0.00% | 0.0057 | 0.0103 |
+| Cylinder | analytic | 0.1996 | 0.5681 | 0.9476 | 1.50% | 0.1600 | 1.0845 |
+| Torus | analytic | 0.0196 | 0.0372 | 0.1080 | 0.04% | 0.0150 | 0.0517 |
+| Frustum | analytic | 0.2283 | 0.6459 | 1.2756 | 1.35% | 0.0546* | 1.7830 |
+| Slab | analytic | 0.1381 | 0.3258 | 0.8764 | 3.06% | 0.3066 | 1.5518 |
+| Filleted box | qualified mesh | 0.7185 | 1.1183 | 8.2177 | 5.77% | 0.4915 | 2.4165 |
+| Rounded rectangle prism | qualified mesh | 0.1528 | 0.4099 | 0.8805 | 2.63% | 0.2805 | 0.7547 |
+| Sharp box | analytic | 0.5736 | 1.3367 | 2.1009 | 5.04% | 0.4446 | 2.1047 |
+| Chamfered box | qualified mesh | 0.0639 | 0.1597 | 0.3637 | 3.01% | 0.0568 | 0.4496 |
+| Through hole | qualified mesh | 0.9530 | 1.2365 | 19.2282 | 4.99% | 0.4284 | 2.2173 |
+| Counterbore | qualified mesh | 0.6337 | 1.0304 | 13.0835 | 4.96% | 0.4388 | 1.7753 |
+| Thin plate | analytic | 0.3129 | 0.5693 | 1.1880 | 16.44% | 0.4090* | 2.6613 |
+| Bent Sheet Metal `ProfileDelta` | qualified mesh | 1.6104 | 2.7820 | 17.8555 | 13.37% | 4.2494* | 12.6771 |
+| Phone-like chassis | qualified mesh | 0.4115 | 0.9548 | 2.3914 | 3.00% | 0.6991* | 2.3416 |
+
+`*` The zero-set statistic is conditional on a bracketed crossing. The frustum bracketed 115/128 probes; only 1/128 plate probes, 4/128 bent-sheet probes, and 23/128 chassis probes bracketed a root, so the latter three values must not be read as broad reconstruction success.
+
+PAT materially beats the nearest oriented tangent-plane baseline over most complete fixtures. It is not uniformly better where CAD intent is least smooth: close to sharp-box edges the PAT RMS was 0.95 mm versus 0.39 mm for the plane baseline, and at corners it was 1.34 mm versus 0.66 mm. PAT rounds and biases corners rather than preserving their exact intersection semantics. Hole and counterbore transitions show the same local smoothing plus large far/inside outliers.
+
+The torus-on-torus test is a strong sanity check: 0.0196 mm RMS, 0.0150 mm zero-set RMS, and 0.04% sign errors with an exact torus of major radius 12 mm and minor radius 3 mm. The sphere is better still. PAT is genuinely effective in its intended smooth-curvature regime.
+
+## Sampling, noise, missing data, and orientation
+
+Sphere precompute scaled approximately linearly: 1k, 2k, 5k, and 20k points took 1.65 s, 3.29 s, 5.99 s, and 21.6 s. Sphere error was already near its floor at 1k–2k and improved only modestly with more points. The 100k density requested in the broad matrix was not run: CPU/JAX precompute extrapolates beyond the useful X0 budget and does not change the observed authority boundary.
+
+| Sphere perturbation | RMS | p95 | Sign error |
+|---|---:|---:|---:|
+| 0.01 mm position noise | 0.0058 | 0.0104 | 0.00% |
+| 0.05 mm position noise | 0.0205 | 0.0390 | 0.00% |
+| 0.10 mm position noise | 0.0390 | 0.0778 | 2.72% |
+| 0.50 mm position noise | 0.5859 | 0.7111 | 15.02% |
+| 25-degree normal noise | 0.0803 | 0.1469 | 1.10% |
+| 5% locally flipped normals | 0.1684 | 0.1535 | 1.43% |
+| 25% missing cap | 0.3544 | 0.8342 | 5.21% |
+| 25% random removal | 0.0055 | 0.0104 | 0.00% |
+| Clustered/nonuniform density | 0.0100 | 0.0170 | 0.00% |
+
+Random thinning is benign when coverage remains global. A coherent missing region is not. Consistent outward normals are a hard preprocessing requirement: angular degradation is gradual, while inversions inject the wrong local sign and outliers. Curvature approaching sample spacing likewise degrades once a 64-point neighborhood spans materially different sheets or feature branches.
+
+The intentionally open slab produced 4.19 mm RMS, 9.70 mm p95, and 32.4% sign errors, with 1,037 false-material classifications versus 12 false-void classifications. Signed distance is not meaningful for this case. A local unsigned residual may still be useful if the caller explicitly opts out of occupancy semantics.
+
+## Performance and memory
+
+Environment: Windows 10 build 26200, AMD Family 25 Model 97, 16 logical CPUs, Python 3.11.2, JAX `TFRT_CPU_0`; NVIDIA RTX 3070 8 GB present but not used by this JAX installation.
+
+| Queries | Time | Throughput |
+|---:|---:|---:|
+| 1 | 78.1 us | 12.8k/s |
+| 1,000 | 7.90 ms | 127k/s |
+| 100,000 | 0.536 s | 186k/s |
+| 1,000,000 | 5.544 s | 180k/s |
+
+The query stage is CPU/OpenMP and analytic. The dominant interactive cost is per-cloud preprocessing: local neighborhood construction, JAX model inference, torus conversion, and index construction. The harness records their aggregate because the public implementation does not expose stable separate timers for all four stages.
+
+Representation storage is approximately 48 bytes/source point for float64 point+normal data, 56 bytes/source point for torus parameters, and 256 bytes/source point for 64 precompute neighbor indices. A 32-neighbor query batch also needs about 128 bytes/query for indices before temporary arrays. The model file is 6.37 MB and its parameters occupy about 6.35 MB as float32. The first measured process gained roughly 720 MB RSS because loading JAX/XLA and allocator state dominates compact model/field storage; subsequent per-case readings are allocator-cached and are not additive object sizes.
+
+No supported upstream GPU query path was found. GPU precompute is possible where JAX has a matching accelerator build, but was not available in this Windows environment. ONNX export is not direct: the model is Flax/JAX with custom preprocessing and the native analytic evaluator. TorchScript does not apply. A portable inference proof would need `jax2tf`/SavedModel or a separately validated translation and exact coefficient-parity tests; that is deliberately deferred.
+
+## Field operations and query relevance
+
+The harness solves `phi(x) = 0` and `phi(x) - 1 mm = 0` along known normals. On the sphere, zero-set RMS was 0.0057 mm and the +1 mm offset RMS was 0.0057 mm, showing that analytic offset/morphology is useful on favorable smooth closed data. Extracted surfaces remain derived approximations, not CAD offsets.
+
+Sphere tracing used 961 rays. Of 489 expected hits, PAT found 481, missed 8, produced no false hits, averaged 13.7 steps for hits, and reached a maximum of 73. That is adequate for experimental visualization but not a proof that the blended field is a globally conservative distance bound.
+
+The occupancy experiment uses `phi(x) < 0`. It is excellent for a clean sphere and unacceptable for a thin plate, bent sheet, sharp/open geometry, or incomplete scans. PAT therefore should not currently feed authoritative cut-cell FEA material classification. It may be tested later as one experimental classifier with boundary uncertainty and an independent admission check.
+
+For clearance and fitting, PAT can supply a smooth residual from a well-oriented scan to an exact CAD query set. It must not supply authoritative minimum clearance: coherent holes, thin walls, and far-field outliers can change both magnitude and sign. The practical near-term use is a robustly truncated residual for reconstruction guidance or ICP-like fitting, cross-checked against exact Aetheris geometry.
+
+## Failure modes
+
+- Sharp edges and corners are rounded and biased; the local plane baseline is better immediately around the sharp-box features.
+- Close parallel sheets contaminate each other's 64-point neighborhoods. Thin-wall sign is unreliable even when global orientation is correct.
+- Coherent missing patches create false continuation and sign failures; random thinning is much less harmful.
+- Open surfaces do not define a stable inside/outside relation for this implementation.
+- Normal noise degrades curvature prediction; local flips are especially hazardous.
+- Nonuniform density was tolerated on the tested sphere but changes median normalization and neighbor support, so it is not an invariant guarantee.
+- Far/inside queries on holed BReps produced rare but very large outliers, up to 19.2 mm in this corpus.
+- The learned predictor was trained around clean 2,048-point shapes. Dense, noisy, incomplete, thin CAD-like inputs are out of distribution and must be admitted empirically, not assumed.
+
+## Authority boundary and future domain shape
+
+The correct relationship is:
+
+```text
+ImportedPointCloud
+ -> PointTorusField (source-derived, approximate, provenance-bearing)
+ -> Reconstruction / Analysis / Experimental field queries
+ -> explicit reconstruction and admission step, if a mesh or BRep is desired
+```
+
+It is not:
+
+```text
+Firmament solid -> PAT -> replacement topology or manufacturing authority
+```
+
+PAT should live alongside imported/reconstructed geometry as a query/evaluation authority with declared source, scale, valid distance band, sign capability, and confidence/qualification metadata. It should not implement Aetheris' exact distance interface and should not become a CIR topology source. A future, non-frozen sketch is:
+
+```text
+PointTorusField
+ SourcePointCloud
+ NormalField
+ LocalTorusParameters
+ KernelSettings
+ Acceleration
+ ValidityBand
+ SignCapability
+ Provenance
+```
+
+`SignCapability` must be an admitted state, not a Boolean assumption: for example, unavailable for open/unoriented input, locally qualified for incomplete data, or closed-oriented-qualified after validation. Queries outside `ValidityBand` should reject or explicitly return an unqualified result. The approximate field and any derived mesh must be hard-type-separated from exact distance, occupancy, and canonical geometry interfaces so ordinary assignment cannot promote them accidentally.
+
+Any `phi=0` mesh must be marked derived/approximate. Promotion to canonical BRep requires an explicit reconstruction/admission workflow with its own tolerances and validation. Firmament solids must continue through existing BRep authority.
+
+## Determinism
+
+Repeating precompute and query with the same cloud, normals, weights, and settings on the measured CPU path produced a maximum difference of 0.0 mm. The model has dropout disabled. Accelerator kernels were not exercised; a future GPU qualification must record device/version and numeric tolerance rather than assuming bitwise determinism.
+
+## Reproduction
+
+From the repository root in PowerShell:
+
+```powershell
+pwsh -File tools/PATDogfoodX0/run.ps1 -Phase all
+```
+
+The command chain hash-pins and fetches upstream, applies the two documented compiler-only compatibility edits in the ignored clone, validates the model hash, builds the native/Python package, exports Aetheris fixtures, builds and inspects the programmable Sheet Metal profile, runs the author demo, executes the corpus, writes raw CSV/JSON, and generates plots/renders.
+
+Useful bounded phases are:
+
+```powershell
+pwsh -File tools/PATDogfoodX0/run.ps1 -Phase prepare
+pwsh -File tools/PATDogfoodX0/run.ps1 -Phase demo
+pwsh -File tools/PATDogfoodX0/run.ps1 -Phase benchmark
+```
+
+Tracked compact evidence is in [PAT-DOGFOOD-X0.evidence.json](PAT-DOGFOOD-X0.evidence.json). Raw evidence is ignored under:
+
+```text
+artifacts/local/pat-x0/demo/demo.json
+artifacts/local/pat-x0/benchmark/query-evidence.csv
+artifacts/local/pat-x0/benchmark/summary.json
+artifacts/local/pat-x0/benchmark/benchmark-plots.png
+artifacts/local/pat-x0/benchmark/*-slice.png
+```
+
+Each raw query row records fixture, point count, perturbation scenario/level, category, PAT value, truth value, absolute and signed error, sign correctness, baseline value, and timing context.
+
+## Fresh-agent qualification
+
+Three agents were given only the tracked guide, scripts, and evidence—no hidden run instructions.
+
+1. The reproduction agent ran `prepare` and `benchmark`, validated the pinned revision/model, produced 99,870 query rows, and independently recovered the sphere and sharp-box values in this report. It also recovered the sharp edge/corner reversal versus the tangent-plane baseline and 0.0 mm deterministic repeat deltas. Its only workflow friction was that the runner has no per-fixture filter, so the bounded reproduction executes the full corpus.
+2. The authority agent placed `PointTorusField` in Imported Geometry / Reconstruction, required provenance, a validity band, admitted sign capability, and hard type separation, and independently rejected exact-distance, BRep, Firmament, CIR-topology, manufacturing, cut-cell occupancy, and exact-clearance authority. It identified the risk that a generic “SDF-like” interface could accidentally erase these qualifications; the boundary above now states rejection/unqualified behavior explicitly.
+3. The extensibility agent added the existing canonical capped frustum without changing PAT. It introduced a closed-form exact SDF and exact support lifting, proved mesh vertices within `9.99e-13` mm and sampled points within `7.11e-15` mm of that authority, and ran the full case. PAT measured 0.2283 mm RMS, 0.6459 mm p95, 1.35% sign errors, and 115/128 bracketed zero probes. Focused CLI tests passed 443/443.
+
+Repository validation compiled the full `Aetheris.slnx`. The parallel Debug test invocation reported two unrelated tessellation-sensitive failures: one deterministic-scaffold assertion and one five-second spring display-tessellation timeout. Each exact failed test passed immediately when rerun alone with `-m:1` (1/1 and 1/1). PAT's Python compilation, PowerShell parse, compact/raw JSON checks, upstream/model hash checks, fixture exports, benchmark, and `git diff --check` all passed.
+
+## Decision and next experiment
+
+**Does PAT earn a place?** Yes, as a useful but bounded point-cloud SDF-like reconstruction/query field for smooth, closed, consistently oriented data. No, as a general signed-distance or occupancy authority.
+
+**Should Aetheris port it?** Not yet. The evidence justifies preserving the benchmark and evaluating a pinned external wrapper. It does not justify owning a Flax-to-.NET neural implementation, accepting unresolved model redistribution, or baking smooth-field assumptions into CIR. If a production use case survives one more test, the smallest plausible integration is pretrained inference behind a process boundary plus a separately portable analytic/query core—not a full rewrite.
+
+**Narrow follow-up:** PAT-X1 should perform one real scan-vs-CAD fitting experiment on a smooth chassis, using a truncated residual and held-out exact Aetheris queries, while proving a portable model-export path with coefficient parity. Stop if the residual does not improve convergence or if portable inference cannot preserve the six predicted coefficients within an agreed tolerance.
diff --git a/fixtures/Experiments/ContinuumToolsX1/README.md b/fixtures/Experiments/ContinuumToolsX1/README.md
new file mode 100644
index 00000000..1ec3ec9b
--- /dev/null
+++ b/fixtures/Experiments/ContinuumToolsX1/README.md
@@ -0,0 +1,14 @@
+# CONTINUUM-TOOLS-X1 fixture source
+
+The committed fixture is this deterministic recipe rather than generated bulk JSON/OBJ. Run:
+
+```powershell
+dotnet run --project Aetheris.CLI -- continuum make-fixtures --out-dir artifacts/local/continuum-tools-x1
+```
+
+It produces:
+
+- an exact 10 mm sphere represented by six degenerate local tori (`R=0`, `r=10`) plus four queries;
+- a 25 x 25 x 25 scalar SDF grid of an exact 16 x 12 x 10 mm sharp box, deliberately offset from grid nodes.
+
+The resulting files are deterministic, regenerable, and ignored under `artifacts/local/`. They test interchange and analytic/contouring execution, not learned PAT inference.
diff --git a/fixtures/Experiments/DCSDDogfoodX0/sharp-wedge-prism.firmament b/fixtures/Experiments/DCSDDogfoodX0/sharp-wedge-prism.firmament
new file mode 100644
index 00000000..9a37a89f
--- /dev/null
+++ b/fixtures/Experiments/DCSDDogfoodX0/sharp-wedge-prism.firmament
@@ -0,0 +1,15 @@
+Model DcsdSharpWedgePrism {
+ Units: mm
+
+ Triangle2<Explicit> WedgeSection {
+ A: [-30mm, -20mm]
+ B: [30mm, -20mm]
+ C: [-30mm, 20mm]
+ }
+ Profile WedgeProfile {
+ Loop Outer { WedgeSection |> TraceLoop }
+ }
+ Struct Body {
+ Extrude Wedge { Profile: WedgeProfile; From: 0mm; To: 20mm }
+ }
+}
diff --git a/fixtures/Experiments/PATDogfoodX0/phone-like-chassis.firmament b/fixtures/Experiments/PATDogfoodX0/phone-like-chassis.firmament
new file mode 100644
index 00000000..76ef28fe
--- /dev/null
+++ b/fixtures/Experiments/PATDogfoodX0/phone-like-chassis.firmament
@@ -0,0 +1,21 @@
+// Smooth, phone-scale Aetheris geometry for PAT generalization testing. It is
+// intentionally a bounded chassis witness, not a device reconstruction claim.
+Model PatPhoneLikeChassis {
+ Units: mm
+
+ RoundedRect2 Outline {
+ Center: [38.99mm, -81.715mm]
+ Size: [77.98mm, 163.43mm]
+ Radius: 13.9mm
+ }
+ Profile Section {
+ Loop Outer {
+ Outline |> TraceLoop
+ }
+ }
+ Extrude Body {
+ Profile: Section
+ From: 0mm
+ To: 8.75mm
+ }
+}
diff --git a/fixtures/Experiments/PATDogfoodX0/rounded-rectangle-prism.firmament b/fixtures/Experiments/PATDogfoodX0/rounded-rectangle-prism.firmament
new file mode 100644
index 00000000..3a127944
--- /dev/null
+++ b/fixtures/Experiments/PATDogfoodX0/rounded-rectangle-prism.firmament
@@ -0,0 +1,19 @@
+Model PatRoundedRectanglePrism {
+ Units: mm
+
+ RoundedRect2 Outline {
+ Center: [0mm, 0mm]
+ Size: [40mm, 24mm]
+ Radius: 5mm
+ }
+ Profile Section {
+ Loop Outer {
+ Outline |> TraceLoop
+ }
+ }
+ Extrude Body {
+ Profile: Section
+ From: 0mm
+ To: 8mm
+ }
+}
diff --git a/fixtures/Experiments/PATDogfoodX0/slab.firmament b/fixtures/Experiments/PATDogfoodX0/slab.firmament
new file mode 100644
index 00000000..7edcce5e
--- /dev/null
+++ b/fixtures/Experiments/PATDogfoodX0/slab.firmament
@@ -0,0 +1,7 @@
+Model PatSlab {
+ Units: mm
+
+ Box Body {
+ Size: [40mm, 30mm, 3mm]
+ }
+}
diff --git a/fixtures/Experiments/PATDogfoodX0/thin-plate.firmament b/fixtures/Experiments/PATDogfoodX0/thin-plate.firmament
new file mode 100644
index 00000000..b8b57cbd
--- /dev/null
+++ b/fixtures/Experiments/PATDogfoodX0/thin-plate.firmament
@@ -0,0 +1,7 @@
+Model PatThinPlate {
+ Units: mm
+
+ Box Body {
+ Size: [40mm, 30mm, 0.5mm]
+ }
+}
diff --git a/tools/DCSDDogfoodX0/dcsd_x0.py b/tools/DCSDDogfoodX0/dcsd_x0.py
new file mode 100644
index 00000000..4678709f
--- /dev/null
+++ b/tools/DCSDDogfoodX0/dcsd_x0.py
@@ -0,0 +1,495 @@
+from __future__ import annotations
+
+import argparse
+import csv
+import hashlib
+import json
+import math
+import os
+import platform
+import sys
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable
+
+import gpytoolbox as gpy
+import matplotlib
+matplotlib.use('Agg')
+import matplotlib.pyplot as plt
+import numpy as np
+from scipy.spatial import cKDTree
+
+SEED = 20260917
+EPS = 1e-12
+REVISION = 'fa1962cd5825cfc9bb698569714f579e1d75a4e8'
+
+
+@dataclass(frozen=True)
+class Mesh:
+ v: np.ndarray
+ f: np.ndarray
+
+
+@dataclass(frozen=True)
+class Fixture:
+ name: str
+ sdf: Callable[[np.ndarray], np.ndarray] | None
+
+
+def read_obj(path: Path) -> Mesh:
+ vertices: list[list[float]] = []
+ triangles: list[list[int]] = []
+ with path.open('r', encoding='utf-8') as stream:
+ for raw in stream:
+ parts = raw.strip().split()
+ if not parts: continue
+ if parts[0] == 'v': vertices.append([float(x) for x in parts[1:4]])
+ elif parts[0] == 'f':
+ polygon = [int(token.split('/')[0]) - 1 for token in parts[1:]]
+ for i in range(1, len(polygon)-1): triangles.append([polygon[0], polygon[i], polygon[i+1]])
+ return Mesh(np.asarray(vertices, dtype=np.float64), np.asarray(triangles, dtype=np.int64))
+
+
+def write_obj(path: Path, v: np.ndarray, f: np.ndarray) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open('w', encoding='utf-8', newline='\n') as stream:
+ for p in v:
+ stream.write(f'v {p[0]:.17g} {p[1]:.17g} {p[2]:.17g}\n')
+ for face in f:
+ stream.write('f ' + ' '.join(str(int(x) + 1) for x in face) + '\n')
+
+
+def box_sdf(size: tuple[float, float, float]) -> Callable[[np.ndarray], np.ndarray]:
+ half = np.asarray(size) * .5
+ center = np.array([0., 0., half[2]])
+ def evaluate(q: np.ndarray) -> np.ndarray:
+ d = np.abs(q - center) - half
+ return np.linalg.norm(np.maximum(d, 0.), axis=1) + np.minimum(np.max(d, axis=1), 0.)
+ return evaluate
+
+
+def triangular_prism_sdf(vertices: tuple[tuple[float, float], ...], z_min: float,
+ z_max: float) -> Callable[[np.ndarray], np.ndarray]:
+ """Exact SDF for a CCW triangle extruded through a closed z interval."""
+ polygon = np.asarray(vertices, dtype=np.float64)
+ following = np.roll(polygon, -1, axis=0)
+ edges = following - polygon
+ z_center = (z_min + z_max) * .5
+ z_half = (z_max - z_min) * .5
+
+ def evaluate(q: np.ndarray) -> np.ndarray:
+ planar = q[:, :2]
+ offsets = planar[:, None, :] - polygon[None, :, :]
+ edge_length_squared = np.sum(edges * edges, axis=1)
+ t = np.clip(np.sum(offsets * edges[None, :, :], axis=2) / edge_length_squared, 0., 1.)
+ closest = offsets - t[:, :, None] * edges[None, :, :]
+ distance_2d = np.sqrt(np.min(np.sum(closest * closest, axis=2), axis=1))
+ cross = edges[None, :, 0] * offsets[:, :, 1] - edges[None, :, 1] * offsets[:, :, 0]
+ signed_2d = np.where(np.all(cross >= 0., axis=1), -distance_2d, distance_2d)
+ d = np.column_stack((signed_2d, np.abs(q[:, 2] - z_center) - z_half))
+ return np.linalg.norm(np.maximum(d, 0.), axis=1) + np.minimum(np.max(d, axis=1), 0.)
+
+ return evaluate
+
+
+def sphere_sdf(q: np.ndarray) -> np.ndarray:
+ return np.linalg.norm(q, axis=1) - 7.5
+
+
+def torus_sdf(q: np.ndarray) -> np.ndarray:
+ radial = np.linalg.norm(q[:, [0, 2]], axis=1) - 12.
+ return np.sqrt(radial * radial + q[:, 1] * q[:, 1]) - 3.
+
+
+def cylinder_sdf(q: np.ndarray) -> np.ndarray:
+ d = np.column_stack((np.linalg.norm(q[:, :2], axis=1) - 12., np.abs(q[:, 2] - 15.) - 15.))
+ return np.linalg.norm(np.maximum(d, 0.), axis=1) + np.minimum(np.max(d, axis=1), 0.)
+
+
+FIXTURES = {
+ 'sphere': Fixture('sphere', sphere_sdf),
+ 'cylinder': Fixture('cylinder', cylinder_sdf),
+ 'torus': Fixture('torus', torus_sdf),
+ 'sharp_box': Fixture('sharp_box', box_sdf((80., 50., 25.))),
+ 'sharp_wedge_prism': Fixture('sharp_wedge_prism', triangular_prism_sdf(
+ ((-30., -20.), (30., -20.), (-30., 20.)), 0., 20.)),
+ 'thin_plate': Fixture('thin_plate', box_sdf((40., 30., .5))),
+ 'filleted_box': Fixture('filleted_box', None),
+ 'rounded_rectangle_prism': Fixture('rounded_rectangle_prism', None),
+ 'chamfered_box': Fixture('chamfered_box', None),
+ 'through_hole': Fixture('through_hole', None),
+ 'counterbore': Fixture('counterbore', None),
+ 'phone_like_chassis': Fixture('phone_like_chassis', None),
+ 'bent_sheet': Fixture('bent_sheet', None),
+}
+
+
+def rotation() -> np.ndarray:
+ rng = np.random.default_rng(919993)
+ axis = rng.random(3); axis /= np.linalg.norm(axis)
+ angle = float(rng.random() * 2 * np.pi)
+ k = np.array([[0., -axis[2], axis[1]], [axis[2], 0., -axis[0]], [-axis[1], axis[0], 0.]])
+ return np.eye(3) + math.sin(angle) * k + (1 - math.cos(angle)) * (k @ k)
+
+
+def author_rotation() -> np.ndarray:
+ # run_ours.py uses NumPy's legacy global RandomState API.
+ rng = np.random.RandomState(919993)
+ axis = rng.rand(3); axis /= np.linalg.norm(axis)
+ angle = float(rng.rand() * 2 * np.pi)
+ k = np.array([[0., -axis[2], axis[1]], [axis[2], 0., -axis[0]], [-axis[1], axis[0], 0.]])
+ return np.eye(3) + math.sin(angle) * k + (1 - math.cos(angle)) * (k @ k)
+
+
+def triangulate(f: np.ndarray) -> np.ndarray:
+ if f.size == 0 or f.shape[1] == 3: return f.astype(np.int64)
+ return np.vstack((f[:, [0, 1, 2]], f[:, [0, 2, 3]])).astype(np.int64)
+
+
+def surface_sample(mesh: Mesh, count: int, seed: int) -> np.ndarray:
+ tri = mesh.v[mesh.f]
+ area = np.linalg.norm(np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]), axis=1)
+ rng = np.random.default_rng(seed)
+ idx = rng.choice(len(tri), count, p=area / np.sum(area))
+ uv = rng.random((count, 2)); flip = uv.sum(axis=1) > 1; uv[flip] = 1 - uv[flip]
+ bary = np.column_stack((1 - uv[:, 0] - uv[:, 1], uv[:, 0], uv[:, 1]))
+ return np.sum(tri[idx] * bary[:, :, None], axis=1)
+
+
+def topology(v: np.ndarray, f: np.ndarray) -> dict:
+ if len(f) == 0: return {'boundary_edges': 0, 'nonmanifold_edges': 0, 'components': 0, 'euler': 0}
+ edges = np.sort(np.vstack((f[:, [0,1]], f[:, [1,2]], f[:, [2,0]])), axis=1)
+ unique, counts = np.unique(edges, axis=0, return_counts=True)
+ parent = np.arange(len(v))
+ def find(x: int) -> int:
+ while parent[x] != x: parent[x] = parent[parent[x]]; x = parent[x]
+ return x
+ for a, b in unique:
+ ra, rb = find(int(a)), find(int(b))
+ if ra != rb: parent[rb] = ra
+ used = np.unique(f)
+ return {'boundary_edges': int(np.sum(counts == 1)), 'nonmanifold_edges': int(np.sum(counts > 2)),
+ 'components': len({find(int(x)) for x in used}), 'euler': int(len(used) - len(unique) + len(f))}
+
+
+def quality(v: np.ndarray, f: np.ndarray) -> dict:
+ if len(f) == 0: return {'min_angle_deg': math.nan, 'p99_aspect': math.nan, 'sliver_rate': math.nan}
+ tri = v[f]; e = np.stack((tri[:,1]-tri[:,0], tri[:,2]-tri[:,1], tri[:,0]-tri[:,2]), axis=1)
+ lengths = np.linalg.norm(e, axis=2)
+ area2 = np.linalg.norm(np.cross(e[:,0], -e[:,2]), axis=1)
+ aspect = np.max(lengths, axis=1) ** 2 / np.maximum(area2, EPS)
+ a = np.degrees(np.arccos(np.clip(np.sum((-e[:,2])*e[:,0], axis=1) / np.maximum(lengths[:,2]*lengths[:,0], EPS), -1, 1)))
+ b = np.degrees(np.arccos(np.clip(np.sum((-e[:,0])*e[:,1], axis=1) / np.maximum(lengths[:,0]*lengths[:,1], EPS), -1, 1)))
+ mins = np.minimum(np.minimum(a, b), 180-a-b)
+ return {'min_angle_deg': float(np.min(mins)), 'p99_aspect': float(np.percentile(aspect, 99)), 'sliver_rate': float(np.mean(mins < 5.))}
+
+
+def error_stats(values: np.ndarray) -> dict:
+ values = np.abs(values[np.isfinite(values)])
+ return {'rms_mm': float(np.sqrt(np.mean(values**2))), 'p50_mm': float(np.percentile(values,50)),
+ 'p95_mm': float(np.percentile(values,95)), 'p99_mm': float(np.percentile(values,99)),
+ 'max_mm': float(np.max(values))}
+
+
+def exact_surface_error(fixture: Fixture, source: Mesh, p: np.ndarray, r: np.ndarray, center: np.ndarray) -> np.ndarray:
+ local = (p - center) @ r.T + center
+ if fixture.sdf is not None: return fixture.sdf(local)
+ return np.asarray(gpy.signed_distance(p, source.v, source.f)[0])
+
+
+def run_case(contouring, fixture: Fixture, source_local: Mesh, cells: int, method: str,
+ noise_voxels: float = 0., quantize: str = 'none', outer_iters: int = 100,
+ inner_iters: int = 100, rotation_matrix: np.ndarray | None = None) -> tuple[dict, Mesh, np.ndarray]:
+ r = rotation() if rotation_matrix is None else rotation_matrix; center = (source_local.v.min(0) + source_local.v.max(0)) * .5
+ scale_mm = float(np.max(source_local.v.max(0) - source_local.v.min(0)))
+ # Match upstream run_ours.py: normalize the longest bbox dimension to 1,
+ # then rotate to avoid grid bias. Fixed optimization weights live here.
+ source_normalized = Mesh(((source_local.v - center) / scale_mm) @ r, source_local.f)
+ source = Mesh(source_normalized.v * scale_mm + center, source_local.f)
+ bounds_min, bounds_max = source_normalized.v.min(0), source_normalized.v.max(0)
+ extent = float(np.max(bounds_max - bounds_min)); pad = max(extent * .08, 1e-3)
+ lo = bounds_min - pad; hi = bounds_max + pad
+ gv = contouring._contouring_cpp_module._grid(lo, hi, cells+1, cells+1, cells+1)
+ h_normalized = float(np.max((hi-lo)/cells))
+ h = h_normalized * scale_mm
+ if fixture.sdf is not None:
+ local_mm = (gv @ r.T) * scale_mm + center
+ s = fixture.sdf(local_mm) / scale_mm
+ else:
+ s = np.asarray(gpy.signed_distance(gv, source_normalized.v, source_normalized.f)[0])
+ if noise_voxels:
+ s = s + np.random.default_rng(SEED).normal(0., noise_voxels*h_normalized, len(s))
+ if quantize == 'float16': s = s.astype(np.float16).astype(np.float64)
+ opts = {'method': getattr(contouring._contouring_cpp_module.ContouringMethod, method), 'verbose': False}
+ if method == 'Ours':
+ opts.update({'outer_iters':outer_iters, 'inner_iters':inner_iters, 'hermite_update':True,
+ 'new_hermite_pos_weight':.2, 'new_face_pos_weight':.2,
+ 'new_hermite_normal_weight':.2, 'mu':.1, 'dc_weight':.02,
+ 'sphere_weight':1., 'svd_threshold':.01, 'batch_size':200000})
+ print(f' {method}: invoke ({len(gv)} samples, outer={outer_iters}, inner={inner_iters})', flush=True)
+ start = time.perf_counter()
+ v, faces = contouring.py_contouring(s, gv, cells+1, cells+1, cells+1, 0., opts, None, None)
+ seconds = time.perf_counter() - start
+ print(f' {method}: returned in {seconds:.3f}s', flush=True)
+ f = triangulate(np.asarray(faces)); v = np.asarray(v) * scale_mm + center
+ reconstructed = Mesh(v, f)
+ if len(f):
+ sample_count = min(12000, max(4000, len(f)*3))
+ p = surface_sample(reconstructed, sample_count, SEED)
+ exact_samples = surface_sample(source, min(20000, max(8000, len(source.f)*4)), SEED+1)
+ if fixture.sdf is not None:
+ forward = exact_surface_error(fixture, source, p, r, center)
+ else:
+ # Qualified mesh fixtures use a deterministic dense-surface proxy;
+ # analytic fixtures above retain exact distance authority.
+ forward = cKDTree(exact_samples).query(p, workers=-1)[0]
+ reconstruction_samples = surface_sample(reconstructed, min(20000, max(8000, len(f)*4)), SEED+2)
+ reverse = cKDTree(reconstruction_samples).query(exact_samples, workers=-1)[0]
+ metrics = error_stats(forward)
+ metrics['symmetric_rms_mm'] = float(np.sqrt(np.mean(np.concatenate((np.abs(forward), reverse))**2)))
+ metrics['approx_hausdorff_mm'] = float(max(np.max(np.abs(forward)), np.max(reverse)))
+ else:
+ metrics = {k: math.nan for k in ('rms_mm','p50_mm','p95_mm','p99_mm','max_mm','symmetric_rms_mm','approx_hausdorff_mm')}
+ record = {'fixture':fixture.name, 'method':method, 'cells':cells, 'grid_nodes':int(len(gv)),
+ 'voxel_mm':h, 'noise_voxels':noise_voxels, 'quantize':quantize, 'seconds':seconds,
+ 'outer_iters':outer_iters if method == 'Ours' else 0,
+ 'inner_iters':inner_iters if method == 'Ours' else 0,
+ 'vertices':int(len(v)), 'triangles':int(len(f)), **metrics, **topology(v,f), **quality(v,f)}
+ return record, reconstructed, s
+
+
+def visual(path: Path, source: Mesh, meshes: list[tuple[str,Mesh]], fixture: Fixture, r: np.ndarray | None = None) -> None:
+ fig, axes = plt.subplots(1, len(meshes)+1, figsize=(4*(len(meshes)+1),4), subplot_kw={'projection':'3d'})
+ all_items = [('Exact Aetheris', source)] + meshes
+ for ax, (title, mesh) in zip(axes, all_items):
+ f = mesh.f
+ if len(f) > 12000: f = f[::max(1,len(f)//12000)]
+ ax.plot_trisurf(mesh.v[:,0], mesh.v[:,1], mesh.v[:,2], triangles=f, linewidth=.05, color='#75aadb', edgecolor='#29445c')
+ ax.set_title(title); ax.set_axis_off(); ax.view_init(25, 35); ax.set_box_aspect((1,1,.8))
+ fig.tight_layout(); fig.savefig(path, dpi=150); plt.close(fig)
+
+
+def setup(local: Path):
+ upstream = local/'upstream'
+ sys.path.insert(0, str(upstream/'src'/'python'))
+ sys.path.insert(0, str(upstream))
+ import contouring
+ return contouring
+
+
+def demo(local: Path) -> None:
+ contouring = setup(local); out = local/'demo'; out.mkdir(parents=True, exist_ok=True)
+ cube = read_obj(local/'upstream'/'data'/'cube.obj')
+ cube = Mesh(gpy.normalize_points(cube.v), cube.f)
+ # The author path obtains samples from mesh signed distance, not an oracle.
+ fixture = Fixture('author_cube', None)
+ published_rotation = author_rotation()
+ mc, mm, _ = run_case(contouring, fixture, cube, 32, 'MarchingCubes', rotation_matrix=published_rotation)
+ ours, om, _ = run_case(contouring, fixture, cube, 32, 'Ours', rotation_matrix=published_rotation)
+ write_obj(out/'author-cube-mc.obj', mm.v, mm.f); write_obj(out/'author-cube-ours.obj', om.v, om.f)
+ visual(out/'author-cube.png', cube, [('Marching Cubes',mm),('DCSD',om)], fixture)
+ (out/'demo.json').write_text(json.dumps({'revision':REVISION,'input':'upstream/data/cube.obj','mc':mc,'dcsd':ours},indent=2),encoding='utf-8')
+ print(json.dumps({'mc_seconds':mc['seconds'],'dcsd_seconds':ours['seconds'],'output':str(out)},indent=2))
+
+
+def benchmark(local: Path) -> None:
+ contouring = setup(local); mesh_root = local/'aetheris-meshes'; out = local/'benchmark'; out.mkdir(parents=True,exist_ok=True)
+ # The 100x100 published optimizer is deliberately expensive (~82 s even
+ # for the 32^3 cube). Use it on the decision fixtures; use an explicitly
+ # labeled 10x20 screen to expose broad compatibility/failure behavior.
+ cases = [(n,32,0.,'none',10,20) for n in FIXTURES]
+ cases += [(n,32,0.,'none',100,100) for n in ('sphere','sharp_box','thin_plate','bent_sheet')]
+ cases += [('sphere',64,0.,'none',10,20),('torus',64,0.,'none',10,20),
+ ('sharp_box',64,0.,'none',100,100),('thin_plate',64,0.,'none',10,20)]
+ cases += [('sharp_box',32,x,'none',10,20) for x in (.05,.2)] + [('sharp_box',32,0.,'float16',10,20)]
+ records=[]; visuals={}
+ for name,cells,noise,quant,outer,inner in cases:
+ source=read_obj(mesh_root/f'{name}.obj'); fixture=FIXTURES[name]
+ methods=['MarchingCubes','Ours']
+ print(f'CASE {name} {cells} noise={noise} quant={quant}',flush=True)
+ for method in methods:
+ rec,mesh,_=run_case(contouring,fixture,source,cells,method,noise,quant,outer,inner); records.append(rec)
+ key=(name,cells,noise,quant,outer,inner); visuals.setdefault(key,{})[method]=mesh
+ write_obj(out/f'{name}-{cells}-{noise}-{quant}-{outer}x{inner}-{method}.obj',mesh.v,mesh.f)
+ # Determinism: exact repeat, including vertex ordering.
+ src=read_obj(mesh_root/'sharp_box.obj'); a,ma,_=run_case(contouring,FIXTURES['sharp_box'],src,32,'Ours',outer_iters=10,inner_iters=20); b,mb,_=run_case(contouring,FIXTURES['sharp_box'],src,32,'Ours',outer_iters=10,inner_iters=20)
+ deterministic={'shape_equal':ma.v.shape==mb.v.shape and ma.f.shape==mb.f.shape,
+ 'faces_equal':bool(np.array_equal(ma.f,mb.f)),
+ 'max_vertex_delta_mm':float(np.max(np.abs(ma.v-mb.v))) if ma.v.shape==mb.v.shape else math.inf}
+ for key in [('sharp_box',32,0.,'none',100,100),('thin_plate',32,0.,'none',100,100),('bent_sheet',32,0.,'none',100,100),('sphere',32,0.,'none',100,100)]:
+ source=read_obj(mesh_root/f'{key[0]}.obj'); visual(out/f'{key[0]}-comparison.png',source,[(m,visuals[key][m]) for m in ('MarchingCubes','Ours')],FIXTURES[key[0]])
+ with (out/'metrics.csv').open('w',newline='',encoding='utf-8') as stream:
+ writer=csv.DictWriter(stream,fieldnames=list(records[0])); writer.writeheader(); writer.writerows(records)
+ summary={'schema':'aetheris.dcsd-dogfood-x0.v1','revision':REVISION,'seed':SEED,
+ 'environment':{'platform':platform.platform(),'python':platform.python_version(),'cpu_count':os.cpu_count()},
+ 'published_defaults':{'outer_iters':100,'inner_iters':100,'hermite_update':True,'mu':.1,'dc_weight':.02,'sphere_weight':1.,'svd_threshold':.01,'blend_weights':[.2,.2,.2]},
+ 'screening_profile':{'outer_iters':10,'inner_iters':20,'purpose':'broad bounded failure-mode screen; not used as the primary quality claim'},
+ 'records':records,'determinism':deterministic,
+ 'skipped_resolutions':{'128':'bounded X0 runtime; 64 already exposes thin-feature and scaling behavior','256':'~17.2M samples and impractical published 100x100 optimization on this CPU'}}
+ (out/'summary.json').write_text(json.dumps(summary,indent=2,allow_nan=True),encoding='utf-8')
+ # Simple evidence plots.
+ fig,axes=plt.subplots(1,3,figsize=(14,4))
+ clean=[r for r in records if r['noise_voxels']==0 and r['quantize']=='none']
+ for method in ('MarchingCubes','Ours'):
+ x=[r['voxel_mm'] for r in clean if r['method']==method]; y=[r['rms_mm'] for r in clean if r['method']==method]
+ axes[0].scatter(x,y,label=method,alpha=.75); axes[1].scatter([r['grid_nodes'] for r in clean if r['method']==method],[r['seconds'] for r in clean if r['method']==method],label=method,alpha=.75)
+ noise=[r for r in records if r['fixture']=='sharp_box' and r['cells']==32 and r['quantize']=='none']
+ for method in ('MarchingCubes','Ours'):
+ rows=[r for r in noise if r['method']==method]; axes[2].plot([r['noise_voxels'] for r in rows],[r['rms_mm'] for r in rows],'o-',label=method)
+ axes[0].set(xlabel='voxel size (mm)',ylabel='surface RMS (mm)',title='Error vs sampling'); axes[1].set(xlabel='grid nodes',ylabel='seconds',title='Runtime scaling'); axes[1].set_xscale('log'); axes[1].set_yscale('log'); axes[2].set(xlabel='SDF noise (voxels)',ylabel='surface RMS (mm)',title='Sharp box noise');
+ for ax in axes: ax.grid(alpha=.25); ax.legend()
+ fig.tight_layout(); fig.savefig(out/'plots.png',dpi=160); plt.close(fig)
+ print(json.dumps({'cases':len(records),'determinism':deterministic,'output':str(out)},indent=2))
+
+
+def wedge(local: Path) -> None:
+ """Run only the new exact sharp-prism screening witness."""
+ contouring = setup(local)
+ source = read_obj(local/'aetheris-meshes'/'sharp_wedge_prism.obj')
+ fixture = FIXTURES['sharp_wedge_prism']
+ out = local/'benchmark'
+ out.mkdir(parents=True, exist_ok=True)
+ records = []
+ meshes = []
+ for method in ('MarchingCubes', 'Ours'):
+ record, mesh, _ = run_case(contouring, fixture, source, 32, method,
+ outer_iters=10, inner_iters=20)
+ records.append(record)
+ meshes.append((method, mesh))
+ write_obj(out/f'sharp_wedge_prism-32-0.0-none-10x20-{method}.obj', mesh.v, mesh.f)
+ center = (source.v.min(0) + source.v.max(0)) * .5
+ rotated_source = Mesh((source.v - center) @ rotation() + center, source.f)
+ visual(out/'sharp-wedge-prism-comparison.png', rotated_source, meshes, fixture)
+ evidence = {
+ 'schema': 'aetheris.dcsd-dogfood-x0.wedge.v1',
+ 'source': 'fixtures/Experiments/DCSDDogfoodX0/sharp-wedge-prism.firmament',
+ 'field': 'exact analytic signed distance to the triangular prism',
+ 'profile': {'cells': 32, 'outer_iters': 10, 'inner_iters': 20},
+ 'records': records,
+ }
+ path = out/'sharp-wedge-prism-screen.json'
+ path.write_text(json.dumps(evidence, indent=2), encoding='utf-8')
+ print(json.dumps({'records': records, 'output': str(path)}, indent=2))
+
+
+def thin_sweep(local: Path) -> None:
+ contouring = setup(local); mesh_root = local/'aetheris-meshes'; out = local/'benchmark'; out.mkdir(parents=True,exist_ok=True)
+ base = read_obj(mesh_root/'thin_plate.obj'); records=[]
+ source_thickness = float(base.v[:,2].max() - base.v[:,2].min())
+ for thickness in (10., 3., 1., .5, .25):
+ vertices = base.v.copy()
+ vertices[:,2] = (vertices[:,2] - vertices[:,2].min()) / source_thickness * thickness
+ source = Mesh(vertices, base.f); fixture = Fixture(f'thin_{thickness:g}mm', box_sdf((40.,30.,thickness)))
+ for cells in (32,64):
+ for method in ('MarchingCubes','Ours'):
+ rec, mesh, _ = run_case(contouring,fixture,source,cells,method,outer_iters=10,inner_iters=20)
+ center=(source.v.min(0)+source.v.max(0))*.5
+ local=(mesh.v-center)@rotation().T+center
+ rec['requested_thickness_mm']=thickness
+ rec['reconstructed_z_span_mm']=float(np.max(local[:,2])-np.min(local[:,2])) if len(local) else math.nan
+ records.append(rec)
+ write_obj(out/f'thin-{thickness:g}mm-{cells}-{method}.obj',mesh.v,mesh.f)
+ (out/'thin-sweep.json').write_text(json.dumps({'profile':'10x20 screening','records':records},indent=2),encoding='utf-8')
+ fig,axes=plt.subplots(1,2,figsize=(10,4))
+ for method in ('MarchingCubes','Ours'):
+ for cells,style in ((32,'o-'),(64,'s--')):
+ rows=[r for r in records if r['method']==method and r['cells']==cells]
+ label=f'{method} {cells}^3'
+ axes[0].plot([r['requested_thickness_mm'] for r in rows],[r['rms_mm'] for r in rows],style,label=label)
+ axes[1].plot([r['requested_thickness_mm'] for r in rows],[r['nonmanifold_edges'] for r in rows],style,label=label)
+ axes[0].set(xscale='log',yscale='log',xlabel='plate thickness (mm)',ylabel='surface RMS (mm)',title='Thin-wall distance')
+ axes[1].set(xscale='log',yscale='symlog',xlabel='plate thickness (mm)',ylabel='nonmanifold edges',title='Thin-wall topology')
+ for ax in axes: ax.grid(alpha=.25); ax.legend(fontsize=7)
+ fig.tight_layout(); fig.savefig(out/'thin-sweep.png',dpi=160); plt.close(fig)
+ print(json.dumps({'cases':len(records),'output':str(out/'thin-sweep.json')},indent=2))
+
+
+def box_feature_metrics(mesh: Mesh, voxel_mm: float) -> dict:
+ r = rotation(); center = np.array([0.,0.,12.5]); local_v = (mesh.v-center) @ r.T + center
+ lo=np.array([-40.,-25.,0.]); hi=np.array([40.,25.,25.])
+ corners=np.array([[x,y,z] for x in (lo[0],hi[0]) for y in (lo[1],hi[1]) for z in (lo[2],hi[2])])
+ corners_rot=(corners-center)@r+center
+ corner_error=cKDTree(mesh.v).query(corners_rot)[0]
+ tri=mesh.v[mesh.f]; normals=np.cross(tri[:,1]-tri[:,0],tri[:,2]-tri[:,0]); normals/=np.maximum(np.linalg.norm(normals,axis=1,keepdims=True),EPS)
+ edges=np.sort(np.vstack((mesh.f[:,[0,1]],mesh.f[:,[1,2]],mesh.f[:,[2,0]])),axis=1)
+ face_ids=np.tile(np.arange(len(mesh.f)),3)
+ order=np.lexsort((edges[:,1],edges[:,0])); edges=edges[order]; face_ids=face_ids[order]
+ unique,starts,counts=np.unique(edges,axis=0,return_index=True,return_counts=True)
+ sharp_mid=[]; angle_error=[]
+ for edge,start,count in zip(unique,starts,counts):
+ if count != 2: continue
+ n0,n1=normals[face_ids[start]],normals[face_ids[start+1]]
+ angle=math.degrees(math.acos(float(np.clip(abs(np.dot(n0,n1)),-1,1))))
+ if angle > 30:
+ sharp_mid.append((mesh.v[edge[0]]+mesh.v[edge[1]])*.5); angle_error.append(abs(angle-90.))
+ true_segments=[]
+ for i,a in enumerate(corners_rot):
+ for j,b in enumerate(corners_rot):
+ if j>i and np.sum(np.abs(corners[i]-corners[j])>EPS)==1: true_segments.append((a,b))
+ def segment_distance(p,a,b):
+ ab=b-a; t=np.clip(np.dot(p-a,ab)/np.dot(ab,ab),0,1); return np.linalg.norm(p-(a+t*ab))
+ edge_error=np.array([min(segment_distance(p,a,b) for a,b in true_segments) for p in sharp_mid])
+ # Face-interior vertices: nearest supporting plane, at least two voxels from all face boundaries.
+ d=np.column_stack((abs(local_v[:,0]-lo[0]),abs(local_v[:,0]-hi[0]),abs(local_v[:,1]-lo[1]),abs(local_v[:,1]-hi[1]),abs(local_v[:,2]-lo[2]),abs(local_v[:,2]-hi[2])))
+ nearest=np.argmin(d,axis=1); residual=np.min(d,axis=1)
+ margin=np.minimum(local_v-lo,hi-local_v)
+ interior=np.array([margin[i,(nearest[i]//2+1)%3] > 2*voxel_mm and margin[i,(nearest[i]//2+2)%3] > 2*voxel_mm for i in range(len(local_v))])
+ plane=residual[interior]
+ return {'edge_candidate_count':len(edge_error),'edge_rms_mm':float(np.sqrt(np.mean(edge_error**2))) if len(edge_error) else math.nan,
+ 'edge_p95_mm':float(np.percentile(edge_error,95)) if len(edge_error) else math.nan,'edge_max_mm':float(np.max(edge_error)) if len(edge_error) else math.nan,
+ 'corner_rms_mm':float(np.sqrt(np.mean(corner_error**2))),'corner_p95_mm':float(np.percentile(corner_error,95)),'corner_max_mm':float(np.max(corner_error)),
+ 'dihedral_mean_abs_error_deg':float(np.mean(angle_error)) if angle_error else math.nan,'dihedral_p95_abs_error_deg':float(np.percentile(angle_error,95)) if angle_error else math.nan,
+ 'plane_interior_vertex_count':int(np.sum(interior)),'plane_residual_rms_mm':float(np.sqrt(np.mean(plane**2))) if len(plane) else math.nan,'plane_residual_max_mm':float(np.max(plane)) if len(plane) else math.nan}
+
+
+def analyze(local: Path) -> None:
+ out=local/'benchmark'; summary=json.loads((out/'summary.json').read_text(encoding='utf-8')); result={}
+ for cells in (32,64):
+ for method,outer,inner in (('MarchingCubes',100,100),('Ours',100,100)):
+ path=out/f'sharp_box-{cells}-0.0-none-{outer}x{inner}-{method}.obj'
+ record=next(r for r in summary['records'] if r['fixture']=='sharp_box' and r['cells']==cells and r['method']==method and (method=='MarchingCubes' or r['outer_iters']==100) and r['noise_voxels']==0 and r['quantize']=='none')
+ result[f'{method}-{cells}']=box_feature_metrics(read_obj(path),record['voxel_mm'])
+ (out/'sharp-feature-metrics.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
+ print(json.dumps(result,indent=2))
+
+
+def open_surface(local: Path) -> None:
+ contouring=setup(local); out=local/'benchmark'; out.mkdir(parents=True,exist_ok=True)
+ v=np.array([[-20.,-15.,0.],[20.,-15.,0.],[20.,15.,0.],[-20.,15.,0.]])
+ source=Mesh(v,np.array([[0,1,2],[0,2,3]],dtype=np.int64))
+ fixture=Fixture('open_rectangle',lambda q:q[:,2])
+ records=[]
+ for method in ('MarchingCubes','Ours'):
+ rec,mesh,_=run_case(contouring,fixture,source,32,method,outer_iters=10,inner_iters=20)
+ rec['intended_footprint_mm']=[40.,30.]
+ rec['reconstructed_xy_extent_mm']=(mesh.v.max(0)-mesh.v.min(0))[:2].tolist()
+ records.append(rec); write_obj(out/f'open-rectangle-{method}.obj',mesh.v,mesh.f)
+ (out/'open-surface.json').write_text(json.dumps({'field':'phi=z encodes an unbounded plane; finite patch boundary is absent from signed-volume data','records':records},indent=2),encoding='utf-8')
+ print(json.dumps(records,indent=2))
+
+
+def visual_evidence(local: Path) -> None:
+ out=local/'benchmark'; exact=box_sdf((80.,50.,25.)); center=np.array([0.,0.,12.5]); r=rotation()
+ mesh=read_obj(out/'sharp_box-32-0.0-none-100x100-Ours.obj')
+ q=(mesh.v-center)@r.T+center; err=np.abs(exact(q))
+ fig,axes=plt.subplots(1,3,figsize=(14,4))
+ views=[(0,1,'top / XY',(-42,42),(-27,27)),(0,2,'front / XZ',(-42,42),(-2,27)),(1,2,'side / YZ',(-27,27),(-2,27))]
+ for ax,(a,b,title,xlim,ylim) in zip(axes,views):
+ sc=ax.scatter(q[:,a],q[:,b],c=err,s=3,cmap='magma',vmin=0,vmax=np.percentile(err,99)); ax.set_title(title); ax.set_xlim(*xlim); ax.set_ylim(*ylim); ax.set_aspect('equal'); ax.grid(alpha=.15)
+ fig.colorbar(sc,ax=axes,label='absolute exact SDF error (mm)',shrink=.8); fig.suptitle('DCSD sharp-box vertex error, 32³ published profile'); fig.savefig(out/'sharp-error-heatmap.png',dpi=170,bbox_inches='tight'); plt.close(fig)
+ corner=np.array([40.,25.,25.]); keep=np.linalg.norm(q-corner,axis=1)<8
+ fig,ax=plt.subplots(figsize=(6,5)); sc=ax.scatter(q[keep,0],q[keep,2],c=err[keep],s=12,cmap='magma'); ax.scatter([40],[25],marker='x',s=100,color='cyan',label='exact corner'); ax.set(xlabel='x (mm)',ylabel='z (mm)',title='Sharp corner close-up'); ax.set_aspect('equal'); ax.grid(alpha=.2); ax.legend(); fig.colorbar(sc,ax=ax,label='error (mm)'); fig.savefig(out/'sharp-corner-closeup.png',dpi=170,bbox_inches='tight'); plt.close(fig)
+ x=np.linspace(-46.4,46.4,33); y=np.linspace(-31.4,31.4,33); xx,yy=np.meshgrid(x,y); qq=np.column_stack((xx.ravel(),yy.ravel(),np.full(xx.size,12.5))); phi=exact(qq).reshape(xx.shape)
+ fig,ax=plt.subplots(figsize=(7,5)); im=ax.contourf(xx,yy,phi,levels=32,cmap='coolwarm'); ax.contour(xx,yy,phi,levels=[0],colors='black',linewidths=2); ax.scatter(xx,yy,s=2,color='black',alpha=.25); ax.set_aspect('equal'); ax.set_title('Representative exact SDF grid slice (box mid-plane)'); ax.set_xlabel('x (mm)'); ax.set_ylabel('y (mm)'); fig.colorbar(im,ax=ax,label='signed distance (mm)'); fig.savefig(out/'sdf-grid-slice.png',dpi=170,bbox_inches='tight'); plt.close(fig)
+ noisy=read_obj(out/'sharp_box-32-0.2-none-10x20-Ours.obj'); nq=(noisy.v-center)@r.T+center; ne=np.abs(exact(nq))
+ fig,ax=plt.subplots(figsize=(7,5)); sc=ax.scatter(nq[:,0],nq[:,2],c=ne,s=4,cmap='magma',vmax=np.percentile(ne,99)); ax.set_aspect('equal'); ax.set_title('Sharp box with 0.20-voxel SDF noise'); ax.set_xlabel('x (mm)'); ax.set_ylabel('z (mm)'); fig.colorbar(sc,ax=ax,label='error (mm)'); fig.savefig(out/'sharp-noise.png',dpi=170,bbox_inches='tight'); plt.close(fig)
+ print(json.dumps({'outputs':['sharp-error-heatmap.png','sharp-corner-closeup.png','sdf-grid-slice.png','sharp-noise.png']},indent=2))
+
+
+def main() -> None:
+ parser=argparse.ArgumentParser(); parser.add_argument('command',choices=('demo','benchmark','wedge','thin-sweep','analyze','open-surface','visual-evidence')); parser.add_argument('--local-root',type=Path,required=True); args=parser.parse_args()
+ {'demo':demo,'benchmark':benchmark,'wedge':wedge,'thin-sweep':thin_sweep,'analyze':analyze,'open-surface':open_surface,'visual-evidence':visual_evidence}[args.command](args.local_root.resolve())
+
+
+if __name__=='__main__': main()
diff --git a/tools/DCSDDogfoodX0/requirements.txt b/tools/DCSDDogfoodX0/requirements.txt
new file mode 100644
index 00000000..0adab213
--- /dev/null
+++ b/tools/DCSDDogfoodX0/requirements.txt
@@ -0,0 +1,7 @@
+gpytoolbox==0.3.7
+libigl==2.6.1
+matplotlib==3.10.8
+numpy==2.2.0
+scipy==1.15.0
+trimesh==4.11.1
+
diff --git a/tools/DCSDDogfoodX0/run.ps1 b/tools/DCSDDogfoodX0/run.ps1
new file mode 100644
index 00000000..cec81a1f
--- /dev/null
+++ b/tools/DCSDDogfoodX0/run.ps1
@@ -0,0 +1,122 @@
+param(
+ [ValidateSet('all', 'prepare', 'demo', 'benchmark', 'wedge', 'analyze')]
+ [string]$Phase = 'all'
+)
+
+$ErrorActionPreference = 'Stop'
+$repo = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
+$local = Join-Path $repo 'artifacts\local\dcsd-x0'
+$upstream = Join-Path $local 'upstream'
+$python = Join-Path $local 'venv\Scripts\python.exe'
+$revision = 'fa1962cd5825cfc9bb698569714f579e1d75a4e8'
+
+function Replace-Once([string]$Path, [string]$Old, [string]$New) {
+ $text = Get-Content -LiteralPath $Path -Raw
+ if ($text.Contains($New)) { return }
+ if (-not $text.Contains($Old)) { throw "Expected patch context missing in $Path" }
+ [System.IO.File]::WriteAllText($Path, $text.Replace($Old, $New))
+}
+
+function Prepare-Upstream {
+ New-Item -ItemType Directory -Force $local | Out-Null
+ if (-not (Test-Path (Join-Path $upstream '.git'))) {
+ git -c core.longpaths=true clone --recursive https://github.com/xianacarrera/dual-contouring-of-signed-distance-data.git $upstream
+ }
+ git -C $upstream -c core.longpaths=true checkout --detach $revision
+ git -C $upstream -c core.longpaths=true submodule update --init --recursive
+ if ((git -C $upstream rev-parse HEAD).Trim() -ne $revision) { throw 'Unexpected upstream revision' }
+
+ # Narrow Windows/headless compatibility patch. These edits do not alter the
+ # objective, weights, iteration counts, Hermite update, or connectivity.
+ Replace-Once (Join-Path $upstream 'include\contouring.h') "#pragma once`n" "#pragma once`n#include <vector>`n"
+ Replace-Once (Join-Path $upstream 'include\ui.h') "#pragma once`n" "#pragma once`n#include <vector>`n"
+ $cmake = Join-Path $upstream 'CMakeLists.txt'
+ Replace-Once $cmake "project(contouring)`n" "project(contouring)`n`nfind_package(OpenMP)`n"
+ Replace-Once $cmake 'list(REMOVE_ITEM CONTOURING_SRC_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/cpp/bindings.cpp")' "list(REMOVE_ITEM CONTOURING_SRC_FILES `"`${CMAKE_CURRENT_SOURCE_DIR}/src/cpp/bindings.cpp`")`n# sample_fun.cpp contains an obsolete second contouring() definition which wins on MSVC.`nlist(REMOVE_ITEM CONTOURING_SRC_FILES `"`${CMAKE_CURRENT_SOURCE_DIR}/src/cpp/sample_fun.cpp`")"
+ Replace-Once $cmake " polyscope`n)`n" " polyscope`n)`nif(OpenMP_CXX_FOUND)`n target_link_libraries(contouring PUBLIC OpenMP::OpenMP_CXX)`nendif()`n"
+ Replace-Once (Join-Path $upstream 'src\cpp\ui.cpp') " for (Cell& c : cells) {" " for (int cell_index = 0; cell_index < static_cast<int>(cells.size()); ++cell_index) {`n Cell& c = cells[static_cast<size_t>(cell_index)];"
+ Replace-Once (Join-Path $upstream 'src\cpp\hermite_update.cpp') " for (size_t ei = 0; ei < edge_cells.size(); ++ei) {`n Eigen::Vector4i cell_indices = edge_cells[ei];" " for (int ei = 0; ei < static_cast<int>(edge_cells.size()); ++ei) {`n Eigen::Vector4i cell_indices = edge_cells[static_cast<size_t>(ei)];"
+ Replace-Once (Join-Path $upstream 'src\cpp\contouring.cpp') " for (size_t i = 0; i < cells.size(); ++i) {`n Cell& c = cells[i];" " for (int i = 0; i < static_cast<int>(cells.size()); ++i) {`n Cell& c = cells[static_cast<size_t>(i)];"
+
+ if (-not (Test-Path $python)) { py -3.11 -m venv (Join-Path $local 'venv') }
+ & $python -m pip install -r (Join-Path $PSScriptRoot 'requirements.txt') pybind11==3.0.1 cmake==4.4.3 ninja
+ if ($LASTEXITCODE -ne 0) { throw 'Python dependency installation failed' }
+
+ $build = Join-Path $upstream 'build-win'
+ $pythonAbsolute = (Resolve-Path $python).Path
+ $cmakeExe = Join-Path $local 'venv\Scripts\cmake.exe'
+ & 'C:\Program Files\Microsoft Visual Studio\18\Community\Common7\Tools\Launch-VsDevShell.ps1' -Arch amd64 -HostArch amd64 -NoLogo
+ # The upstream OpenMP annotations compile after the loop-index portability
+ # fixes but make the 32^3 demo exceed 3 minutes (serial: about 37 s).
+ # Keep the faithful deterministic serial path for X0.
+ & $cmakeExe -S $upstream -B $build -G Ninja -DCMAKE_BUILD_TYPE=Release -DPython3_EXECUTABLE=$pythonAbsolute -DCMAKE_DISABLE_FIND_PACKAGE_OpenMP=TRUE
+ if ($LASTEXITCODE -ne 0) { throw 'DCSD CMake configuration failed' }
+ & $cmakeExe --build $build -j 12
+ if ($LASTEXITCODE -ne 0) { throw 'DCSD native build failed' }
+}
+
+function Export-Fixtures {
+ $meshDir = Join-Path $local 'aetheris-meshes'
+ New-Item -ItemType Directory -Force $meshDir | Out-Null
+ $fixtures = [ordered]@{
+ sphere = 'fixtures/Canonical/Primitives/sphere.firmament'
+ cylinder = 'fixtures/Canonical/Basics/cylinder.firmament'
+ torus = 'fixtures/Canonical/Primitives/torus.firmament'
+ frustum = 'fixtures/Canonical/Primitives/frustum.firmament'
+ filleted_box = 'fixtures/Canonical/Primitives/rounded-box.firmament'
+ rounded_rectangle_prism = 'fixtures/Experiments/PATDogfoodX0/rounded-rectangle-prism.firmament'
+ sharp_box = 'fixtures/Canonical/Basics/box.firmament'
+ sharp_wedge_prism = 'fixtures/Experiments/DCSDDogfoodX0/sharp-wedge-prism.firmament'
+ chamfered_box = 'fixtures/Canonical/Features/EdgeFinish/semantic-selection-chamfer.firmament'
+ through_hole = 'fixtures/Canonical/Features/Holes/through-hole.firmament'
+ counterbore = 'fixtures/Canonical/Features/Holes/counterbore.firmament'
+ thin_plate = 'fixtures/Experiments/PATDogfoodX0/thin-plate.firmament'
+ phone_like_chassis = 'fixtures/Experiments/PATDogfoodX0/phone-like-chassis.firmament'
+ }
+ foreach ($entry in $fixtures.GetEnumerator()) {
+ $source = Join-Path $repo $entry.Value
+ $out = Join-Path $meshDir ($entry.Key + '.obj')
+ $implicitStep = [System.IO.Path]::ChangeExtension($source, '.step')
+ $existed = Test-Path $implicitStep
+ dotnet run --project (Join-Path $repo 'Aetheris.CLI') -- mesh $source --format obj --output $out --json
+ if ($LASTEXITCODE -ne 0) { throw "Aetheris export failed for $($entry.Key)" }
+ if (-not $existed -and (Test-Path $implicitStep)) { Remove-Item -LiteralPath $implicitStep }
+ }
+
+ # Exercise the authored SheetMetal ProfileDelta route, not a hand-built bend.
+ $sheetDir = Join-Path $local 'sheetmetal'
+ New-Item -ItemType Directory -Force $sheetDir | Out-Null
+ $source = Join-Path $repo 'fixtures/Canonical/SheetMetal/profile-delta-tab-family.firmament'
+ $step = Join-Path $sheetDir 'profile-delta-tab-formed.step'
+ dotnet run --project (Join-Path $repo 'Aetheris.CLI') -- build $source --output $step --json
+ if ($LASTEXITCODE -ne 0) { throw 'SheetMetal ProfileDelta build failed' }
+ dotnet run --project (Join-Path $repo 'Aetheris.CLI') -- sheetmetal inspect $source --json
+ if ($LASTEXITCODE -ne 0) { throw 'SheetMetal ProfileDelta inspection failed' }
+ dotnet run --project (Join-Path $repo 'Aetheris.CLI') -- mesh $step --format obj --output (Join-Path $meshDir 'bent_sheet.obj') --json
+ if ($LASTEXITCODE -ne 0) { throw 'SheetMetal formed mesh export failed' }
+}
+
+function Export-WedgeFixture {
+ $meshDir = Join-Path $local 'aetheris-meshes'
+ New-Item -ItemType Directory -Force $meshDir | Out-Null
+ $source = Join-Path $repo 'fixtures/Experiments/DCSDDogfoodX0/sharp-wedge-prism.firmament'
+ $out = Join-Path $meshDir 'sharp_wedge_prism.obj'
+ $implicitStep = [System.IO.Path]::ChangeExtension($source, '.step')
+ $existed = Test-Path $implicitStep
+ dotnet run --project (Join-Path $repo 'Aetheris.CLI') -- mesh $source --format obj --output $out --json
+ if ($LASTEXITCODE -ne 0) { throw 'Aetheris export failed for sharp_wedge_prism' }
+ if (-not $existed -and (Test-Path $implicitStep)) { Remove-Item -LiteralPath $implicitStep }
+}
+
+Set-Location $repo
+if ($Phase -in @('all', 'prepare')) { Prepare-Upstream; Export-Fixtures }
+if ($Phase -eq 'wedge') { Prepare-Upstream; Export-WedgeFixture }
+if ($Phase -in @('all', 'demo')) { & $python (Join-Path $PSScriptRoot 'dcsd_x0.py') demo --local-root $local; if ($LASTEXITCODE -ne 0) { throw 'DCSD demo failed' } }
+if ($Phase -in @('all', 'benchmark')) { & $python (Join-Path $PSScriptRoot 'dcsd_x0.py') benchmark --local-root $local; if ($LASTEXITCODE -ne 0) { throw 'DCSD benchmark failed' } }
+if ($Phase -eq 'wedge') { & $python (Join-Path $PSScriptRoot 'dcsd_x0.py') wedge --local-root $local; if ($LASTEXITCODE -ne 0) { throw 'DCSD wedge failed' } }
+if ($Phase -in @('all', 'benchmark')) { & $python (Join-Path $PSScriptRoot 'dcsd_x0.py') thin-sweep --local-root $local; if ($LASTEXITCODE -ne 0) { throw 'DCSD thin sweep failed' } }
+if ($Phase -in @('all', 'benchmark')) { & $python (Join-Path $PSScriptRoot 'dcsd_x0.py') open-surface --local-root $local; if ($LASTEXITCODE -ne 0) { throw 'DCSD open-surface test failed' } }
+if ($Phase -in @('all', 'benchmark')) { & $python (Join-Path $PSScriptRoot 'dcsd_x0.py') analyze --local-root $local; if ($LASTEXITCODE -ne 0) { throw 'DCSD feature analysis failed' } }
+if ($Phase -in @('all', 'benchmark')) { & $python (Join-Path $PSScriptRoot 'dcsd_x0.py') visual-evidence --local-root $local; if ($LASTEXITCODE -ne 0) { throw 'DCSD visual evidence failed' } }
+if ($Phase -eq 'analyze') { & $python (Join-Path $PSScriptRoot 'dcsd_x0.py') analyze --local-root $local; if ($LASTEXITCODE -ne 0) { throw 'DCSD feature analysis failed' } }
+if ($Phase -eq 'analyze') { & $python (Join-Path $PSScriptRoot 'dcsd_x0.py') visual-evidence --local-root $local; if ($LASTEXITCODE -ne 0) { throw 'DCSD visual evidence failed' } }
diff --git a/tools/PATDogfoodX0/pat_x0.py b/tools/PATDogfoodX0/pat_x0.py
new file mode 100644
index 00000000..4207cd9b
--- /dev/null
+++ b/tools/PATDogfoodX0/pat_x0.py
@@ -0,0 +1,805 @@
+from __future__ import annotations
+
+import argparse
+import csv
+import hashlib
+import json
+import math
+import os
+import platform
+import subprocess
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable
+
+import matplotlib
+
+matplotlib.use('Agg')
+import matplotlib.pyplot as plt
+import numpy as np
+
+from pointsastori.infer import PointsAsTori
+from pointsastori.shape_3d import TriangleMesh
+
+
+SEED = 20260917
+EPS = 1.0e-9
+
+
+@dataclass(frozen=True)
+class MeshData:
+ vertices: np.ndarray
+ faces: np.ndarray
+ corner_normals: np.ndarray
+
+
+@dataclass(frozen=True)
+class Fixture:
+ name: str
+ truth_kind: str
+ exact_sdf: Callable[[np.ndarray], np.ndarray] | None = None
+
+
+def sha256(path: Path) -> str:
+ value = hashlib.sha256()
+ with path.open('rb') as stream:
+ for chunk in iter(lambda: stream.read(1024 * 1024), b''):
+ value.update(chunk)
+ return value.hexdigest().upper()
+
+
+def read_obj(path: Path) -> MeshData:
+ vertices: list[list[float]] = []
+ normals: list[list[float]] = []
+ triangles: list[list[int]] = []
+ triangle_normal_indices: list[list[int]] = []
+ with path.open('r', encoding='utf-8') as stream:
+ for raw in stream:
+ parts = raw.strip().split()
+ if not parts:
+ continue
+ if parts[0] == 'v':
+ vertices.append([float(x) for x in parts[1:4]])
+ elif parts[0] == 'vn':
+ normals.append([float(x) for x in parts[1:4]])
+ elif parts[0] == 'f':
+ corners = parts[1:]
+ for j in range(1, len(corners) - 1):
+ tri_tokens = [corners[0], corners[j], corners[j + 1]]
+ vi: list[int] = []
+ ni: list[int] = []
+ for token in tri_tokens:
+ fields = token.split('/')
+ vi.append(int(fields[0]) - 1)
+ normal_index = int(fields[2]) - 1 if len(fields) > 2 and fields[2] else -1
+ ni.append(normal_index)
+ triangles.append(vi)
+ triangle_normal_indices.append(ni)
+
+ v = np.asarray(vertices, dtype=np.float64)
+ f = np.asarray(triangles, dtype=np.int64)
+ geometric = np.cross(v[f[:, 1]] - v[f[:, 0]], v[f[:, 2]] - v[f[:, 0]])
+ geometric /= np.maximum(np.linalg.norm(geometric, axis=1, keepdims=True), EPS)
+ if normals and all(index >= 0 for row in triangle_normal_indices for index in row):
+ source_normals = np.asarray(normals, dtype=np.float64)
+ cn = source_normals[np.asarray(triangle_normal_indices, dtype=np.int64)]
+ else:
+ cn = np.repeat(geometric[:, None, :], 3, axis=1)
+ cn /= np.maximum(np.linalg.norm(cn, axis=2, keepdims=True), EPS)
+ return MeshData(v, f, cn)
+
+
+def sample_surface(mesh: MeshData, count: int, seed: int, mode: str = 'area') -> tuple[np.ndarray, np.ndarray]:
+ rng = np.random.default_rng(seed)
+ tri = mesh.vertices[mesh.faces]
+ twice_area = np.linalg.norm(np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]), axis=1)
+ if mode == 'area':
+ probability = twice_area / np.sum(twice_area)
+ elif mode == 'uniform-triangle':
+ probability = None
+ else:
+ raise ValueError(mode)
+ face_index = rng.choice(len(mesh.faces), size=count, replace=True, p=probability)
+ uv = rng.random((count, 2))
+ swap = np.sum(uv, axis=1) > 1.0
+ uv[swap] = 1.0 - uv[swap]
+ bary = np.column_stack((1.0 - uv[:, 0] - uv[:, 1], uv[:, 0], uv[:, 1]))
+ selected_tri = tri[face_index]
+ points = np.sum(selected_tri * bary[:, :, None], axis=1)
+ selected_normals = mesh.corner_normals[face_index]
+ out_normals = np.sum(selected_normals * bary[:, :, None], axis=1)
+ out_normals /= np.maximum(np.linalg.norm(out_normals, axis=1, keepdims=True), EPS)
+ return points, out_normals
+
+
+def sphere_sdf(q: np.ndarray) -> np.ndarray:
+ return np.linalg.norm(q, axis=1) - 7.5
+
+
+def torus_sdf(q: np.ndarray) -> np.ndarray:
+ # Aetheris' canonical Torus axis is +Y.
+ radial = np.linalg.norm(q[:, [0, 2]], axis=1) - 12.0
+ return np.sqrt(radial * radial + q[:, 1] * q[:, 1]) - 3.0
+
+
+def box_sdf(size: tuple[float, float, float]) -> Callable[[np.ndarray], np.ndarray]:
+ half = np.asarray(size, dtype=np.float64) * 0.5
+ center = np.array([0.0, 0.0, half[2]])
+
+ def evaluate(q: np.ndarray) -> np.ndarray:
+ d = np.abs(q - center) - half
+ return np.linalg.norm(np.maximum(d, 0.0), axis=1) + np.minimum(np.max(d, axis=1), 0.0)
+
+ return evaluate
+
+
+def cylinder_sdf(q: np.ndarray) -> np.ndarray:
+ radial = np.linalg.norm(q[:, :2], axis=1) - 12.0
+ axial = np.abs(q[:, 2] - 15.0) - 15.0
+ d = np.column_stack((radial, axial))
+ return np.linalg.norm(np.maximum(d, 0.0), axis=1) + np.minimum(np.max(d, axis=1), 0.0)
+
+
+def frustum_sdf(q: np.ndarray) -> np.ndarray:
+ """Exact SDF for the canonical capped frustum, centered for evaluation."""
+ half_height = 15.0
+ bottom_radius = 20.0
+ top_radius = 10.0
+ radial_axial = np.column_stack((np.linalg.norm(q[:, :2], axis=1), q[:, 2] - half_height))
+ cap_radius = np.where(radial_axial[:, 1] < 0.0, bottom_radius, top_radius)
+ cap = np.column_stack(
+ (
+ radial_axial[:, 0] - np.minimum(radial_axial[:, 0], cap_radius),
+ np.abs(radial_axial[:, 1]) - half_height,
+ )
+ )
+ upper = np.array([top_radius, half_height])
+ slope = np.array([top_radius - bottom_radius, 2.0 * half_height])
+ projection = np.clip(
+ np.sum((upper - radial_axial) * slope, axis=1) / np.dot(slope, slope),
+ 0.0,
+ 1.0,
+ )
+ side = radial_axial - upper + projection[:, None] * slope
+ sign = np.where((side[:, 0] < 0.0) & (cap[:, 1] < 0.0), -1.0, 1.0)
+ return sign * np.sqrt(np.minimum(np.sum(cap * cap, axis=1), np.sum(side * side, axis=1)))
+
+
+FIXTURES = [
+ Fixture('sphere', 'analytic', sphere_sdf),
+ Fixture('cylinder', 'analytic', cylinder_sdf),
+ Fixture('torus', 'analytic', torus_sdf),
+ Fixture('frustum', 'analytic', frustum_sdf),
+ Fixture('slab', 'analytic', box_sdf((40.0, 30.0, 3.0))),
+ Fixture('filleted_box', 'qualified-mesh'),
+ Fixture('rounded_rectangle_prism', 'qualified-mesh'),
+ Fixture('sharp_box', 'analytic', box_sdf((80.0, 50.0, 25.0))),
+ Fixture('chamfered_box', 'qualified-mesh'),
+ Fixture('through_hole', 'qualified-mesh'),
+ Fixture('counterbore', 'qualified-mesh'),
+ Fixture('thin_plate', 'analytic', box_sdf((40.0, 30.0, 0.5))),
+ Fixture('bent_sheet', 'qualified-mesh'),
+ Fixture('phone_like_chassis', 'qualified-mesh'),
+]
+
+
+def truth_evaluator(fixture: Fixture, mesh: MeshData) -> Callable[[np.ndarray], np.ndarray]:
+ if fixture.exact_sdf is not None:
+ return fixture.exact_sdf
+ bound = TriangleMesh(mesh.vertices, mesh.faces)
+ return lambda q: np.asarray(bound.evaluate_signed_distance(q), dtype=np.float64)
+
+
+def snap_analytic_samples(
+ fixture: Fixture, points: np.ndarray, normals: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+ """Lift tessellation samples back to exact admitted analytic supports."""
+ p = points.copy()
+ n = normals.copy()
+ if fixture.name == 'sphere':
+ n = p / np.maximum(np.linalg.norm(p, axis=1, keepdims=True), EPS)
+ p = 7.5 * n
+ elif fixture.name == 'torus':
+ radial = p[:, [0, 2]]
+ radial_unit = radial / np.maximum(np.linalg.norm(radial, axis=1, keepdims=True), EPS)
+ centerline = np.column_stack((12.0 * radial_unit[:, 0], np.zeros(len(p)), 12.0 * radial_unit[:, 1]))
+ n = p - centerline
+ n /= np.maximum(np.linalg.norm(n, axis=1, keepdims=True), EPS)
+ p = centerline + 3.0 * n
+ elif fixture.name == 'cylinder':
+ cap = np.abs(n[:, 2]) > 0.7
+ p[cap, 2] = np.where(n[cap, 2] > 0.0, 30.0, 0.0)
+ n[cap] = np.column_stack((np.zeros(np.sum(cap)), np.zeros(np.sum(cap)), np.sign(n[cap, 2])))
+ side = ~cap
+ radial = p[side, :2]
+ radial_unit = radial / np.maximum(np.linalg.norm(radial, axis=1, keepdims=True), EPS)
+ p[side, :2] = 12.0 * radial_unit
+ n[side] = np.column_stack((radial_unit, np.zeros(np.sum(side))))
+ elif fixture.name == 'frustum':
+ cap = np.abs(n[:, 2]) > 0.7
+ p[cap, 2] = np.where(n[cap, 2] > 0.0, 30.0, 0.0)
+ n[cap] = np.column_stack((np.zeros(np.sum(cap)), np.zeros(np.sum(cap)), np.sign(n[cap, 2])))
+ side = ~cap
+ radial = p[side, :2]
+ radial_unit = radial / np.maximum(np.linalg.norm(radial, axis=1, keepdims=True), EPS)
+ radius = 20.0 - p[side, 2] / 3.0
+ p[side, :2] = radius[:, None] * radial_unit
+ side_normal = np.column_stack((radial_unit, np.full(np.sum(side), 1.0 / 3.0)))
+ n[side] = side_normal / np.linalg.norm(side_normal, axis=1, keepdims=True)
+ return p, n
+
+
+def percentile(values: np.ndarray, p: float) -> float:
+ return float(np.percentile(values, p)) if len(values) else math.nan
+
+
+def summarize_errors(predicted: np.ndarray, truth: np.ndarray) -> dict[str, float | int]:
+ error = predicted - truth
+ absolute = np.abs(error)
+ signed_mask = np.abs(truth) > 1.0e-5
+ sign_correct = np.signbit(predicted[signed_mask]) == np.signbit(truth[signed_mask])
+ false_material = np.sum((predicted[signed_mask] < 0.0) & (truth[signed_mask] > 0.0))
+ false_void = np.sum((predicted[signed_mask] > 0.0) & (truth[signed_mask] < 0.0))
+ return {
+ 'count': int(len(truth)),
+ 'rms_mm': float(np.sqrt(np.mean(error * error))),
+ 'p50_abs_mm': percentile(absolute, 50),
+ 'p95_abs_mm': percentile(absolute, 95),
+ 'p99_abs_mm': percentile(absolute, 99),
+ 'max_abs_mm': float(np.max(absolute)),
+ 'signed_bias_mm': float(np.mean(error)),
+ 'sign_error_count': int(np.sum(~sign_correct)),
+ 'sign_error_rate': float(np.mean(~sign_correct)) if len(sign_correct) else math.nan,
+ 'classification_accuracy': float(np.mean(sign_correct)) if len(sign_correct) else math.nan,
+ 'false_material_count': int(false_material),
+ 'false_void_count': int(false_void),
+ }
+
+
+def query_corpus(
+ fixture: Fixture,
+ mesh: MeshData,
+ surface_points: np.ndarray,
+ surface_normals: np.ndarray,
+ truth: Callable[[np.ndarray], np.ndarray],
+) -> tuple[np.ndarray, np.ndarray]:
+ rng = np.random.default_rng(SEED + 91)
+ indices = rng.choice(len(surface_points), size=min(384, len(surface_points)), replace=False)
+ p = surface_points[indices]
+ n = surface_normals[indices]
+ scale = np.linalg.norm(np.ptp(mesh.vertices, axis=0))
+ near = max(scale * 0.002, 0.01)
+ moderate = max(scale * 0.03, 0.1)
+ queries = []
+ categories = []
+ for distance, category in [
+ (0.0, 'on-surface'),
+ (-near, 'surface-near'),
+ (near, 'surface-near'),
+ (-moderate, 'inside'),
+ (moderate, 'outside'),
+ ]:
+ queries.append(p + distance * n)
+ categories.extend([category] * len(p))
+
+ low = np.min(mesh.vertices, axis=0)
+ high = np.max(mesh.vertices, axis=0)
+ pad = np.maximum((high - low) * 0.35, 0.5)
+ random_queries = rng.uniform(low - pad, high + pad, size=(1200, 3))
+ random_truth = truth(random_queries)
+ queries.append(random_queries)
+ categories.extend(np.where(random_truth < 0.0, 'inside', 'far-field').tolist())
+
+ if fixture.name == 'sharp_box':
+ offsets = rng.normal(0.0, 0.6, size=(400, 3))
+ edge = np.tile(np.array([40.0, 25.0, 12.5]), (200, 1)) + offsets[:200]
+ corner = np.tile(np.array([40.0, 25.0, 25.0]), (200, 1)) + offsets[200:]
+ queries.extend([edge, corner])
+ categories.extend(['sharp-edge-near'] * len(edge))
+ categories.extend(['sharp-corner-near'] * len(corner))
+ elif fixture.name in {'chamfered_box', 'counterbore', 'through_hole'}:
+ feature_index = np.argsort(np.linalg.norm(p[:, :2], axis=1))[: min(250, len(p))]
+ queries.append(p[feature_index] + rng.normal(0.0, near, size=(len(feature_index), 3)))
+ categories.extend(['sharp-feature-near'] * len(feature_index))
+ elif fixture.name in {'thin_plate', 'slab', 'bent_sheet'}:
+ zline = np.linspace(np.min(mesh.vertices[:, 2]) - 1.0, np.max(mesh.vertices[:, 2]) + 1.0, 500)
+ thin = np.column_stack((np.zeros_like(zline), np.zeros_like(zline), zline))
+ queries.append(thin)
+ categories.extend(['thin-wall'] * len(thin))
+
+ return np.vstack(queries), np.asarray(categories, dtype=object)
+
+
+def perturb(
+ points: np.ndarray,
+ normals: np.ndarray,
+ scenario: str,
+ level: float,
+ seed: int,
+) -> tuple[np.ndarray, np.ndarray]:
+ rng = np.random.default_rng(seed)
+ p = points.copy()
+ n = normals.copy()
+ if scenario == 'position-noise':
+ p += rng.normal(0.0, level, size=p.shape)
+ elif scenario == 'normal-noise':
+ n += rng.normal(0.0, math.radians(level), size=n.shape)
+ n /= np.maximum(np.linalg.norm(n, axis=1, keepdims=True), EPS)
+ elif scenario == 'normal-flips':
+ indices = rng.choice(len(n), size=max(1, int(level * len(n))), replace=False)
+ n[indices] *= -1.0
+ elif scenario == 'missing-cap':
+ threshold = np.quantile(p[:, 2], 1.0 - level)
+ keep = p[:, 2] < threshold
+ p, n = p[keep], n[keep]
+ elif scenario == 'random-missing':
+ keep = rng.random(len(p)) >= level
+ p, n = p[keep], n[keep]
+ elif scenario == 'nonuniform-density':
+ weights = 0.1 + np.square((p[:, 0] - np.min(p[:, 0])) / max(np.ptp(p[:, 0]), EPS))
+ indices = rng.choice(len(p), size=len(p), replace=True, p=weights / np.sum(weights))
+ p, n = p[indices], n[indices]
+ elif scenario == 'open-surface':
+ keep = n[:, 2] > 0.9
+ p, n = p[keep], n[keep]
+ return p, n
+
+
+def zero_offsets(
+ pat: PointsAsTori,
+ points: np.ndarray,
+ normals: np.ndarray,
+ target: float = 0.0,
+) -> dict[str, float | int]:
+ count = min(128, len(points))
+ p = points[:count]
+ n = normals[:count]
+ span = max(float(np.linalg.norm(np.ptp(points, axis=0))) * 0.08, 0.2)
+ lo = np.full(count, -span)
+ hi = np.full(count, span)
+ flo = pat.signed_distance(p + lo[:, None] * n) - target
+ fhi = pat.signed_distance(p + hi[:, None] * n) - target
+ valid = np.isfinite(flo) & np.isfinite(fhi) & (np.signbit(flo) != np.signbit(fhi))
+ if not np.any(valid):
+ return {'root_count': 0, 'unbracketed': count, 'rms_mm': math.nan, 'p95_mm': math.nan, 'max_mm': math.nan}
+ pv, nv = p[valid], n[valid]
+ lv, hv = lo[valid], hi[valid]
+ for _ in range(28):
+ mid = (lv + hv) * 0.5
+ fm = pat.signed_distance(pv + mid[:, None] * nv) - target
+ left_value = pat.signed_distance(pv + lv[:, None] * nv) - target
+ choose_right = np.signbit(fm) == np.signbit(left_value)
+ lv = np.where(choose_right, mid, lv)
+ hv = np.where(choose_right, hv, mid)
+ root = (lv + hv) * 0.5
+ expected = target
+ error = np.abs(root - expected)
+ return {
+ 'root_count': int(len(error)),
+ 'unbracketed': int(count - len(error)),
+ 'rms_mm': float(np.sqrt(np.mean(error * error))),
+ 'p95_mm': percentile(error, 95),
+ 'max_mm': float(np.max(error)),
+ }
+
+
+def run_case(
+ fixture: Fixture,
+ mesh: MeshData,
+ point_count: int,
+ scenario: str,
+ level: float,
+ sampling: str,
+) -> tuple[list[dict], dict, PointsAsTori, np.ndarray, np.ndarray]:
+ base_points, base_normals = sample_surface(mesh, point_count, SEED + point_count, sampling)
+ base_points, base_normals = snap_analytic_samples(fixture, base_points, base_normals)
+ points, normals = perturb(base_points, base_normals, scenario, level, SEED + point_count + 7)
+ truth = truth_evaluator(fixture, mesh)
+ queries, categories = query_corpus(fixture, mesh, base_points, base_normals, truth)
+
+ import psutil
+
+ rss_before = psutil.Process().memory_info().rss
+ started = time.perf_counter()
+ pat = PointsAsTori(points, normals)
+ precompute_seconds = time.perf_counter() - started
+ rss_after = psutil.Process().memory_info().rss
+ tori = pat._tdf.get_tori()
+ finite_tori = np.isfinite(tori[0]).all(axis=1) & np.isfinite(tori[1]).all(axis=1)
+ finite_tori &= np.isfinite(tori[2]) & np.isfinite(tori[3])
+
+ started = time.perf_counter()
+ predicted = np.asarray(pat.signed_distance(queries), dtype=np.float64)
+ query_seconds = time.perf_counter() - started
+ exact = truth(queries)
+
+ nearest_started = time.perf_counter()
+ from scipy.spatial import cKDTree
+
+ nearest = cKDTree(points).query(queries, k=1)[1]
+ baseline = np.sum((queries - points[nearest]) * normals[nearest], axis=1)
+ baseline_seconds = time.perf_counter() - nearest_started
+
+ repeat = np.asarray(pat.signed_distance(queries), dtype=np.float64)
+ deterministic_max_delta = float(np.max(np.abs(repeat - predicted)))
+ records: list[dict] = []
+ for i in range(len(queries)):
+ records.append(
+ {
+ 'fixture': fixture.name,
+ 'point_count': int(len(points)),
+ 'requested_point_count': point_count,
+ 'sampling': sampling,
+ 'scenario': scenario,
+ 'noise_level': level,
+ 'query_category': str(categories[i]),
+ 'query_x_mm': float(queries[i, 0]),
+ 'query_y_mm': float(queries[i, 1]),
+ 'query_z_mm': float(queries[i, 2]),
+ 'pat_mm': float(predicted[i]),
+ 'truth_mm': float(exact[i]),
+ 'absolute_error_mm': float(abs(predicted[i] - exact[i])),
+ 'sign_correct': bool(abs(exact[i]) <= 1.0e-6 or np.signbit(predicted[i]) == np.signbit(exact[i])),
+ 'baseline_tangent_mm': float(baseline[i]),
+ 'baseline_absolute_error_mm': float(abs(baseline[i] - exact[i])),
+ }
+ )
+
+ groups = {}
+ for category in sorted(set(categories.tolist())):
+ mask = categories == category
+ groups[category] = summarize_errors(predicted[mask], exact[mask])
+ groups[category]['baseline_rms_mm'] = summarize_errors(baseline[mask], exact[mask])['rms_mm']
+ # Occupancy has no defined positive/negative answer exactly on the boundary.
+ # Keep those samples in distance metrics but exclude them from aggregate
+ # classification metrics.
+ overall = summarize_errors(predicted, exact)
+ classification_mask = categories != 'on-surface'
+ classified = summarize_errors(predicted[classification_mask], exact[classification_mask])
+ for key in (
+ 'sign_error_count',
+ 'sign_error_rate',
+ 'classification_accuracy',
+ 'false_material_count',
+ 'false_void_count',
+ ):
+ overall[key] = classified[key]
+ overall['baseline_rms_mm'] = summarize_errors(baseline, exact)['rms_mm']
+ summary = {
+ 'fixture': fixture.name,
+ 'truth_authority': fixture.truth_kind,
+ 'requested_point_count': point_count,
+ 'actual_point_count': int(len(points)),
+ 'sampling': sampling,
+ 'scenario': scenario,
+ 'level': level,
+ 'precompute_seconds': precompute_seconds,
+ 'rss_delta_bytes': int(rss_after - rss_before),
+ 'query_count': int(len(queries)),
+ 'query_seconds': query_seconds,
+ 'queries_per_second': float(len(queries) / query_seconds),
+ 'baseline_query_seconds': baseline_seconds,
+ 'finite_torus_count': int(np.sum(finite_tori)),
+ 'nonfinite_torus_count': int(len(finite_tori) - np.sum(finite_tori)),
+ 'deterministic_repeat_max_delta_mm': deterministic_max_delta,
+ 'overall': overall,
+ 'by_category': groups,
+ 'zero_level': zero_offsets(pat, base_points, base_normals, 0.0),
+ 'offset_plus_1mm': zero_offsets(pat, base_points, base_normals, 1.0),
+ }
+ return records, summary, pat, points, normals
+
+
+def machine_info() -> dict:
+ try:
+ gpu = subprocess.check_output(
+ ['nvidia-smi', '--query-gpu=name,memory.total,driver_version', '--format=csv,noheader'],
+ text=True,
+ ).strip()
+ except Exception as exc: # pragma: no cover - diagnostic only
+ gpu = f'unavailable: {exc}'
+ import jax
+
+ return {
+ 'platform': platform.platform(),
+ 'processor': platform.processor(),
+ 'python': platform.python_version(),
+ 'jax_devices': [str(device) for device in jax.devices()],
+ 'gpu': gpu,
+ 'cpu_count': os.cpu_count(),
+ }
+
+
+def plot_slice(
+ output: Path,
+ name: str,
+ mesh: MeshData,
+ pat: PointsAsTori,
+ truth: Callable[[np.ndarray], np.ndarray],
+ points: np.ndarray,
+ axis: int = 2,
+) -> None:
+ low = np.min(mesh.vertices, axis=0)
+ high = np.max(mesh.vertices, axis=0)
+ pad = np.maximum((high - low) * 0.12, 0.5)
+ varying = [i for i in range(3) if i != axis]
+ a = np.linspace(low[varying[0]] - pad[varying[0]], high[varying[0]] + pad[varying[0]], 180)
+ b = np.linspace(low[varying[1]] - pad[varying[1]], high[varying[1]] + pad[varying[1]], 180)
+ aa, bb = np.meshgrid(a, b)
+ queries = np.zeros((aa.size, 3), dtype=np.float64)
+ queries[:, varying[0]] = aa.ravel()
+ queries[:, varying[1]] = bb.ravel()
+ queries[:, axis] = (low[axis] + high[axis]) * 0.5
+ predicted = pat.signed_distance(queries).reshape(aa.shape)
+ exact = truth(queries).reshape(aa.shape)
+ error = np.abs(predicted - exact)
+
+ fig, axes = plt.subplots(1, 3, figsize=(14, 4.2), constrained_layout=True)
+ mask = np.abs(points[:, axis] - queries[0, axis]) < max((high[axis] - low[axis]) * 0.08, 0.2)
+ axes[0].scatter(points[mask, varying[0]], points[mask, varying[1]], s=2, alpha=0.65)
+ axes[0].set_title(f'{name}: oriented source slice')
+ im = axes[1].imshow(
+ predicted,
+ origin='lower',
+ extent=[a[0], a[-1], b[0], b[-1]],
+ cmap='coolwarm',
+ vmin=-max(np.ptp(a), np.ptp(b)) * 0.08,
+ vmax=max(np.ptp(a), np.ptp(b)) * 0.08,
+ )
+ axes[1].contour(aa, bb, predicted, levels=[0.0], colors=['black'], linewidths=1.5)
+ axes[1].contour(aa, bb, exact, levels=[0.0], colors=['lime'], linewidths=1.0, linestyles='--')
+ axes[1].set_title('PAT zero (black) / truth (green)')
+ fig.colorbar(im, ax=axes[1], label='PAT phi (mm)')
+ heat = axes[2].imshow(error, origin='lower', extent=[a[0], a[-1], b[0], b[-1]], cmap='magma')
+ axes[2].set_title('absolute distance error')
+ fig.colorbar(heat, ax=axes[2], label='mm')
+ for panel in axes:
+ panel.set_aspect('equal')
+ panel.set_xlabel(f'axis {varying[0]} (mm)')
+ panel.set_ylabel(f'axis {varying[1]} (mm)')
+ fig.savefig(output / f'{name}-slice.png', dpi=160)
+ plt.close(fig)
+
+
+def plots(output: Path, summaries: list[dict]) -> None:
+ density = [
+ s for s in summaries
+ if s['fixture'] == 'sphere' and s['scenario'] == 'clean' and s['sampling'] == 'area'
+ ]
+ density.sort(key=lambda item: item['actual_point_count'])
+ noise = [s for s in summaries if s['fixture'] == 'sphere' and s['scenario'] == 'position-noise']
+ noise.sort(key=lambda item: item['level'])
+ normals = [s for s in summaries if s['fixture'] == 'sphere' and s['scenario'] == 'normal-noise']
+ normals.sort(key=lambda item: item['level'])
+ thickness = [s for s in summaries if s['fixture'] in {'thin_plate', 'slab'} and s['scenario'] == 'clean']
+
+ fig, axes = plt.subplots(2, 3, figsize=(15, 8), constrained_layout=True)
+ axes[0, 0].plot([x['actual_point_count'] for x in density], [x['overall']['rms_mm'] for x in density], 'o-')
+ axes[0, 0].set_xscale('log')
+ axes[0, 0].set_title('sphere error vs density')
+ axes[0, 0].set_xlabel('points')
+ axes[0, 0].set_ylabel('RMS (mm)')
+ axes[0, 1].plot([x['actual_point_count'] for x in density], [x['precompute_seconds'] for x in density], 'o-')
+ axes[0, 1].set_xscale('log')
+ axes[0, 1].set_title('precompute time vs input points')
+ axes[0, 1].set_xlabel('points')
+ axes[0, 1].set_ylabel('seconds')
+ axes[0, 2].plot([x['actual_point_count'] for x in density], [x['query_seconds'] for x in density], 'o-')
+ axes[0, 2].set_xscale('log')
+ axes[0, 2].set_title('query time vs input points')
+ axes[0, 2].set_xlabel('points (fixed query corpus)')
+ axes[0, 2].set_ylabel('seconds')
+ axes[1, 0].plot([x['level'] for x in noise], [x['overall']['rms_mm'] for x in noise], 'o-', label='position')
+ axes[1, 0].set_title('sphere error vs position noise')
+ axes[1, 0].set_xlabel('sigma (mm)')
+ axes[1, 0].set_ylabel('RMS (mm)')
+ axes[1, 1].plot([x['level'] for x in normals], [x['overall']['sign_error_rate'] for x in normals], 'o-')
+ axes[1, 1].set_title('sign error vs normal noise')
+ axes[1, 1].set_xlabel('noise scale (degrees)')
+ axes[1, 1].set_ylabel('sign error rate')
+ axes[1, 2].bar([x['fixture'] for x in thickness], [x['overall']['sign_error_rate'] for x in thickness])
+ axes[1, 2].set_title('sign error vs plate thickness')
+ axes[1, 2].set_ylabel('sign error rate')
+ fig.savefig(output / 'benchmark-plots.png', dpi=160)
+ plt.close(fig)
+
+
+def sphere_trace_probe(pat: PointsAsTori) -> dict[str, float | int]:
+ coordinates = np.linspace(-9.0, 9.0, 31)
+ xx, yy = np.meshgrid(coordinates, coordinates)
+ origins = np.column_stack((xx.ravel(), yy.ravel(), np.full(xx.size, -20.0)))
+ distance_along = np.zeros(len(origins))
+ active = np.ones(len(origins), dtype=bool)
+ hit = np.zeros(len(origins), dtype=bool)
+ steps = np.zeros(len(origins), dtype=np.int32)
+ for _ in range(128):
+ if not np.any(active):
+ break
+ index = np.flatnonzero(active)
+ q = origins[index].copy()
+ q[:, 2] += distance_along[index]
+ phi = pat.signed_distance(q)
+ converged = np.abs(phi) < 1.0e-4
+ hit[index[converged]] = True
+ steps[index] += 1
+ advance_index = index[~converged]
+ distance_along[advance_index] += np.maximum(np.abs(phi[~converged]), 1.0e-4)
+ escaped = distance_along > 45.0
+ active = ~(hit | escaped)
+ expected = xx.ravel() ** 2 + yy.ravel() ** 2 <= 7.5**2
+ return {
+ 'ray_count': int(len(origins)),
+ 'expected_hit_count': int(np.sum(expected)),
+ 'hit_count': int(np.sum(hit)),
+ 'missed_intersections': int(np.sum(expected & ~hit)),
+ 'false_hits': int(np.sum(~expected & hit)),
+ 'mean_steps_for_hits': float(np.mean(steps[hit])) if np.any(hit) else math.nan,
+ 'max_steps': int(np.max(steps)),
+ }
+
+
+def demo(local: Path) -> None:
+ output = local / 'demo'
+ output.mkdir(parents=True, exist_ok=True)
+ source = local / 'upstream' / 'data' / 'block.obj'
+ mesh = TriangleMesh.read_OBJ(str(source))
+ mesh.center_and_scale()
+ started = time.perf_counter()
+ points, normals = mesh.sample_uniform_point_cloud(2048, 0.0, 0.0, 42)
+ sample_seconds = time.perf_counter() - started
+ started = time.perf_counter()
+ pat = PointsAsTori(points, normals)
+ precompute_seconds = time.perf_counter() - started
+ x = np.linspace(-1.2, 1.2, 220)
+ y = np.linspace(-1.2, 1.2, 220)
+ xx, yy = np.meshgrid(x, y)
+ queries = np.column_stack((xx.ravel(), yy.ravel(), np.zeros(xx.size)))
+ started = time.perf_counter()
+ predicted = pat.signed_distance(queries)
+ query_seconds = time.perf_counter() - started
+ truth = mesh.evaluate_signed_distance(queries)
+ record = {
+ 'upstream_revision': '253bf9fc5e79831a03f0486e0c42feeb67c1c546',
+ 'input': 'data/block.obj',
+ 'input_sha256': sha256(source),
+ 'mesh_vertices': 2132,
+ 'mesh_triangles': 4272,
+ 'point_count': 2048,
+ 'sampling': 'upstream area-uniform mesh sampling',
+ 'seed': 42,
+ 'position_noise': 0.0,
+ 'normal_flips': 0.0,
+ 'model_k_neighbors': 64,
+ 'query_neighbors': 32,
+ 'sample_seconds': sample_seconds,
+ 'precompute_seconds': precompute_seconds,
+ 'query_count': int(len(queries)),
+ 'query_seconds': query_seconds,
+ 'accuracy_vs_packaged_mesh': summarize_errors(predicted, truth),
+ 'deviation': 'Headless public Python API (32-NN analytic queries) replaces the interactive OpenGL shader; the GUI defaults to an all-point shader blend.',
+ 'machine': machine_info(),
+ }
+ (output / 'demo.json').write_text(json.dumps(record, indent=2), encoding='utf-8')
+
+ fig, axes = plt.subplots(1, 3, figsize=(14, 4.2), constrained_layout=True)
+ axes[0].scatter(points[:, 0], points[:, 1], s=2)
+ axes[0].set_title('published block: 2,048 samples')
+ field = predicted.reshape(xx.shape)
+ exact = truth.reshape(xx.shape)
+ axes[1].imshow(field, origin='lower', extent=[x[0], x[-1], y[0], y[-1]], cmap='coolwarm', vmin=-0.4, vmax=0.4)
+ axes[1].contour(xx, yy, field, levels=[0.0], colors=['black'])
+ axes[1].contour(xx, yy, exact, levels=[0.0], colors=['lime'], linestyles='--')
+ axes[1].set_title('PAT zero / packaged mesh truth')
+ heat = axes[2].imshow(np.abs(field - exact), origin='lower', extent=[x[0], x[-1], y[0], y[-1]], cmap='magma')
+ axes[2].set_title('absolute error')
+ fig.colorbar(heat, ax=axes[2])
+ for panel in axes:
+ panel.set_aspect('equal')
+ fig.savefig(output / 'author-demo.png', dpi=160)
+ plt.close(fig)
+ print(json.dumps(record, indent=2))
+
+
+def benchmark(local: Path) -> None:
+ output = local / 'benchmark'
+ output.mkdir(parents=True, exist_ok=True)
+ mesh_root = local / 'aetheris-meshes'
+ all_records: list[dict] = []
+ summaries: list[dict] = []
+ visual: dict[str, tuple[MeshData, PointsAsTori, np.ndarray, Callable[[np.ndarray], np.ndarray]]] = {}
+
+ cases: list[tuple[Fixture, int, str, float, str]] = []
+ for fixture in FIXTURES:
+ cases.append((fixture, 2048, 'clean', 0.0, 'area'))
+ sphere = FIXTURES[0]
+ for count in (1024, 5000, 20000):
+ cases.append((sphere, count, 'clean', 0.0, 'area'))
+ cases.append((sphere, 2048, 'clean', 0.0, 'uniform-triangle'))
+ for sigma in (0.01, 0.05, 0.1, 0.5):
+ cases.append((sphere, 2048, 'position-noise', sigma, 'area'))
+ for degrees in (2.0, 10.0, 25.0):
+ cases.append((sphere, 2048, 'normal-noise', degrees, 'area'))
+ cases.extend(
+ [
+ (sphere, 2048, 'normal-flips', 0.05, 'area'),
+ (sphere, 2048, 'missing-cap', 0.10, 'area'),
+ (sphere, 2048, 'missing-cap', 0.25, 'area'),
+ (sphere, 2048, 'random-missing', 0.25, 'area'),
+ (sphere, 2048, 'nonuniform-density', 1.0, 'area'),
+ (next(fixture for fixture in FIXTURES if fixture.name == 'slab'), 2048, 'open-surface', 1.0, 'area'),
+ ]
+ )
+
+ for fixture, count, scenario, level, sampling in cases:
+ mesh = read_obj(mesh_root / f'{fixture.name}.obj')
+ print(f'CASE {fixture.name} points={count} scenario={scenario} level={level} sampling={sampling}', flush=True)
+ records, summary, pat, points, _ = run_case(fixture, mesh, count, scenario, level, sampling)
+ all_records.extend(records)
+ summaries.append(summary)
+ key = f'{fixture.name}-{scenario}-{str(level).replace(".", "p")}'
+ if (fixture.name, scenario, level) in {
+ ('sphere', 'clean', 0.0),
+ ('sharp_box', 'clean', 0.0),
+ ('sphere', 'position-noise', 0.5),
+ ('sphere', 'missing-cap', 0.25),
+ }:
+ visual[key] = (mesh, pat, points, truth_evaluator(fixture, mesh))
+
+ with (output / 'query-evidence.csv').open('w', newline='', encoding='utf-8') as stream:
+ writer = csv.DictWriter(stream, fieldnames=list(all_records[0].keys()))
+ writer.writeheader()
+ writer.writerows(all_records)
+
+ performance_fixture = read_obj(mesh_root / 'sphere.obj')
+ perf_points, perf_normals = sample_surface(performance_fixture, 2048, SEED)
+ perf_pat = PointsAsTori(perf_points, perf_normals)
+ rng = np.random.default_rng(SEED + 303)
+ performance = []
+ for count in (1, 1000, 100000, 1000000):
+ q = rng.uniform(-12.0, 12.0, size=(count, 3))
+ perf_pat.signed_distance(q[: min(count, 1000)])
+ started = time.perf_counter()
+ perf_pat.signed_distance(q)
+ elapsed = time.perf_counter() - started
+ performance.append({'query_count': count, 'seconds': elapsed, 'queries_per_second': count / elapsed})
+
+ manifest = {
+ 'schema': 'aetheris.pat-dogfood-x0.v1',
+ 'generated_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
+ 'seed': SEED,
+ 'machine': machine_info(),
+ 'upstream_revision': '253bf9fc5e79831a03f0486e0c42feeb67c1c546',
+ 'model_sha256': 'AAA2F3882C36AC32D57361377A73AC830C47D03D6167D51249127A6C40EF7FF9',
+ 'model_bytes': 6366869,
+ 'query_performance': performance,
+ 'sphere_tracing': sphere_trace_probe(perf_pat),
+ 'storage_model': {
+ 'point_and_normal_bytes_per_point': 48,
+ 'torus_parameter_bytes_per_point': 56,
+ 'precompute_neighbor_index_bytes_per_point': 256,
+ 'query_neighbor_index_bytes_per_query': 128,
+ },
+ 'summaries': summaries,
+ }
+ (output / 'summary.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
+ plots(output, summaries)
+ for key, (mesh, pat, points, truth) in visual.items():
+ axis = 1 if key.startswith('torus') else 2
+ plot_slice(output, key, mesh, pat, truth, points, axis)
+ print(json.dumps({'summary': str(output / 'summary.json'), 'record_count': len(all_records)}, indent=2))
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument('command', choices=['demo', 'benchmark'])
+ parser.add_argument('--local-root', type=Path, required=True)
+ args = parser.parse_args()
+ if args.command == 'demo':
+ demo(args.local_root.resolve())
+ else:
+ benchmark(args.local_root.resolve())
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/PATDogfoodX0/requirements.txt b/tools/PATDogfoodX0/requirements.txt
new file mode 100644
index 00000000..71363ac8
--- /dev/null
+++ b/tools/PATDogfoodX0/requirements.txt
@@ -0,0 +1 @@
+matplotlib==3.11.2
diff --git a/tools/PATDogfoodX0/run.ps1 b/tools/PATDogfoodX0/run.ps1
new file mode 100644
index 00000000..eb6ac4a5
--- /dev/null
+++ b/tools/PATDogfoodX0/run.ps1
@@ -0,0 +1,116 @@
+param(
+ [ValidateSet('all', 'prepare', 'demo', 'benchmark')]
+ [string]$Phase = 'all'
+)
+
+$ErrorActionPreference = 'Stop'
+$repo = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
+$local = Join-Path $repo 'artifacts\local\pat-x0'
+$upstream = Join-Path $local 'upstream'
+$python = Join-Path $local 'venv\Scripts\python.exe'
+$revision = '253bf9fc5e79831a03f0486e0c42feeb67c1c546'
+$modelHash = 'AAA2F3882C36AC32D57361377A73AC830C47D03D6167D51249127A6C40EF7FF9'
+
+function Prepare-Upstream {
+ New-Item -ItemType Directory -Force $local | Out-Null
+ if (-not (Test-Path (Join-Path $upstream '.git'))) {
+ git clone --recursive https://github.com/nzfeng/points-as-tori.git $upstream
+ }
+ git -C $upstream checkout --detach $revision
+ git -C $upstream submodule update --init --recursive
+
+ $actualRevision = (git -C $upstream rev-parse HEAD).Trim()
+ if ($actualRevision -ne $revision) { throw "Unexpected PAT revision $actualRevision" }
+ $weight = Join-Path $upstream 'src\pointsastori\models\FundamentalFormPredictor.pkl'
+ $actualHash = (Get-FileHash $weight -Algorithm SHA256).Hash
+ if ($actualHash -ne $modelHash) { throw "Unexpected model hash $actualHash" }
+
+ # Upstream commit 253bf9f needs two source-only MSVC compatibility fixes.
+ $shape2d = Join-Path $upstream 'src\cpp\shape_2d.cpp'
+ $shape3d = Join-Path $upstream 'src\cpp\shape_3d.cpp'
+ $shape2dText = Get-Content $shape2d -Raw
+ if ($shape2dText -notmatch '#include <numeric>') {
+ $shape2dText = $shape2dText.Replace('#include <cstring>', "#include <cstring>`r`n#include <numeric>")
+ [System.IO.File]::WriteAllText($shape2d, $shape2dText)
+ }
+ $shape3dText = Get-Content $shape3d -Raw
+ $shape3dText = $shape3dText.Replace(
+ 'for (size_t i = 0; i < points.size(); ++i)',
+ 'for (int i = 0; i < static_cast<int>(points.size()); ++i)')
+ [System.IO.File]::WriteAllText($shape3d, $shape3dText)
+
+ if (-not (Test-Path $python)) { py -3.11 -m venv (Join-Path $local 'venv') }
+ $installStamp = Join-Path $local 'installed-revision.txt'
+ $expectedStamp = "$revision-msvc-compat-v1"
+ $actualStamp = if (Test-Path $installStamp) { (Get-Content $installStamp -Raw).Trim() } else { '' }
+ if ($actualStamp -ne $expectedStamp) {
+ & $python -m pip install --upgrade pip
+ & $python -m pip install $upstream
+ if ($LASTEXITCODE -ne 0) { throw 'PAT package build/install failed' }
+ Set-Content -LiteralPath $installStamp -Value $expectedStamp
+ }
+ & $python -m pip install -r (Join-Path $PSScriptRoot 'requirements.txt')
+}
+
+function Export-Fixtures {
+ $meshDir = Join-Path $local 'aetheris-meshes'
+ New-Item -ItemType Directory -Force $meshDir | Out-Null
+ $fixtures = [ordered]@{
+ sphere = 'fixtures/Canonical/Primitives/sphere.firmament'
+ cylinder = 'fixtures/Canonical/Basics/cylinder.firmament'
+ torus = 'fixtures/Canonical/Primitives/torus.firmament'
+ frustum = 'fixtures/Canonical/Primitives/frustum.firmament'
+ slab = 'fixtures/Experiments/PATDogfoodX0/slab.firmament'
+ # The isolated finite-edge fillet fixture currently fails SurfaceMeshIR
+ # with a zero-area cell; the canonical all-edge RoundedBox is the usable
+ # exact filleted-box witness for this benchmark.
+ filleted_box = 'fixtures/Canonical/Primitives/rounded-box.firmament'
+ rounded_rectangle_prism = 'fixtures/Experiments/PATDogfoodX0/rounded-rectangle-prism.firmament'
+ sharp_box = 'fixtures/Canonical/Basics/box.firmament'
+ chamfered_box = 'fixtures/Canonical/Features/EdgeFinish/semantic-selection-chamfer.firmament'
+ through_hole = 'fixtures/Canonical/Features/Holes/through-hole.firmament'
+ counterbore = 'fixtures/Canonical/Features/Holes/counterbore.firmament'
+ thin_plate = 'fixtures/Experiments/PATDogfoodX0/thin-plate.firmament'
+ phone_like_chassis = 'fixtures/Experiments/PATDogfoodX0/phone-like-chassis.firmament'
+ }
+ foreach ($entry in $fixtures.GetEnumerator()) {
+ $out = Join-Path $meshDir ($entry.Key + '.obj')
+ $source = Join-Path $repo $entry.Value
+ $implicitStep = [System.IO.Path]::ChangeExtension($source, '.step')
+ $implicitStepExisted = Test-Path $implicitStep
+ dotnet run --project (Join-Path $repo 'Aetheris.CLI') -- mesh $source --format obj --output $out --json
+ if ($LASTEXITCODE -ne 0) { throw "Aetheris mesh export failed for $($entry.Key)" }
+ # `aetheris mesh` currently materializes an intermediate STEP beside a
+ # Firmament source. Keep generated benchmark output under artifacts/local.
+ if (-not $implicitStepExisted -and (Test-Path $implicitStep)) {
+ Remove-Item -LiteralPath $implicitStep
+ }
+ }
+
+ # Exercise the real Sheet Metal compiler and a template-specialized
+ # ProfileDelta program. The ordinary mesh command cannot consume authored
+ # SheetMetal syntax directly, so materialize its authoritative formed STEP
+ # first and then tessellate that exact BRep.
+ $sheetDir = Join-Path $local 'sheetmetal'
+ New-Item -ItemType Directory -Force $sheetDir | Out-Null
+ $sheetSource = Join-Path $repo 'fixtures/Canonical/SheetMetal/profile-delta-tab-family.firmament'
+ $formedStep = Join-Path $sheetDir 'profile-delta-tab-formed.step'
+ dotnet run --project (Join-Path $repo 'Aetheris.CLI') -- build $sheetSource --output $formedStep --json
+ if ($LASTEXITCODE -ne 0) { throw 'Authored Sheet Metal formed build failed' }
+ dotnet run --project (Join-Path $repo 'Aetheris.CLI') -- sheetmetal inspect $sheetSource --json
+ if ($LASTEXITCODE -ne 0) { throw 'Authored Sheet Metal inspection failed' }
+ dotnet run --project (Join-Path $repo 'Aetheris.CLI') -- mesh $formedStep --format obj --output (Join-Path $meshDir 'bent_sheet.obj') --json
+ if ($LASTEXITCODE -ne 0) { throw 'Authored Sheet Metal formed mesh failed' }
+}
+
+Set-Location $repo
+if ($Phase -in @('all', 'prepare')) {
+ Prepare-Upstream
+ Export-Fixtures
+}
+if ($Phase -in @('all', 'demo')) {
+ & $python (Join-Path $PSScriptRoot 'pat_x0.py') demo --local-root $local
+}
+if ($Phase -in @('all', 'benchmark')) {
+ & $python (Join-Path $PSScriptRoot 'pat_x0.py') benchmark --local-root $local
+}