Algorithm Search⌘K

Algorithmadvanced

Direct linearization method

Also called DLM tolerance analysis.

Chase and coauthors' tolerance analysis that linearizes the vector loops of an assembly to get sensitivities, then worst case or statistical variation.

Time
O(k (V m + m^3) + V (m + n) + m^3 + n m^2) worst
Space
O(m (m + n)) extra
Where
V = number of vectors in the loops; k = number of Newton steps; m = number of kinematic variables, two per 2D loop; n = number of manufactured variables
Properties
deterministicnot exactiterative
Origin
Kenneth W. Chase, Jinsong Gao, Spencer P. Magleby, 1995

The direct linearization method (DLM) is a tolerance analysis for assemblies whose parts adjust to each other when they are put together, such as a roller that rolls until it touches two surfaces. Chase, Gao and Magleby published it in 1995. The assembly is written as closed vector loops, h(x,u)=0h(x, u) = 0, where xx are the part dimensions that have tolerances and uu are the kinematic variables that the assembly finds by itself. DLM solves the loops once at the nominal dimensions, takes the partial derivatives A=∂h/∂xA = \partial h / \partial x and B=∂h/∂uB = \partial h / \partial u, and gets the sensitivity of every output to every dimension from −B−1A-B^{-1} A, with no explicit formula for the output. The worst-case and RSS formulas of tolerance stack-up then give the variation. Its model of variation is a first-order (small change) Taylor expansion of the assembly function at the nominal point; this page proves it and bounds its error. Monte Carlo analysis solves the loops exactly for each sample instead, at a higher cost.

In plain words

In many assemblies a gap or an angle is not a sum of part dimensions. It comes out of how the parts settle against each other. You can still write the geometry as chains of arrows that must close into loops. Solve these loops once for the nominal parts. Then ask a linear question: if one dimension changes a little, how much must the free quantities change for the loops to stay closed? That answer is one small linear system, and it gives the sensitivity of the output to each dimension. With the sensitivities, the usual stack-up rules give the worst case and the statistical spread. The method is fast and exact for small changes. For large tolerances it misses the curvature of the true assembly function, and it cannot tell that some parts no longer fit together at all.

The problem

Input: closed vector loops with manufactured variables x∈Rnx \in \mathbb{R}^n (lengths and angles of parts, each with a nominal value and a symmetric tolerance TjT_j), kinematic variables u∈Rmu \in \mathbb{R}^m (two per loop in the plane, six per loop in space), a starting guess for uu, and an output, one kinematic variable uku_k such as a gap or a contact angle.

Output: the nominal output uk(x0)u_k(x_0), the sensitivities Sj=∂uk/∂xjS_j = \partial u_k / \partial x_j, the worst-case half-width W=∑j∣Sj∣TjW = \sum_j |S_j| T_j, and the RSS half-width R=∑jSj2Tj2R = \sqrt{\sum_j S_j^2 T_j^2}.

The model of variation is that each xjx_j deviates from its nominal by δj\delta_j: in the worst-case form any ∣δj∣≤Tj|\delta_j| \le T_j, and in the statistical form independent with mean 00 and standard deviation Tj/3T_j / 3. The output is replaced by its first-order expansion uk(x0)+S⋅δu_k(x_0) + S \cdot \delta.

The algorithm

  1. DLM(h, x0, u_guess, T, k) ▷ loops h, nominal x0, tolerances T, output u_k
  2. 1u0 ← NEWTON(h, x0, u_guess) ▷ assemble the nominal parts
  3. 2A ← ∂h/∂x at (x0, u0); B ← ∂h/∂u at (x0, u0)
  4. 3for j ← 1 to n do
  5. 4solve B s_j = −A_j ▷ error if B is singular
  6. 5S_j ← component k of s_j ▷ ∂u_k / ∂x_j
  7. 6W ← Σ_j |S_j| T_j ▷ worst case
  8. 7R ← sqrt(Σ_j S_j² T_j²) ▷ RSS, 3 sigma
  9. 8return u0_k, S, W, R
  10. NEWTON(h, x, u)
  11. 9repeat
  12. 10r ← h(x, u)
  13. 11solve B(x, u) δ = −r; u ← u + δ
  14. 12until |δ| is below a tolerance and |h(x, u)| is small
  15. 13return u

The derivatives. A vector of the loop is sL(cos⁡θ,sin⁡θ)s L (\cos\theta, \sin\theta), with sign ss, length LL (a constant or a variable) and absolute angle θ=θ0+∑cjyj\theta = \theta_0 + \sum c_j y_j, an affine function of angle variables. Its derivative with respect to LL is s(cos⁡θ,sin⁡θ)s (\cos\theta, \sin\theta), and with respect to yjy_j it is sLcj(−sin⁡θ,cos⁡θ)s L c_j (-\sin\theta, \cos\theta). Line L2 sums these over the vectors; no finite differences are needed. The rows of AA and BB are the xx and yy sums of each loop.

