knotflow Lessons PDF ↓ Deutsch Handbook Modeller ↗ Source

Lesson 3.11 · III Modelling

Constructing instead of computing

What this is about: whoever writes a model as text often works out by hand where a point has to lie for everything to fit: trigonometry, intersections, distances. A person at a drawing board works differently. They construct: A is here, B there, the line through B is at 43°, at C there is a right angle, and the circle touches all three sides. Where C lies and how big the circle is follows from that. This lesson builds a solver for it. It finds the unknowns from conditions and says when a construction fixes too little, says something twice, or contradicts itself.

What you should know first: the language (part II), records and functions as values (lesson 2.2). For the later part, Newton's method from lesson 3.6 helps.

A triangular plate given by its angles, with a hole in the inscribed circle

let a = (0, 0)
let b = (50, 0)
let s = solve({c: (25, 20), m: (22, 7), r: 5}, v => [
  angle_at(a, b, v.c) - 43,        // the angle at B
  angle_at(a, v.c, b) - 90,        // a right angle at C
  touches(v.m, v.r, a, b),         // the circle touches all three sides
  touches(v.m, v.r, b, v.c),
  touches(v.m, v.r, a, v.c)])

1. Conditions are equations

Every unknown is a number. A point in the plane has two (x and y), a circle three (centre and radius). Every condition is an equation that should become zero:

Condition Equation (should be 0)
the angle at B is 43° angle_at(a, b, c) - 43
C lies on the line through A and B on_line(c, a, b)
the circle (m, r) touches the line through A and B touches(m, r, a, b)
the lines a–b and c–d are at right angles perpendicular(a, b, c, d)
P and Q are 30 mm apart apart(p, q, 30)

These functions live in the prelude, written in the language itself. Whoever needs another condition writes it as a small function that gives zero when the condition holds.

solve(start, equations) takes two things:

It returns the record in which all the equations are zero.

2. What the starting values decide

A construction often has several solutions. The angle of 43° can point up or down, and three lines are touched not only by the circle inside but also by three circles outside. solve finds a solution near the starting values, mostly the nearest one. So a roughly right start (C above, the circle inside) says which one is meant. That goes for every unknown: whoever looks for a point on a curve gives its parameter t a fitting start too. CAD programs do the same, which is why a sketch there sometimes jumps into the other position when it is pulled far.

3. Too little, twice, contradictory

Like a CAD program, solve checks whether the construction is fixed exactly:

The warnings appear like all others: in the browser below the text, on the command line before the result.

4. Constructing and building on

What solve gives back are ordinary numbers and points, and you build on them as usual:

A param before the construction turns it into a slider: drag the angle at B, and solve solves the sketch again, and the plate follows.

A condition need not be about points and lines: any number that becomes 0 will do. A cup that holds 250 ml (250 000 mm³) needs a height that volume decides:

param ml = 250 in 100..500 "capacity [ml]"

// the inside of a cup: floor and wall, its height h unknown
fn inside(h) = chain([line((0, 0), (30, 0)), line((30, 0), (36, h))])

let s = solve({h: 80}, v => [volume(revolve(inside(v.h))) - ml * 1000])

export revolve(thicken(inside(s.h), -2))

volume measures the revolved inside with a flat face at the top, the level of a full cup, and solve finds h = 72.9 mm. That works because volume integrates the exact surface (Gauss quadrature over its knot spans): the result moves smoothly with h, and the derivative solve takes by small steps (section 5) is the true one. A volume counted from triangles would jump each time the tessellation gets another row, and the equation would never quite hold – for solve, measures must come from the exact geometry.

5. How the solver works

solve looks for the unknowns x for which all equations f(x) are zero, by the Levenberg–Marquardt method. That is Newton's method with a brake:

  1. At the current place, the derivatives of all equations with respect to all unknowns are found by small steps in each direction. That gives the matrix J: one row per equation, one column per unknown.
  2. A Newton step would assume the equations are linear nearby, and jump straight to where they would be zero. Far from the solution that is not true. So the step is damped: sometimes a small step downhill, sometimes a whole Newton step, depending on how well the last one went.
  3. If f gets smaller, the step counts and the next one may be bolder. Otherwise it gets smaller. The same happens when the equations are not even defined where the step lands (a logarithm of a negative number, the direction between two points that coincide).

A construction mixes lengths and angles, and sometimes sizes of a metre and of a hundredth of a millimetre. So that no equation vanishes beside the others, each is weighed by the length of its row of J at the start. What is made small is then how far each one is from holding, measured in the unknowns. "Holds" is decided per equation too: it may be off by 10⁻⁹ of what its unknowns move in it, curvature included: at a double root (two curves touching) the derivative is 0, and the equation still holds.

Then solve reads off J whether the equations fix the unknowns (section 3): how many independent things they say, what can still move and what is said twice. Section 8, a deeper look, shows how.

