From 8979fe1c96b168bb00632f2f159dd53e044aa368 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Mon, 16 Nov 2026 23:33:44 +0900 Subject: [PATCH] perf: a faster compiled kernel for the distributed helix friction model The distributed model (friction_model="distributed", and "auto" on non-planar paths) spent all of its time in the compiled increment solver: on an hour of the 66 kV template at 10 Hz about 1.28 million substeps of 0.1 kappa_on, each with 3.8 Newton solves on average. compute_fatigue on one thread, warm: 43.0 s before, 13.1 s after, against 3.2 s for the direction-tied cap (13.6x -> 4.1x); shipped fatigue examples 1.14-1.59x -> 1.01-1.28x of the direction-tied time. _distributed_kernel_fast solves the same increments with the same equations, convergence tests, fall-backs and substep rule: - Newton starts from the increment of the last substep (1.2-1.6 solves per substep instead of 3.8); an increment is solved again from zero, as in the reference, if that start fails, and the slide of a full-slip increment is fixed by the same rule as in the reference (_full_slip_slide), so the start does not reach the kept fields; - the Jacobian factorisation is kept between solves and eliminated from both ends towards the middle row (twisted, with the Sherman-Morrison corner correction), so a changed row refactors only the rows between it and the middle; - residual, bound and stick/slip pattern in one pass per iterate, reciprocals instead of divisions. The previous kernel stays as the reference, used without numba (CABLEXSEC_DISABLE_NUMBA=1). tests/test_distributed_fast.py compares the two (planar, rotating, one-sided, full slip; signed and uniform bound; contact shape, pressure history, pressure factor, static and dynamic law; kept kinematics), checks the kept factorisation against dense algebra after row changes, singular pivots and the fall-backs; the stick_check reference values hold for both kernels. Round-off differences: wire stress at most 3.4e-15 of the largest, damage 1.2e-15 (66 kV template) and at most 1.4e-12 relative (shipped examples), energies 1e-15, kept u, p and step slip to round-off. With a finite healing time heal/break-away events are round-off sensitive in either kernel alone. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 33 +- release/check_coverage.py | 1 + .../mechanics/distributed_friction.py | 910 +++++++++++++++++- tests/test_distributed_fast.py | 346 +++++++ tests/test_distributed_friction.py | 37 +- tests/test_friction_kernels.py | 5 +- validation/validation_report.md | 6 +- 7 files changed, 1318 insertions(+), 20 deletions(-) create mode 100644 tests/test_distributed_fast.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a4c6b0..35f431c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,8 +58,9 @@ All notable changes to CableXSec are recorded in this file. The format follows against 1.8–2.6 in the distributed model. On planar and flat paths (minor over major axis up to about 0.3) its ranges are at or above the distributed ones. The result is unchanged; an explicit `friction_model` keeps the chosen law without the warning. Cost of the distributed - model on one thread: 1.0–1.5 times the direction-tied time on the shipped fatigue examples, - 13–16 times on the 66 kV template (substeps of 0.1 `κ_on`); with `"auto"` the largest damage + model on one thread: 1.0–1.3 times the direction-tied time on the shipped fatigue examples, + about 4 times on the 66 kV template (substeps of 0.1 `κ_on`; see Changed for the faster + kernel); with `"auto"` the largest damage of the shipped examples changes by at most 0.02 %, on an hour of the 66 kV template at 10 Hz it is 0.92 of the direction-tied value. Tests: tests/test_biaxial_friction_default.py. - A bound option of the distributed friction model, `distributed_bound` in `compute_fatigue` @@ -180,6 +181,34 @@ All notable changes to CableXSec are recorded in this file. The format follows ### Changed +- The distributed helix friction model (`friction_model="distributed"`, and `"auto"` on + non-planar paths) runs about three times faster on the 66 kV template. `compute_fatigue` on + one thread, warm, an hour of the 66 kV template at 10 Hz (36 001 samples, both armour + layers): 43.0 s before, 13.1 s after, against 3.2 s for the direction-tied cap (13.6 times + before, 4.1 times after). Shipped fatigue examples: 1.14–1.59 times the direction-tied time + before, 1.01–1.28 times after. All of the time was in the compiled increment solver: about + 1.28 million substeps of 0.1 `κ_on`, each with 3.8 Newton solves on average and several passes + over the 556–580 helix nodes per solve. The substep rule, the equations, the convergence + tests and the defaults are unchanged; a new compiled kernel solves each increment faster: + Newton starts from the increment of the last substep (the substeps of a sample are equal + steps, so this usually has the converged stick/slip pattern: 1.2–1.6 solves per substep), the + factorisation of its Jacobian is kept between solves and eliminated from both ends towards + the middle row, so a row that changes refactors only the rows between it and the middle, and + the residual, bound and pattern of an iterate are formed in one pass. An increment is solved + again from zero, as before, if that start fails. The previous kernel is + kept as the reference: it runs without numba (`CABLEXSEC_DISABLE_NUMBA=1`) and the tests + compare the two (tests/test_distributed_fast.py: planar, rotating, one-sided and full-slip + paths, both bound forms, contact shape, pressure history, pressure factor and static/dynamic + law, kept kinematics; the recorded values of the independent stick_check solver hold for + both). Differences are round-off: wire stress at most 3.4e-15 of the largest, damage + 1.2e-15 (66 kV template) and at most 1.4e-12 relative (shipped examples, damages of order + 1e-12), energies 1e-15 of the largest, kept displacement and slip fields to round-off (both + kernels fix the slide of a full-slip increment by the same rule, see Fixed). With a finite + healing time of a friction law a node's heal and break-away events can move by a substep + under any round-off change (on a 32-node helix with the uniform bound a relative change of + 1e-15 in the curvature moves the reference stress by 0.24 %; the kernels differ by 0.24 % + there and by 4e-15 with the default nodes). + - The distributed friction model of the fatigue path accepts a constant stick modulus other than the layer's (one block of a thermal history, which recomputes `ξ` from its moduli) as the Yun coefficient `ξ = k/(E cos²α)` of that state. Before, any stick modulus other than the layer's diff --git a/release/check_coverage.py b/release/check_coverage.py index 18e9f44..9dce36f 100644 --- a/release/check_coverage.py +++ b/release/check_coverage.py @@ -35,6 +35,7 @@ "tests/test_friction_law.py", "tests/test_friction_pressure.py", "tests/test_distributed_slide.py", + "tests/test_distributed_fast.py", ) diff --git a/src/cablexsec/mechanics/distributed_friction.py b/src/cablexsec/mechanics/distributed_friction.py index ce023fa..682cf80 100644 --- a/src/cablexsec/mechanics/distributed_friction.py +++ b/src/cablexsec/mechanics/distributed_friction.py @@ -61,7 +61,11 @@ ``1e-12 h`` times the largest force term). Sample increments larger than ``max_increment`` (in units of ``kappa_on``) are subdivided by linear interpolation of curvature and pressure; an increment that fails to converge is -repeated with twice as many substeps. +repeated with twice as many substeps. With numba the increments are solved by +a faster kernel with the same equations, tests and fall-backs: Newton starts +from the increment of the last substep and the factorisation of its Jacobian +is kept between solves (section "Fast compiled kernel"); the results agree +with the reference kernel to round-off. Full slip: when every node of an increment is on its bound, the equations fix the forces, the tractions and ``u - p``, but not a slide ``c`` common to the @@ -147,6 +151,10 @@ #: of a full-slip increment (:func:`_full_slip_slide`); the node that takes #: the stick row in full slip sits on its bound to round-off. _ON_BOUND = 1e-9 +#: Use :func:`_distributed_kernel_fast` (numba active) instead of the +#: reference :func:`_distributed_kernel`; both solve the same increments and +#: agree to round-off (tests/test_distributed_fast.py). +_FAST_KERNEL = HAVE_NUMBA # --------------------------------------------------------------------------- # @@ -1114,6 +1122,897 @@ def _distributed_kernel( return out, hist, slip, stats, fld +# --------------------------------------------------------------------------- # +# Fast compiled kernel # +# --------------------------------------------------------------------------- # +# Same increments, equations, convergence tests, fall-backs and substep rule +# as the reference kernel above; only the way each increment is solved +# differs, so the results agree with the reference to round-off +# (tests/test_distributed_fast.py; with a finite healing time of a friction +# law, the heal and break-away events of a node can move by a substep under a +# round-off change, in either kernel alone as much as between them): +# +# - Newton starts from the increment of the last substep instead of zero +# (the substeps of a sample are equal steps), so the first linearisation +# usually has the converged stick/slip pattern; an increment is solved again +# from zero, as in the reference, if that start fails. Both kernels then +# fix the slide of a full-slip increment by the same rule +# (:func:`_full_slip_slide`), so the start does not reach the kept fields; +# - the factorisation of the Newton Jacobian is kept between solves. A row is +# a function of its node's stick/slip key and friction factor only, and +# the system is eliminated from both ends towards the middle row (twisted +# factorisation), so a changed row invalidates only the pivots between it +# and the middle; the stick zones move by a node or two per substep; +# - the residual, bound and pattern of an iterate are formed in one pass, the +# converged pass gives the segment forces, the two halves of every sweep +# run as independent recurrences, and divisions by ``h``, ``k_hat`` and the +# pivots are multiplications by their reciprocals. +# +# Rows of the factorisation cache ``mat`` (shape (_M_ROWS, N)); rows below +# the middle row ``m = N // 2`` hold the top-down elimination, rows above it +# the bottom-up one. +_M_LOWER = 0 # coefficient of v_{j-1} +_M_DIAG = 1 # coefficient of v_j +_M_UPPER = 2 # coefficient of v_{j+1} +_M_PC = 3 # eliminated neighbour coefficient over the pivot +_M_PIV = 4 # 1 / pivot +_M_OFF = 5 # eliminated coefficient over the pivot +_M_ZS = 6 # Sherman--Morrison column, elimination sweep +_M_ZB = 7 # Sherman--Morrison column, solved +_M_KEY = 8 # key the row was built from (_OVERRIDE: stick row in full slip) +_M_FAC = 9 # friction factor the row was built with +_M_ROWS = 10 +#: Row key of the node that takes the stick row in full slip. +_OVERRIDE = 8.0 +# ``mstate`` = [first stale row of the top half, last stale row of the bottom +# half, 1 + v.z, beta / gam, 1 / middle pivot, a node of the solution sticks]. +_CLEAN_LO = 1 << 60 +_CLEAN_HI = -1 + + +@njit(cache=True) +def _set_row( + j: int, + key: float, + mj: float, + lam: float, + ih: float, + stick_diag: float, + mat: FloatArray, +) -> None: + """Jacobian row ``j`` of :func:`_solve_capstan_newton` for node key + ``key`` (``state + 4 sm``) and friction factor ``mj``.""" + mat[_M_KEY, j] = key + mat[_M_FAC, j] = mj + if key == 4.0 or key == _OVERRIDE: + mat[_M_LOWER, j] = -ih + mat[_M_DIAG, j] = stick_diag + mat[_M_UPPER, j] = -ih + else: + sm = 1.0 if key > 2.0 else 0.0 + state = key - 4.0 * sm + q = 0.5 * (lam * mj) * state * sm + mat[_M_LOWER, j] = -(ih + q) + mat[_M_DIAG, j] = 2.0 * ih + mat[_M_UPPER, j] = -(ih - q) + + +@njit(cache=True) +def _twisted_refactor(n: int, mat: FloatArray, mstate: FloatArray) -> bool: + """Update the stale pivots of the twisted factorisation of ``mat``. + + The cyclic system is the tridiagonal one with modified corners plus a + Sherman--Morrison correction, as in :func:`_cyclic_solve_general`. Top + rows ``i < m`` are eliminated downwards, bottom rows ``i > m`` upwards; + rows ``mstate[0] .. m - 1`` and ``m + 1 .. mstate[1]`` are recomputed. + False for a (numerically) singular system. + """ + lo = mat[_M_LOWER] + dg = mat[_M_DIAG] + up = mat[_M_UPPER] + pc = mat[_M_PC] + piv = mat[_M_PIV] + off = mat[_M_OFF] + zs = mat[_M_ZS] + zb = mat[_M_ZB] + m = n // 2 + s = int(min(mstate[0], m)) + e = int(max(mstate[1], m)) + if s == 0: + e = n - 1 # row 0 sets the corners of the last row + beta = lo[0] + alpha = up[n - 1] + gam = -dg[0] + if s == 0: + bet = dg[0] - gam + if bet == 0.0: + return False + pc[0] = up[0] / bet + r = 1.0 / bet + piv[0] = r + off[0] = 0.0 + zs[0] = gam * r + s = 1 + if e == n - 1: + g = dg[n - 1] - alpha * beta / gam + if g == 0.0: + return False + pc[n - 1] = lo[n - 1] / g + r = 1.0 / g + piv[n - 1] = r + off[n - 1] = 0.0 + zs[n - 1] = alpha * r + e = n - 2 + top = m - s if m > s else 0 + bottom = e - m if e > m else 0 + both = min(top, bottom) + pct = pc[s - 1] if s > 0 else 0.0 + zt = zs[s - 1] if s > 0 else 0.0 + pcb = pc[e + 1] if e + 1 < n else 0.0 + zbt = zs[e + 1] if e + 1 < n else 0.0 + for k in range(both): + i = s + k + a = lo[i] + bet = dg[i] - a * pct + i2 = e - k + c = up[i2] + g = dg[i2] - c * pcb + if bet == 0.0 or g == 0.0: + return False + pct = up[i] / bet + pcb = lo[i2] / g + r = 1.0 / bet + r2 = 1.0 / g + o = a * r + o2 = c * r2 + zt = -o * zt + zbt = -o2 * zbt + pc[i] = pct + piv[i] = r + off[i] = o + zs[i] = zt + pc[i2] = pcb + piv[i2] = r2 + off[i2] = o2 + zs[i2] = zbt + for k in range(both, top): + i = s + k + a = lo[i] + bet = dg[i] - a * pct + if bet == 0.0: + return False + pct = up[i] / bet + r = 1.0 / bet + o = a * r + zt = -o * zt + pc[i] = pct + piv[i] = r + off[i] = o + zs[i] = zt + for k in range(both, bottom): + i2 = e - k + c = up[i2] + g = dg[i2] - c * pcb + if g == 0.0: + return False + pcb = lo[i2] / g + r2 = 1.0 / g + o2 = c * r2 + zbt = -o2 * zbt + pc[i2] = pcb + piv[i2] = r2 + off[i2] = o2 + zs[i2] = zbt + gm = dg[m] - lo[m] * pc[m - 1] - up[m] * pc[m + 1] + if gm == 0.0: + return False + rgm = 1.0 / gm + zt = (-(lo[m] * zs[m - 1]) - up[m] * zs[m + 1]) * rgm + zb[m] = zt + zbt = zt + left = m + right = n - 1 - m + both = min(left, right) + for k in range(1, both + 1): + zt = zs[m - k] - pc[m - k] * zt + zbt = zs[m + k] - pc[m + k] * zbt + zb[m - k] = zt + zb[m + k] = zbt + for k in range(both + 1, left + 1): + zt = zs[m - k] - pc[m - k] * zt + zb[m - k] = zt + for k in range(both + 1, right + 1): + zbt = zs[m + k] - pc[m + k] * zbt + zb[m + k] = zbt + bg = beta / gam + den = 1.0 + (zb[0] + bg * zb[n - 1]) + if den == 0.0 or not math.isfinite(den): + return False + mstate[0] = _CLEAN_LO + mstate[1] = _CLEAN_HI + mstate[2] = den + mstate[3] = bg + mstate[4] = rgm + return True + + +@njit(cache=True) +def _twisted_solve( + rhs: FloatArray, v: FloatArray, wy: FloatArray, mat: FloatArray, mstate: FloatArray +) -> bool: + """``v += A^-1 rhs`` for the cyclic tridiagonal Jacobian held in ``mat`` + (stale pivots are updated first); False for a singular system.""" + n = rhs.size + stale = mstate[0] < n or mstate[1] >= 0 + if stale and not _twisted_refactor(n, mat, mstate): + mstate[0] = 0.0 + mstate[1] = n - 1 + return False + lo = mat[_M_LOWER] + up = mat[_M_UPPER] + pc = mat[_M_PC] + piv = mat[_M_PIV] + off = mat[_M_OFF] + zb = mat[_M_ZB] + m = n // 2 + top = m + bottom = n - 1 - m + both = min(top, bottom) + wt = 0.0 + wb = 0.0 + for k in range(both): + i2 = n - 1 - k + wt = rhs[k] * piv[k] - off[k] * wt + wb = rhs[i2] * piv[i2] - off[i2] * wb + wy[k] = wt + wy[i2] = wb + for k in range(both, top): + wt = rhs[k] * piv[k] - off[k] * wt + wy[k] = wt + for k in range(both, bottom): + i2 = n - 1 - k + wb = rhs[i2] * piv[i2] - off[i2] * wb + wy[i2] = wb + xm = (rhs[m] - lo[m] * wy[m - 1] - up[m] * wy[m + 1]) * mstate[4] + wy[m] = xm + wt = xm + wb = xm + for k in range(1, both + 1): + wt = wy[m - k] - pc[m - k] * wt + wb = wy[m + k] - pc[m + k] * wb + wy[m - k] = wt + wy[m + k] = wb + for k in range(both + 1, top + 1): + wt = wy[m - k] - pc[m - k] * wt + wy[m - k] = wt + for k in range(both + 1, bottom + 1): + wb = wy[m + k] - pc[m + k] * wb + wy[m + k] = wb + fac = (wy[0] + mstate[3] * wy[n - 1]) / mstate[2] + for i in range(n): + v[i] += wy[i] - fac * zb[i] + return True + + +@njit(cache=True) +def _capstan_newton_fast( + y: FloatArray, + z0: FloatArray, + rho: float, + gnode: FloatArray, + khat: float, + lam: float, + h: float, + tol: float, + v: FloatArray, + b: FloatArray, + nn: FloatArray, + rhs: FloatArray, + wy: FloatArray, + prev: FloatArray, + mfac: FloatArray, + mat: FloatArray, + mstate: FloatArray, +) -> int: + """:func:`_solve_capstan_newton` with the kept twisted factorisation. + + On return ``nn`` and ``b`` hold the segment forces and bounds of the + returned ``v``, and ``mstate[5]`` is one if a node sticks clear of its + bound there (by the margin of :func:`_full_slip_slide`, which then leaves + the increment as it is). Returns iterations, or -1 (caller falls back to + the fixed point). + """ + n = y.size + ih = 1.0 / h + stick_diag = 2.0 * ih + h * khat + rk = mat[_M_KEY] + rm = mat[_M_FAC] + last_res = math.inf + for it in range(_MAX_NEWTON): + lo_s = mstate[0] + hi_s = mstate[1] + res = 0.0 + any_elastic = False + same = it > 0 + firm = False + nearest = 0 + gap = math.inf + n_prev = y[n - 1] + (v[0] - v[n - 1]) * ih + for j in range(n): + vj = v[j] + nj = y[j] + ((v[j + 1] if j + 1 < n else v[0]) - vj) * ih + nn[j] = nj + mj = mfac[j] + bj = mj * (rho * gnode[j] + lam * 0.5 * (nj + n_prev)) + if bj < 0.0: + bj = 0.0 + b[j] = bj + r = z0[j] + vj + kr = khat * r + excess = abs(kr) - bj + if excess < gap: + gap = excess + nearest = j + if excess < 0.0: + key = 4.0 + t = kr + any_elastic = True + if abs(kr) < bj * (1.0 - _ON_BOUND): + firm = True + else: + key = 5.0 if r > 0.0 else 3.0 + t = bj if r > 0.0 else -bj + if not bj > 0.0: + key -= 4.0 + if key != prev[j]: + same = False + prev[j] = key + if key != rk[j] or ((key == 5.0 or key == 3.0) and mj != rm[j]): + _set_row(j, key, mj, lam, ih, stick_diag, mat) + if j < lo_s: + lo_s = j + if j > hi_s: + hi_s = j + g = nj - n_prev - h * t + rhs[j] = g + if abs(g) > res: + res = abs(g) + n_prev = nj + mstate[0] = lo_s + mstate[1] = hi_s + if res <= tol or (same and any_elastic and res <= 1e6 * tol): + mstate[5] = 1.0 if firm else 0.0 + return it + if not math.isfinite(res): + return -1 + if it > 3 and res > last_res: + return -1 + last_res = res + if gap >= 0.0: + # Full slip: the node nearest to sticking takes the stick row so + # that the tractions can balance. + _set_row(nearest, _OVERRIDE, mfac[nearest], lam, ih, stick_diag, mat) + if nearest < mstate[0]: + mstate[0] = nearest + if nearest > mstate[1]: + mstate[1] = nearest + if not _twisted_solve(rhs, v, wy, mat, mstate): + return -1 + return -1 + + +@njit(cache=True) +def _advance_fast( + ax: float, + ay: float, + rho: float, + cs: FloatArray, + sn: FloatArray, + gnode: FloatArray, + khat: float, + lam: float, + h: float, + u: FloatArray, + p: FloatArray, + nf: FloatArray, + tau: FloatArray, + e: FloatArray, + energy: FloatArray, + work: FloatArray, + stats: NDArray[np.int64], + capstan_newton: bool, + mfac: FloatArray, + law: FloatArray, + lstate: FloatArray, + ptab: FloatArray, + p_ref: float, + vlast: FloatArray, + mat: FloatArray, + mstate: FloatArray, +) -> bool: + """:func:`_advance` started from ``vlast``, the increment of the last + substep, with the kept Newton factorisation; ``vlast`` receives the + increment of this one.""" + n = u.size + ih = 1.0 / h + ik = 1.0 / khat + y = work[0] + z0 = work[1] + b = work[2] + v = work[3] + vn = work[4] + vt = work[5] + dv = work[6] + d = work[7] + rhs = work[8] + cp = work[9] + wy = work[10] + wz = work[11] + ncur = work[12] + enew = work[13] + nn = work[14] + prev = work[17] + broke = work[18] + bend = work[19] + pfac = work[21] + has_table = ptab.shape[1] > 0 + law_on = law[0] != 0.0 and law[1] != law[2] + newton = lam > 0.0 and capstan_newton + # Without a pressure table the node factors are the law factors. + meff = work[20] if has_table else mfac + if has_table: + for j in range(n): + pfac[j] = _pressure_factor(p_ref * rho * gnode[j], ptab) + meff[j] = mfac[j] * pfac[j] + if law_on: + for j in range(n): + broke[j] = 0.0 + scale = 1.0 + for j in range(n): + ej = ax * cs[j] + ay * sn[j] + enew[j] = ej + yj = ej + ((u[j + 1] if j + 1 < n else u[0]) - u[j]) * ih + y[j] = yj + z0[j] = u[j] - p[j] + v[j] = vlast[j] + if abs(yj) > scale: + scale = abs(yj) + if abs(ej) > scale: + scale = abs(ej) + if rho > scale: + scale = rho + tol = 1e-12 * h * scale + # The segment forces of the solution: those of the converged Newton pass, + # or of the fixed point. + nsol = nn + sticks = False + for attempt in range(n + 1): + if attempt > 0: + for j in range(n): + v[j] = 0.0 + # Started from the prediction; solved again from zero (the start of + # the reference) if that fails. + predicted = attempt == 0 + while True: + converged = False + if newton: + iters = _capstan_newton_fast( + y, + z0, + rho, + gnode, + khat, + lam, + h, + tol, + v, + b, + nn, + rhs, + wy, + prev, + meff, + mat, + mstate, + ) + if iters >= 0: + if iters > stats[1]: + stats[1] = iters + stats[4] += iters + nsol = nn + converged = True + sticks = mstate[5] != 0.0 + elif predicted: + predicted = False + for j in range(n): + v[j] = 0.0 + continue + else: + stats[6] += 1 + for j in range(n): + v[j] = 0.0 + if not converged: + for j in range(n): + ncur[j] = nf[j] + if not _fixed_point( + y, + z0, + rho, + gnode, + khat, + lam, + h, + tol, + v, + b, + d, + rhs, + dv, + cp, + wy, + wz, + vn, + vt, + ncur, + stats, + meff, + ): + if not predicted: + return False + predicted = False + for j in range(n): + v[j] = 0.0 + continue + nsol = ncur + sticks = False + break + if not law_on: + break + changed = False + for j in range(n): + if lstate[0, j] != 0.0: + jm = j - 1 if j > 0 else n - 1 + bj = meff[j] * (rho * gnode[j] + lam * 0.5 * (nsol[j] + nsol[jm])) + if bj < 0.0: + bj = 0.0 + if abs(khat * (z0[j] + v[j])) > bj: + mfac[j] = law[2] + if has_table: + meff[j] = mfac[j] * pfac[j] + lstate[0, j] = 0.0 + broke[j] = 1.0 + changed = True + if not changed: + break + if not sticks: + # A node that sticks fixes the slide; the Newton pass has found one. + _full_slip_slide(z0, v, nsol, meff, rho, gnode, khat, lam) + w_be = 0.0 + diss = 0.0 + rem = 0.0 + n_prev = nsol[n - 1] + for j in range(n): + nj = nsol[j] + bj = meff[j] * (rho * gnode[j] + lam * 0.5 * (nj + n_prev)) + if bj < 0.0: + bj = 0.0 + bend[j] = bj + vj = v[j] + t = khat * (z0[j] + vj) + slipped = False + if t > bj: + t = bj + slipped = True + elif t < -bj: + t = -bj + slipped = True + unew = u[j] + vj + dp = (unew - t * ik) - p[j] + diss += h * t * dp + ej = enew[j] + w_be += h * nj * (ej - e[j]) + dn = nj - nf[j] + dt = t - tau[j] + rem += 0.5 * h * dn * dn + 0.5 * h * dt * dt * ik + u[j] = unew + p[j] += dp + tau[j] = t + nf[j] = nj + e[j] = ej + vlast[j] = vj + n_prev = nj + if law_on: + if slipped or broke[j] != 0.0: + lstate[0, j] = 0.0 + lstate[1, j] = 0.0 + mfac[j] = law[2] + elif lstate[0, j] == 0.0: + lstate[1, j] += law[4] + if lstate[1, j] >= law[3]: + lstate[0, j] = 1.0 + mfac[j] = law[1] + energy[0] += w_be + energy[1] += diss + energy[2] += rem + return True + + +@njit(cache=True) +def _fixed_point( + y: FloatArray, + z0: FloatArray, + rho: float, + gnode: FloatArray, + khat: float, + lam: float, + h: float, + tol: float, + v: FloatArray, + b: FloatArray, + d: FloatArray, + rhs: FloatArray, + dv: FloatArray, + cp: FloatArray, + wy: FloatArray, + wz: FloatArray, + vn: FloatArray, + vt: FloatArray, + ncur: FloatArray, + stats: NDArray[np.int64], + mfac: FloatArray, +) -> bool: + """Fixed point on the bound of :func:`_solve_increment` (the reference + scheme; used for ``lam = 0``, ``capstan_newton=False`` and fall-backs).""" + n = y.size + for it in range(_MAX_FIXED_POINT): + for j in range(n): + jm = j - 1 if j > 0 else n - 1 + b[j] = mfac[j] * (rho * gnode[j] + lam * 0.5 * (ncur[j] + ncur[jm])) + if b[j] < 0.0: + b[j] = 0.0 + iters = _solve_fixed_bound( + y, z0, b, khat, h, tol, v, vn, vt, dv, d, rhs, cp, wy, wz + ) + if iters < 0: + return False + if iters > stats[1]: + stats[1] = iters + stats[4] += iters + diff = 0.0 + big = 1.0 + for j in range(n): + jp = j + 1 if j + 1 < n else 0 + n_new = y[j] + (v[jp] - v[j]) / h + if abs(n_new - ncur[j]) > diff: + diff = abs(n_new - ncur[j]) + if abs(n_new) > big: + big = abs(n_new) + ncur[j] = n_new + if not math.isfinite(diff): + return False + if lam == 0.0 or diff <= 1e-12 * big: + if it + 1 > stats[2]: + stats[2] = it + 1 + stats[5] += it + 1 + return True + return False + + +@njit(cache=True) +def _distributed_kernel_fast( + ax_path: FloatArray, + ay_path: FloatArray, + rho_path: FloatArray, + khat: float, + lam: float, + gnode: FloatArray, + phase0: float, + xi: float, + max_increment: float, + wire_index: NDArray[np.int64], + wire_frac: FloatArray, + record_field: bool, + capstan_newton: bool = True, + record_index: NDArray[np.int64] | None = None, + kinematics: FloatArray | None = None, + law: FloatArray | None = None, + dt_path: FloatArray | None = None, + ptab: FloatArray | None = None, + p_ref: float = 0.0, +) -> tuple[FloatArray, FloatArray, FloatArray, NDArray[np.int64], FloatArray]: + """:func:`_distributed_kernel` with the fast increment solver (same + arguments and results, to round-off).""" + n = gnode.size + if n < 3: + return _distributed_kernel( + ax_path, + ay_path, + rho_path, + khat, + lam, + gnode, + phase0, + xi, + max_increment, + wire_index, + wire_frac, + record_field, + capstan_newton, + record_index, + kinematics, + law, + dt_path, + ptab, + p_ref, + ) + h = 2.0 * math.pi / n + n_t = ax_path.size + n_w = wire_index.size + cs = np.empty(n) + sn = np.empty(n) + for j in range(n): + cs[j] = math.cos(phase0 + j * h) + sn[j] = math.sin(phase0 + j * h) + u = np.zeros(n) + p = np.zeros(n) + nf = np.zeros(n) + tau = np.zeros(n) + e = np.zeros(n) + vlast = np.zeros(n) + su = np.empty(n) + sp = np.empty(n) + snf = np.empty(n) + stau = np.empty(n) + se = np.empty(n) + svlast = np.empty(n) + work = np.zeros((22, n)) + mat = np.full((_M_ROWS, n), np.nan) + mstate = np.zeros(6) + mstate[1] = n - 1 + table = np.zeros((2, 0)) + if ptab is not None: + table = ptab + mfac = np.ones(n) + smfac = np.ones(n) + lstate = np.zeros((2, n)) + slstate = np.zeros((2, n)) + lparams = np.zeros(5) + if law is not None: + lparams[0] = 1.0 + lparams[1] = law[0] + lparams[2] = law[1] + lparams[3] = law[2] + for j in range(n): + mfac[j] = law[0] + lstate[0, j] = 1.0 + energy = np.zeros(3) + senergy = np.zeros(3) + stats = np.zeros(7, dtype=np.int64) + out = np.empty((n_w, n_t)) + hist = np.empty((n_t, 4)) + slip = np.empty(n_t) + fld = np.empty((n_t if record_field else 0, n)) + ax0 = 0.0 + ay0 = 0.0 + rho0 = rho_path[0] if n_t > 0 else 0.0 + ik = 1.0 / khat + for i in range(n_t): + ax1 = ax_path[i] + ay1 = ay_path[i] + rho1 = rho_path[i] + step = math.sqrt((ax1 - ax0) ** 2 + (ay1 - ay0) ** 2) * xi + nsub = 1 + if max_increment > 0.0 and step > max_increment: + nsub = int(math.ceil(step / max_increment)) + for j in range(n): + su[j] = u[j] + sp[j] = p[j] + snf[j] = nf[j] + stau[j] = tau[j] + se[j] = e[j] + svlast[j] = vlast[j] + for k in range(3): + senergy[k] = energy[k] + for j in range(n): + smfac[j] = mfac[j] + slstate[0, j] = lstate[0, j] + slstate[1, j] = lstate[1, j] + ok = False + for _attempt in range(_MAX_HALVINGS + 1): + ok = True + if dt_path is not None: + lparams[4] = dt_path[i] / nsub + for s in range(1, nsub + 1): + f = s / nsub + if not _advance_fast( + ax0 + f * (ax1 - ax0), + ay0 + f * (ay1 - ay0), + rho0 + f * (rho1 - rho0), + cs, + sn, + gnode, + khat, + lam, + h, + u, + p, + nf, + tau, + e, + energy, + work, + stats, + capstan_newton, + mfac, + lparams, + lstate, + table, + p_ref, + vlast, + mat, + mstate, + ): + ok = False + break + if ok: + break + for j in range(n): + u[j] = su[j] + p[j] = sp[j] + nf[j] = snf[j] + tau[j] = stau[j] + e[j] = se[j] + vlast[j] = svlast[j] + for k in range(3): + energy[k] = senergy[k] + for j in range(n): + mfac[j] = smfac[j] + lstate[0, j] = slstate[0, j] + lstate[1, j] = slstate[1, j] + nsub *= 2 + if not ok: + stats[0] = -(i + 1) + return out, hist, slip, stats, fld + stats[3] += nsub + ax0 = ax1 + ay0 = ay1 + rho0 = rho1 + stored = 0.0 + n_slip = 0 + for j in range(n): + jm = j - 1 if j > 0 else n - 1 + stored += 0.5 * h * (nf[j] * nf[j] + tau[j] * tau[j] * ik) + if law is None: + bj = rho1 * gnode[j] + lam * 0.5 * (nf[j] + nf[jm]) + if bj < 0.0: + bj = 0.0 + else: + bj = work[19, j] # bound of the last increment + if bj > 0.0 and abs(tau[j]) >= bj * (1.0 - 1e-9): + n_slip += 1 + hist[i, 0] = energy[0] + hist[i, 1] = energy[1] + hist[i, 2] = stored + hist[i, 3] = energy[2] + slip[i] = n_slip / n + for k in range(n_w): + j0 = wire_index[k] + j1 = j0 + 1 if j0 + 1 < n else 0 + out[k, i] = (1.0 - wire_frac[k]) * nf[j0] + wire_frac[k] * nf[j1] + if record_field: + for j in range(n): + fld[i, j] = nf[j] + if record_index is not None and kinematics is not None: + row = record_index[i] + if row >= 0: + for j in range(n): + kinematics[row, 0, j] = u[j] + kinematics[row, 1, j] = p[j] + kinematics[row, 2, j] = p[j] - sp[j] + kinematics[row, 3, j] = nf[j] + return out, hist, slip, stats, fld + + # --------------------------------------------------------------------------- # # Physical wrapper # # --------------------------------------------------------------------------- # @@ -1376,8 +2275,11 @@ def distributed_friction_history( raise CableInputError( "field samples must be increasing indices of the history" ) + # The fast kernel when compiled; the reference kernel otherwise (it is + # the faster of the two as Python) and on request (tests). + kernel = _distributed_kernel_fast if _FAST_KERNEL else _distributed_kernel if kept is None and law is None: - out, hist, slip, stats, fld = _distributed_kernel( + out, hist, slip, stats, fld = kernel( kx / kappa_c, ky / kappa_c, pressure / p_ref, @@ -1397,7 +2299,7 @@ def distributed_friction_history( index = np.full(count, -1, dtype=np.int64) index[kept] = np.arange(kept.size) kinematics = np.zeros((kept.size, 4, n_nodes)) - out, hist, slip, stats, fld = _distributed_kernel( + out, hist, slip, stats, fld = kernel( kx / kappa_c, ky / kappa_c, pressure / p_ref, @@ -1420,7 +2322,7 @@ def distributed_friction_history( if kept is not None: index[kept] = np.arange(kept.size) kinematics = np.zeros((kept.size, 4, n_nodes)) - out, hist, slip, stats, fld = _distributed_kernel( + out, hist, slip, stats, fld = kernel( kx / kappa_c, ky / kappa_c, pressure / p_ref, diff --git a/tests/test_distributed_fast.py b/tests/test_distributed_fast.py new file mode 100644 index 0000000..ca648bd --- /dev/null +++ b/tests/test_distributed_fast.py @@ -0,0 +1,346 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""The fast distributed-friction kernel must reproduce the reference kernel. + +``_distributed_kernel_fast`` (used when numba is active) solves the same +increments as ``_distributed_kernel`` with a predicted start and a kept +factorisation; the two agree to round-off on every output: wire forces, +energies, slip fraction, segment field and kept kinematics. +""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest + +import cablexsec as cx +from cablexsec._numba import kernels_compiled +from cablexsec.mechanics import distributed_friction as dfm +from cablexsec.mechanics.friction_law import FrictionLaw + +PI = math.pi +# Relative to the largest value of each output; the kernels differ by the +# order of floating-point operations only. +RTOL = 1e-10 +# Interpreted kernels (no numba, or the coverage pass) take shorter histories. +COMPILED = kernels_compiled() +STEPS = 240 if COMPILED else 48 +INCREMENT = 0.1 if COMPILED else 0.5 + + +def _paths(kind, steps=STEPS): + t = np.linspace(0.0, 1.0, steps) + if kind == "planar": + return 6.0 * np.sin(6 * PI * t) * (0.4 + t), np.zeros(steps) + if kind == "rotating": + a = np.minimum(1.0, 4 * t) * 2.5 + return a * np.cos(8 * PI * t), a * np.sin(8 * PI * t) + if kind == "one_sided": + # Bending that never reverses its sign: partial unloading only. + return 3.0 + 2.0 * np.sin(5 * PI * t), 0.5 + 0.3 * np.cos(3 * PI * t) + if kind == "full_slip": + # A planar ramp far beyond the slip onset: every node at the bound. + return np.linspace(0.0, 60.0, steps), np.zeros(steps) + raise ValueError(kind) + + +def _run(kernel, ax, ay, *, khat=0.33, lam=0.127, nodes=48, **options): + rho = options.pop("rho", None) + g = options.pop("g", None) + samples = options.pop("record_index", None) + kinematics = None + if samples is not None: + kinematics = np.zeros((int(samples.max()) + 1, 4, nodes)) + out = kernel( + np.ascontiguousarray(ax, dtype=float), + np.ascontiguousarray(ay, dtype=float), + np.ones(len(ax)) if rho is None else np.ascontiguousarray(rho, dtype=float), + float(khat), + float(lam), + np.ones(nodes) if g is None else np.ascontiguousarray(g, dtype=float), + options.pop("phase0", 0.0), + options.pop("xi", 1.0), + options.pop("max_increment", INCREMENT), + np.arange(0, nodes, 4, dtype=np.int64), + np.zeros(len(range(0, nodes, 4))), + True, + options.pop("newton", True), + samples, + kinematics, + *options.pop("law", ()), + ) + assert not options + return out, kinematics + + +def _assert_kinematics_close(fast, ref): + """Kept helix fields ``(samples, [u, p, step slip, n], N)``, also in full + slip, where both kernels fix the slide of ``u`` and ``p`` by the same + rule (``_full_slip_slide``).""" + scale = max(float(np.abs(ref[:, :3]).max()), 1.0) + assert np.abs(fast[:, 3] - ref[:, 3]).max() <= RTOL * np.abs(ref[:, 3]).max() + assert np.abs(fast[:, :3] - ref[:, :3]).max() <= RTOL * scale + + +def _assert_close(fast, ref): + (f_out, f_hist, f_slip, f_stats, f_fld), f_kin = fast + (r_out, r_hist, r_slip, r_stats, r_fld), r_kin = ref + assert f_stats[0] == r_stats[0] == 0 + assert f_stats[3] == r_stats[3] # the same substeps + pairs = [(f_out, r_out), (f_fld, r_fld)] + if r_kin is not None: + _assert_kinematics_close(f_kin, r_kin) + for a, b in pairs: + scale = max(float(np.abs(b).max()), 1e-300) + assert np.abs(a - b).max() <= RTOL * scale + # Energies on the scale of the largest one: the dissipation of an + # elastic path and the remainder are themselves round-off there. + scale = float(np.abs(r_hist).max()) + assert np.abs(f_hist - r_hist).max() <= RTOL * scale + np.testing.assert_allclose(f_slip, r_slip, rtol=0, atol=2.0 / f_fld.shape[1]) + + +@pytest.mark.parametrize("kind", ["planar", "rotating", "one_sided", "full_slip"]) +@pytest.mark.parametrize("lam", [0.127, 0.0], ids=["signed", "uniform"]) +def test_fast_kernel_matches_reference(kind, lam): + ax, ay = _paths(kind) + for khat in (0.33, 4.4): + args = {"khat": khat, "lam": lam} + ref = _run(dfm._distributed_kernel, ax, ay, **args) + fast = _run(dfm._distributed_kernel_fast, ax, ay, **args) + _assert_close(fast, ref) + + +def test_fast_kernel_matches_reference_with_shape_pressure_and_kinematics(): + ax, ay = _paths("rotating") + nodes = 64 + rho = 1.0 + 0.3 * np.sin(np.linspace(0.0, 9.0, ax.size)) + g = 1.0 + 0.25 * np.cos(2 * PI * np.arange(nodes) / nodes) + index = np.full(ax.size, -1, dtype=np.int64) + index[::17] = np.arange(index[::17].size) + common = {"nodes": nodes, "rho": rho, "g": g, "phase0": PI / nodes} + for newton in (True, False): + options = dict(common, newton=newton) + ref = _run(dfm._distributed_kernel, ax, ay, record_index=index, **options) + fast = _run(dfm._distributed_kernel_fast, ax, ay, record_index=index, **options) + _assert_close(fast, ref) + + +def test_fast_kernel_matches_reference_with_friction_law(): + ax, ay = _paths("planar") + nodes = 48 + rho = 1.0 + 0.4 * np.sin(np.linspace(0.0, 7.0, ax.size)) + table = np.array([[0.5, 1.5], [1.2, 0.8]]) # [P, f]: falls with pressure + for law in ( + (np.array([1.3, 1.0, 0.0]), np.full(ax.size, 0.01), None, 0.0), + (np.array([1.3, 1.0, 0.05]), np.full(ax.size, 0.01), table, 1.0), + (np.array([1.0, 1.0, math.inf]), np.zeros(ax.size), table, 1.0), + ): + options = {"nodes": nodes, "rho": rho, "law": law} + ref = _run(dfm._distributed_kernel, ax, ay, **options) + fast = _run(dfm._distributed_kernel_fast, ax, ay, **options) + _assert_close(fast, ref) + + +def test_fast_kernel_on_a_small_helix(): + # Fewer than three nodes go to the reference kernel unchanged. + ax, ay = _paths("rotating", steps=40) + for nodes in (2, 3, 4): + ref = _run(dfm._distributed_kernel, ax, ay, nodes=nodes) + fast = _run(dfm._distributed_kernel_fast, ax, ay, nodes=nodes) + _assert_close(fast, ref) + + +def _cyclic(rng, n): + lower = -1.0 - 0.3 * rng.random(n) + upper = -1.0 + 0.3 * rng.random(n) + diag = 2.6 + rng.random(n) + dense = np.diag(diag) + for i in range(n): + dense[i, (i - 1) % n] += lower[i] + dense[i, (i + 1) % n] += upper[i] + return lower, diag, upper, dense + + +@pytest.mark.parametrize("n", [3, 4, 7, 16, 33]) +def test_kept_twisted_factorisation_solves_after_row_changes(n): + """Pivots kept outside the changed rows give the dense solution.""" + rng = np.random.default_rng(n) + mat = np.full((dfm._M_ROWS, n), np.nan) + mstate = np.array([0.0, n - 1.0, 0.0, 0.0, 0.0, 0.0]) + lower, diag, upper, dense = _cyclic(rng, n) + for trial in range(40): + if trial: + # Change one to three rows, marking them stale as the Newton pass does. + for j in rng.choice(n, size=min(n, 1 + trial % 3), replace=False): + lower[j] = -1.0 - 0.3 * rng.random() + upper[j] = -1.0 + 0.3 * rng.random() + diag[j] = 2.6 + rng.random() + mstate[0] = min(mstate[0], j) + mstate[1] = max(mstate[1], j) + dense = np.diag(diag) + for i in range(n): + dense[i, (i - 1) % n] += lower[i] + dense[i, (i + 1) % n] += upper[i] + mat[dfm._M_LOWER] = lower + mat[dfm._M_DIAG] = diag + mat[dfm._M_UPPER] = upper + rhs = rng.normal(size=n) + v = np.full(n, 0.5) + assert dfm._twisted_solve(rhs, v, np.empty(n), mat, mstate) + assert mstate[0] >= n and mstate[1] < 0 + np.testing.assert_allclose(v - 0.5, np.linalg.solve(dense, rhs), atol=1e-12) + + +def test_twisted_factorisation_reports_singular_pivots(): + n = 8 + lower, diag, upper, _ = _cyclic(np.random.default_rng(1), n) + # Zero pivots: row 0, a top row, a bottom row, the corner row and the + # middle row (the entries named are set to zero). + for row, zeros in ( + (0, (dfm._M_DIAG,)), + (2, (dfm._M_DIAG, dfm._M_LOWER)), + (6, (dfm._M_DIAG, dfm._M_UPPER)), + (n - 1, (dfm._M_DIAG, dfm._M_UPPER)), + (n // 2, (dfm._M_DIAG, dfm._M_LOWER, dfm._M_UPPER)), + ): + mat = np.full((dfm._M_ROWS, n), np.nan) + mat[dfm._M_LOWER] = lower + mat[dfm._M_DIAG] = diag + mat[dfm._M_UPPER] = upper + for band in zeros: + mat[band, row] = 0.0 + mstate = np.array([0.0, n - 1.0, 0.0, 0.0, 0.0, 0.0]) + assert not dfm._twisted_solve(np.ones(n), np.zeros(n), np.empty(n), mat, mstate) + assert mstate[0] == 0.0 and mstate[1] == n - 1 + + +python_kernels = pytest.mark.skipif( + COMPILED, reason="replaces kernel functions, which needs them as Python" +) + + +@python_kernels +@pytest.mark.parametrize("lam", [0.127, 0.0]) +def test_fast_kernel_fall_backs(monkeypatch, lam): + """Without its Newton the fast kernel falls back to the fixed point of + the reference; an increment that never converges names its sample.""" + ax, ay = _paths("rotating", steps=30) + ref = _run(dfm._distributed_kernel, ax, ay, lam=lam, nodes=16) + monkeypatch.setattr(dfm, "_capstan_newton_fast", lambda *args: -1) + fast = _run(dfm._distributed_kernel_fast, ax, ay, lam=lam, nodes=16) + _assert_close(fast, ref) + if lam > 0.0: + assert fast[0][3][6] == fast[0][3][3] # every substep fell back + calls = [] + + def fixed_point_failing_after_three(*args): + calls.append(1) + return len(calls) <= 3 and real_fixed_point(*args) + + real_fixed_point = dfm._fixed_point + monkeypatch.setattr(dfm, "_fixed_point", fixed_point_failing_after_three) + (out, _h, _s, stats, _f), _ = _run( + dfm._distributed_kernel_fast, ax, ay, lam=lam, nodes=16, max_increment=math.inf + ) + assert stats[0] == -4 # samples 0-2 advanced, sample 3 not, after 12 halvings + np.testing.assert_allclose(out[:, :3], ref[0][0][:, :3], rtol=0, atol=1e-12) + + +@python_kernels +def test_fast_newton_restarts_from_zero_before_the_fixed_point(monkeypatch): + ax, ay = _paths("rotating", steps=30) + ref = _run(dfm._distributed_kernel, ax, ay, nodes=16) + real = dfm._capstan_newton_fast + + def failing_from_a_prediction(*args): + v = args[8] + return -1 if np.any(v != 0.0) else real(*args) + + monkeypatch.setattr(dfm, "_capstan_newton_fast", failing_from_a_prediction) + fast = _run(dfm._distributed_kernel_fast, ax, ay, nodes=16) + _assert_close(fast, ref) + assert fast[0][3][6] == 0 # no fixed-point fall-back + + +def _armour(): + cable = cx.load_cable(cx.iea_task49_66kv_yaml_path(), geometry_override=None) + return cx.cable_to_fatigue_layers(cable, contact_tension_N=1e5)[0].spec + + +def _histories(monkeypatch, law, bound): + spec = _armour() + t = np.linspace(0.0, 30.0, 301 if COMPILED else 61) + kx = 0.004 * np.sin(2 * PI * 0.1 * t) + ky = 0.002 * np.sin(2 * PI * 0.1 * t + 1.0) + pressure = spec.contact_pressure_Pa * (1.0 + 0.2 * np.sin(2 * PI * 0.07 * t)) + healing = law is not None and math.isfinite(law.stick_time_s) + runs = [] + for fast in (False, True): + monkeypatch.setattr(dfm, "_FAST_KERNEL", fast) + runs.append( + dfm.distributed_friction_history( + spec, + kx, + ky, + contact_pressure_Pa=pressure, + friction_law=law, + time_s=t if healing else None, + bound=bound, + field_samples=np.arange(0, t.size, 10), + nodes_per_pitch=None if COMPILED else 32, + ) + ) + return runs + + +_ENERGIES = ( + "dissipation_J_per_m", + "stored_J_per_m", + "endpoint_work_J_per_m", + "integration_remainder_J_per_m", +) + + +@pytest.mark.parametrize("bound", ["signed", "uniform"]) +@pytest.mark.parametrize( + "law", + [None, FrictionLaw(pressure_factor=((2e4, 1.1), (1.5e5, 0.9)))], + ids=["no_law", "pressure_factor"], +) +def test_public_history_is_the_reference_to_round_off(monkeypatch, bound, law): + ref, fast = _histories(monkeypatch, law, bound) + assert ( + np.abs(fast.stress_Pa - ref.stress_Pa).max() + <= RTOL * np.abs(ref.stress_Pa).max() + ) + _assert_kinematics_close(fast.kinematic_field, ref.kinematic_field) + energy = np.abs(ref.endpoint_work_J_per_m).max() + for name in _ENERGIES: + a, b = getattr(fast, name), getattr(ref, name) + assert np.abs(a - b).max() <= RTOL * energy, name + assert fast.parameters["substeps"] == ref.parameters["substeps"] + + +@pytest.mark.parametrize("bound", ["signed", "uniform"]) +def test_public_history_with_healing_matches_the_reference(monkeypatch, bound): + """With a finite healing time a node's factor follows binary events (it + heals after sticking long enough, breaks away when its trial traction + leaves the static bound) that a round-off change can move by a substep, + in the reference as much as between the kernels. On the 32-node history + of the interpreted run with the uniform bound a relative change of 1e-15 + in the curvature moves the largest reference stress by 0.24 % of its + peak, as much as the kernels differ there; with the default nodes + (compiled run) they agree to round-off. + """ + law = FrictionLaw(static_factor=1.2, dynamic_factor=1.0, stick_time_s=0.5) + ref, fast = _histories(monkeypatch, law, bound) + tol = RTOL if COMPILED else 0.01 + scale = np.abs(ref.stress_Pa).max() + assert np.abs(fast.stress_Pa - ref.stress_Pa).max() <= tol * scale + energy = np.abs(ref.endpoint_work_J_per_m).max() + for name in _ENERGIES: + a, b = getattr(fast, name), getattr(ref, name) + assert np.abs(a - b).max() <= tol * energy, name diff --git a/tests/test_distributed_friction.py b/tests/test_distributed_friction.py index 167b5f7..cc17502 100644 --- a/tests/test_distributed_friction.py +++ b/tests/test_distributed_friction.py @@ -34,6 +34,10 @@ compiled = pytest.mark.skipif( not dfm.HAVE_NUMBA, reason="long histories need the compiled kernel" ) +#: The recorded values hold for the reference and the fast kernel. +both_kernels = pytest.mark.parametrize( + "kernel", ["_distributed_kernel", "_distributed_kernel_fast"] +) # --------------------------------------------------------------------------- # @@ -50,12 +54,25 @@ def _rotation(a, revolutions, steps_per_rev, ramp_steps=200): return np.concatenate([rx, a * np.cos(th)]), np.concatenate([ry, a * np.sin(th)]) -def _kernel(ax, ay, khat, lam, nodes, *, rho=None, g=None, phase0=None, newton=True): - """Normalised kernel on the stick_check grid (segments at (j + 1/2) h).""" +def _kernel( + ax, + ay, + khat, + lam, + nodes, + *, + rho=None, + g=None, + phase0=None, + newton=True, + kernel="_distributed_kernel", +): + """Normalised kernel on the stick_check grid (segments at (j + 1/2) h); + ``kernel`` names the reference or the fast kernel.""" ax = np.ascontiguousarray(ax, dtype=float) ay = np.ascontiguousarray(ay, dtype=float) h = 2 * PI / nodes - out = dfm._distributed_kernel( + out = getattr(dfm, kernel)( ax, ay, np.ones(ax.size) if rho is None else np.ascontiguousarray(rho, dtype=float), @@ -201,6 +218,7 @@ def advance(self, ax, ay, rho): # (1) agreement with the reference results # # --------------------------------------------------------------------------- # @compiled +@both_kernels @pytest.mark.parametrize( ("khat", "lutchansky", "d_rev"), [ @@ -208,18 +226,18 @@ def advance(self, ax, ay, rho): (3.0, 1.0039049199273009e-05, 7.622586096093627), ], ) -def test_stick_check_verification_cases(khat, lutchansky, d_rev): +def test_stick_check_verification_cases(khat, lutchansky, d_rev, kernel): xi = khat / (1 + khat) # Below slip the field is the Lutchansky shear-lag solution a xi cos(phi). a = 0.8 / xi ax, ay = _ramp((a, 0.0), 50) - fld = _kernel(ax, ay, khat, 0.0, 256)[4] + fld = _kernel(ax, ay, khat, 0.0, 256, kernel=kernel)[4] phi = (np.arange(256) + 0.5) * 2 * PI / 256 err = np.abs(fld[-1] - a * xi * np.cos(phi)).max() assert err == pytest.approx(lutchansky, rel=1e-8) # Steady rotation at a_bar = 1.3: dissipation of the 4th revolution. ax, ay = _rotation(1.3 / xi, 4, 720) - hist = _kernel(ax, ay, khat, 0.0, 256)[1] + hist = _kernel(ax, ay, khat, 0.0, 256, kernel=kernel)[1] d = hist[:, 1] assert d[-1] - d[-721] == pytest.approx(d_rev, rel=1e-10) identity = hist[:, 0] - hist[:, 1] - hist[:, 2] - hist[:, 3] @@ -227,9 +245,10 @@ def test_stick_check_verification_cases(khat, lutchansky, d_rev): @compiled -def test_stick_check_rigid_limit_and_capstan_cases(): +@both_kernels +def test_stick_check_rigid_limit_and_capstan_cases(kernel): ax, ay = _rotation(2.0 * 1.001, 3, 720) - hist = _kernel(ax, ay, 1000.0, 0.0, 256)[1] + hist = _kernel(ax, ay, 1000.0, 0.0, 256, kernel=kernel)[1] assert hist[-1, 1] - hist[-721, 1] == pytest.approx(30.622844477479035, rel=1e-10) # Capstan case, signed bound: the NumPy port of stick_check gives # 29.42502785927062 (the former lam |n| bound: 26.579392168691143). The @@ -246,7 +265,7 @@ def test_stick_check_rigid_limit_and_capstan_cases(): d_ref = float(np.sum(dissipated[-720:])) assert d_ref == pytest.approx(29.42502785927062, rel=1e-10) for newton in (True, False): - hist = _kernel(ax, ay, 0.33, 0.127, 256, newton=newton)[1] + hist = _kernel(ax, ay, 0.33, 0.127, 256, newton=newton, kernel=kernel)[1] d_rev = hist[-1, 1] - hist[-721, 1] assert d_rev == pytest.approx(d_ref, rel=1e-10) diff --git a/tests/test_friction_kernels.py b/tests/test_friction_kernels.py index 21d09a3..5887c08 100644 --- a/tests/test_friction_kernels.py +++ b/tests/test_friction_kernels.py @@ -282,7 +282,8 @@ def test_distributed_contact_shape_is_checked(armour): def test_unconverged_kernel_names_the_sample(armour, monkeypatch): - kernel = dfm._distributed_kernel + name = "_distributed_kernel_fast" if dfm._FAST_KERNEL else "_distributed_kernel" + kernel = getattr(dfm, name) def failing_at_sample_2(*args): out, hist, slip, stats, fld = kernel(*args) @@ -290,7 +291,7 @@ def failing_at_sample_2(*args): stats[0] = -3 # the kernel's status for sample index 2 return out, hist, slip, stats, fld - monkeypatch.setattr(dfm, "_distributed_kernel", failing_at_sample_2) + monkeypatch.setattr(dfm, name, failing_at_sample_2) with pytest.raises(CableInputError, match="did not converge at sample 2"): dfm.distributed_friction_history( armour, np.full(4, 0.01), np.zeros(4), nodes_per_pitch=16 diff --git a/validation/validation_report.md b/validation/validation_report.md index 6654bae..8bc97e2 100644 --- a/validation/validation_report.md +++ b/validation/validation_report.md @@ -67,9 +67,9 @@ Every row is computed from published data or closed-form references in this repo ## Test taxonomy (full gate suite) -- analytical_sanity: `1153 passed, 3219 deselected` -- independent_method: `76 passed, 4296 deselected` -- full_scale: `31 passed, 4341 deselected` +- analytical_sanity: `1153 passed, 3248 deselected` +- independent_method: `76 passed, 4325 deselected` +- full_scale: `31 passed, 4370 deselected` Run `pytest -m ` to reproduce each group.