Why −B−1A-B^{-1} A. If xx changes by δx\delta x and uu by δu\delta u, the loops stay closed to first order when A δx+B δu=0A\, \delta x + B\, \delta u = 0, so δu=−B−1A δx\delta u = -B^{-1} A\, \delta x. Lines L3 to L5 compute column jj of −B−1A-B^{-1} A and keep row kk. When the output is not a kinematic variable but a function g(x,u)g(x, u), the same columns give ∂g/∂xj+∇ug⋅sj\partial g / \partial x_j + \nabla_u g \cdot s_j.

Example

The one-way clutch. This is Chase's standard 2D example. A hub has a flat at distance aa from the centre of a ring of inner radius ee, and a roller of radius cc wedges between them. The kinematic variables are the position bb of the roller contact along the flat and the pressure angle ϕ\phi between the two contact normals, which decides whether the clutch locks. The loop goes from the ring centre along the flat (bb at 0∘0^\circ), up to the flat (aa at 90∘90^\circ), up to the roller centre (cc at 90∘90^\circ), and back to the ring centre along the line through the roller contact (c−ec - e at 90∘−ϕ90^\circ - \phi). It closes when cos⁡ϕ=(a+c)/(e−c)\cos\phi = (a + c)/(e - c) and b2+(a+c)2=(e−c)2b^2 + (a + c)^2 = (e - c)^2.

Take a=27.645a = 27.645, c=11.43c = 11.43, e=50.8e = 50.8 mm, each with tolerance T=0.0127T = 0.0127 mm. Newton's method gives b=4.8105b = 4.8105 mm and ϕ=7.0184∘\phi = 7.0184^\circ. DLM gives:

dimension SjS_j (rad per mm) ∣Sj∣Tj\lvert S_j \rvert T_j (rad)
aa −0.20788-0.20788 0.002640.00264
cc −0.41420-0.41420 0.005260.00526
ee +0.20632+0.20632 0.002620.00262

These agree with the derivatives of the closed form, ∂ϕ/∂a=−1/((e−c)sin⁡ϕ)\partial \phi / \partial a = -1/((e - c)\sin\phi) and so on. The worst case is W=0.01052W = 0.01052 rad, so ϕ=7.018∘±0.603∘\phi = 7.018^\circ \pm 0.603^\circ, and the RSS value is R=0.00644R = 0.00644 rad, so ϕ=7.018∘±0.369∘\phi = 7.018^\circ \pm 0.369^\circ at 3 sigma. At the eight corners of the tolerance box the exact ϕ\phi ranges from −0.631∘-0.631^\circ to +0.579∘+0.579^\circ around the nominal: the linear range ±0.603∘\pm 0.603^\circ is off by 0.03∘0.03^\circ at each end, the second-order error that the correctness proof bounds. With T=0.05T = 0.05 mm on each dimension DLM says ±2.37∘\pm 2.37^\circ, but the corners give −3.03∘-3.03^\circ to +2.07∘+2.07^\circ, a clearly skewed range. With T=0.1T = 0.1 mm the corner a+Ta + T, c+Tc + T, e−Te - T has a+c>e−ca + c > e - c, so the roller does not fit at all; DLM still returns a number.

A linear stack. The housing gap of the stack-up page, G=A−B−C−DG = A - B - C - D with A=50±0.10A = 50 \pm 0.10 and B,C,DB, C, D of 20,15,14.8±0.0520, 15, 14.8 \pm 0.05, written as one loop, gives sensitivities +1,−1,−1,−1+1, -1, -1, -1, nominal 0.200.20, W=0.25W = 0.25 and R=0.0175≈0.1323R = \sqrt{0.0175} \approx 0.1323, the stack-up results.

Correctness

The proof is in the correctness proof. In short:

  • The partial derivatives of line L2 are exact, by the chain rule on each vector.
  • If BB is nonsingular at the nominal assembly, the implicit function theorem gives a smooth solution u(x)u(x) near x0x_0 with derivative −B−1A-B^{-1} A. So the sensitivities of line L5 are the exact first derivatives of the output.
  • By Taylor's theorem, uk(x0+δ)=uk(x0)+S⋅δ+r(δ)u_k(x_0 + \delta) = u_k(x_0) + S \cdot \delta + r(\delta) with ∣r(δ)∣≤12M∣δ∣2|r(\delta)| \le \tfrac12 M |\delta|^2, where MM bounds the Hessian of uku_k.
  • The worst-case value WW of line L6 is the exact range of the linear part over the tolerance box, and the true range is within W+12M∣T∣2W + \tfrac12 M |T|^2.
  • If the deviations are independent with standard deviations Tj/3T_j / 3, the linear part has standard deviation exactly R/3R / 3. If they are also normal, it lies in ±R\pm R with probability 0.99730.9973. Independence is needed for the variance and normality for the probability.
  • If every angle is a constant, the loops are linear and DLM is exact for any change.
Proof: The DLM sensitivities are the exact first derivatives, and the worst-case and RSS results follow with a second-order errorfull

