Algorithm Search⌘K

Techniquecore

Vector loop closure equation

Also called loop closure equation, Raven's method.

Writes a closed linkage as a sum of link vectors equal to zero, solves the scalar equations for the unknown angles, and differentiates them for velocities.

The vector loop closure equation describes a closed kinematic chain as a cycle of link vectors whose sum is zero. Each link is a vector of fixed length and unknown angle, so the loop gives two scalar equations per planar loop, and these fix as many unknown angles as there are equations once the input angles are given. Its time derivatives are linear in the velocities and the accelerations, so after the position step the rest of the analysis is linear algebra. Raven proposed this way of writing the analysis in 1958, and it is the standard first step of position analysis in the textbooks.

This page uses the notation of the four-bar linkage: the ground dd runs from O2=(0,0)O_2 = (0, 0) to O4=(d,0)O_4 = (d, 0), the input (crank) aa runs from O2O_2 to the pin AA, the coupler bb runs from AA to the pin BB, and the output cc runs from O4O_4 to BB. The angles θ2,θ3,θ4\theta_2, \theta_3, \theta_4 of aa, bb, cc are measured counterclockwise from the ground line. With complex numbers for plane vectors, the loop is

aeiθ2+beiθ3−ceiθ4−d=0.a e^{i\theta_2} + b e^{i\theta_3} - c e^{i\theta_4} - d = 0.

In plain words

Walk around a closed linkage from one fixed pivot, along each link in turn, and you come back to where you started. So the arrows of the links add up to nothing. Each arrow has a known length and an unknown direction. Split the sum into its sideways part and its up-and-down part, and you get two equations for each closed loop.

If you know the angle of the input link, you can solve these equations for the other angles. A loop of four bars usually gives two answers, because the linkage can be put together in two mirror-image ways. To get speeds, take the rate of change of the same equations. The unknown speeds then appear in a simple linear system, which has no answer only when two links are in line.

When it applies

  • The mechanism is a closed chain of rigid links with lower pairs (pins and slides), and you know its input angles or input slide positions. Count the inputs with the Grübler formula, which says how many are needed. The page on degrees of freedom analysis gives the count and its exceptions.
  • The question is about position, velocity or acceleration: where is each link, how fast does it turn, and where does a point on the coupler go.
  • The number of independent loops is L=j−n+1L = j - n + 1 for nn links and jj joints. A four-bar or a slider-crank has one loop and two scalar equations. A six-bar has two loops and four equations.
  • An open chain, such as a serial robot arm, has no loop. Its positions come from forward kinematics, a product of link transforms, and need no equation solving. Loop closure is the step that makes a chain with a cycle harder than an open one.

The template

The holes of the template are the loop (which vectors, which unknowns), the elimination that leaves one unknown, and the rule that names the branch. The block below fills them for the four-bar. The slider-crank mechanism fills them in the same way with xx as one unknown.

  1. FOURBAR-POSITIONS(a, b, c, d, θ2)
  2. 1K1 ← d/a; K2 ← d/c; K3 ← (a² − b² + c² + d²)/(2ac) ▷ hole 1: the loop
  3. 2A ← cos θ2 − K1 − K2 cos θ2 + K3; B ← −2 sin θ2; C ← K1 − (K2 + 1) cos θ2 + K3
  4. 3Δ ← B² − 4AC ▷ hole 2: eliminate θ3
  5. 4if Δ < 0 then return ∅ ▷ the loop does not close at θ2
  6. 5for each root t of A t² + B t + C = 0, with t = ∞ when A = 0:
  7. 6θ4 ← 2 arctan t; θ3 ← atan2(c sin θ4 − a sin θ2, d + c cos θ4 − a cos θ2)
  8. 7σ ← +1 if B is left of the directed line from A to O4, else −1 ▷ hole 3: the branch
  9. 8return the triples (θ3, θ4, σ), with σ = +1 first
  10. FOURBAR-VELOCITIES(θ2, θ3, θ4, ω2)
  11. 9solve [−b sin θ3, c sin θ4; b cos θ3, −c cos θ4] (ω3, ω4) = (a ω2 sin θ2, −a ω2 cos θ2)

Hole 1, the loop. Split the loop equation into its real and imaginary parts:

acos⁡θ2+bcos⁡θ3−ccos⁡θ4−d=0,asin⁡θ2+bsin⁡θ3−csin⁡θ4=0.a\cos\theta_2 + b\cos\theta_3 - c\cos\theta_4 - d = 0, \qquad a\sin\theta_2 + b\sin\theta_3 - c\sin\theta_4 = 0.

Hole 2, the elimination. Put the coupler terms alone on one side, bcos⁡θ3=ccos⁡θ4+d−acos⁡θ2b\cos\theta_3 = c\cos\theta_4 + d - a\cos\theta_2 and bsin⁡θ3=csin⁡θ4−asin⁡θ2b\sin\theta_3 = c\sin\theta_4 - a\sin\theta_2, then square and add. The left side becomes b2b^2, and θ3\theta_3 is gone:

b2=a2+c2+d2+2cdcos⁡θ4−2adcos⁡θ2−2accos⁡(θ2−θ4).b^2 = a^2 + c^2 + d^2 + 2cd\cos\theta_4 - 2ad\cos\theta_2 - 2ac\cos(\theta_2 - \theta_4).

Divide by 2ac2ac to get the Freudenstein equation K1cos⁡θ4−K2cos⁡θ2+K3=cos⁡(θ2−θ4)K_1\cos\theta_4 - K_2\cos\theta_2 + K_3 = \cos(\theta_2 - \theta_4) with the constants of line L1. Expand cos⁡(θ2−θ4)\cos(\theta_2 - \theta_4) and collect the terms in θ4\theta_4:

Pcos⁡θ4+Qsin⁡θ4+R=0,P=K1−cos⁡θ2,Q=−sin⁡θ2,R=K3−K2cos⁡θ2.P\cos\theta_4 + Q\sin\theta_4 + R = 0, \quad P = K_1 - \cos\theta_2, \quad Q = -\sin\theta_2, \quad R = K_3 - K_2\cos\theta_2.

With t=tan⁡(θ4/2)t = \tan(\theta_4/2), cos⁡θ4=(1−t2)/(1+t2)\cos\theta_4 = (1 - t^2)/(1 + t^2) and sin⁡θ4=2t/(1+t2)\sin\theta_4 = 2t/(1 + t^2). Multiply by 1+t21 + t^2 to get (R−P)t2+2Qt+(R+P)=0(R - P)t^2 + 2Qt + (R + P) = 0, which is the quadratic At2+Bt+C=0At^2 + Bt + C = 0 of line L2, with discriminant Δ=4(P2+Q2−R2)\Delta = 4(P^2 + Q^2 - R^2).

Hole 3, the branch. Line L7 names each solution by the side of the diagonal AO4AO_4 on which BB lies. When the crank is above the ground line, the solution with σ=+1\sigma = +1 has O2O_2 and BB on opposite sides of AO4AO_4, so the links do not cross. This is the open assembly. The solution with σ=−1\sigma = -1 is the crossed assembly.

Why the quadratic gives exactly the two assemblies

Fix θ2\theta_2, and assume a,b,c,d>0a, b, c, d > 0 and A≠O4A \ne O_4.

  1. An assembly is the same as a solution θ4\theta_4 of the Freudenstein equation. The equation of hole 2 says ∣ceiθ4+d−aeiθ2∣=b|c e^{i\theta_4} + d - a e^{i\theta_2}| = b. Given a solution θ4\theta_4, the vector ceiθ4+d−aeiθ2c e^{i\theta_4} + d - a e^{i\theta_2} has length b>0b > 0, so it is beiθ3b e^{i\theta_3} for exactly one θ3\theta_3 in (−π,π](-\pi, \pi], and this is the atan2 of line L6. The pair satisfies the loop. Conversely, every assembly gives a solution, as the derivation shows.
  2. The solutions θ4\theta_4 match the roots tt one to one. The map θ4↦tan⁡(θ4/2)\theta_4 \mapsto \tan(\theta_4/2) is a bijection from (−π,π)(-\pi, \pi) onto the real line, and θ4=π\theta_4 = \pi is the root t=∞t = \infty. That value solves Pcos⁡θ4+Qsin⁡θ4+R=0P\cos\theta_4 + Q\sin\theta_4 + R = 0 exactly when R−P=0R - P = 0, that is when A=0A = 0, and then the quadratic drops to degree one. So the solutions in (−π,π](-\pi, \pi] are the finite roots, plus θ4=π\theta_4 = \pi when A=0A = 0.
  3. There are 0, 1 or 2 solutions, as Δ<0\Delta < 0, =0= 0, >0> 0. Since A≠O4A \ne O_4, (P,Q)≠(0,0)(P, Q) \ne (0, 0), and the equation says that the unit vector (cos⁡θ4,sin⁡θ4)(\cos\theta_4, \sin\theta_4) lies on the line Px+Qy+R=0Px + Qy + R = 0. That line is at distance ∣R∣/P2+Q2|R|/\sqrt{P^2 + Q^2} from the origin, so it meets the unit circle twice, once or never as P2+Q2−R2P^2 + Q^2 - R^2 is positive, zero or negative.
  4. The two assemblies are mirror images. Each BB lies on the circle of radius bb about AA and on the circle of radius cc about O4O_4. Two circles with different centers meet in two points that are mirror images in the line of centers AO4AO_4, or in one point on that line. So the two solutions have opposite σ\sigma, and Δ=0\Delta = 0 exactly when BB is on the line AO4AO_4, which means that the coupler and the output are in line. That is a toggle position.
  5. The branch does not change between toggles. As θ2\theta_2 moves, the roots move continuously. The sign σ\sigma of a root can change only when BB crosses the line AO4AO_4, and by step 4 that happens only at a toggle. So on an interval of θ2\theta_2 without a toggle, following one root keeps one value of σ\sigma. ■\blacksquare