6. The whole set of conditions

CAD programs offer roughly the same conditions in sketches: coincident, on a line or a circle, midpoint, symmetric, concentric, horizontal, vertical, parallel, perpendicular, tangent, equal length, plus dimensions for distances and angles. Assemblies add mates between parts: fastened, hinge, slider, ball joint. The prelude has them all, each as a small function in the language; the list is in the handbook, chapter 9.

Two things need care when writing them.

A sign. The equation should pass through 0 at the solution, not just touch 0. Whoever writes a number's square instead of the number (x² should be 0) gets a solution that is only good to about the root of the tolerance, and no warning: near the solution the equation is flat, and solve stops as soon as its value is small enough. So on_line measures the distance with a sign (the z component of the cross product, that is: left or right of the line), and so does parallel. Absolute values like distance_to_line or angle_at do well where the solution is not at 0: the distance should be 30, the angle 43°. A related trap are jumps: angle_from jumps from 180° to −180°, so angle_from(…) - 180 never passes through 0. For that there is angle_is(a, b, c, d, w): it turns the first line by w and measures the angle that is left.

As many equations as it fixes. A condition may give several equations, as a point or a list. symmetric(p, q, a, b) is two: the middle of p and q lies on the axis, and p–q is at right angles to it. "Two axes parallel" (aligned) is two, not three: z₁ · x₂ = 0 and z₁ · y₂ = 0. A cross product z₁ × z₂ = 0 would have three components for two degrees of freedom, and solve would report one of them as redundant. A special case are points drawn in the plane and compared with points in space: their z equation is always 0 and says nothing. So solve does not count equations that depend on no unknown and hold as redundant.

Assemblies. A part's placement is six unknowns: a translation and a rotation, written as a vector whose direction is the axis and whose length is the angle (section 8). Rotations are given between −180° and 180°. A mate takes two connectors (frames on the parts) and gives as many equations as the freedom it takes: the hinge five (the same origin: three, parallel axes: two), so one turn is left. How much movement an assembly has left, solve reads off the rank of J, as for a sketch.

The mates say that axes are parallel, not which way they point. "Fastened" therefore has four solutions: the one meant, and three where the part is turned half round one of its axes. Which one solve takes is again decided by the start, like "flip" in CAD programs. To be sure, check afterwards with assert(dot(c1.x, c2.x) > 0, …).

7. Limits

8. A deeper look: Levenberg–Marquardt, rank and rotations

Levenberg–Marquardt. The damped step of section 5 solves (JᵀJ + λ·D) δ = −Jᵀf. D is the diagonal of JᵀJ, so each unknown is damped in its own measure, but at least a thousandth as much as the strongest one: otherwise an unknown that hardly moves the equations would take nearly all of the step. With a large λ it is a small step downhill, with a small λ a Newton step. If a step counts, λ goes down, otherwise it grows. The same happens when the equations are not even defined where the step lands (a logarithm of a negative number, the direction between two points that coincide).

Rank and degrees of freedom. The check of section 3 reads everything off J where the search ended. First, every row and every column of J is brought to length 1; otherwise an angle beside a cubic metre would look like nothing and count as a degree of freedom.

The Jacobi method finds the eigenvalues: it rotates the symmetric matrix until it is diagonal. It needs only square roots, no trigonometric functions. So the browser and the command line compute the same, bit for bit (lesson 1.4).

Rotations as a vector. A part's rotation is a vector w whose direction is the axis and whose length is the angle. Rodrigues' formula turns a vector v by it:

v' = v cos α + (k × v) sin α + k (k · v)(1 − cos α), with α = |w| and k = w / α.

For small angles this form has no special position like Euler angles, where two axes can coincide and a degree of freedom seems to vanish. At α = 0, k is undefined, but the rotation is the identity and the derivatives are fine. Not so at α = 360°: there the rotation is the identity too, but the direction of w changes nothing any more, and solve would report two degrees of freedom that are none. So rotations are given between −180° and 180°.

Try it yourself

cargo run --release -p kf -- render examples/construction.kf -o out/plate.png
cargo run --release -p kf -- render examples/construction.kf -D at_b=70 -o out/plate.stl
  1. Leave out the right angle at C in construction.kf. What does the warning say, and where does C move when you drag the angle at B?
  2. Give the angle at A as well, once fitting (90° − the angle at B) and once not. What do the messages say?
  3. Put the circle's starting value outside the triangle. Which circle does solve find now?
  4. Write a condition of your own: the circle should pass through the point (10, 5).
  5. In linkage.kf, set the coupler to 40 and the rocker to 30. Now the crank can no longer turn all the way round. What does solve report? Why does the model fail at every crank angle, not only at those that do not work? (Hint: the coupler curve.)