Setting. The loops give mm equations h(x,u)=0h(x, u) = 0, with x∈Rnx \in \mathbb{R}^n the manufactured variables and u∈Rmu \in \mathbb{R}^m the kinematic variables. Each component of hh is a sum of terms ±Lcos⁡θ\pm L \cos\theta or ±Lsin⁡θ\pm L \sin\theta, where LL is a constant or a variable and θ\theta is an affine function of the variables, so hh is infinitely differentiable. Let h(x0,u0)=0h(x_0, u_0) = 0, and let A=∂h/∂xA = \partial h / \partial x and B=∂h/∂uB = \partial h / \partial u at (x0,u0)(x_0, u_0). The output is one kinematic variable uku_k.

Claim.

  1. The partial derivatives that lines L2 and L4 use are exact.
  2. If BB is nonsingular, then near x0x_0 there is a unique smooth solution u(x)u(x) with u(x0)=u0u(x_0) = u_0, and the vector SS of line L5 is the gradient of uk(x)u_k(x) at x0x_0.
  3. For a change δ\delta of xx, uk(x0+δ)=uk(x0)+S⋅δ+r(δ)u_k(x_0 + \delta) = u_k(x_0) + S \cdot \delta + r(\delta) with ∣r(δ)∣≤12M∣δ∣2|r(\delta)| \le \tfrac12 M |\delta|^2, where MM bounds the norm of the Hessian of uku_k on the segment from x0x_0 to x0+δx_0 + \delta.
  4. If ∣δj∣≤Tj|\delta_j| \le T_j for all jj, the linear part S⋅δS \cdot \delta ranges exactly over [−W,W][-W, W] with W=∑j∣Sj∣TjW = \sum_j |S_j| T_j (line L6). So the true output lies in uk(x0)±(W+12M∣T∣2)u_k(x_0) \pm (W + \tfrac12 M |T|^2).
  5. If the δj\delta_j are independent with mean 00 and standard deviations σj=Tj/3\sigma_j = T_j / 3, the linear part has standard deviation exactly 13∑jSj2Tj2\tfrac13 \sqrt{\sum_j S_j^2 T_j^2}, one third of line L7. If the δj\delta_j are also normal, the linear part is normal and lies within ±\pm the RSS value with probability 0.99730.9973.
  6. If every angle is a constant, and every variable is a length, then u(x)u(x) is affine and r≡0r \equiv 0: DLM is exact for any size of change.

Proof of 1. A term sL(cos⁡θ,sin⁡θ)s L (\cos\theta, \sin\theta) with θ=θ0+∑jcjyj\theta = \theta_0 + \sum_j c_j y_j has the partial derivative s(cos⁡θ,sin⁡θ)s (\cos\theta, \sin\theta) with respect to LL when LL is a variable, and sLcj(−sin⁡θ,cos⁡θ)s L c_j (-\sin\theta, \cos\theta) with respect to yjy_j, by the chain rule. The function loop_jacobian adds exactly these terms, and a variable that occurs in several terms gets the sum of their derivatives. □\square

Proof of 2. This is the implicit function theorem (Rudin, Principles of Mathematical Analysis, Theorem 9.28): hh is continuously differentiable, h(x0,u0)=0h(x_0, u_0) = 0 and BB is invertible, so there are neighborhoods UU of x0x_0 and VV of u0u_0 and a unique continuously differentiable u:U→Vu : U \to V with h(x,u(x))=0h(x, u(x)) = 0. Here hh is smooth, so uu is smooth too. Differentiate h(x,u(x))=0h(x, u(x)) = 0 at x0x_0: A+B Du(x0)=0A + B\, Du(x_0) = 0, so Du(x0)=−B−1ADu(x_0) = -B^{-1} A. Line L4 solves Bsj=−AjB s_j = -A_j for each column jj of AA, so sjs_j is column jj of −B−1A-B^{-1} A, and line L5 takes its component kk, which is ∂uk/∂xj\partial u_k / \partial x_j. □\square

Proof of 3. Let ϕ(τ)=uk(x0+τδ)\phi(\tau) = u_k(x_0 + \tau \delta) for τ∈[0,1]\tau \in [0, 1], assuming the segment lies in UU. Taylor's theorem with the Lagrange remainder gives ϕ(1)=ϕ(0)+ϕ′(0)+12ϕ′′(τ∗)\phi(1) = \phi(0) + \phi'(0) + \tfrac12 \phi''(\tau^*) for some τ∗∈(0,1)\tau^* \in (0, 1). Here ϕ′(0)=S⋅δ\phi'(0) = S \cdot \delta and ϕ′′(τ)=δTH(x0+τδ) δ\phi''(\tau) = \delta^{\mathsf T} H(x_0 + \tau \delta)\, \delta, with HH the Hessian of uku_k, so ∣ϕ′′(τ∗)∣≤M∣δ∣2|\phi''(\tau^*)| \le M |\delta|^2. □\square