When A=O4A = O_4, which needs a=da = d and θ2=0\theta_2 = 0, the equation is R=0R = 0: if b=cb = c every θ4\theta_4 is an assembly and the output turns freely, and otherwise there is none.

Velocity

Take the time derivative of the loop with ωk=θ˙k\omega_k = \dot\theta_k: iaω2eiθ2+ibω3eiθ3−icω4eiθ4=0i a\omega_2 e^{i\theta_2} + i b\omega_3 e^{i\theta_3} - i c\omega_4 e^{i\theta_4} = 0. Its real and imaginary parts are the system of line L9. The determinant is bcsin⁡(θ3−θ4)bc\sin(\theta_3 - \theta_4), and Cramer's rule gives

ω3=aω2sin⁡(θ4−θ2)bsin⁡(θ3−θ4),ω4=aω2sin⁡(θ2−θ3)csin⁡(θ4−θ3).\omega_3 = \frac{a\omega_2\sin(\theta_4 - \theta_2)}{b\sin(\theta_3 - \theta_4)}, \qquad \omega_4 = \frac{a\omega_2\sin(\theta_2 - \theta_3)}{c\sin(\theta_4 - \theta_3)}.

The system has no unique solution exactly at a toggle, the case Δ=0\Delta = 0 of step 4. A second derivative gives the accelerations from a system with the same matrix and a new right side.

Cost and accuracy

One position solve is a fixed number of operations, and so is each velocity solve. The quadratic should be solved in the stable form q=−12(B+sign⁡(B)Δ)q = -\tfrac12(B + \operatorname{sign}(B)\sqrt\Delta), t1=q/At_1 = q/A, t2=C/qt_2 = C/q, as on the quadratic formula page. The implementation keeps the roots as angles, θ4/2=atan2⁡(q,A)\theta_4/2 = \operatorname{atan2}(q, A) and atan2⁡(C,q)\operatorname{atan2}(C, q), so that A=0A = 0 needs no special case. Near a toggle the two roots meet and the position is ill-conditioned: a small change of a length moves θ4\theta_4 by about the square root of that change.

Classic examples

A crank-rocker, both branches. Take a=2a = 2, b=7b = 7, c=5c = 5, d=6d = 6, a crank-rocker by the Grashof condition. Then K1=3K_1 = 3, K2=6/5K_2 = 6/5, K3=4/5K_3 = 4/5. At θ2=0\theta_2 = 0, A=−12/5A = -12/5, B=0B = 0, C=8/5C = 8/5, so t2=2/3t^2 = 2/3, cos⁡θ4=1/5\cos\theta_4 = 1/5, and the open assembly has B=(7,26)B = (7, 2\sqrt6) and θ4=78.463°\theta_4 = 78.463°. At θ2=180°\theta_2 = 180°, A=−2A = -2, B=0B = 0, C=6C = 6, so t=±3t = \pm\sqrt3 and θ4=±120°\theta_4 = \pm 120° exactly. In between (ω2=1\omega_2 = 1 rad/s):

θ2\theta_2 AA BB CC open θ3\theta_3, θ4\theta_4 ω3\omega_3, ω4\omega_4 (open) crossed θ3\theta_3, θ4\theta_4
0° −2.4 0 1.6 44.415°, 78.463° −0.5, −0.5 315.585°, 281.537°
60° −2.3 −1.732 2.7 26.311°, 75.229° −0.0996, 0.2944 295.476°, 246.558°
90° −2.2 −2 3.8 25.278°, 86.219° 0.0216, 0.4138 297.852°, 236.911°
120° −2.1 −1.732 4.9 27.268°, 98.950° 0.1081, 0.4209 304.936°, 233.254°
180° −2 0 6 38.213°, 120° 0.25, 0.25 321.787°, 240°

At θ2=90°\theta_2 = 90°, Δ=37.44\Delta = 37.44 and the roots are t=0.936t = 0.936 (open) and t=−1.845t = -1.845 (crossed). The angle between coupler and output is the transmission angle, θ4−θ3\theta_4 - \theta_3 on the open branch, here from 34.05° at θ2=0\theta_2 = 0 to 81.79° at θ2=180°\theta_2 = 180°. The tests of this page check these values, a residual of the loop below 10−910^{-9} on thousands of random linkages, and the velocities against finite differences.

The slider-crank. For the slider-crank mechanism with offset ee, the slider pin is B=(x,e)B = (x, e) and the loop is aeiθ2+beiθ3−x−ie=0a e^{i\theta_2} + b e^{i\theta_3} - x - ie = 0. The imaginary part gives sin⁡θ3=(e−asin⁡θ2)/b\sin\theta_3 = (e - a\sin\theta_2)/b directly, so no half-angle step is needed, and x=acos⁡θ2±b2−(e−asin⁡θ2)2x = a\cos\theta_2 \pm \sqrt{b^2 - (e - a\sin\theta_2)^2}. The two signs are the two branches, with the slider on either side of the crank pin. The velocity is ω3=−aω2cos⁡θ2/(bcos⁡θ3)\omega_3 = -a\omega_2\cos\theta_2/(b\cos\theta_3) and x˙=−aω2sin⁡θ2−bω3sin⁡θ3\dot x = -a\omega_2\sin\theta_2 - b\omega_3\sin\theta_3.

