Commit a3d5346d2c

a3d5346d2cfd2a50ded18c1076105e9267f30484

parent: 3a50925562

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-22 20:37 UTC

Hold a multi-degree-of-freedom step's spare freedom near its linear angles

Ref #7

Layout: unified · split

Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift +91 −13
@@ -418,9 +418,11 @@ func sheetExtent(_ file: FoldFile) -> Double {
418/// Holds the driver (the first axis in `record`) linear on its window and solves the other axes 418/// Holds the driver (the first axis in `record`) linear on its window and solves the other axes
419/// on a loop's cycle, the tree path between the two sides of a loop crease, so the loops stay 419/// on a loop's cycle, the tree path between the two sides of a loop crease, so the loops stay
420/// closed: damped Gauss–Newton on the gap between vertex copies, continued along the window from 420/// closed: damped Gauss–Newton on the gap between vertex copies, continued along the window from
421/// the previous samples. Each solved axis takes the driver's window and a curve of 257 samples, or 421/// the previous samples. Where closure leaves the solved axes free, each sample is then moved
422/// none when it is linear to within 1e-9°; the last sample is the end angle exactly. Axes on no 422/// toward the linear angles within those free directions (`LoopKinematics.settle`). Each solved
423/// cycle stay linear on their own windows. 423/// axis takes the driver's window and a curve of 257 samples, or none when it is linear to within
424/// 1e-9°; the last sample is the end angle exactly. Axes on no cycle stay linear on their own
425/// windows.
424/// 426///
425/// - Throws: `solvedAxisWindowConflict` when a solved axis is scripted on another window. 427/// - Throws: `solvedAxisWindowConflict` when a solved axis is scripted on another window.
426func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, loops: [Int], 428func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, loops: [Int],
@@ -451,6 +453,7 @@ func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, loops: [Int],
451 } 453 }
452 guess[driver] = linear(step.axes[driver], u) 454 guess[driver] = linear(step.axes[driver], u)
453 guard kinematics.solve(&guess, free: free) <= tolerance else { throw CompileError.noRigidMotion(step: n) } 455 guard kinematics.solve(&guess, free: free) <= tolerance else { throw CompileError.noRigidMotion(step: n) }
456 kinematics.settle(&guess, toward: step.axes.map { linear($0, u) }, free: free, tolerance: tolerance)
454 samples.append(guess) 457 samples.append(guess)
455 } 458 }
456 459
@@ -650,16 +653,7 @@ struct LoopKinematics {
650 var cost = r.reduce(0) { $0 + $1 * $1 } 653 var cost = r.reduce(0) { $0 + $1 * $1 }
651 for _ in 0..<iterations { 654 for _ in 0..<iterations {
652 if cost < 1e-26 { break } 655 if cost < 1e-26 { break }
653 let h = 1e-6 656 let jacobian = self.jacobian(angles, free: free)
654 var jacobian = Array(repeating: [Double](repeating: 0, count: free.count), count: r.count)
655 for (k, a) in free.enumerated() {
656 var probe = angles
657 probe[a] += h
658 let plus = residual(probe)
659 probe[a] -= 2 * h
660 let minus = residual(probe)
661 for i in r.indices { jacobian[i][k] = (plus[i] - minus[i]) / (2 * h) }
662 }
663 var improved = false 657 var improved = false
664 for _ in 0..<20 { 658 for _ in 0..<20 {
665 var normal = Array(repeating: [Double](repeating: 0, count: free.count), count: free.count) 659 var normal = Array(repeating: [Double](repeating: 0, count: free.count), count: free.count)
@@ -693,8 +687,92 @@ struct LoopKinematics {
693 } 687 }
694 return gap(angles) 688 return gap(angles)
695 } 689 }
690
691 /// The residual's derivatives by the angles in `free`, by central differences: one row per
692 /// residual entry, one column per free axis.
693 func jacobian(_ angles: [Double], free: [Int]) -> [[Double]] {
694 let h = 1e-6
695 var jacobian: [[Double]] = []
696 for (k, a) in free.enumerated() {
697 var probe = angles
698 probe[a] += h
699 let plus = residual(probe)
700 probe[a] -= 2 * h
701 let minus = residual(probe)
702 if k == 0 { jacobian = Array(repeating: [Double](repeating: 0, count: free.count), count: plus.count) }
703 for i in plus.indices { jacobian[i][k] = (plus[i] - minus[i]) / (2 * h) }
704 }
705 return jacobian
706 }
707
708 /// Moves the angles in `free` toward `target` within the null space of the closure Jacobian J,
709 /// by δ = ε(JᵀJ + εI)⁻¹(target − angles) three times, then solves again. ε is 1e-6 of JᵀJ's
710 /// largest eigenvalue, so δ takes the null space's part of the difference and almost none of
711 /// the rest. When JᵀJ has no eigenvalue below 1e-10 of its largest (closure fixes every free
712 /// axis, as at a vertex with one degree of freedom) or the solve does not close to `tolerance`,
713 /// `angles` is left as it was.
714 func settle(_ angles: inout [Double], toward target: [Double], free: [Int], tolerance: Double) {
715 var x = angles
716 for _ in 0..<3 {
717 let j = jacobian(x, free: free)
718 var normal = Array(repeating: [Double](repeating: 0, count: free.count), count: free.count)
719 for row in j {
720 for a in free.indices {
721 for b in free.indices { normal[a][b] += row[a] * row[b] }
722 }
723 }
724 let (values, vectors) = symmetricEigen(normal)
725 guard let largest = values.max(), largest > 0, values.contains(where: { $0 < 1e-10 * largest }) else { return }
726 let epsilon = 1e-6 * largest
727 let difference = free.map { target[$0] - x[$0] }
728 for (value, vector) in zip(values, vectors) {
729 let along = zip(vector, difference).reduce(0) { $0 + $1.0 * $1.1 } * epsilon / (value + epsilon)
730 for (k, a) in free.enumerated() { x[a] += along * vector[k] }
731 }
732 }
733 guard solve(&x, free: free) <= tolerance else { return }
734 angles = x
735 }
696} 736}
697 737
738/// The eigenvalues of a symmetric matrix and a unit eigenvector for each, by cyclic Jacobi
739/// rotations.
740private func symmetricEigen(_ matrix: [[Double]]) -> (values: [Double], vectors: [[Double]]) {
741 let n = matrix.count
742 var a = matrix
743 var v = (0..<n).map { i in (0..<n).map { $0 == i ? 1.0 : 0.0 } }
744 for _ in 0..<100 {
745 var off = 0.0
746 for p in 0..<n { for q in (p + 1)..<n { off += a[p][q] * a[p][q] } }
747 let scale = (0..<n).reduce(0) { $0 + a[$1][$1] * a[$1][$1] }
748 if off <= 1e-30 * scale { break }
749 for p in 0..<n {
750 for q in (p + 1)..<n where a[p][q] != 0 {
751 let theta = (a[q][q] - a[p][p]) / (2 * a[p][q])
752 let t = (theta >= 0 ? 1.0 : -1.0) / (abs(theta) + (theta * theta + 1).squareRoot())
753 let c = 1 / (t * t + 1).squareRoot(), s = t * c
754 for k in 0..<n {
755 let (akp, akq) = (a[k][p], a[k][q])
756 a[k][p] = c * akp - s * akq
757 a[k][q] = s * akp + c * akq
758 }
759 for k in 0..<n {
760 let (apk, aqk) = (a[p][k], a[q][k])
761 a[p][k] = c * apk - s * aqk
762 a[q][k] = s * apk + c * aqk
763 }
764 for k in 0..<n {
765 let (vkp, vkq) = (v[k][p], v[k][q])
766 v[k][p] = c * vkp - s * vkq
767 v[k][q] = s * vkp + c * vkq
768 }
769 }
770 }
771 }
772 return ((0..<n).map { a[$0][$0] }, (0..<n).map { i in (0..<n).map { v[$0][i] } })
773}
774
775
698/// Gaussian elimination with partial pivoting; nil when `a` is singular. 776/// Gaussian elimination with partial pivoting; nil when `a` is singular.
699private func solveLinear(_ a: [[Double]], _ b: [Double]) -> [Double]? { 777private func solveLinear(_ a: [[Double]], _ b: [Double]) -> [Double]? {
700 var m = a, x = b 778 var m = a, x = b
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/preliminary-cp.fold added +11
@@ -0,0 +1,11 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Preliminary base",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [2, 1], [2, 2], [1, 2], [0, 2], [0, 1], [1, 1]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0],
8 [8, 1], [8, 2], [8, 3], [8, 5], [8, 6], [8, 7]],
9 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "M", "V", "M", "M", "V", "M"],
10 "faces_vertices": [[0, 1, 8, 7], [1, 2, 8], [2, 3, 8], [8, 3, 4, 5], [8, 5, 6], [7, 8, 6]]
11}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/preliminary.foldscript added +14
@@ -0,0 +1,14 @@
1{
2 "creasePattern": "preliminary-cp.fold",
3 "title": "Preliminary base",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Collapse into a preliminary base: bring the left, right and top corners down to the bottom corner along the creases.",
8 "creases": [[[1, 1], [1, 0]], [[1, 1], [2, 0]], [[1, 1], [2, 1]], [[1, 1], [1, 2]], [[1, 1], [0, 2]], [[1, 1], [0, 1]]],
9 "movingSide": [[1.4, 0.4], [1.8, 0.8], [1.6, 1.6], [0.8, 1.8], [0.4, 1.4]],
10 "angles": [-180, 180, -180, -180, 180, -180],
11 "viewpoint": {"eye": [0, 0, 1], "up": [1, 1, 0]}
12 }
13 ]
14}
Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift +10
@@ -1,4 +1,5 @@
1import Foundation 1import Foundation
2import simd
2import Testing 3import Testing
3import FoldCompiler 4import FoldCompiler
4import FoldFormat 5import FoldFormat
@@ -57,6 +58,15 @@ func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) th
57 } 58 }
58} 59}
59 60
61@Test func aDegreeSixVertexCollapsesToAPreliminaryBase() throws {
62 // four midlines and two diagonal halves: two degrees of freedom beyond the driver, held near
63 // their linear angles; the three moving corners land on the still one, flat
64 let out = try compiled("preliminary")
65 let last = out.frames[1].verticesCoords
66 for v in [2, 4, 6] { #expect(simd_distance(last[v], last[0]) < 1e-9, "corner \(v)") }
67 #expect(last.allSatisfy { abs($0.z) < 1e-9 })
68}
69
60@Test func anUnresolvedCreaseNamesItsStepAndReference() { 70@Test func anUnresolvedCreaseNamesItsStepAndReference() {
61 #expect(throws: CompileError.unresolvedCrease(step: 2, crease: .betweenVertices(SIMD2(0, 1), SIMD2(1, 1)))) { 71 #expect(throws: CompileError.unresolvedCrease(step: 2, crease: .betweenVertices(SIMD2(0, 1), SIMD2(1, 1)))) {
62 try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")), 72 try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")),