Proof of 4. The linear function S⋅δS \cdot \delta is separable, so its maximum over the box ∣δj∣≤Tj|\delta_j| \le T_j is ∑jmax⁡∣δj∣≤TjSjδj=∑j∣Sj∣Tj\sum_j \max_{|\delta_j| \le T_j} S_j \delta_j = \sum_j |S_j| T_j, at δj=Tjsign⁡(Sj)\delta_j = T_j \operatorname{sign}(S_j). Its minimum is −W-W by symmetry, and every value between is taken because the box is connected. Adding the bound of part 3, with ∣δ∣≤∣T∣|\delta| \le |T|, gives the range of the true output. □\square

This is the worst-case formula of tolerance stack-up applied to the sensitivities. It is exact for the linear part only. The true range can be larger or smaller than ±W\pm W by up to 12M∣T∣2\tfrac12 M |T|^2, and it need not be symmetric.

Proof of 5. By linearity of expectation E[S⋅δ]=0E[S \cdot \delta] = 0, and by independence the variances add: Var⁡(S⋅δ)=∑jSj2σj2=19∑jSj2Tj2\operatorname{Var}(S \cdot \delta) = \sum_j S_j^2 \sigma_j^2 = \tfrac19 \sum_j S_j^2 T_j^2. A linear combination of independent normal variables is normal, and a normal variable lies within 3 standard deviations of its mean with probability 2Φ(3)−1≈0.99732\Phi(3) - 1 \approx 0.9973. □\square

This is the RSS formula of tolerance stack-up. Independence is needed for the variance, and normality only for the probability. The remainder rr adds a bias: E[r(δ)]=12∑jHjjσj2+O(σ3)E[r(\delta)] = \tfrac12 \sum_j H_{jj} \sigma_j^2 + O(\sigma^3) for smooth uku_k and symmetric δj\delta_j, which shifts the mean of the output away from uk(x0)u_k(x_0). DLM does not see this shift.

Proof of 6. With constant angles, h(x,u)=Px+Qu+ch(x, u) = P x + Q u + c for constant matrices PP and QQ and a constant vector cc, and then A=PA = P and B=QB = Q at every point. If QQ is invertible, u(x)=−Q−1(Px+c)u(x) = -Q^{-1}(P x + c), which is affine, so its Hessian is zero and M=0M = 0 in part 3. □\square

Line L1 and the Newton loop. Lines L9 to L12 are Newton's method for h(x0,u)=0h(x_0, u) = 0. The implementation returns only when the last step is below the tolerance and the residual is below 10−910^{-9}, and otherwise raises an error, so every returned u0u_0 satisfies the loops to that accuracy. Newton's method converges quadratically from a start close enough to a solution with nonsingular BB; from a poor start it can fail or reach another assembly branch, such as the crossed form of a four-bar. That is why the caller supplies the starting guess.

Complexity

Each Newton step of lines L9 to L12 builds the m×mm \times m matrix BB in O(Vm)O(V m) time and solves with it in O(m3)O(m^3), so the nominal assembly costs O(k(Vm+m3))O(k (V m + m^3)) for kk steps. Line L2 builds AA and BB in O(V(m+n))O(V (m + n)). Factor BB once in O(m3)O(m^3), and each of the nn solves of line L4 costs O(m2)O(m^2), so the sensitivities cost O(m3+nm2)O(m^3 + n m^2). The code of this page eliminates afresh for each column, O(nm3)O(n m^3), which is fine for the few loops of a real assembly. Lines L6 and L7 take O(n)O(n). The extra space is O(m(m+n))O(m (m + n)) for AA and BB. Unlike Monte Carlo, the cost does not grow with the number of samples: one linear solve replaces all of them.

Properties

  • Local. The sensitivities are exact derivatives at the nominal point, and the variation is exact only for the linear part.
  • Symmetric. Its worst-case and RSS ranges are symmetric about the nominal output, even when the true range is not.
  • Distribution-free variance. The RSS variance of the linear part needs independence but no distribution shape.
  • Exact for linear loops. With fixed angles, the output is affine in the dimensions and the method has no error.
  • Deterministic. The same input gives the same output; no sampling.

Variants and improvements

  • 3D loops. Gao, Chase and Magleby replace the 2D vectors by 3D vectors and rotations, with six equations per loop.
  • Geometric feature variations. Form, orientation and position variations of features can be modeled as extra small vectors or rotations at the contacts, which keeps the method linear. The small displacement torsor and Jacobian-torsor models build the same kind of linear map from 3D feature frames.
  • Mean shift and second order. The proof shows the bias 12∑jHjjσj2\tfrac12 \sum_j H_{jj} \sigma_j^2 of the output mean. Adding second derivatives estimates it. The estimated mean shift model of the stack-up page adds a worst-case part for process drift.
  • Allocation. The sensitivities are the input of tolerance allocation, which chooses the TjT_j at least cost.
  • Simulation. When the assembly is far from linear or a fit can fail, Monte Carlo analysis solves the loops for each sample.

When to use it

Use DLM for an assembly with small kinematic adjustments where the tolerances are small against the dimensions, as in most machined parts. It gives sensitivities, which show where tightening a tolerance helps most, and it costs one linear solve. Check the result with Monte Carlo when the tolerances are large relative to the curvature of the assembly function, when the output is near a limit of assembly (such as the clutch at large tolerances), or when the distributions are far from normal.