Function generation. The elimination of hole 2, read the other way, is the Freudenstein equation. There the angles are given and the lengths are unknown, and the equation is linear in K1,K2,K3K_1, K_2, K_3.

The Grashof class by a sweep. Sweep θ2\theta_2 over a full turn and test Δ≥0\Delta \ge 0 at each step. The input turns fully exactly when the loop closes for every θ2\theta_2. The tests check this sweep against the inequality of the Grashof condition for every joint of 500 random integer linkages.

Six-bars. A Watt or Stephenson six-bar has two independent loops. Choose them so that one loop holds the input and only one other unknown pair, solve that loop as a four-bar, and then solve the second loop with the now known angles. Where no such order exists, solve the four scalar equations together with Newton's method for systems.

A planar two-link arm. The inverse kinematics of a planar 2R arm is the loop closure of the triangle made by the two links and the line to the target. The elbow-up and elbow-down solutions are its two branches.

Variations

  • Vector components instead of complex numbers. The same equations follow from ∑rk(cos⁡θk,sin⁡θk)=0\sum r_k(\cos\theta_k, \sin\theta_k) = 0. The complex form makes the derivatives short, since ddteiθ=iωeiθ\frac{d}{dt}e^{i\theta} = i\omega e^{i\theta}.
  • Other unknowns. The unknowns can be any two of the angles and slide lengths of a loop. An inverted slider-crank has a slide of variable length along a link that turns, and the loop is solved for that length and an angle in the same way.
  • Numerical solution. For many loops, or for spatial loops, solve the loop equations with Newton's method from the last position, as Norton (Section 4.14) does for planar loops. A spatial loop is written as the product of 4×44 \times 4 link transforms equal to the identity. This gives only the branch near the start point. All branches need homotopy continuation or elimination with a resultant.
  • Points on a link. After the angles are known, a coupler point is aeiθ2+pei(θ3+δ)a e^{i\theta_2} + p e^{i(\theta_3 + \delta)} for its distance pp and angle δ\delta from AA. The set of these points is the coupler curve.

Pitfalls

  • arctan instead of atan2. θ3=arctan⁡((csin⁡θ4−asin⁡θ2)/(d+ccos⁡θ4−acos⁡θ2))\theta_3 = \arctan\big((c\sin\theta_4 - a\sin\theta_2)/(d + c\cos\theta_4 - a\cos\theta_2)\big) loses the quadrant, and the wrong value still looks reasonable. Use atan2 with the two parts, as in line L6.
  • Branch jumps in a sweep. Two roots taken in a fixed order (first the minus sign, then the plus sign) can swap when AA changes sign, and an animation then jumps from one assembly to the other. Name each root by σ\sigma as in line L7, or follow the root that is nearest to the last position.
  • Division by A. The textbook form t=(−B±Δ)/(2A)t = (-B \pm \sqrt\Delta)/(2A) fails when A=0A = 0 (θ4=π\theta_4 = \pi) and loses digits when ∣A∣|A| is small. Use the stable form or the angle form above.
  • Toggle positions. At Δ=0\Delta = 0 the velocity system is singular. Code that divides by sin⁡(θ3−θ4)\sin(\theta_3 - \theta_4) there returns a huge number. The implementation raises an error instead.
  • A small residual is not a good answer. Near a toggle many angles give a small residual. Check Δ\Delta against a tolerance relative to the size of AA, BB and CC, as line L4 does, and report the toggle.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

vector_loop_closure.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vector-loop-closure/. The authors are listed in prov/V3P14V.jsonl.

"""Vector loop closure for the planar four-bar and the offset slider-crank.

Four-bar notation (Norton): ground d from O2 = (0, 0) to O4 = (d, 0), input
(crank) a from O2 to the crank pin A, coupler b from A to B, output c from O4
to B. All angles are measured counterclockwise from the +x axis, which is the
ground line. The loop equation is

    a e^(i theta2) + b e^(i theta3) - c e^(i theta4) - d = 0.

For a given theta2 the half-angle substitution t = tan(theta4 / 2) turns the
loop into A t^2 + B t + C = 0. Its two roots are the two assemblies. The
branch of an assembly is +1 when B lies to the left of the directed line from
A to O4 and -1 when it lies to the right. With the ground on the +x axis and
the crank above it, branch +1 is the open assembly and -1 the crossed one.

Slider-crank: crank a from O2 = (0, 0) to A, connecting rod b from A to the
slider pin B = (x, e), and the slider moves on the line y = e (offset e). The
loop is a e^(i theta2) + b e^(i theta3) - x - i e = 0. Branch +1 has the
slider pin to the right of A (x > a cos theta2), branch -1 to the left.

Floats are used for the angles. The Grashof tests use the link lengths as
given, so they are exact for int or Fraction lengths.
"""

