Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add judgment qualification command for Antonia
Yuechen Li53941ec2c9a9
diff --git a/Aetheris.Humanoid.Tests/HumanoidX3Tests.cs b/Aetheris.Humanoid.Tests/HumanoidX3Tests.csnew file mode 100644index 00000000..bc1c415f--- /dev/null+++ b/Aetheris.Humanoid.Tests/HumanoidX3Tests.cs@@ -0,0 +1,99 @@+using System.Numerics;+using Aetheris.Humanoid;+using Aetheris.Kernel.Core.Judgment;+using Xunit;++namespace Aetheris.Humanoid.Tests;++public sealed class HumanoidX3Tests+{+ private static HumanoidDeformationContext Context(double degrees = 45)+ {+ var root = Matrix4x4.Identity;+ var hip = Matrix4x4.CreateTranslation(-10,0,100);+ Matrix4x4.Invert(hip,out var inverse);+ var skeleton = new HumanoidSkeleton("patch", "rest", "row-vector",+ [new("root",HumanoidJointKind.Root,AnatomicalSide.Center,null,HumanoidTransform.Identity,root,root),+ new("pelvis",HumanoidJointKind.Pelvis,AnatomicalSide.Center,0,HumanoidTransform.Identity,root,root),+ new("hip",HumanoidJointKind.LeftHip,AnatomicalSide.Left,1,HumanoidTransform.FromTranslation(new(-10,0,100)),hip,inverse)],+ new Dictionary<HumanoidJointKind,HumanoidJointKind>());+ var surface = new HumanoidSurface("patch", "triangles", "fixed",+ [new("a",new(-10,0,90),HumanoidRegionKind.LeftThigh,0),new("b",new(-8,0,90),HumanoidRegionKind.LeftThigh,1),new("c",new(-10,2,90),HumanoidRegionKind.LeftThigh,2),new("d",new(-12,0,90),HumanoidRegionKind.Chest,3)],+ [new("inside",0,1,2,HumanoidRegionKind.LeftThigh,null),new("outside",0,2,3,HumanoidRegionKind.Chest,null)], [], null,+ [new(0,[new(1,.5),new(2,.5)]),new(1,[new(1,.5),new(2,.5)]),new(2,[new(1,.5),new(2,.5)]),new(3,[new(1,.5),new(2,.5)])],[],new Dictionary<HumanoidRegionKind,HumanoidRegionKind>());+ var solved = HumanoidKinematicSolver.Solve(skeleton,new("pose","patch","rest",0,[new(HumanoidJointKind.LeftHip,degrees)])).Pose!;+ return HumanoidDeformationContext.Create(surface,skeleton,0,solved,HumanoidJointKind.LeftHip);+ }+ [Fact]+ public void DualQuaternionBlendMatchesAnalyticHalfRotationAboutFixedHipCenter()+ {+ var context=Context(90);+ var candidate=HumanoidDeformationCandidates.Generate(context,new("analytic",TransitionBlendMethod.DualQuaternion,1));+ var index=context.Vertices.ToList().FindIndex(v=>v.SurfaceIndex==1);+ var expected=new Aetheris.Kernel.Core.Math.Point3D(-8,Math.Sqrt(50),100-Math.Sqrt(50));+ Assert.InRange((candidate.PatchPositions[index]-expected).Length,0,.0001);+ }+ [Fact]+ public void LocalGeneratorsPreserveBoundaryAndNeverChangeTopology()+ {+ var context = Context();+ Assert.Equal(2,context.Vertices.Count(v => v.Boundary));+ foreach(var spec in HumanoidDeformationCandidates.Default)+ {+ var c = HumanoidDeformationCandidates.Generate(context,spec);+ var assembled = context.AssembleDiagnostic(c);+ Assert.Equal(context.Baseline[3],assembled[3]);+ Assert.All(context.Vertices.Where(v=>v.Boundary),v=>Assert.Equal(context.Baseline[v.SurfaceIndex],assembled[v.SurfaceIndex]));+ var metrics = HumanoidDeformationJudgment.Measure(context,c);+ Assert.Equal(0,metrics.BoundaryMaximumMm); Assert.Equal(0,metrics.FixedAttachmentMaximumMm);+ }+ }+ [Fact]+ public void CompressionCollapseBoundaryAndNonfiniteCandidatesCannotWin()+ {+ var context = Context();+ var baseline = HumanoidDeformationCandidates.Generate(context,HumanoidDeformationCandidates.Default[0]);+ var points = baseline.PatchPositions.ToArray(); points[1] = points[0];+ var c = baseline with {Id="collapsed",PatchPositions=points};+ var m = new MeasuredDeformationCandidate(c,HumanoidDeformationJudgment.Measure(context,c));+ var result=HumanoidDeformationJudgment.Model(DeformationPolicy.HipV1).Evaluate(context,[new(c.Id,m)]);+ Assert.Null(result.Winner);+ Assert.Contains(result.Candidates[0].Rules,r=>r.Id=="noncollapsed"&&!r.Result.Passed);+ points = baseline.PatchPositions.ToArray(); points[0] = points[0] + new Aetheris.Kernel.Core.Math.Vector3D(1,0,0);+ c = baseline with{Id="broken-boundary",PatchPositions=points};+ var metrics=HumanoidDeformationJudgment.Measure(context,c);+ Assert.True(metrics.BoundaryMaximumMm>.9);+ points[0]=new(double.NaN,0,0);+ Assert.False(HumanoidDeformationJudgment.Measure(context,c).Finite);+ }+ [Fact]+ public void EmptyCandidateSetDoesNotReturnBaselineMesh()+ {+ var result=HumanoidDeformationJudgment.Evaluate(Context(),DeformationPolicy.HipV1,[]);+ Assert.False(result.IsSuccess); Assert.Null(result.Positions); Assert.Null(result.WinnerId);+ Assert.Contains(result.Diagnostics,d=>d.Code=="HUM300");+ }+ [Fact]+ public void OptionalUtilityTermDoesNotModifyGenerators()+ {+ var context=Context(0);+ var result=HumanoidDeformationJudgment.Evaluate(context,DeformationPolicy.HipV1,+ extraTerms:[new("attachment-drift",.2,(c,_)=>new(1/(1+c.Metrics.FixedAttachmentMaximumMm/.001),c.Metrics.FixedAttachmentMaximumMm,"mm","Bounded attachment residual utility."))]);+ Assert.True(result.IsSuccess);+ Assert.Contains(result.Trace.Single(t=>t.Id==result.WinnerId).Scores,s=>s.Id=="attachment-drift");+ }+ [Fact]+ public void SelectionAndGeometryAreIndependentOfGeneratorEnumeration()+ {+ var context=Context(0);+ var first=HumanoidDeformationJudgment.Evaluate(context,DeformationPolicy.HipV1);+ var second=HumanoidDeformationJudgment.Evaluate(context,DeformationPolicy.HipV1,HumanoidDeformationCandidates.Default.Reverse().ToArray());+ Assert.Equal(first.WinnerId,second.WinnerId); Assert.Equal(first.Positions,second.Positions);+ }+ [Fact]+ public void PolicyCannotAdmitAStalePoseContext()+ {+ var context=Context();+ Assert.Throws<InvalidOperationException>(()=>HumanoidDeformationContext.Create(context.Surface,context.Skeleton,1,context.Solved,context.Joint));+ }+}diff --git a/Aetheris.Humanoid/HumanoidDeformationContext.cs b/Aetheris.Humanoid/HumanoidDeformationContext.csnew file mode 100644index 00000000..5bbbcf4c--- /dev/null+++ b/Aetheris.Humanoid/HumanoidDeformationContext.cs@@ -0,0 +1,141 @@+using System.Numerics;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Humanoid;++public enum SurfaceAttachmentClass { FixedToExistingEvaluation, BlendedTransition }+public sealed record DeformationPatchVertex(int SurfaceIndex, SurfaceAttachmentClass Attachment, bool Boundary);+public sealed record DeformationCandidate(string Id, IReadOnlyList<Point3D> PatchPositions, string Construction);++/// <summary>One closed face region with a fixed boundary. Only a solved X2 pose can create this context.</summary>+public sealed class HumanoidDeformationContext+{+ private HumanoidDeformationContext() { }+ public HumanoidSurface Surface { get; private init; } = null!;+ public HumanoidSkeleton Skeleton { get; private init; } = null!;+ public SolvedHumanoidPose Solved { get; private init; } = null!;+ public HumanoidJointKind Joint { get; private init; }+ public long ShapeRevision => Solved.ShapeRevision;+ public IReadOnlyList<Point3D> Baseline { get; private init; } = null!;+ public IReadOnlyList<DeformationPatchVertex> Vertices { get; private init; } = null!;+ public IReadOnlyList<HumanoidFace> Faces { get; private init; } = null!;+ public IReadOnlyList<(int A, int B)> Edges { get; private init; } = null!;+ internal IReadOnlyDictionary<int, int> LocalIndex { get; private init; } = null!;+ internal IReadOnlyList<Matrix4x4> SkinTransforms { get; private init; } = null!;++ public static HumanoidDeformationContext Create(HumanoidSurface surface, HumanoidSkeleton skeleton,+ long shapeRevision, SolvedHumanoidPose solved, HumanoidJointKind joint)+ {+ var left = joint.ToString().StartsWith("Left");+ var hip = joint is HumanoidJointKind.LeftHip or HumanoidJointKind.RightHip;+ var knee = joint is HumanoidJointKind.LeftKnee or HumanoidJointKind.RightKnee;+ if (!hip && !knee) throw new ArgumentException("HUM308: Only hip and knee patch contexts are implemented.");+ if (!skeleton.Joints.Any(j => j.Kind == joint)) throw new ArgumentException("Missing patch joint.");+ // X2 performs the revision/skeleton/binding checks before any candidate is generated.+ var baseline = HumanoidConstrainedSurface.Evaluate(surface, skeleton, shapeRevision, solved).Positions;+ surface = surface with+ {+ Vertices = Array.AsReadOnly(surface.Vertices.ToArray()), Faces = Array.AsReadOnly(surface.Faces.ToArray()),+ SkinWeights = Array.AsReadOnly(surface.SkinWeights.Select(w => w with { Weights = Array.AsReadOnly(w.Weights.ToArray()) }).ToArray())+ };+ skeleton = solved.Skeleton;+ var prefix = left ? "Left" : "Right";+ var parent = hip ? HumanoidJointKind.Pelvis : Enum.Parse<HumanoidJointKind>(prefix + "Hip");+ var regions = hip ? new[] { HumanoidRegionKind.Pelvis, Enum.Parse<HumanoidRegionKind>(prefix + "Thigh") }+ : new[] { Enum.Parse<HumanoidRegionKind>(prefix + "Thigh"), Enum.Parse<HumanoidRegionKind>(prefix + "Shin"), Enum.Parse<HumanoidRegionKind>(prefix + "Knee") };+ var faces = surface.Faces.Where(f => regions.Contains(f.Region)).ToArray();+ if (faces.Length == 0) throw new ArgumentException("HUM308: Empty transition patch.");+ var indices = faces.SelectMany(f => new[] { f.A, f.B, f.C }).Distinct().Order().ToArray();+ var boundary = surface.Faces.Where(f => !regions.Contains(f.Region)).SelectMany(f => new[] { f.A, f.B, f.C }).ToHashSet();+ var vertices = indices.Select(i =>+ {+ var weights = surface.SkinWeights[i].Weights;+ var activeWeight = weights.Where(w => skeleton.Joints[w.JointIndex].Kind == joint).Sum(w => w.Weight);+ var editable = !boundary.Contains(i) && activeWeight > 1e-8 && activeWeight < 1 - 1e-8 &&+ weights.All(w => skeleton.Joints[w.JointIndex].Kind == joint || skeleton.Joints[w.JointIndex].Kind == parent);+ return new DeformationPatchVertex(i, editable ? SurfaceAttachmentClass.BlendedTransition : SurfaceAttachmentClass.FixedToExistingEvaluation, boundary.Contains(i));+ }).ToArray();+ var edges = new SortedSet<(int, int)>();+ foreach (var f in faces) { Add(f.A, f.B); Add(f.B, f.C); Add(f.C, f.A); }+ void Add(int a, int b) => edges.Add(a < b ? (a, b) : (b, a));+ return new()+ {+ Surface = surface, Skeleton = skeleton, Solved = solved, Joint = joint,+ Baseline = baseline, Vertices = Array.AsReadOnly(vertices), Faces = Array.AsReadOnly(faces),+ Edges = Array.AsReadOnly(edges.ToArray()),+ LocalIndex = new System.Collections.ObjectModel.ReadOnlyDictionary<int, int>(indices.Select((v, i) => (v, i)).ToDictionary(x => x.v, x => x.i)),+ SkinTransforms = Array.AsReadOnly(skeleton.Joints.Select((j, i) => j.InverseBind * solved.GlobalTransforms[i]).ToArray())+ };+ }++ /// <summary>Diagnostic assembly helper. Callers must not treat rejected candidate positions as admitted output.</summary>+ public IReadOnlyList<Point3D> AssembleDiagnostic(DeformationCandidate candidate)+ {+ if (candidate.PatchPositions.Count != Vertices.Count) throw new ArgumentException("Patch position count mismatch.");+ var result = Baseline.ToArray();+ for (var i = 0; i < Vertices.Count; i++) result[Vertices[i].SurfaceIndex] = candidate.PatchPositions[i];+ return Array.AsReadOnly(result);+ }+}++public enum TransitionBlendMethod { Linear, DualQuaternion }+public sealed record TransitionCandidateSpec(string Id, TransitionBlendMethod Method, double WeightExponent);++public static class HumanoidDeformationCandidates+{+ public static IReadOnlyList<TransitionCandidateSpec> Default { get; } = Array.AsReadOnly(new TransitionCandidateSpec[]+ {+ new("lbs.baseline", TransitionBlendMethod.Linear, 1),+ new("lbs.weights-softened", TransitionBlendMethod.Linear, .5),+ new("lbs.weights-sharpened", TransitionBlendMethod.Linear, 2),+ new("dqs.baseline-weights", TransitionBlendMethod.DualQuaternion, 1),+ new("dqs.weights-softened", TransitionBlendMethod.DualQuaternion, .5),+ new("dqs.weights-sharpened", TransitionBlendMethod.DualQuaternion, 2)+ });++ public static DeformationCandidate Generate(HumanoidDeformationContext context, TransitionCandidateSpec spec)+ {+ if (!Enum.IsDefined(spec.Method) || !double.IsFinite(spec.WeightExponent) || spec.WeightExponent is < .5 or > 2)+ throw new ArgumentException("Bounded transition generators support exponents [0.5,2].");+ var output = new Point3D[context.Vertices.Count];+ for (var i = 0; i < output.Length; i++)+ {+ var patch = context.Vertices[i];+ var index = patch.SurfaceIndex;+ if (patch.Attachment == SurfaceAttachmentClass.FixedToExistingEvaluation ||+ spec.Method == TransitionBlendMethod.Linear && spec.WeightExponent == 1)+ { output[i] = context.Baseline[index]; continue; }+ var weights = context.Surface.SkinWeights[index].Weights;+ var total = weights.Sum(w => Math.Pow(w.Weight, spec.WeightExponent));+ var modified = weights.Select(w => w with { Weight = Math.Pow(w.Weight, spec.WeightExponent) / total }).ToArray();+ var p = context.Surface.Vertices[index].Position;+ var source = new Vector3((float)p.X, (float)p.Y, (float)p.Z);+ Vector3 transformed;+ if (spec.Method == TransitionBlendMethod.Linear)+ transformed = modified.Aggregate(Vector3.Zero, (sum, w) => sum + Vector3.Transform(source, context.SkinTransforms[w.JointIndex]) * (float)w.Weight);+ else transformed = DualQuaternionPoint(source, modified, context.SkinTransforms);+ output[i] = new(transformed.X, transformed.Y, transformed.Z);+ }+ return new(spec.Id, Array.AsReadOnly(output), $"{spec.Method}; normalized generated X1 weights exponent={spec.WeightExponent:R}; fixed patch boundary; no source-weight claim");+ }++ private static Vector3 DualQuaternionPoint(Vector3 point, IReadOnlyList<JointWeight> weights, IReadOnlyList<Matrix4x4> transforms)+ {+ var real = new Quaternion(0, 0, 0, 0); var dual = real;+ var reference = Quaternion.CreateFromRotationMatrix(transforms[weights[0].JointIndex]);+ foreach (var w in weights)+ {+ var m = transforms[w.JointIndex];+ var q = Quaternion.Normalize(Quaternion.CreateFromRotationMatrix(m));+ var d = Quaternion.Multiply(new Quaternion(m.Translation, 0), q) * .5f;+ var sign = Quaternion.Dot(reference, q) < 0 ? -1 : 1;+ real += q * (float)(w.Weight * sign); dual += d * (float)(w.Weight * sign);+ }+ var length = real.Length();+ if (length < 1e-8f) throw new InvalidOperationException("Degenerate dual-quaternion blend.");+ real *= 1 / length; dual *= 1 / length;+ dual -= real * Quaternion.Dot(real, dual);+ var translation = Quaternion.Multiply(dual, Quaternion.Conjugate(real)) * 2;+ return Vector3.Transform(point, real) + new Vector3(translation.X, translation.Y, translation.Z);+ }+}diff --git a/Aetheris.Humanoid/HumanoidDeformationJudgment.cs b/Aetheris.Humanoid/HumanoidDeformationJudgment.csnew file mode 100644index 00000000..fc2ffdcc--- /dev/null+++ b/Aetheris.Humanoid/HumanoidDeformationJudgment.cs@@ -0,0 +1,136 @@+using System.Numerics;+using Aetheris.Kernel.Core.Judgment;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Humanoid;++public sealed record DeformationMetrics(bool Finite, double MinimumEdgeRatio, double MaximumEdgeRatio,+ double EdgeDistortionMedian, double EdgeDistortionP95, double EdgeDistortionP99, double EdgeDistortionMaximum,+ double MinimumAreaRatio, double MaximumAreaRatio, double MeanAbsoluteLogEdgeRatio, double MeanAbsoluteLogAreaRatio,+ int CollapsedFaces, int OrientationReversalProxies, double FixedAttachmentMaximumMm,+ double BoundaryMaximumMm, double BaselineDriftRmsMm, IReadOnlyList<string> FlaggedFaceIds);+public sealed record MeasuredDeformationCandidate(DeformationCandidate Candidate, DeformationMetrics Metrics);+public sealed record DeformationPolicy(string Version, double MinimumEdgeRatio = .25, double MaximumEdgeRatio = 4,+ double MinimumAreaRatio = .1, double MaximumAreaRatio = 8, double FixedAttachmentToleranceMm = .001,+ double BoundaryToleranceMm = .001, double MetricWeight = .65, double AreaWeight = .25, double BaselineAgreementWeight = .10)+{+ public static DeformationPolicy HipV1 { get; } = new("humanoid.hip.deformation.v1");+ public static DeformationPolicy KneeV1 { get; } = new("humanoid.knee.deformation.v1");+}+public sealed record HumanoidDeformationDecision(string PolicyVersion, string? WinnerId, string? RunnerUpId,+ bool TieBroken, IReadOnlyList<JudgmentCandidateTrace> Trace,+ IReadOnlyList<MeasuredDeformationCandidate> Candidates, IReadOnlyList<Point3D>? Positions,+ ConstrainedSurfaceEvidence? FinalSurfaceEvidence, IReadOnlyList<KinematicDiagnostic> Diagnostics)+{+ public bool IsSuccess => Positions is not null;+}++/// <summary>Region policy is separate from construction. The shared JudgmentModel owns scoring and selection.</summary>+public static class HumanoidDeformationJudgment+{+ public static JudgmentModel<MeasuredDeformationCandidate, HumanoidDeformationContext> Model(DeformationPolicy policy,+ IReadOnlyList<JudgmentScoreTerm<MeasuredDeformationCandidate, HumanoidDeformationContext>>? extraTerms = null)+ {+ if (string.IsNullOrWhiteSpace(policy.Version) || !double.IsFinite(policy.MinimumEdgeRatio) || policy.MinimumEdgeRatio is <= 0 or > 1 ||+ !double.IsFinite(policy.MaximumEdgeRatio) || policy.MaximumEdgeRatio < 1 ||+ !double.IsFinite(policy.MinimumAreaRatio) || policy.MinimumAreaRatio is <= 0 or > 1 ||+ !double.IsFinite(policy.MaximumAreaRatio) || policy.MaximumAreaRatio < 1 ||+ !double.IsFinite(policy.FixedAttachmentToleranceMm) || policy.FixedAttachmentToleranceMm <= 0 ||+ !double.IsFinite(policy.BoundaryToleranceMm) || policy.BoundaryToleranceMm <= 0)+ throw new ArgumentException("Invalid deformation policy thresholds.");+ JudgmentRule<MeasuredDeformationCandidate, HumanoidDeformationContext> Rule(string id, string code,+ Func<DeformationMetrics, double> metric, double limit, Func<double, double, bool> predicate, string evidence)+ => new(id, (c, _) => new(predicate(metric(c.Metrics), limit), code, metric(c.Metrics), limit, evidence));+ var rules = new JudgmentRule<MeasuredDeformationCandidate, HumanoidDeformationContext>[]+ {+ Rule("finite", "HUM303", m => m.Finite ? 0 : 1, 0, (x,l) => x == l, "All patch positions must be finite."),+ Rule("noncollapsed", "HUM303", m => m.CollapsedFaces, 0, (x,l) => x == l, "Triangle area >= 0.0001 mm2."),+ Rule("orientation-proxy", "HUM303", m => m.OrientationReversalProxies, 0, (x,l) => x == l, "No dominant-influence transported-normal reversals; intersection certification unavailable."),+ Rule("compression", "HUM301", m => m.MinimumEdgeRatio, policy.MinimumEdgeRatio, (x,l) => x >= l, "Each unique patch edge: deformed/rest >= lower bound."),+ Rule("stretch", "HUM302", m => m.MaximumEdgeRatio, policy.MaximumEdgeRatio, (x,l) => x <= l, "Each unique patch edge: deformed/rest <= upper bound."),+ Rule("area-compression", "HUM301", m => m.MinimumAreaRatio, policy.MinimumAreaRatio, (x,l) => x >= l, "Every patch triangle retains bounded area."),+ Rule("area-stretch", "HUM302", m => m.MaximumAreaRatio, policy.MaximumAreaRatio, (x,l) => x <= l, "Every patch triangle has bounded area expansion."),+ Rule("fixed-attachment", "HUM304", m => m.FixedAttachmentMaximumMm, policy.FixedAttachmentToleranceMm, (x,l) => x <= l, "Protected vertices follow the existing solved evaluation."),+ Rule("boundary", "HUM305", m => m.BoundaryMaximumMm, policy.BoundaryToleranceMm, (x,l) => x <= l, "Shared boundary vertices coincide with unchanged neighboring surface.")+ };+ var terms = new List<JudgmentScoreTerm<MeasuredDeformationCandidate, HumanoidDeformationContext>>+ {+ new("edge-metric", policy.MetricWeight, (c, _) => new(1 / (1 + c.Metrics.MeanAbsoluteLogEdgeRatio), c.Metrics.MeanAbsoluteLogEdgeRatio, "mean(abs(log(ratio)))", "1/(1+mean absolute log edge ratio); neutral=1.")),+ new("area-metric", policy.AreaWeight, (c, _) => new(1 / (1 + c.Metrics.MeanAbsoluteLogAreaRatio), c.Metrics.MeanAbsoluteLogAreaRatio, "mean(abs(log(ratio)))", "1/(1+mean absolute log area ratio); neutral=1.")),+ new("baseline-agreement", policy.BaselineAgreementWeight, (c, _) => new(1 / (1 + c.Metrics.BaselineDriftRmsMm / 10), c.Metrics.BaselineDriftRmsMm, "mm RMS", "1/(1+RMS/10mm). X1 baseline agreement, NOT Antonia source agreement."))+ };+ if (extraTerms is not null) terms.AddRange(extraTerms);+ return new(policy.Version, rules, terms);+ }++ public static HumanoidDeformationDecision Evaluate(HumanoidDeformationContext context, DeformationPolicy policy,+ IReadOnlyList<TransitionCandidateSpec>? specs = null,+ IReadOnlyList<JudgmentScoreTerm<MeasuredDeformationCandidate, HumanoidDeformationContext>>? extraTerms = null,+ Action<string, double>? recordTiming = null)+ {+ var timer = System.Diagnostics.Stopwatch.StartNew();+ var generated = (specs ?? HumanoidDeformationCandidates.Default).Select(s => HumanoidDeformationCandidates.Generate(context, s)).ToArray();+ recordTiming?.Invoke("candidateGenerationMs", timer.Elapsed.TotalMilliseconds);+ timer.Restart();+ var candidates = generated.Select(c => new MeasuredDeformationCandidate(c, Measure(context, c))).ToArray();+ recordTiming?.Invoke("metricMeasurementMs", timer.Elapsed.TotalMilliseconds);+ var result = Model(policy, extraTerms).Evaluate(context, candidates.Select(c => new JudgmentOption<MeasuredDeformationCandidate>(c.Candidate.Id, c)).ToArray(), recordTiming);+ timer.Restart();+ var diagnostics = new List<KinematicDiagnostic>+ {+ new("HUM307", "No admitted, correspondence-verified source posed surface is available. Source-agreement scoring is disabled.")+ };+ IReadOnlyList<Point3D>? positions = null;+ ConstrainedSurfaceEvidence? final = null;+ if (result.Winner is { } winner)+ {+ var assembled = context.AssembleDiagnostic(winner.Value.Candidate);+ final = HumanoidConstrainedSurface.Inspect(context.Surface, context.Skeleton, context.Solved.GlobalTransforms, assembled);+ if (final.IsAdmissible) positions = assembled;+ else diagnostics.Add(new("HUM300", "Local selection failed final whole-surface screening, including unported regions; no mesh admitted."));+ if (result.TieBroken) diagnostics.Add(new("HUM306", "Utilities tie within shared-engine epsilon 1e-12; ordinal stable candidate ID wins."));+ }+ else diagnostics.Add(new("HUM300", "No admissible local deformation candidate. No fallback mesh is returned."));+ recordTiming?.Invoke("assemblyAndFinalValidationMs", timer.Elapsed.TotalMilliseconds);+ return new(policy.Version, result.Winner?.Id, result.RunnerUp, result.TieBroken, result.Candidates,+ Array.AsReadOnly(candidates), positions, final, diagnostics.AsReadOnly());+ }++ public static DeformationMetrics Measure(HumanoidDeformationContext context, DeformationCandidate candidate)+ {+ if (candidate.PatchPositions.Count != context.Vertices.Count) throw new ArgumentException("Patch position count mismatch.");+ var finite = candidate.PatchPositions.All(p => double.IsFinite(p.X) && double.IsFinite(p.Y) && double.IsFinite(p.Z));+ if (!finite) return new(false, 0, double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue,+ 0, double.MaxValue, double.MaxValue, double.MaxValue, 0, 0, double.MaxValue, double.MaxValue, double.MaxValue, []);+ Point3D P(int i) => candidate.PatchPositions[context.LocalIndex[i]];+ Point3D R(int i) => context.Surface.Vertices[i].Position;+ var ratios = context.Edges.Select(e => Ratio((P(e.A) - P(e.B)).Length, (R(e.A) - R(e.B)).Length)).ToArray();+ var distortion = ratios.Select(r => r > 0 ? Math.Max(r, 1 / r) : double.MaxValue).Order().ToArray();+ var areas = new List<double>(); var flags = new List<string>(); var collapsed = 0;+ foreach (var f in context.Faces)+ {+ var oldNormal = (R(f.B) - R(f.A)).Cross(R(f.C) - R(f.A));+ var normal = (P(f.B) - P(f.A)).Cross(P(f.C) - P(f.A));+ areas.Add(Ratio(normal.Length, oldNormal.Length));+ var joint = new[] { f.A, f.B, f.C }.SelectMany(i => context.Surface.SkinWeights[i].Weights)+ .GroupBy(w => w.JointIndex).OrderByDescending(g => g.Sum(w => w.Weight)).ThenBy(g => g.Key).First().Key;+ var expected = Vector3.TransformNormal(new((float)oldNormal.X, (float)oldNormal.Y, (float)oldNormal.Z), context.SkinTransforms[joint]);+ if (normal.LengthSquared < 4e-8) collapsed++;+ else if (normal.Dot(new(expected.X, expected.Y, expected.Z)) <= 0) flags.Add(f.Id);+ }+ var fixedDrift = 0d; var boundaryDrift = 0d; var totalDrift = 0d;+ for (var i = 0; i < context.Vertices.Count; i++)+ {+ var v = context.Vertices[i]; var drift = (candidate.PatchPositions[i] - context.Baseline[v.SurfaceIndex]).Length;+ totalDrift += drift * drift;+ if (v.Attachment == SurfaceAttachmentClass.FixedToExistingEvaluation) fixedDrift = Math.Max(fixedDrift, drift);+ if (v.Boundary) boundaryDrift = Math.Max(boundaryDrift, drift);+ }+ return new(true, ratios.Min(), ratios.Max(), Percentile(.5), Percentile(.95), Percentile(.99), distortion[^1],+ areas.Min(), areas.Max(), ratios.Average(Log), areas.Average(Log), collapsed, flags.Count,+ fixedDrift, boundaryDrift, Math.Sqrt(totalDrift / context.Vertices.Count), flags.AsReadOnly());+ double Percentile(double p) => distortion[(int)Math.Ceiling(p * distortion.Length) - 1];+ static double Ratio(double a, double b) => b > 0 && double.IsFinite(a) ? a / b : double.MaxValue;+ static double Log(double ratio) => ratio > 0 ? Math.Abs(Math.Log(ratio)) : Math.Log(double.MaxValue);+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Judgment/JudgmentModelTests.cs b/Aetheris.Kernel.Core.Tests/Judgment/JudgmentModelTests.csnew file mode 100644index 00000000..1d772e5f--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Judgment/JudgmentModelTests.cs@@ -0,0 +1,65 @@+using Aetheris.Kernel.Core.Judgment;++namespace Aetheris.Kernel.Core.Tests.Judgment;++public sealed class JudgmentModelTests+{+ private sealed record Candidate(bool Allowed, double Quality);+ private static JudgmentModel<Candidate, int> Model(Func<Candidate, int, JudgmentScoreEvidence>? score = null) => new("test.v1",+ [new("allowed", (c, _) => new(c.Allowed, "test-reject", c.Allowed ? 0 : 1, 0, "Explicit hard constraint."))],+ [new("quality", 1, score ?? ((c, _) => new(c.Quality, c.Quality, "unitless", "Test quality.")))]);++ [Fact]+ public void HardRejectedCandidateCannotWinAndIsNeverScored()+ {+ var calls = 0;+ var result = Model((c, _) => { calls++; Assert.True(c.Allowed); return new(c.Quality, c.Quality, "unitless", "witness"); })+ .Evaluate(0, [new("invalid", new(false, 1)), new("valid", new(true, .2))]);+ Assert.Equal("valid", result.Winner!.Id); Assert.Equal(1, calls);+ Assert.Empty(result.Candidates.Single(c => c.Id == "invalid").Scores);+ Assert.False(result.Candidates.Single(c => c.Id == "invalid").Admissible);+ }+ [Fact]+ public void TraceContainsAllTermsRunnerUpAndStableTie()+ {+ var options = new JudgmentOption<Candidate>[] { new("z", new(true, .7)), new("a", new(true, .7)), new("bad", new(false, 1)) };+ var first = Model().Evaluate(0, options); var second = Model().Evaluate(0, options.Reverse().ToArray());+ Assert.Equal("a", first.Winner!.Id); Assert.Equal(first.Winner.Id, second.Winner!.Id);+ Assert.Equal("z", first.RunnerUp); Assert.True(first.TieBroken);+ Assert.Equal(.7, first.Candidates.Single(c => c.Id == "a").TotalScore);+ }+ [Fact]+ public void NoSurvivorMeansNoWinnerOrFallback()+ {+ var result = Model().Evaluate(0, [new("bad", new(false, 1))]);+ Assert.Null(result.Winner); Assert.Null(result.RunnerUp); Assert.Null(result.Candidates[0].TotalScore);+ }+ [Theory]+ [InlineData(double.NaN)]+ [InlineData(double.PositiveInfinity)]+ [InlineData(1.01)]+ [InlineData(-.01)]+ public void InvalidUtilityIsRejected(double utility)+ {+ var result = Model().Evaluate(0, [new("bad", new(true, utility)), new("valid", new(true, .5))]);+ Assert.Equal("valid", result.Winner!.Id);+ Assert.Contains(result.Candidates.Single(c => c.Id == "bad").Rules, r => r.Result.Code == "judgment-invalid-score");+ }+ [Fact]+ public void InvalidWeightsAndDuplicateIdsFailExplicitly()+ {+ var model = new JudgmentModel<Candidate, int>("test", [new("rule", (_,_) => new(true,"ok",0,0,"ok"))],+ [new("invalid", double.NaN, (_,_) => new(.5,.5,"unitless","test"))]);+ Assert.Throws<ArgumentException>(() => model.Evaluate(0, [new("a", new(true,.5))]));+ Assert.Throws<ArgumentException>(() => Model().Evaluate(0, [new("a", new(true,.5)), new("a", new(true,.5))]));+ }+ [Fact]+ public void SharedChooserAndPolicyAdapterSelectSameWinnerForEquivalentSemantics()+ {+ var options = new JudgmentOption<Candidate>[] { new("a",new(true,.3)), new("b",new(true,.8)), new("c",new(false,1)) };+ var old = new JudgmentEngine<int>().Evaluate(0, options.Select(o => new JudgmentCandidate<int>(o.Id, _ => o.Value.Allowed, _ => o.Value.Quality)).ToArray());+ var current = Model().Evaluate(0, options);+ Assert.Equal(old.Selection!.Value.Candidate.Name, current.Winner!.Id);+ Assert.Equal(old.Selection.Value.Score, current.Candidates.Single(t => t.Id == current.Winner.Id).TotalScore);+ }+}diff --git a/Aetheris.Kernel.Core/Judgment/JudgmentModel.cs b/Aetheris.Kernel.Core/Judgment/JudgmentModel.csnew file mode 100644index 00000000..8bd4fdb9--- /dev/null+++ b/Aetheris.Kernel.Core/Judgment/JudgmentModel.cs@@ -0,0 +1,84 @@+namespace Aetheris.Kernel.Core.Judgment;++public sealed record JudgmentRuleEvidence(bool Passed, string Code, double Measured, double Limit, string Evidence);+public sealed record JudgmentScoreEvidence(double Utility, double RawValue, string Unit, string Evidence);+public sealed record JudgmentRule<TCandidate, TContext>(string Id,+ Func<TCandidate, TContext, JudgmentRuleEvidence> Evaluate);+public sealed record JudgmentScoreTerm<TCandidate, TContext>(string Id, double Weight,+ Func<TCandidate, TContext, JudgmentScoreEvidence> Evaluate);+public sealed record JudgmentOption<TCandidate>(string Id, TCandidate Value);+public sealed record JudgmentRuleTrace(string Id, JudgmentRuleEvidence Result);+public sealed record JudgmentScoreTrace(string Id, double Weight, JudgmentScoreEvidence Result);+public sealed record JudgmentCandidateTrace(string Id, bool Admissible,+ IReadOnlyList<JudgmentRuleTrace> Rules, IReadOnlyList<JudgmentScoreTrace> Scores, double? TotalScore);+public sealed record JudgmentModelResult<TCandidate>(string PolicyVersion,+ JudgmentOption<TCandidate>? Winner, string? RunnerUp, bool TieBroken,+ IReadOnlyList<JudgmentCandidateTrace> Candidates);++/// <summary>+/// Inspectable policy adapter over the existing chooser. It does not implement another argmax.+/// Utilities are finite [0,1], positive weights are normalized by Utility.Weighted, and hard+/// rules run before any score term. Existing JudgmentEngine callers retain their exact behavior.+/// </summary>+public sealed class JudgmentModel<TCandidate, TContext>(string version,+ IReadOnlyList<JudgmentRule<TCandidate, TContext>> rules,+ IReadOnlyList<JudgmentScoreTerm<TCandidate, TContext>> scoreTerms)+{+ public string Version { get; } = version;+ public IReadOnlyList<JudgmentRule<TCandidate, TContext>> Rules { get; } = Array.AsReadOnly(rules.ToArray());+ public IReadOnlyList<JudgmentScoreTerm<TCandidate, TContext>> ScoreTerms { get; } = Array.AsReadOnly(scoreTerms.ToArray());++ public JudgmentModelResult<TCandidate> Evaluate(TContext context, IReadOnlyList<JudgmentOption<TCandidate>> options,+ Action<string, double>? recordTiming = null)+ {+ if (string.IsNullOrWhiteSpace(Version) || Rules.Count == 0 || ScoreTerms.Count == 0 ||+ Rules.Select(r => r.Id).Distinct(StringComparer.Ordinal).Count() != Rules.Count ||+ ScoreTerms.Select(t => t.Id).Distinct(StringComparer.Ordinal).Count() != ScoreTerms.Count ||+ ScoreTerms.Any(t => !double.IsFinite(t.Weight) || t.Weight <= 0) ||+ !double.IsFinite(ScoreTerms.Sum(t => t.Weight)))+ throw new ArgumentException("Judgment policy needs a version, unique rules/terms, and finite positive score weights.");+ var ordered = options.OrderBy(o => o.Id, StringComparer.Ordinal).ToArray();+ if (ordered.Any(o => string.IsNullOrWhiteSpace(o.Id)) || ordered.Select(o => o.Id).Distinct(StringComparer.Ordinal).Count() != ordered.Length)+ throw new ArgumentException("Candidate IDs must be nonempty and unique.");+ var timer = System.Diagnostics.Stopwatch.StartNew();+ var traces = new List<JudgmentCandidateTrace>();+ foreach (var option in ordered)+ {+ var ruleResults = Rules.Select(r =>+ {+ var result = r.Evaluate(option.Value, context);+ if (!double.IsFinite(result.Measured) || !double.IsFinite(result.Limit))+ result = new(false, "judgment-nonfinite-rule", 0, 0, "Rule returned nonfinite measurement or limit.");+ return new JudgmentRuleTrace(r.Id, result);+ }).ToArray();+ var admitted = ruleResults.All(r => r.Result.Passed);+ var scores = admitted ? ScoreTerms.Select(t => new JudgmentScoreTrace(t.Id, t.Weight, t.Evaluate(option.Value, context))).ToArray() : [];+ if (scores.Any(s => !double.IsFinite(s.Result.Utility) || s.Result.Utility < 0 || s.Result.Utility > 1 || !double.IsFinite(s.Result.RawValue)))+ {+ admitted = false;+ ruleResults = [.. ruleResults, new("finite-bounded-utility", new(false, "judgment-invalid-score", 0, 1, "Score term returned a nonfinite or out-of-range utility/raw value."))];+ scores = []; // Do not serialize NaN/Infinity or silently normalize invalid scores.+ }+ double? total = admitted ? Utility.Weighted(scores.Select(s => (s.Result.Utility, s.Weight)).ToArray()) : null;+ traces.Add(new(option.Id, admitted, Array.AsReadOnly(ruleResults), Array.AsReadOnly(scores), total));+ }+ recordTiming?.Invoke("admissibilityAndUtilityMs", timer.Elapsed.TotalMilliseconds);+ timer.Restart();+ var lookup = traces.ToDictionary(t => t.Id, StringComparer.Ordinal);+ var candidates = ordered.Select(o => new JudgmentCandidate<IReadOnlyDictionary<string, JudgmentCandidateTrace>>(+ o.Id, c => c[o.Id].Admissible, c => c[o.Id].TotalScore!.Value,+ c => string.Join("; ", c[o.Id].Rules.Where(r => !r.Result.Passed).Select(r => r.Result.Code + ": " + r.Result.Evidence)))).ToArray();+ var engine = new JudgmentEngine<IReadOnlyDictionary<string, JudgmentCandidateTrace>>();+ var decision = engine.Evaluate(lookup, candidates);+ if (!decision.IsSuccess)+ {+ recordTiming?.Invoke("selectionMs", timer.Elapsed.TotalMilliseconds);+ return new(Version, null, null, false, traces.AsReadOnly());+ }+ var selected = decision.Selection!.Value;+ var runner = engine.Evaluate(lookup, candidates.Where(c => c.Name != selected.Candidate.Name).ToArray()).Selection;+ recordTiming?.Invoke("selectionMs", timer.Elapsed.TotalMilliseconds);+ return new(Version, ordered.Single(o => o.Id == selected.Candidate.Name), runner?.Candidate.Name,+ runner is { } r && double.Abs(r.Score - selected.Score) <= 1e-12, traces.AsReadOnly());+ }+}diff --git a/docs/public/humanoid-judgment.md b/docs/public/humanoid-judgment.mdnew file mode 100644index 00000000..aa4d58a3--- /dev/null+++ b/docs/public/humanoid-judgment.md@@ -0,0 +1,179 @@+# Humanoid deformation judgment (X3 research)++**Status: Meaningful progression.** The shared Judgment Engine now supports+inspectable rule/utility policies. Six hip candidates are compared on the X1+Antonia candidate after the X2 constrained solve. Hip70, hip90 and abduction45+have **no admissible candidate**; no surface is returned for those poses.+Antonia is not promoted to canonical runtime status. See the+[release record](../release/HUMANOID-X3.md).++## Evaluate a hip++```csharp+using System.Text.Json;+using Aetheris.Humanoid;++var source = JsonSerializer.Deserialize<AntoniaAdoptionCandidate>(+ File.ReadAllText("artifacts/local/humanoid-x1/antonia-adoption-candidate.json"),+ HumanoidArtifactIO.JsonOptions)!;+var surface = source.SourcePoseSurface with+{+ Vertices = source.SourcePoseSurface.Vertices.Select((v, i) =>+ v with { Position = source.PreparedPositions[i] }).ToArray()+};+var skeleton = source.PreparedSkeleton;+var request = new RequestedHumanoidPose("hip70", skeleton.SkeletonId,+ skeleton.RestPoseId, 0, [new(HumanoidJointKind.LeftHip, 70)]);+var solve = HumanoidKinematicSolver.Solve(skeleton, request);+if (solve.Pose is not { } solved) throw new InvalidOperationException("Pose rejected.");+var context = HumanoidDeformationContext.Create(surface, skeleton, 0, solved,+ HumanoidJointKind.LeftHip);+var decision = HumanoidDeformationJudgment.Evaluate(context, DeformationPolicy.HipV1);+Console.WriteLine(JsonSerializer.Serialize(new+{+ decision.IsSuccess, decision.WinnerId, decision.RunnerUpId,+ decision.TieBroken, decision.Trace, decision.Diagnostics+}, HumanoidArtifactIO.JsonOptions));+// decision.Positions is null on failure. Never substitute a rejected diagnostic candidate.+```++The [X2 guide](humanoid-kinematics.md) defines the upstream joint domain and+revision checks. X3 never changes that solve, its centers or link lengths.+Only a `SolvedHumanoidPose` can create a deformation context; a stale shape or+rest skeleton fails before candidate generation.++## Candidates and patch ownership++`HumanoidDeformationCandidates.Default` contains six `TransitionCandidateSpec`+values: Linear and DualQuaternion, each with weight exponents 1, 0.5 and 2.+Each generator normalizes the modified X1 generated weights. These are **not+Antonia-authored weights**. DQS is a bounded rigid-transform interpolation+candidate, not a dynamics or tissue solver. Candidate construction contains no+utility constants.++Hip owns the selected-side thigh and pelvis face regions. All incident+vertices and unique edges participate in inspection. A vertex shared with an+outside face is fixed exactly to the existing solved baseline. Editable+vertices must have only pelvis/selected-hip influences, with both nonzero.+Other vertices are `FixedToExistingEvaluation`; eligible ones are+`BlendedTransition`. These are **X3 provisional classifications derived from+the X1 field**, not artist-reviewed anatomical attachments inherited from X2.+No sliding classification or behavior is claimed.++`DeformationCandidate.PatchPositions` indexes `context.Vertices` in stable+surface-index order. `context.AssembleDiagnostic(candidate)` is explicitly a+diagnostic helper; it can assemble rejected geometry for inspection. The+ordinary decision returns `Positions` only after a local winner also passes+the full X2 surface screen. Unported regions use their old deformation only+when the resulting whole surface passes that screen.++## Policy++`DeformationPolicy.HipV1` uses version `humanoid.hip.deformation.v1`.+Hard rules are evaluated before any utility term:++| Rule | Requirement |+|---|---|+| Finite | Finite patch coordinates |+| Noncollapsed | Triangle area at least 0.0001 mm² |+| Orientation proxy | Zero dominant-influence transported-normal reversals |+| Edge compression/stretch | Every unique edge deformed/rest ratio in [0.25, 4] |+| Area compression/stretch | Every triangle deformed/rest area ratio in [0.1, 8] |+| Fixed attachment | Drift from protected baseline at most 0.001 mm |+| Boundary continuity | Drift of shared boundary vertices at most 0.001 mm |++These are provisional engineering screening bounds, not clinical or material+strain limits. Collision/exclusion, self-intersection certification, silhouette+quality and volume preservation are **not implemented**. The normal test is+explicitly a proxy. Passing these rules alone does not establish a valid human.++For admitted candidates only, utility is the normalized weighted mean:++| Term | Weight | Utility [0,1] |+|---|---:|---|+| edge-metric | 0.65 | `1/(1 + mean(abs(log(edge ratio))))` |+| area-metric | 0.25 | `1/(1 + mean(abs(log(area ratio))))` |+| baseline-agreement | 0.10 | `1/(1 + RMS displacement from X1 / 10mm)` |++The last term measures conservative agreement with **X1**, not authored+Antonia source behavior. Source agreement is disabled, with `HUM307`, because+no admitted correspondence-verified posed source surface is available.+Weights and thresholds are explicit code/configuration, not runtime UI settings+and not calibrated from source samples. Do not change them merely to admit+the failing hip70 cases.++The shared `JudgmentModel<TCandidate,TContext>` runs rules and records their+measurements, limits, diagnostics and evidence. It records every score term's+raw value, unit, utility and weight. It uses `Utility.Weighted` and the existing+`JudgmentEngine` for winner and runner-up selection. IDs are unique and sorted+ordinally; equal priorities and utility differences within the engine's+1e-12 epsilon resolve by stable ID. Invalid utilities/weights cannot be+silently treated as useful scores. No second argmax was introduced.++`WinnerId` describes local selection. `IsSuccess` and nonnull `Positions`+describe final surface admission. A local winner can still fail the final+screen. `HUM300` indicates no admitted surface, `HUM301/302` metric limits,+`HUM303` collapse/orientation/nonfinite failure, `HUM304` protected-attachment+drift, `HUM305` boundary failure, `HUM306` a tie, and `HUM307` absent source+behavior. Rejected candidates have **no utility scores**.++## Add a score term without changing generators++`HumanoidDeformationJudgment.Model(policy, extraTerms)` exposes the reusable+policy, and `Evaluate(context, policy, extraTerms: ...)` uses it directly.+Extra terms have type+`JudgmentScoreTerm<MeasuredDeformationCandidate, HumanoidDeformationContext>`+from `Aetheris.Kernel.Core.Judgment`. Their callback returns+`JudgmentScoreEvidence(Utility, RawValue, Unit, Evidence)`.++```csharp+using Aetheris.Kernel.Core.Judgment;+var term = new JudgmentScoreTerm<MeasuredDeformationCandidate, HumanoidDeformationContext>(+ "protected-attachment-residual", 0.2,+ (candidate, _) => new JudgmentScoreEvidence(+ 1 / (1 + candidate.Metrics.FixedAttachmentMaximumMm / 0.001),+ candidate.Metrics.FixedAttachmentMaximumMm, "mm",+ "Bounded utility for residual at protected attachments."));+var decisionWithTerm = HumanoidDeformationJudgment.Evaluate(context,+ DeformationPolicy.HipV1, extraTerms: [term]);+```++Useful inputs include `candidate.Metrics.FixedAttachmentMaximumMm`,+`BoundaryMaximumMm`, `BaselineDriftRmsMm`, `MeanAbsoluteLogEdgeRatio` and+`MeanAbsoluteLogAreaRatio`. Attachment drift remains a hard rule even if an+extra utility term rewards lower residuals. The current generators pin those+protected vertices exactly, so attachment utility will normally tie; do not+invent discrimination. `BaselineDriftRmsMm` is not anatomical attachment drift.++## Reuse boundary: knee and composition++The same context factory supports LeftKnee/RightKnee, using selected thigh,+shin and knee regions and only hip/knee blend influences. Use+`DeformationPolicy.KneeV1` for a differently versioned instance of the same+rule/score model. This exists for an isolated architecture reuse witness.+**Knee production migration is deferred because hip qualification failed.**+Shoulder contexts are rejected; X2 has no admitted compound shoulder solve.++There is no multi-patch orchestrator, overlapping-patch arbitration, cache or+quantized pose library in this progression. One context makes one decision;+it preserves all outside vertices. Do not independently apply overlapping+hip and knee winners and claim qualified composition. Candidate constructions+vary continuously with input transforms, but discrete winner changes have not+been certified temporally continuous. Timings are separate from deterministic+trace/geometry outputs.++## Reproduction and evidence++```powershell+pwsh -File scripts/inspect-antonia-deformation-source.ps1+dotnet run --project tools/Aetheris.Humanoid.X0 -- judge-antonia --input artifacts/local/humanoid-x1/antonia-adoption-candidate.json --out-dir artifacts/local/humanoid-x3+```++The nine cases are flexion 0/30/45/70/90 and abduction 0/15/30/45. Each has+`<pose>.trace.json` with all candidates' rule results and measured metrics.+`hip-flexion-70.trace.json` intentionally has no winner. Use+`hip-flexion-45.trace.json` to inspect a selected winner and runner-up.+All candidates are exported only as `*.diagnostic.obj`; `*.winner.obj` is+written only for an admitted full surface. Files live under ignored+`artifacts/local/humanoid-x3/`. Raw CR2 is retained there for read-only audit,+not installed as a runtime dependency or committed.diff --git a/docs/release/HUMANOID-X3.md b/docs/release/HUMANOID-X3.mdnew file mode 100644index 00000000..2ea44db0--- /dev/null+++ b/docs/release/HUMANOID-X3.md@@ -0,0 +1,241 @@+# HUMANOID-X3 — judgment-driven deformation++**Verdict: Meaningful progression. Not Accepted.**++The existing Judgment Engine now chooses among explicit local hip deformation+candidates with hard-rule traces, normalized utilities, stable tie-breaking,+runner-up evidence and fail-closed materialization. It does **not** yet solve+Antonia's hip70 deformation. That pose, hip90 and abduction45 have no admissible+candidate and return `HUM300` with no surface. No low score can override a+hard failure, and no invalid baseline is used as fallback.++The detailed [public policy/API guide](../public/humanoid-judgment.md) defines+the construction families, patch/attachment boundaries, equations, weights,+thresholds, diagnostics and current limits. This is a research path over the+unpromoted Antonia candidate, not a claimed canonical-body promotion.++## Source deformation audit++Original source: Antonia Polygon 1.2, revision+`08c9767691daad1382dfc6980ee83e31514b4879`,+`Runtime/libraries/Character/Antonia/Antonia-1.2.cr2`, SHA-256+`ff97bcbff1a0f8f86fbc39122196787fd6b46dec914b6d55574ed764f3142d62`.+The original [attribution/license notice](../../fixtures/Canonical/Humanoid/antonia-original-LICENSE.txt)+is preserved. The existing geometry admission excludes source rigs/weights;+this work performs pinned **declaration inspection only**, without silently+extending canonical/runtime admission. No source CR2, weight map, morph delta+or expanded source dump is committed.++The CR2 contains `sphereMatsRaw`, `calcWeights`, per-axis joint angle/falloff+declarations, `doBulge` controls and `JCM-lThighIn` driven morph data. It is not+a simple reusable array of vertex weights. No qualified Poser deformation+evaluator or correspondence-preserving posed export is present, so **zero+source poses were sampled**. Source baseline, source-displacement agreement,+source-derived calibration and source-weighted candidates are unavailable.+`HUM307` records this honestly; the conservative X1-agreement score is never+labeled source agreement. The original authoring is retained as evidence for+the next experiment, not discarded or approximated as a supposed import.++The authored left-hip channel center `(0.036, 0.386, -0.023)` maps through+X1's documented original-source coordinate conversion to+`(-90.1642, -33.8029, 964.5312) mm`. The existing seam-derived proxy is+`(-80.4492, -17.0089, 857.4617) mm`: a **108.8131 mm difference**.+This is a material reference discrepancy, not proof that a center replacement+alone fixes the body. X3 preserves the X2 solve and center for a controlled+candidate comparison; it does not tune skinning to conceal this discrepancy.++## Shared Judgment Engine and CAD compatibility++`JudgmentModel<TCandidate,TContext>` is a small adapter over the existing+`JudgmentEngine` and `Utility.Weighted`. It adds named rule and utility terms,+measurement/normalization evidence, per-candidate traces, runner-up and tie+reporting. It sorts unique candidate IDs before invoking the existing chooser;+it does not duplicate argmax or change legacy chooser semantics. Rejected+candidates are never scored. Nonfinite/out-of-range utilities fail explicitly.++Audit: bounded fillet uses explicit predicates with legacy strategy scores+100/150/175 and a −1 reject sentinel; bounded chamfer similarly uses predicate+and strategy-ranking candidates. Surfacing BlendBoundary already separates+qualification from normalized utility and calls the shared chooser.+Those existing policies and priorities are left unchanged. Moving their+constants merely for visual uniformity would not improve the hip experiment.+New adapter tests compare its winner with the legacy chooser for equivalent+semantics; CAD regression runs are recorded below.++## Hip70 candidate evidence++The same constrained hip70 solve is fed to all six candidates. All use the+unchanged topology and generated X1 weights; exponents modify only eligible+blend vertices. Boundary and protected vertices remain exact. DQS is a rigid+transform interpolation alternative, not a simulation.++| Candidate | Min edge ratio | Max edge ratio | Max bidirectional distortion | Reversal proxies | Result |+|---|---:|---:|---:|---:|---|+| LBS baseline | 0.06081 | 4.66 | 16.44 | 12 | Reject |+| LBS softened weights | 0.1089 | 7.08 | 9.18 | 4 | Reject |+| LBS sharpened weights | 0.1089 | 7.54 | 9.18 | 38 | Reject |+| DQS baseline weights | 0.06609 | 5.17 | 15.13 | 8 | Reject |+| DQS softened weights | 0.06609 | 7.54 | 15.13 | 12 | Reject |+| DQS sharpened weights | 0.06609 | 8.19 | 15.13 | 46 | Reject |++The softened LBS construction improves one compression statistic but worsens+stretch and still reverses normals. It is not a winner or qualified fix.+All hip70 utilities are intentionally unevaluated because hard rules fail.+There is no runner-up among inadmissible constructions.++## Pose domain++| Pose | Admitted result |+|---|---|+| Flexion 0 | DQS baseline weights |+| Flexion 30 | LBS baseline |+| Flexion 45 | LBS baseline |+| Flexion 70 | No candidate; no mesh |+| Flexion 90 | No candidate; no mesh |+| Abduction 0 | DQS baseline weights |+| Abduction 15 | LBS baseline |+| Abduction 30 | LBS baseline |+| Abduction 45 | No candidate; no mesh |++No ROM or rejection threshold is reduced/relaxed to improve the verdict.+Neutral ties can favor the ordinal DQS ID; the generated geometry is still+screened. Discrete winner-switch continuity is not yet qualified.++## Remaining boundaries and next convergent step++X3 introduces provisional fixed/blended classifications from the old field;+X2 did not already provide reviewed skin attachment classes. Protected drift+is measured against the existing solved evaluation, not a validated tissue+attachment manifold. Collision/exclusion, side-crossing, certified surface+intersection, silhouette and volume constraints are absent. Orientation is a+transported-normal proxy. These limitations are visible in the policy docs;+the report does not claim complete geometric or anatomical admissibility.++Only one local patch is selected at a time. No overlapping hip/knee composition+or caching is qualified. Knee uses the same model/context machinery only for+an isolated reuse witness; production migration waits for a credible hip+candidate. Shoulder remains blocked by the missing X2 compound solution.++Next: obtain correspondence-preserving posed reference output from the pinned+original Antonia setup, verify the authored center/frame conversion, and+compare a deliberately revised shape/bind definition separately from candidate+policy changes. Characterize its falloff and region behavior before adding a+source-informed candidate. Do not guess Poser bulge/JCM evaluation, import+unverified weights wholesale, or continue adding candidate variants around an+uncalibrated reference frame.++Reproduce through the public guide. Generated traces, all candidate diagnostic+meshes, admitted winners, timings and source audit live under+`artifacts/local/humanoid-x3/`.++## Visual review and heatmaps++++++Blue is compression; red is stretch; grey is near-preserved. Color is the+largest absolute log edge ratio per triangle, saturated at the 4× policy+bound. Saturation does not mean the metric is only 4×: exact extremes remain+in the trace. Matched front/back shaded and heatmap views exist for hip45,+hip70, hip90 and abduction30/45. The camera/material is identical across each+comparison. Failed examples explicitly say `REJECTED-softened-candidate`.+No source-reference panel is fabricated.++Assistant visual review: hip70's crease persists in both constructions;+the softened candidate does not resolve the transition. **Fail**. Hip45's+selected LBS equals its baseline and retains the pre-existing body contours;+screen pass is not anatomical acceptance. **NeedsReview**. Human signoff is+not supplied. Existing shoulder abnormalities are not hidden or addressed.++## Fresh-agent qualification++Three fresh agents used only the public policy guide, permitted traces or+candidate artifact, and exported DLL signatures. No implementation source+or release report was supplied.++- **Explain decision: Pass.** Hip70 has no winner/runner-up and no utility+ evaluations. For hip45 the agent independently recomputed LBS utility+ **0.969265389** against DQS runner-up **0.960241703**; both are admitted,+ four alternatives fail hard rules, and there is no tie.+- **Add score term: Pass.** A separate probe added protected-attachment+ utility `1/(1+residual/0.001mm)` through `extraTerms`, with deliberately+ overwhelming weight 1000. Neutral scored six candidates, hip45 scored two,+ hip70 scored zero. Hip70 still returned null positions. Protected residual+ is zero for existing survivors, so this term honestly ties; it is not+ confused with baseline RMS drift. The guide now includes the concrete+ score-term constructor example after this API feedback.+- **New region: Pass for isolated reuse.** The same architecture admitted+ neutral (six candidates), knee45 (four), and knee90 (two). Knee90 selected+ `dqs.weights-softened`; knee90+hip70 had no candidate and returned `HUM300`+ with null positions. This is not a production knee migration or proof of+ multi-patch composition. Hip qualification is still required first.++## Validation++Focused tests: **52/52 humanoid**, **112/112 core Judgment/chamfer/fillet**,+**141/141 Firmament/surfacing/chamfer/fillet**. These include a known+half-rotation DQS endpoint witness, boundary/protected-attachment checks,+stale-context rejection, hard-rule score suppression, invalid utility/weight+handling, deterministic tie/reordered enumeration, and policy extension.+Existing CAD candidate code, scores and tie priorities were unchanged.++Full build passed with 0 errors and 7 warnings (existing WebAssembly/analyzer+warnings). Full-suite results and the measured performance comparison follow.++Replay reproduced all **70** deterministic files byte for byte: nine traces,+54 diagnostic meshes, six admitted meshes and aggregate evidence. The+aggregate SHA-256 is+`281042725bb8fe31e656eeaa28c219167cd55e0b45fded87864a45ba6fd61666`.+Timings are deliberately separate from deterministic evidence. Qualification+also removes a previous pose's winner file if a later run rejects that pose.++Repository layout validation passed (4374 tracked files inspected), and+`git diff --check` reported no whitespace errors.++The full active solution suite (`Category!=SlowCorpus`) finished with **3645+passed, 3 failed**. It is not a green full-suite result. The failures were:++- `ThroughHole_RecipeLayerHasNoMeaningfulRuntimeRegression`: legacy 12.921 ms+ versus recipe 98.916 ms for 100 iterations, failing its timing assertion.+- `Ftc07ViewMaterialization_FailsWithDiagnosticInsteadOfHang`: the bounded+ viewer returned tessellation-timeout diagnostics instead of the expected+ diagnostic match.+- `FreshAuthoredPhoneUsesGenericPlateauAndMeshesEveryFace`: display meshing+ exceeded its bounded budget after 5603 ms on a plane face.++These paths were not modified. **All three passed on individual isolated+reruns** (`isolated-core.log`, `isolated-server.log`, `isolated-firmament.log`);+this is consistent with execution-budget sensitivity, but does not erase the+failures above. Full output is in+`artifacts/local/humanoid-x3/full-tests.log`.++The reproduction script passed with `-SkipFetch -SkipRender -SkipFullTests`,+rechecking pinned source inspection, tool build, corpus, byte replay and all+305 focused tests. Rendering and the full solution checks were run separately+as documented above. Public documentation qualification also passed.++## Performance++The qualification runner times the old X2 constrained evaluation independently+on each of the same nine poses. This includes skinning and its surface screen,+but excludes the already-solved kinematic pose. X3 context creation also runs+that baseline and prepares the patch; its judgment time is additional.++| Stage | Mean ms | Range ms |+|---|---:|---:|+| Old constrained deformation and screen | 120.77 | 91.86–303.61 |+| X3 context, including baseline and patch preparation | 124.38 | 99.34–268.44 |+| Six-candidate generation | 1.68 | 1.12–4.31 |+| Candidate metric measurement | 39.91 | 34.88–46.20 |+| Hard rules and admitted utility | 0.52 | 0.01–4.46 |+| Shared-engine winner/runner selection | 0.60 | 0.02–4.19 |+| Assembly and final screen | 64.62 | 0–108.63 |+| Total judgment after context | 108.03 | 39.16–173.34 |++Mean X3 context plus judgment is **232.41 ms**, approximately **1.92 times**+the independently measured old path in this run. Rejected cases skip final+assembly/screening. These are single-process qualification measurements,+including first-use overhead, not a statistically controlled benchmark or+interactive-performance claim. Timing evidence is in `timings.json`; the+dominant additional work is geometry measurement/final screening, not argmax.diff --git a/scripts/inspect-antonia-deformation-source.ps1 b/scripts/inspect-antonia-deformation-source.ps1new file mode 100644index 00000000..0c9a8a61--- /dev/null+++ b/scripts/inspect-antonia-deformation-source.ps1@@ -0,0 +1,51 @@+[CmdletBinding()]+param([switch]$SkipFetch)+$ErrorActionPreference = 'Stop'+Push-Location (Split-Path -Parent $PSScriptRoot)+try {+ $outDir = 'artifacts/local/humanoid-x3'+ $sourceDir = "$outDir/source"+ New-Item -ItemType Directory -Force $sourceDir | Out-Null+ $revision = '08c9767691daad1382dfc6980ee83e31514b4879'+ $relative = 'Runtime/libraries/Character/Antonia/Antonia-1.2.cr2'+ $expected = 'ff97bcbff1a0f8f86fbc39122196787fd6b46dec914b6d55574ed764f3142d62'+ $path = "$sourceDir/Antonia-1.2.cr2"+ if (-not (Test-Path -LiteralPath $path)) {+ if ($SkipFetch) { throw 'Missing pinned original CR2 audit input.' }+ Invoke-WebRequest "https://raw.githubusercontent.com/odf/Antonia.Polygon/$revision/$relative" -OutFile $path+ }+ if ((Get-FileHash -LiteralPath $path).Hash.ToLowerInvariant() -ne $expected) { throw 'Original CR2 hash mismatch.' }+ $text = Get-Content -LiteralPath $path -Raw+ $channels = foreach ($axis in @('X','Z')) {+ $label = 'lThigh_joint' + $axis.ToLowerInvariant()+ $pattern = '(?ms)^\t\tjoint' + $axis + ' ' + $label + '\r?\n\t\t\t\{.*?^\t\t\t\}'+ $match = [regex]::Match($text, $pattern)+ if (-not $match.Success) { throw "Missing expected pinned channel: $label" }+ $declarations = @($match.Value -split '\r?\n' | Where-Object { $_ -match '^\s*(angles|center|doBulge|posBulgeLeft|posBulgeRight|negBulgeLeft|negBulgeRight|jointMult|calcWeights)\b' } | ForEach-Object { $_.Trim() })+ [ordered]@{channel=$label;declarations=$declarations;hasSphereMatsRaw=$match.Value.Contains('sphereMatsRaw')}+ }+ $candidate = Get-Content artifacts/local/humanoid-x1/antonia-adoption-candidate.json -Raw | ConvertFrom-Json+ $centerText = @($channels[0].declarations | Where-Object { $_.StartsWith('center ') })+ if ($centerText.Count -ne 1) { throw 'Expected exactly one center declaration in the inspected channel.' }+ $center = @($centerText[0].Split(' ', [System.StringSplitOptions]::RemoveEmptyEntries) | Select-Object -Skip 1 | ForEach-Object { [double]::Parse($_,[System.Globalization.CultureInfo]::InvariantCulture) })+ $authored = @((-$center[0] * $candidate.scaleToMm), (($center[2] - $candidate.sourcePelvisZ) * $candidate.scaleToMm), (($center[1] - $candidate.sourceSoleY) * $candidate.scaleToMm))+ $joint = $candidate.preparedSkeleton.joints | Where-Object kind -eq 'LeftHip'+ $existing = @($joint.globalBind.m41, $joint.globalBind.m42, $joint.globalBind.m43)+ $squared = 0.0+ for ($i=0; $i -lt 3; $i++) { $squared += [Math]::Pow($authored[$i] - $existing[$i],2) }+ [ordered]@{+ schema='aetheris.humanoid.antonia-source-deformation-audit.v1'+ revision=$revision;sourcePath=$relative;sha256=$expected+ status='Pinned declaration inspection only; not a source deformation evaluator or runtime rig admission'+ originalNotice='fixtures/Canonical/Humanoid/antonia-original-LICENSE.txt'+ channels=$channels+ hasJointControlledThighMorphs=$text.Contains('targetGeom JCM-lThighIn')+ authoredHipCenterCanonicalMm=$authored+ candidateHipCenterCanonicalMm=$existing+ centerDifferenceMm=[Math]::Sqrt($squared)+ sourceBehaviorSampled=$false+ runtimeImported=$false+ blocker='Original CR2 uses Poser joint falloff matrices, bulge controls and driven morphs. No qualified Poser evaluator/correspondence-preserving posed export is present; no weights or behavior are inferred from declarations alone.'+ } | ConvertTo-Json -Depth 8 | Set-Content "$outDir/source-deformation-audit.json"+}+finally { Pop-Location }diff --git a/scripts/qualify-humanoid-x3.ps1 b/scripts/qualify-humanoid-x3.ps1new file mode 100644index 00000000..6986d13a--- /dev/null+++ b/scripts/qualify-humanoid-x3.ps1@@ -0,0 +1,51 @@+[CmdletBinding()]+param(+ [string]$Candidate = 'artifacts/local/humanoid-x1/antonia-adoption-candidate.json',+ [string]$Blender = 'C:\Program Files\Blender Foundation\Blender 5.2\blender.exe',+ [switch]$SkipFetch,+ [switch]$SkipRender,+ [switch]$SkipFullTests+)+$ErrorActionPreference = 'Stop'+Push-Location (Split-Path -Parent $PSScriptRoot)+try {+ $outDir = 'artifacts/local/humanoid-x3'+ New-Item -ItemType Directory -Force $outDir | Out-Null+ if (-not (Test-Path -LiteralPath $Candidate)) { throw 'Generate the X1 Antonia candidate first.' }+ & "$PSScriptRoot/inspect-antonia-deformation-source.ps1" -SkipFetch:$SkipFetch+ dotnet build tools/Aetheris.Humanoid.X0/Aetheris.Humanoid.X0.csproj > "$outDir/tool-build.log"+ if ($LASTEXITCODE -ne 0) { throw 'Judgment research tool build failed.' }+ foreach ($target in @($outDir, "$outDir/replay")) {+ dotnet run --no-build --project tools/Aetheris.Humanoid.X0 -- judge-antonia --input $Candidate --out-dir $target+ if ($LASTEXITCODE -ne 0) { throw 'Judgment qualification command failed.' }+ }+ $e = Get-Content "$outDir/evidence.json" -Raw | ConvertFrom-Json+ if ($e.cases.Count -ne 9) { throw 'Unexpected hip pose corpus.' }+ foreach ($case in $e.cases) {+ if ($case.metrics.Count -ne 6) { throw "Unexpected candidate set: $($case.name)" }+ if ($case.isSuccess -and -not $case.finalSurfaceEvidence.isAdmissible) { throw 'Winner failed final screen.' }+ if (@($case.trace | Where-Object { -not $_.admissible -and $_.scores.Count -gt 0 }).Count -gt 0) { throw 'Inadmissible candidate was scored.' }+ }+ $files = @('evidence.json') + @(Get-ChildItem -LiteralPath $outDir -File | Where-Object { $_.Name -like '*.obj' -or $_.Name -like '*.trace.json' } | Select-Object -ExpandProperty Name)+ foreach ($file in $files) {+ if ((Get-FileHash "$outDir/$file").Hash -ne (Get-FileHash "$outDir/replay/$file").Hash) { throw "Replay mismatch: $file" }+ }+ if (-not $SkipRender) {+ & $Blender --background --factory-startup --disable-autoexec --python-exit-code 1 --python scripts/render-humanoid-x3.py > "$outDir/render.log"+ if ($LASTEXITCODE -ne 0) { throw 'Judgment diagnostic rendering failed.' }+ }+ dotnet test Aetheris.Humanoid.Tests/Aetheris.Humanoid.Tests.csproj --verbosity minimal > "$outDir/humanoid-tests.log"+ if ($LASTEXITCODE -ne 0) { throw 'Humanoid tests failed.' }+ dotnet test Aetheris.Kernel.Core.Tests/Aetheris.Kernel.Core.Tests.csproj --filter 'FullyQualifiedName~Judgment|FullyQualifiedName~Chamfer|FullyQualifiedName~Fillet' --verbosity minimal > "$outDir/cad-core-tests.log"+ if ($LASTEXITCODE -ne 0) { throw 'Core Judgment/CAD regression failed.' }+ dotnet test Aetheris.Kernel.Firmament.Tests/Aetheris.Kernel.Firmament.Tests.csproj --filter 'FullyQualifiedName~SurfX2BlendBoundary|FullyQualifiedName~Fillet|FullyQualifiedName~Chamfer' --verbosity minimal > "$outDir/cad-firmament-tests.log"+ if ($LASTEXITCODE -ne 0) { throw 'Firmament/surfacing CAD regression failed.' }+ if (-not $SkipFullTests) {+ dotnet build Aetheris.slnx -m:1 > "$outDir/build.log"+ if ($LASTEXITCODE -ne 0) { throw 'Solution build failed.' }+ dotnet test Aetheris.slnx --no-build --filter 'Category!=SlowCorpus' --verbosity minimal > "$outDir/full-tests.log"+ if ($LASTEXITCODE -ne 0) { throw 'Full active suite failed; inspect full-tests.log.' }+ }+ Write-Host 'X3 judgment progression reproduced. Hip70/90 and abduction45 remain rejected; no acceptance claim.'+}+finally { Pop-Location }diff --git a/scripts/render-humanoid-x3.py b/scripts/render-humanoid-x3.pynew file mode 100644index 00000000..aa210e04--- /dev/null+++ b/scripts/render-humanoid-x3.py@@ -0,0 +1,75 @@+"""Matched X3 diagnostic views. A failed candidate is never labeled as a winner."""+import argparse+import json+import math+import runpy+from pathlib import Path+import sys++import bpy+from mathutils import Vector+helpers = runpy.run_path(str(Path(__file__).with_name('render-humanoid-x2.py')))+setup, obj_mesh, render, material = (helpers[n] for n in ('setup', 'obj_mesh', 'render', 'material'))+++def points(path):+ return [Vector(tuple(float(x) for x in line.split()[1:4]))+ for line in path.read_text().splitlines() if line.startswith('v ')]+++def heatmap(obj, rest, posed):+ # Blue = compression; red = stretch; grey = near-preserved. Saturates at policy 4x.+ obj.data.materials.clear()+ for bucket in range(33):+ t = (bucket - 16) / 16+ color = (.65 + .3 * t, .65 * (1 - t), .65 * (1 - t)) if t >= 0 else (.65 * (1 + t), .65 * (1 + t), .65 - .3 * t)+ obj.data.materials.append(material('signed-log-edge-' + str(bucket), color))+ for face in obj.data.polygons:+ ids = list(face.vertices)+ signed = []+ for a, b in zip(ids, ids[1:] + ids[:1]):+ before = (rest[a] - rest[b]).length+ after = (posed[a] - posed[b]).length+ signed.append(math.log(max(after / before, 1e-12)) if before else 0)+ value = max(signed, key=abs) / math.log(4)+ face.material_index = round(16 + 16 * min(1, max(-1, value)))+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument('--out-dir', default='artifacts/local/humanoid-x3')+ args = parser.parse_args(sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else [])+ out = Path(args.out_dir)+ evidence = json.loads((out / 'evidence.json').read_text())+ rest = points(out / 'hip-flexion-0.lbs.baseline.diagnostic.obj')+ rendered = []+ for case in evidence['cases']:+ name = case['name']+ if name not in ('hip-flexion-45','hip-flexion-70','hip-flexion-90','hip-abduction-30','hip-abduction-45'):+ continue+ selected = case['winnerId'] if case['isSuccess'] else 'lbs.weights-softened'+ role = 'winner' if case['isSuccess'] else 'REJECTED-softened-candidate'+ baseline_path = out / (name + '.lbs.baseline.diagnostic.obj')+ candidate_path = out / (name + '.' + selected + '.diagnostic.obj')+ for is_heatmap in (False, True):+ scene = setup()+ a = obj_mesh(baseline_path, -.55)+ b = obj_mesh(candidate_path, .55)+ if is_heatmap:+ heatmap(a, rest, points(baseline_path))+ heatmap(b, rest, points(candidate_path))+ scene.display.shading.show_cavity = False+ scene.camera.data.ortho_scale = 2.4+ for view, eye in [('front', (0,6,1.4)), ('back', (0,-6,1.4))]:+ scene.camera.location = eye+ scene.camera.rotation_euler = (Vector((0,0,.9))-scene.camera.location).to_track_quat('-Z','Y').to_euler()+ filename = name + '.' + role + '.' + ('heatmap-' if is_heatmap else '') + view + '.png'+ render(scene, out / filename)+ rendered.append({'file':filename,'left':'X1 LBS baseline','right':selected,'rightStatus':role,+ 'sourceBaseline':'Unavailable; no source deformation was sampled',+ 'heatmap':'Blue compression, red stretch, grey near-preserved; log ratio saturation at 4x' if is_heatmap else None})+ (out / 'render-manifest.json').write_text(json.dumps(rendered,indent=2))+++if __name__ == '__main__':+ main()diff --git a/tools/Aetheris.Humanoid.X0/JudgmentQualification.cs b/tools/Aetheris.Humanoid.X0/JudgmentQualification.csnew file mode 100644index 00000000..82d617b4--- /dev/null+++ b/tools/Aetheris.Humanoid.X0/JudgmentQualification.cs@@ -0,0 +1,70 @@+using System.Diagnostics;+using System.Security.Cryptography;+using System.Text.Json;+using Aetheris.Humanoid;+using Aetheris.Kernel.Core.Math;++internal static class JudgmentQualification+{+ public static int Run(string input, string output)+ {+ var candidate = JsonSerializer.Deserialize<AntoniaAdoptionCandidate>(File.ReadAllText(input), HumanoidArtifactIO.JsonOptions)!;+ if (candidate.SourcePoseSurface.TopologyId != AntoniaSurfaceAdoption.CandidateTopologyId) throw new InvalidDataException("Expected Antonia adoption candidate.");+ var surface = candidate.SourcePoseSurface with { Vertices = candidate.SourcePoseSurface.Vertices.Select((v,i) => v with { Position = candidate.PreparedPositions[i] }).ToArray() };+ var skeleton = candidate.PreparedSkeleton;+ Directory.CreateDirectory(output);+ var cases = new List<object>(); var timings = new List<object>();+ foreach (var (name, joint) in Poses())+ {+ var solve = HumanoidKinematicSolver.Solve(skeleton, new(name, skeleton.SkeletonId, skeleton.RestPoseId, 0, [joint]));+ if (solve.Pose is not { } solved) throw new InvalidOperationException("Qualification pose did not solve: " + name);+ var watch = Stopwatch.StartNew();+ _ = HumanoidConstrainedSurface.Evaluate(surface, skeleton, 0, solved);+ var oldConstrainedPathMs = watch.Elapsed.TotalMilliseconds;+ watch.Restart();+ var context = HumanoidDeformationContext.Create(surface, skeleton, 0, solved, joint.Joint);+ var contextMs = watch.Elapsed.TotalMilliseconds;+ watch.Restart();+ var phases = new Dictionary<string, double>();+ var decision = HumanoidDeformationJudgment.Evaluate(context, DeformationPolicy.HipV1, recordTiming: (phase, ms) => phases[phase] = ms);+ var judgmentMs = watch.Elapsed.TotalMilliseconds;+ var trace = new+ {+ name, requested = joint, decision.PolicyVersion, decision.IsSuccess, decision.WinnerId, decision.RunnerUpId, decision.TieBroken,+ decision.Trace, metrics = decision.Candidates.Select(c => new { c.Candidate.Id, c.Candidate.Construction, c.Metrics }),+ decision.Diagnostics, decision.FinalSurfaceEvidence,+ patch = new { vertices = context.Vertices.Count, editableVertices = context.Vertices.Count(v => v.Attachment == SurfaceAttachmentClass.BlendedTransition),+ boundaryVertices = context.Vertices.Count(v => v.Boundary), faces = context.Faces.Count, edges = context.Edges.Count },+ maximumCenterResidualMm = solved.Residuals.Max(r => r.CenterMm), maximumLengthResidualMm = solved.Residuals.Max(r => r.LinkLengthMm)+ };+ File.WriteAllText(Path.Combine(output, name + ".trace.json"), JsonSerializer.Serialize(trace, HumanoidArtifactIO.JsonOptions));+ foreach (var c in decision.Candidates)+ Export(Path.Combine(output, name + "." + c.Candidate.Id + ".diagnostic.obj"), surface, context.AssembleDiagnostic(c.Candidate));+ var winnerPath = Path.Combine(output, name + ".winner.obj");+ if (decision.Positions is { } positions) Export(winnerPath, surface, positions);+ else if (File.Exists(winnerPath)) File.Delete(winnerPath);+ cases.Add(trace); timings.Add(new { name, oldConstrainedPathMs, contextMs, judgmentMs, phases });+ }+ File.WriteAllText(Path.Combine(output, "evidence.json"), JsonSerializer.Serialize(new+ {+ schema = "aetheris.humanoid.x3.judgment.v1", sourceCandidateSha256 = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(input))),+ surface.TopologyId, surface.ConnectivityHash, policy = DeformationPolicy.HipV1, candidateSpecs = HumanoidDeformationCandidates.Default,+ sourceBehavior = "Unavailable: original Poser CR2 audit is separate; X1 weights are Aetheris-generated, not source weights.", cases+ }, HumanoidArtifactIO.JsonOptions));+ File.WriteAllText(Path.Combine(output, "timings.json"), JsonSerializer.Serialize(timings, HumanoidArtifactIO.JsonOptions));+ Console.WriteLine($"Judgment qualification evidence: {Path.Combine(output, "evidence.json")}. Inspect winner and failure gates; command success is not milestone acceptance.");+ return 0;+ }+ private static IEnumerable<(string, AnatomicalJointRequest)> Poses()+ {+ foreach (var angle in new[] { 0d, 30, 45, 70, 90 }) yield return ($"hip-flexion-{angle}", new(HumanoidJointKind.LeftHip, angle));+ foreach (var angle in new[] { 0d, 15, 30, 45 }) yield return ($"hip-abduction-{angle}", new(HumanoidJointKind.LeftHip, AbductionDegrees: angle));+ }+ private static void Export(string path, HumanoidSurface surface, IReadOnlyList<Point3D> positions)+ {+ using var writer = new StreamWriter(path);+ writer.WriteLine("# NONCANONICAL Antonia X3 research; CC-BY-3.0 Olaf Delgado-Friedrichs; no endorsement; diagnostic candidates may fail.");+ foreach (var p in positions) writer.WriteLine(FormattableString.Invariant($"v {p.X:R} {p.Y:R} {p.Z:R}"));+ foreach (var f in surface.Faces) writer.WriteLine($"f {f.A+1} {f.B+1} {f.C+1}");+ }+}diff --git a/tools/Aetheris.Humanoid.X0/Program.cs b/tools/Aetheris.Humanoid.X0/Program.csindex ab506828..30fb6edf 100644--- a/tools/Aetheris.Humanoid.X0/Program.cs+++ b/tools/Aetheris.Humanoid.X0/Program.cs@@ -15,6 +15,7 @@ static int Run(string[] args)"generate"=>Generate(args[1..]),"adopt-antonia"=>AdoptAntonia(args[1..]),"constrained-antonia"=>ConstrainedQualification.Run(Required(args, "--input"), Value(args, "--out-dir") ?? Path.Combine("artifacts", "local", "humanoid-x2")),+ "judge-antonia"=>JudgmentQualification.Run(Required(args, "--input"), Value(args, "--out-dir") ?? Path.Combine("artifacts", "local", "humanoid-x3")),"inspect"=>Inspect(args[1..]),"morph"=>Morph(args[1..]),"pose"=>Pose(args[1..]),@@ -110,4 +111,4 @@ static string? Value(string[] args,string name){var i=Array.IndexOf(args,name);rstatic string Required(string[] args,string name)=>Value(args,name)??throw new ArgumentException($"Missing {name}.");static string Kebab(string s)=>string.Concat(s.Select((c,i)=>char.IsUpper(c)&&i>0?"-"+char.ToLowerInvariant(c):char.ToLowerInvariant(c).ToString()));static int Fail(string message){Console.Error.WriteLine(message);Usage();return 1;}-static void Usage()=>Console.WriteLine("Aetheris.Humanoid research tooling (X0 synthetic / X1 unpromoted / X2 constrained progression)\n constrained-antonia --input <candidate.json> [--out-dir <dir>]\n adopt-antonia --source <Antonia-1.2.obj> --notice <original-README> [--out-dir <dir>]\n generate [--out-dir <dir>]\n inspect --input <canonical.json>\n morph --input <canonical.json> --output <variant.json> [--height <mm>] [--arm-length <delta-mm>] [--leg-length <delta-mm>] [--shoulder-width <delta-mm>]\n pose --input <canonical.json> --output <posed.obj> [--left-elbow-deg <deg>] [--left-shoulder-deg <deg>] [--left-hip-deg <deg>] [--left-knee-deg <deg>]\n sweep --input <canonical.json> --output <evidence.json>");+static void Usage()=>Console.WriteLine("Aetheris.Humanoid research tooling (X0 synthetic / X1 unpromoted / X2 constrained / X3 judgment progression)\n judge-antonia --input <candidate.json> [--out-dir <dir>]\n constrained-antonia --input <candidate.json> [--out-dir <dir>]\n adopt-antonia --source <Antonia-1.2.obj> --notice <original-README> [--out-dir <dir>]\n generate [--out-dir <dir>]\n inspect --input <canonical.json>\n morph --input <canonical.json> --output <variant.json> [--height <mm>] [--arm-length <delta-mm>] [--leg-length <delta-mm>] [--shoulder-width <delta-mm>]\n pose --input <canonical.json> --output <posed.obj> [--left-elbow-deg <deg>] [--left-shoulder-deg <deg>] [--left-hip-deg <deg>] [--left-knee-deg <deg>]\n sweep --input <canonical.json> --output <evidence.json>");