Pitfalls

  • Singular B. Near a toggle position of a linkage, or when two kinematic vectors are parallel, BB is singular or close to it, and the sensitivities blow up. The method then says nothing useful.
  • The wrong branch. A loop can close in several ways, such as the open and crossed forms of a four-bar linkage. Newton's method finds the one near its starting guess; start from the drawing.
  • Parts that do not fit. DLM never checks that each sample assembles. A worst-case corner can be impossible, as in the clutch example.
  • Units. Angles are in radians in the derivatives. A tolerance in degrees must be converted.
  • Correlated dimensions. RSS assumes independent dimensions. Two dimensions from one setup are not.
  • Mean shift. A curved assembly function moves the mean of the output away from its nominal value even for centred inputs; DLM reports the nominal value as the mean.

Implementations

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.

direct_linearization_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-linearization-method/. The authors are listed in prov/3NRTQF.jsonl.

"""Direct linearization method (DLM) for 2D vector loops.

An assembly is a list of closed vector loops in the plane. Each vector is a
triple (sign, length, angle):

- sign is +1 or -1;
- length is a number or the name of a variable;
- angle is a pair (const, coefs): the absolute angle in radians is
  const + sum(coef * value[name] for name, coef in coefs.items()).

The variables are split into manufactured ones x (part dimensions with
tolerances) and kinematic ones u (the adjustments of the assembly, such as a
gap, a contact position or a joint angle). Loop closure is h(x, u) = 0, two
equations per loop. DLM solves the loops at the nominal x, forms the partial
derivatives A = dh/dx and B = dh/du, and takes the sensitivities of a
kinematic output u_k as the k-th row of -B^-1 A. The worst-case and RSS
variations then follow from the stack-up formulas.
"""

import math


def vector_angle(angle, values):
    """Absolute angle of a vector from its (const, coefs) description."""
    const, coefs = angle
    return const + sum(c * values[name] for name, c in coefs.items())


def vector_length(length, values):
    return values[length] if isinstance(length, str) else float(length)


def loop_residual(loops, values):
    """h(x, u): the x and y sums of each loop, 2 numbers per loop."""
    out = []
    for loop in loops:
        sx = sy = 0.0
        for sign, length, angle in loop:
            L = vector_length(length, values)
            th = vector_angle(angle, values)
            sx += sign * L * math.cos(th)
            sy += sign * L * math.sin(th)
        out += [sx, sy]
    return out


def loop_jacobian(loops, values, names):
    """Partial derivatives of h with respect to the variables in names.

    d/d(length L) of sign * L * (cos t, sin t) is sign * (cos t, sin t), and
    d/d(angle variable with coefficient c) is sign * L * c * (-sin t, cos t).
    """
    col = {n: j for j, n in enumerate(names)}
    rows = [[0.0] * len(names) for _ in range(2 * len(loops))]
    for i, loop in enumerate(loops):
        for sign, length, angle in loop:
            L = vector_length(length, values)
            th = vector_angle(angle, values)
            ct, st = math.cos(th), math.sin(th)
            if isinstance(length, str) and length in col:
                j = col[length]
                rows[2 * i][j] += sign * ct
                rows[2 * i + 1][j] += sign * st
            for name, c in angle[1].items():
                if name in col:
                    j = col[name]
                    rows[2 * i][j] += -sign * L * c * st
                    rows[2 * i + 1][j] += sign * L * c * ct
    return rows


def solve_linear(M, rhs):
    """Solve M y = rhs by Gaussian elimination with partial pivoting.

    Raises ValueError if M is singular to working precision.
    """
    n = len(M)
    if any(len(r) != n for r in M) or len(rhs) != n:
        raise ValueError("the system is not square")
    a = [list(map(float, r)) + [float(b)] for r, b in zip(M, rhs)]
    scale = max((abs(v) for r in M for v in r), default=0.0) or 1.0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if abs(a[p][k]) <= 1e-12 * scale:
            raise ValueError("B is singular: the loops do not fix the kinematic variables")
        a[k], a[p] = a[p], a[k]
        for i in range(k + 1, n):
            f = a[i][k] / a[k][k]
            if f:
                for j in range(k, n + 1):
                    a[i][j] -= f * a[k][j]
    y = [0.0] * n
    for k in range(n - 1, -1, -1):
        s = a[k][n] - sum(a[k][j] * y[j] for j in range(k + 1, n))
        y[k] = s / a[k][k]
    return y


def solve_assembly(loops, x, u_guess, kin_names, tol=1e-13, max_iter=60):
    """Newton's method for h(x, u) = 0 in the kinematic variables u.

    x and u_guess are dicts. Returns the dict of all values at the solution.
    Raises ValueError if Newton does not converge.
    """
    values = dict(x)
    values.update(u_guess)
    for _ in range(max_iter):  # @line L9
        r = loop_residual(loops, values)  # @line L10
        B = loop_jacobian(loops, values, kin_names)
        step = solve_linear(B, [-v for v in r])  # @line L11
        for name, d in zip(kin_names, step):
            values[name] += d
        if max(abs(d) for d in step) <= tol * (1.0 + max(abs(values[n]) for n in kin_names)):  # @line L12
            if max(abs(v) for v in loop_residual(loops, values)) <= 1e-9:
                return values  # @line L13
    raise ValueError("Newton's method did not converge")