import math

TOL = 1e-12


def freudenstein_k(a, b, c, d):
    """The constants K1, K2, K3 of the four-bar."""
    return d / a, d / c, (a * a - b * b + c * c + d * d) / (2 * a * c)


def _branch(a, c, d, theta2, theta4):
    """+1 if B is left of the directed line A -> O4, -1 if right, 0 if on it."""
    ax, ay = a * math.cos(theta2), a * math.sin(theta2)
    bx, by = d + c * math.cos(theta4), c * math.sin(theta4)
    cross = (d - ax) * (by - ay) - (0.0 - ay) * (bx - ax)
    scale = (abs(a) + abs(c) + abs(d)) ** 2
    if abs(cross) <= 1e-12 * scale:
        return 0
    return 1 if cross > 0 else -1


def fourbar_positions(a, b, c, d, theta2):
    """The assemblies of the four-bar at the input angle theta2.

    Returns a list of (theta3, theta4, branch), with the open assembly
    (branch +1) first. The list is empty when the loop cannot close, and it
    holds one entry when the two assemblies coincide (a toggle position).
    """
    k1, k2, k3 = freudenstein_k(a, b, c, d)  # @line L1
    c2, s2 = math.cos(theta2), math.sin(theta2)
    qa = c2 - k1 - k2 * c2 + k3  # @line L2
    qb = -2.0 * s2
    qc = k1 - (k2 + 1.0) * c2 + k3
    disc = qb * qb - 4.0 * qa * qc  # @line L3
    scale = (abs(qa) + abs(qb) + abs(qc)) ** 2 + 1.0
    if disc < -TOL * scale:  # @line L4
        return []
    # stable roots of qa t^2 + qb t + qc = 0, kept as angles so that t = inf
    # (theta4 = pi, when qa = 0) needs no special case
    if disc <= TOL * scale:
        halves = [math.atan2(-qb, 2.0 * qa)]  # a double root: a toggle position
    else:
        r = math.sqrt(disc)
        q = -0.5 * (qb + (r if qb >= 0 else -r))
        halves = [math.atan2(q, qa), math.atan2(qc, q)]  # @line L5
    out = []
    for h in halves:
        t4 = 2.0 * h
        t3 = math.atan2(c * math.sin(t4) - a * s2, d + c * math.cos(t4) - a * c2)  # @line L6
        out.append((t3, t4, _branch(a, c, d, theta2, t4)))  # @line L7
    if len(out) == 2 and abs(math.remainder(out[0][1] - out[1][1], 2 * math.pi)) <= 1e-9:
        out = [out[0]]
    out.sort(key=lambda p: -p[2])
    return out  # @line L8


def fourbar_velocities(a, b, c, theta2, theta3, theta4, omega2):
    """omega3 and omega4 from the derivative of the loop equation.

    Raises ZeroDivisionError at a toggle position, where theta3 = theta4 mod pi.
    """
    # [-b sin t3,  c sin t4] [w3]   [ a w2 sin t2]
    # [ b cos t3, -c cos t4] [w4] = [-a w2 cos t2]
    m11, m12 = -b * math.sin(theta3), c * math.sin(theta4)  # @line L9
    m21, m22 = b * math.cos(theta3), -c * math.cos(theta4)
    r1, r2 = a * omega2 * math.sin(theta2), -a * omega2 * math.cos(theta2)
    det = m11 * m22 - m12 * m21
    if abs(det) <= 1e-14 * (abs(b) * abs(c) + 1.0):
        raise ZeroDivisionError("toggle position: the velocity is not determined")
    return (r1 * m22 - m12 * r2) / det, (m11 * r2 - r1 * m21) / det


def fourbar_residual(a, b, c, d, theta2, theta3, theta4):
    """|a e^(i t2) + b e^(i t3) - c e^(i t4) - d|."""
    z = a * complex(math.cos(theta2), math.sin(theta2)) + b * complex(math.cos(theta3), math.sin(theta3))
    z -= c * complex(math.cos(theta4), math.sin(theta4)) + d
    return abs(z)


def slider_crank_positions(a, b, e, theta2):
    """The assemblies of the offset slider-crank: a list of (x, theta3, branch)."""
    ax, ay = a * math.cos(theta2), a * math.sin(theta2)
    h = e - ay
    disc = b * b - h * h
    if disc < -TOL * (b * b + 1.0):
        return []
    r = math.sqrt(max(disc, 0.0))
    out = []
    for sign in (1, -1) if r > 0 else (1,):
        x = ax + sign * r
        out.append((x, math.atan2(h, x - ax), sign if r > 0 else 0))
    return out


def slider_crank_velocity(a, b, theta2, theta3, omega2):
    """omega3 and the slider speed dx/dt from the derivative of the loop."""
    # real: -a w2 sin t2 - b w3 sin t3 - x' = 0, imag: a w2 cos t2 + b w3 cos t3 = 0
    c3 = math.cos(theta3)
    if abs(c3) <= 1e-14:
        raise ZeroDivisionError("the rod is perpendicular to the slide")
    w3 = -a * omega2 * math.cos(theta2) / (b * c3)
    return w3, -a * omega2 * math.sin(theta2) - b * w3 * math.sin(theta3)