def dlm(loops, x0, u_guess, man_names, kin_names, tolerances, output):
    """Direct linearization of a kinematic output.

    loops: the vector loops; x0: nominal manufactured values (dict);
    u_guess: a starting guess for the kinematic values (dict);
    man_names, kin_names: the variable names in order;
    tolerances: dict name -> symmetric tolerance T_j;
    output: the name of the kinematic variable that is the assembly output.

    Returns a dict with the nominal output, the sensitivities, the worst-case
    half-width sum |S_j| T_j and the RSS half-width sqrt(sum S_j^2 T_j^2).
    """
    if 2 * len(loops) != len(kin_names):
        raise ValueError("need exactly two kinematic variables per loop")
    values = solve_assembly(loops, x0, u_guess, kin_names)  # @line L1
    A = loop_jacobian(loops, values, man_names)  # @line L2
    B = loop_jacobian(loops, values, kin_names)
    k = kin_names.index(output)
    sens = {}
    for j, name in enumerate(man_names):  # @line L3
        col = solve_linear(B, [-A[i][j] for i in range(len(A))])  # @line L4
        sens[name] = col[k]  # @line L5
    worst = sum(abs(sens[n]) * tolerances[n] for n in man_names)  # @line L6
    rss = math.sqrt(sum((sens[n] * tolerances[n]) ** 2 for n in man_names))  # @line L7
    return {"nominal": values[output], "values": values, "sens": sens, "worst": worst, "rss": rss}  # @line L8


# Example assemblies used on the page and in the tests.

def clutch_loops():
    """One-way clutch: hub flat at distance a, roller radius c, ring radius e.

    Kinematic variables: b (contact point along the flat) and phi (the
    pressure angle between the two contact normals). The loop goes from the
    ring centre along the flat (b), up to the flat (a), up to the roller
    centre (c), and back to the ring centre along the line of radius e - c,
    whose angle is 90 degrees minus phi.
    """
    half_pi = math.pi / 2
    back = (half_pi, {"phi": -1.0})
    return [[
        (1, "b", (0.0, {})),
        (1, "a", (half_pi, {})),
        (1, "c", (half_pi, {})),
        (1, "c", back),
        (-1, "e", back),
    ]]


def fourbar_loops():
    """Four-bar linkage with fixed input angle th2 (a constant of the model).

    Manufactured: crank a, coupler b, rocker c, ground d.
    Kinematic: coupler angle th3 and rocker angle th4.
    """
    return [[
        (1, "a", (0.0, {"th2": 1.0})),
        (1, "b", (0.0, {"th3": 1.0})),
        (-1, "c", (0.0, {"th4": 1.0})),
        (-1, "d", (0.0, {})),
    ]]


def linear_stack_loops():
    """End gap of a 1D stack: G = A - B - C - D, written as a vector loop.

    The vertical vectors (kinematic h, constant 1) only make B square.
    """
    return [[
        (1, "A", (0.0, {})),
        (-1, "B", (0.0, {})),
        (-1, "C", (0.0, {})),
        (-1, "D", (0.0, {})),
        (-1, "G", (0.0, {})),
        (1, "h", (math.pi / 2, {})),
        (-1, 1.0, (math.pi / 2, {})),
    ]]
test_direct_linearization_method.py 183 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-linearization-method/. The authors are listed in prov/3NRTQF.jsonl.

import itertools
import math
import random

import pytest

from direct_linearization_method import (
    clutch_loops,
    dlm,
    fourbar_loops,
    linear_stack_loops,
    loop_residual,
    solve_assembly,
)

CLUTCH_X = {"a": 27.645, "c": 11.43, "e": 50.8}
CLUTCH_MAN = ["a", "c", "e"]
CLUTCH_KIN = ["b", "phi"]
CLUTCH_GUESS = {"b": 4.0, "phi": 0.1}


def clutch_exact(x):
    """Closed form of the clutch: cos(phi) = (a + c) / (e - c)."""
    a, c, e = x["a"], x["c"], x["e"]
    q = (a + c) / (e - c)
    return math.acos(q), math.sqrt((e - c) ** 2 - (a + c) ** 2)


def clutch_phi(x):
    return solve_assembly(clutch_loops(), x, CLUTCH_GUESS, CLUTCH_KIN)["phi"]


def test_clutch_solution_matches_closed_form():
    v = solve_assembly(clutch_loops(), CLUTCH_X, CLUTCH_GUESS, CLUTCH_KIN)
    phi, b = clutch_exact(CLUTCH_X)
    assert v["phi"] == pytest.approx(phi, abs=1e-12)
    assert v["b"] == pytest.approx(b, abs=1e-10)
    assert math.degrees(v["phi"]) == pytest.approx(7.0, abs=0.05)
    assert max(abs(r) for r in loop_residual(clutch_loops(), v)) < 1e-10