def slider_crank_residual(a, b, e, theta2, x, theta3):
    z = a * complex(math.cos(theta2), math.sin(theta2)) + b * complex(math.cos(theta3), math.sin(theta3))
    return abs(z - complex(x, e))


def joint_turns_fully(x, y, u, v):
    """True if the joint between adjacent links x and y turns through 360 degrees.

    u and v are the other two links. The joint angle phi is feasible exactly
    when the diagonal delta, delta^2 = x^2 + y^2 - 2 x y cos(phi), closes a
    triangle with u and v, so the test is exact for int or Fraction lengths.
    """
    return x + y <= u + v and abs(x - y) >= abs(u - v)


def grashof_class(a, b, c, d):
    """The class of the four-bar with ground d, input a, coupler b, output c.

    Returns one of 'crank-rocker', 'double-crank', 'grashof double-rocker',
    'rocker-crank', 'change point' or 'triple-rocker'. Assumes positive
    lengths and that the loop closes, 2 l <= a + b + c + d.
    """
    links = sorted([a, b, c, d])
    s, p, q, l = links
    if s + l > p + q:
        return "triple-rocker"
    if s + l == p + q:
        return "change point"
    if d == s:
        return "double-crank"
    if a == s:
        return "crank-rocker"
    if c == s:
        return "rocker-crank"
    return "grashof double-rocker"


def input_turns_by_sweep(a, b, c, d, steps=720):
    """True if the loop closes at every theta2 of a sweep that holds 0 and pi."""
    for k in range(steps):
        theta2 = 2 * math.pi * k / steps
        if not fourbar_positions(a, b, c, d, theta2):
            return False
    return True
test_vector_loop_closure.py 205 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vector-loop-closure/. The authors are listed in prov/V3P14V.jsonl.

import math
import random
import unittest
from fractions import Fraction

from vector_loop_closure import (
    fourbar_positions,
    fourbar_residual,
    fourbar_velocities,
    freudenstein_k,
    grashof_class,
    input_turns_by_sweep,
    joint_turns_fully,
    slider_crank_positions,
    slider_crank_residual,
    slider_crank_velocity,
)


def closes(lengths):
    """The loop can be assembled with some angles: the longest link is at most the sum of the others."""
    return 2 * max(lengths) <= sum(lengths)


def joint_turns_by_sweep(links, k, steps=720):
    """Sweep the joint between links[k] and links[k + 1] of the cycle (d, a, b, c)."""
    g, i, cpl, o = (links[(k + j) % 4] for j in range(4))
    return input_turns_by_sweep(i, cpl, o, g, steps)


class TestFourBarPositions(unittest.TestCase):
    def test_exact_half_angle_example(self):
        # a = 2, b = 7, c = 5, d = 6 at theta2 = 0: A = -12/5, B = 0, C = 8/5, so t^2 = 2/3
        k1, k2, k3 = freudenstein_k(Fraction(2), Fraction(7), Fraction(5), Fraction(6))
        self.assertEqual((k1, k2, k3), (Fraction(3), Fraction(6, 5), Fraction(4, 5)))
        qa, qb, qc = 1 - k1 - k2 + k3, 0, k1 - (k2 + 1) + k3
        self.assertEqual((qa, qc), (Fraction(-12, 5), Fraction(8, 5)))
        self.assertEqual(-qc / qa, Fraction(2, 3))
        ps = fourbar_positions(2, 7, 5, 6, 0.0)
        self.assertEqual([p[2] for p in ps], [1, -1])
        self.assertAlmostEqual(math.tan(ps[0][1] / 2), math.sqrt(2 / 3), places=12)
        self.assertAlmostEqual(math.tan(ps[1][1] / 2), -math.sqrt(2 / 3), places=12)
        # B = (7, 2 sqrt 6) on the open branch
        self.assertAlmostEqual(6 + 5 * math.cos(ps[0][1]), 7.0, places=12)
        self.assertAlmostEqual(5 * math.sin(ps[0][1]), 2 * math.sqrt(6), places=12)

    def test_residual_random(self):
        rng = random.Random(20261114)
        count = 0
        for _ in range(3000):
            a, b, c, d = (rng.uniform(0.2, 10.0) for _ in range(4))
            theta2 = rng.uniform(-math.pi, math.pi)
            for t3, t4, br in fourbar_positions(a, b, c, d, theta2):
                self.assertLess(fourbar_residual(a, b, c, d, theta2, t3, t4), 1e-9 * (a + b + c + d))
                count += 1
        self.assertGreater(count, 2000)

    def test_two_assemblies_are_mirror_images(self):
        rng = random.Random(7)
        for _ in range(500):
            a, b, c, d = (rng.uniform(0.5, 6.0) for _ in range(4))
            theta2 = rng.uniform(0, 2 * math.pi)
            ps = fourbar_positions(a, b, c, d, theta2)
            if len(ps) != 2:
                continue
            self.assertEqual({ps[0][2], ps[1][2]}, {1, -1})
            ax, ay = a * math.cos(theta2), a * math.sin(theta2)
            pts = [(d + c * math.cos(t4), c * math.sin(t4)) for _, t4, _ in ps]
            # both B are at distance b from A and c from O4, so they are mirror images in line A O4
            for bx, by in pts:
                self.assertAlmostEqual(math.hypot(bx - ax, by - ay), b, delta=1e-9 * (a + b + c + d))
                self.assertAlmostEqual(math.hypot(bx - d, by), c, delta=1e-9 * (a + b + c + d))

    def test_no_assembly_when_triangle_fails(self):
        # a = 2, d = 6, b = 3, c = 2: the diagonal is between 4 and 8, but b + c = 5
        self.assertEqual(fourbar_positions(2, 3, 2, 6, math.pi), [])
        self.assertTrue(fourbar_positions(2, 3, 2, 6, 0.0))

    def test_velocities_against_finite_differences(self):
        rng = random.Random(11)
        h = 1e-6
        tested = 0
        for _ in range(400):
            a, b, c, d = (rng.uniform(0.5, 6.0) for _ in range(4))
            theta2 = rng.uniform(0, 2 * math.pi)
            ps = fourbar_positions(a, b, c, d, theta2)
            pm = fourbar_positions(a, b, c, d, theta2 - h)
            pp = fourbar_positions(a, b, c, d, theta2 + h)
            if len(ps) != 2 or len(pm) != 2 or len(pp) != 2:
                continue
            for k in range(2):
                t3, t4, br = ps[k]
                if abs(math.sin(t3 - t4)) < 0.05:
                    continue
                w3, w4 = fourbar_velocities(a, b, c, theta2, t3, t4, 1.0)
                fd3 = math.remainder(pp[k][0] - pm[k][0], 2 * math.pi) / (2 * h)
                fd4 = math.remainder(pp[k][1] - pm[k][1], 2 * math.pi) / (2 * h)
                self.assertAlmostEqual(w3, fd3, delta=1e-4 * (1 + abs(w3)))
                self.assertAlmostEqual(w4, fd4, delta=1e-4 * (1 + abs(w4)))
                tested += 1
        self.assertGreater(tested, 200)

    def test_toggle_velocity_raises(self):
        # at a toggle position the coupler and the output are in line, sin(theta3 - theta4) = 0,
        # and the loop derivative does not fix omega3 and omega4 (here a = 2, b = 4, c = 4, d = 6 at theta2 = pi)
        (t3, t4, _), = fourbar_positions(2, 4, 4, 6, math.pi)
        with self.assertRaises(ZeroDivisionError):
            fourbar_velocities(2, 4, 4, math.pi, t3, t4, 1.0)


class TestGrashofAgainstSweep(unittest.TestCase):
    def test_each_joint_against_sweep(self):
        rng = random.Random(1875)
        seen = set()
        for _ in range(500):
            links = [rng.randint(1, 12) for _ in range(4)]  # cycle (d, a, b, c)
            if not closes(links) or 2 * max(links) == sum(links):
                continue
            d, a, b, c = links
            turns = [joint_turns_by_sweep(links, k, steps=360) for k in range(4)]
            for k in range(4):
                x, y, u, v = (links[(k + j) % 4] for j in range(4))
                self.assertEqual(turns[k], joint_turns_fully(x, y, u, v), (links, k))
            s, p, q, l = sorted(links)
            self.assertEqual(any(turns), s + l <= p + q, links)
            cls = grashof_class(a, b, c, d)
            seen.add(cls)
            if cls == "triple-rocker":
                self.assertFalse(any(turns))
            elif cls == "crank-rocker":
                self.assertEqual((turns[0], turns[3]), (True, False))
            elif cls == "rocker-crank":
                self.assertEqual((turns[0], turns[3]), (False, True))
            elif cls == "double-crank":
                self.assertEqual((turns[0], turns[3]), (True, True))
            elif cls == "grashof double-rocker":
                self.assertEqual((turns[0], turns[3]), (False, False))
                self.assertEqual((turns[1], turns[2]), (True, True))
            if cls not in ("triple-rocker", "change point"):
                # the shortest link turns fully against both neighbours, the other two joints rock
                ks = [k for k in range(4) if links[k] == s]
                if len(ks) == 1:
                    k = ks[0]
                    self.assertTrue(turns[(k - 1) % 4] and turns[k])
                    self.assertFalse(turns[(k + 1) % 4] or turns[(k + 2) % 4])
        self.assertGreaterEqual(len(seen), 5)

    def test_change_point(self):
        # s + l = p + q: 2 + 6 = 4 + 4; the linkage reaches a position with all links in line
        a, b, c, d = 2, 4, 4, 6
        self.assertEqual(grashof_class(a, b, c, d), "change point")
        ps = fourbar_positions(a, b, c, d, math.pi)
        self.assertEqual(len(ps), 1)
        t3, t4, br = ps[0]
        self.assertEqual(br, 0)
        self.assertAlmostEqual(math.sin(t3), 0.0, places=9)
        self.assertAlmostEqual(math.sin(t4), 0.0, places=9)
        self.assertTrue(input_turns_by_sweep(a, b, c, d))