def test_clutch_sensitivities_analytic_and_finite_differences():
    T = {"a": 0.01, "c": 0.0025, "e": 0.0125}
    res = dlm(clutch_loops(), CLUTCH_X, CLUTCH_GUESS, CLUTCH_MAN, CLUTCH_KIN, T, "phi")
    a, c, e = CLUTCH_X["a"], CLUTCH_X["c"], CLUTCH_X["e"]
    s = math.sin(res["nominal"])
    analytic = {
        "a": -1 / (e - c) / s,
        "c": -(e + a) / (e - c) ** 2 / s,
        "e": (a + c) / (e - c) ** 2 / s,
    }
    for name in CLUTCH_MAN:
        assert res["sens"][name] == pytest.approx(analytic[name], rel=1e-9)
        h = 1e-6
        xp, xm = dict(CLUTCH_X), dict(CLUTCH_X)
        xp[name] += h
        xm[name] -= h
        fd = (clutch_phi(xp) - clutch_phi(xm)) / (2 * h)
        assert res["sens"][name] == pytest.approx(fd, rel=1e-6)
    wc = sum(abs(analytic[n]) * T[n] for n in CLUTCH_MAN)
    rss = math.sqrt(sum((analytic[n] * T[n]) ** 2 for n in CLUTCH_MAN))
    assert res["worst"] == pytest.approx(wc, rel=1e-9)
    assert res["rss"] == pytest.approx(rss, rel=1e-9)
    assert res["rss"] <= res["worst"] <= math.sqrt(3) * res["rss"] + 1e-15


def corner_range(x0, T, names, f):
    vals = []
    for signs in itertools.product((-1, 1), repeat=len(names)):
        x = dict(x0)
        for s, n in zip(signs, names):
            x[n] += s * T[n]
        vals.append(f(x))
    return min(vals), max(vals)


def test_clutch_linearization_error_is_second_order():
    """The gap between the DLM worst case and the corner range shrinks like T^2."""
    errs = []
    phi0 = clutch_exact(CLUTCH_X)[0]
    for k in (0.02, 0.002):
        T = {n: k for n in CLUTCH_MAN}
        res = dlm(clutch_loops(), CLUTCH_X, CLUTCH_GUESS, CLUTCH_MAN, CLUTCH_KIN, T, "phi")
        lo, hi = corner_range(CLUTCH_X, T, CLUTCH_MAN, lambda x: clutch_exact(x)[0])
        err = max(abs((hi - phi0) - res["worst"]), abs((phi0 - lo) - res["worst"]))
        errs.append((err, res["worst"]))
    assert errs[0][0] > 0
    assert errs[1][0] / errs[0][0] < 0.02
    assert errs[0][0] < 0.2 * errs[0][1]


FOUR_X = {"a": 40.0, "b": 120.0, "c": 80.0, "d": 100.0, "th2": math.radians(40)}
FOUR_MAN = ["a", "b", "c", "d"]
FOUR_KIN = ["th3", "th4"]


def freudenstein_theta4(x, branch):
    """Closed form for the rocker angle (open branch -1, crossed branch +1)."""
    a, b, c, d, t2 = x["a"], x["b"], x["c"], x["d"], x["th2"]
    k1, k2, k3 = d / a, d / c, (a * a - b * b + c * c + d * d) / (2 * a * c)
    A = math.cos(t2) - k1 - k2 * math.cos(t2) + k3
    B = -2 * math.sin(t2)
    C = k1 - (k2 + 1) * math.cos(t2) + k3
    return 2 * math.atan2(-B + branch * math.sqrt(B * B - 4 * A * C), 2 * A)


def angle_diff(p, q):
    return math.remainder(p - q, 2 * math.pi)


def fourbar_guess(x):
    t4 = freudenstein_theta4(x, -1)
    px = x["c"] * math.cos(t4) + x["d"] - x["a"] * math.cos(x["th2"])
    py = x["c"] * math.sin(t4) - x["a"] * math.sin(x["th2"])
    return {"th3": math.atan2(py, px) + 0.05, "th4": t4 - 0.05}


def test_fourbar_matches_freudenstein():
    rng = random.Random(7)
    for _ in range(40):
        x = dict(FOUR_X)
        x["th2"] = rng.uniform(0, 2 * math.pi)
        v = solve_assembly(fourbar_loops(), x, fourbar_guess(x), FOUR_KIN)
        assert abs(angle_diff(v["th4"], freudenstein_theta4(x, -1))) < 1e-10


def test_fourbar_sensitivities_against_finite_differences():
    T = {"a": 0.05, "b": 0.1, "c": 0.08, "d": 0.1}
    rng = random.Random(11)
    for _ in range(10):
        x0 = dict(FOUR_X)
        x0["th2"] = rng.uniform(0.2, 2 * math.pi - 0.2)
        res = dlm(fourbar_loops(), x0, fourbar_guess(x0), FOUR_MAN, FOUR_KIN, T, "th4")
        for name in FOUR_MAN:
            h = 1e-5
            xp, xm = dict(x0), dict(x0)
            xp[name] += h
            xm[name] -= h
            fd = angle_diff(freudenstein_theta4(xp, -1), freudenstein_theta4(xm, -1)) / (2 * h)
            assert res["sens"][name] == pytest.approx(fd, rel=1e-6, abs=1e-9)


def test_linear_stack_gives_stack_up_formulas():
    x0 = {"A": 50.0, "B": 20.0, "C": 15.0, "D": 14.8}
    T = {"A": 0.10, "B": 0.05, "C": 0.05, "D": 0.05}
    res = dlm(linear_stack_loops(), x0, {"G": 0.0, "h": 0.0}, list(x0), ["G", "h"], T, "G")
    assert res["nominal"] == pytest.approx(0.20, abs=1e-12)
    assert res["sens"] == pytest.approx({"A": 1.0, "B": -1.0, "C": -1.0, "D": -1.0}, abs=1e-12)
    assert res["worst"] == pytest.approx(0.25, abs=1e-12)
    assert res["rss"] == pytest.approx(math.sqrt(0.0175), abs=1e-12)


def random_linear_loop(rng, n):
    """A loop with n manufactured lengths and two kinematic lengths, all at fixed angles."""
    names = ["x%d" % i for i in range(n)]
    loop = [(rng.choice((-1, 1)), nm, (rng.uniform(0, 2 * math.pi), {})) for nm in names]
    t = rng.uniform(0, 2 * math.pi)
    loop.append((1, "p", (t, {})))
    loop.append((1, "q", (t + rng.uniform(0.5, 2.6), {})))
    x0 = {nm: rng.uniform(5, 20) for nm in names}
    return [loop], x0, names


def test_linear_loops_are_exact_for_large_changes():
    rng = random.Random(2026)
    for _ in range(50):
        n = rng.randint(1, 6)
        loops, x0, names = random_linear_loop(rng, n)
        T = {nm: 1.0 for nm in names}
        res = dlm(loops, x0, {"p": 0.0, "q": 0.0}, names, ["p", "q"], T, "q")
        x1 = {nm: v + rng.uniform(-3, 3) for nm, v in x0.items()}
        q1 = solve_assembly(loops, x1, {"p": 0.0, "q": 0.0}, ["p", "q"])["q"]
        pred = res["nominal"] + sum(res["sens"][nm] * (x1[nm] - x0[nm]) for nm in names)
        assert q1 == pytest.approx(pred, abs=1e-8)


def test_singular_b_is_reported():
    loops = [[(1, "x", (0.0, {})), (-1, "p", (0.0, {})), (-1, "q", (0.0, {}))]]
    with pytest.raises(ValueError):
        dlm(loops, {"x": 3.0}, {"p": 1.0, "q": 1.0}, ["x"], ["p", "q"], {"x": 0.1}, "p")

History

Chase and his group at Brigham Young University developed tolerance analysis with vector loops in the 1980s and 1990s. Chase, Gao and Magleby published the general 2D method with small kinematic adjustments in the Journal of Design and Manufacturing in 1995, and Gao, Chase and Magleby the 3D method in IIE Transactions in 1998. Chase's chapters in the Dimensioning and Tolerancing Handbook of 1999 present the method with worked examples, the one-way clutch among them. Chen, Jin, Li and Lai compare DLM with the other 3D tolerance analysis methods in a survey of 2014.

References

  1. Kenneth W. Chase, Jinsong Gao and Spencer P. Magleby, General 2-D tolerance analysis of mechanical assemblies with small kinematic adjustments, Journal of Design and Manufacturing 5(4), 263 to 274, 1995, the whole paper (vector loop models with manufactured and kinematic variables, the matrices A and B of partial derivatives, the sensitivities from B^-1 A, and the worst-case and RSS results)
  2. Jinsong Gao, Kenneth W. Chase and Spencer P. Magleby, Generalized 3-D tolerance analysis of mechanical assemblies with small kinematic adjustments, IIE Transactions 30, 367 to 377, 1998, the whole paper (the extension of the method to 3D vector loops)
  3. Paul J. Drake, Jr. (editor), Dimensioning and Tolerancing Handbook, McGraw-Hill, 1999, the chapters by Kenneth W. Chase on multi-dimensional tolerance analysis with vector loops and on minimum-cost tolerance allocation, which uses the one-way clutch as its 2D example
  4. Walter Rudin, Principles of Mathematical Analysis, 3rd edition, McGraw-Hill, 1976, Theorem 9.28, the implicit function theorem, and Theorem 5.15, Taylor's theorem
  5. Hua Chen, Sun Jin, Zhimin Li and Xinmin Lai, A comprehensive study of three dimensional tolerance analysis methods, Computer-Aided Design 53, 1 to 13, 2014, the part on the direct linearization method and its comparison with the other 3D methods

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 proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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
  • a scene preset for the example