class TestSliderCrank(unittest.TestCase):
    def test_residual_and_branches(self):
        rng = random.Random(3)
        for _ in range(2000):
            a, b = rng.uniform(0.2, 5.0), rng.uniform(0.2, 10.0)
            e = rng.uniform(-3.0, 3.0)
            theta2 = rng.uniform(0, 2 * math.pi)
            ps = slider_crank_positions(a, b, e, theta2)
            for x, t3, br in ps:
                self.assertLess(slider_crank_residual(a, b, e, theta2, x, t3), 1e-9 * (a + b + abs(e) + 1))
            if len(ps) == 2:
                self.assertGreater(ps[0][0], ps[1][0])

    def test_full_rotation_and_stroke(self):
        rng = random.Random(5)
        for _ in range(60):
            a, b, e = rng.randint(1, 6), rng.randint(1, 12), rng.randint(-4, 4)
            sweep = [slider_crank_positions(a, b, e, 2 * math.pi * k / 720) for k in range(720)]
            full = all(sweep)
            self.assertEqual(full, b >= a + abs(e), (a, b, e))
            if b > a + abs(e):
                xs = [p[0][0] for p in sweep]
                stroke = math.sqrt((a + b) ** 2 - e * e) - math.sqrt((b - a) ** 2 - e * e)
                self.assertAlmostEqual(max(xs) - min(xs), stroke, delta=1e-3 * stroke)
                if e == 0:
                    self.assertAlmostEqual(stroke, 2 * a, places=12)

    def test_slider_velocity_against_finite_differences(self):
        rng = random.Random(9)
        h = 1e-6
        for _ in range(300):
            a, b, e = rng.uniform(0.5, 3.0), rng.uniform(4.0, 8.0), rng.uniform(-1.0, 1.0)
            theta2 = rng.uniform(0, 2 * math.pi)
            x, t3, _ = slider_crank_positions(a, b, e, theta2)[0]
            w3, xdot = slider_crank_velocity(a, b, theta2, t3, 2.0)
            xp = slider_crank_positions(a, b, e, theta2 + h)[0][0]
            xm = slider_crank_positions(a, b, e, theta2 - h)[0][0]
            self.assertAlmostEqual(xdot, 2.0 * (xp - xm) / (2 * h), delta=1e-5 * (1 + abs(xdot)))


if __name__ == "__main__":
    unittest.main()

Exercises

  1. For a=2a = 2, b=7b = 7, c=5c = 5, d=6d = 6, show that θ2=180°\theta_2 = 180° gives θ4=120°\theta_4 = 120° exactly, and find the coupler point BB.
  2. Derive the half-angle quadratic for θ3\theta_3 instead of θ4\theta_4. Which constants take the place of K1,K2,K3K_1, K_2, K_3?
  3. Show that the slider-crank with offset ee can be assembled at every θ2\theta_2 exactly when b≥a+∣e∣b \ge a + |e|.
  4. Differentiate the velocity equations once more and write the 2×22 \times 2 system for α3\alpha_3 and α4\alpha_4. Show that its matrix is the matrix of line L9.
  5. For a=2a = 2, b=4b = 4, c=4c = 4, d=6d = 6 at θ2=180°\theta_2 = 180°, show that Δ=0\Delta = 0 and that all four links are in line. Which theorem explains this linkage?

References

  1. Robert L. Norton, Design of Machinery, 6th edition, McGraw-Hill, 2019, Sections 4.5 (p. 187, the vector loop equation for a fourbar on p. 189), 4.6 and 4.7 (pp. 196 to 198, crank-slider), 4.12 (p. 211, toggle positions), 4.13 (p. 212, circuits and branches), 4.14 (p. 214, Newton-Raphson) and 6.7 (p. 321, analytical velocity solutions)
  2. Francis H. Raven, Velocity and acceleration analysis of plane and space mechanisms by means of independent-position equations, Journal of Applied Mechanics 25(1), 1958, 1 to 6, the position equations of a closed loop and their first and second time derivatives
  3. Arthur G. Erdman, George N. Sandor and Sridhar Kota, Mechanism Design, Analysis and Synthesis, Volume 1, 4th edition, Prentice Hall, 2001, the chapters on displacement and velocity analysis of planar linkages
  4. John J. Uicker, Gordon R. Pennock and Joseph E. Shigley, Theory of Machines and Mechanisms, 5th edition, Oxford University Press, 2017, the chapters on position and velocity analysis (loop closure equations)
  5. J. Michael McCarthy and Gim Song Soh, Geometric Design of Linkages, 2nd edition, Springer, 2011, Chapter 2 (pp. 15 to 53), analysis of planar linkages

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples