diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..2b0b264 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,25 @@ +name: tests + +on: + push: + branches: [main] + pull_request: + +jobs: + cpu: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + - name: Install + run: | + python -m pip install --upgrade pip + python -m pip install -e . + - name: Unit tests (CPU; GPU-only tests are skipped) + run: python -m unittest discover -s tests -v + - name: Contact example + run: python examples/contact/point_spacing.py diff --git a/README.md b/README.md index 5900e6c..9433b16 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ Each example keeps its settings beside the code or reference deck. 3. [Warp FEM inventory and public imports](docs/WARP_FEM.md) 4. [Development and prototype provenance](docs/DEVELOPMENT.md) 5. [Validation scope](validation/README.md) +6. [Contact module](docs/CONTACT.md) The examples run from this repository and use synthetic inputs. See [merge/upload instructions](MERGE_NOTES.md). No repository-wide license is assigned by this handoff; retain or select a license diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e9ea6cf..1bea4b0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -17,7 +17,7 @@ src/warp_febio/ materials/ lee_sacks, stvk, neo_hookean, hgo, nitinol loads/ follower_pressure, nodal_force constraints/ dirichlet, multipoint - contact/ search, enforcement + contact/ points, search, potential, enforcement, interface assembly/ residual, tangent solvers/linear/ cg, gmres, preconditioners solvers/nonlinear/ newton, line_search @@ -53,6 +53,7 @@ and preconditioners under `solvers/linear/`, and its load stepping under | A pressure continuation strategy | `loads/follower_pressure.py` for the force and its derivative, `analysis/static.py` for load increments | | A nonlinear solve | `solvers/nonlinear/newton.py` for iteration and convergence, `solvers/linear/` for each linear method | | A deployment procedure | `analysis/procedure.py` for stages, `contact/` for interactions, and `materials/nitinol.py` for state | +| A contact law | `contact/interface.py` for the protocol, `contact/points.py` for the point set, `contact/search.py` for pairing; see [docs/CONTACT.md](CONTACT.md) | | An adjoint | `sensitivity/` using the constrained tangent and transpose actions | Use `contracts.py` as the starting point for residual and tangent interfaces. diff --git a/docs/CONTACT.md b/docs/CONTACT.md new file mode 100644 index 0000000..1828480 --- /dev/null +++ b/docs/CONTACT.md @@ -0,0 +1,213 @@ +# Contact + +Point-based contact for valve leaflets and self-expanding devices: an initial +exploration, built on Kamensky et al. (2018) and FEBio's `FEContactPotential`. +This page is the code map and the list of what is and is not equivalent to FEBio. + +## What is implemented + +| File | Content | +|---|---| +| `contact/points.py` | `ContactPoints`: node-weighted points with integration weight, area, radius offset, body, source element, and the derivative weights that give current normals and current Jacobians. Builders for Quad4 facets (`quad_facet_points`: FEBio default 2x2 Gauss, `higher-order` 4x4, or a regular sub-lattice), Tri3 facets (`tri_facet_points`: 1, 3 or 7 points), 2-node segments for chordae and beam centerlines (`segment_points`, by spacing or count), nodes as points (`node_points`), and `boundary_triangles` for a Tet4 surface. | +| `contact/search.py` | `PairSearch`: float64 `wp.HashGrid` on the points, count-and-fill pair list with a device-side scan, fixed-capacity buffer with a single host overflow check. Exclusion by body, reference distance (`R0_min`), same element (FEBio default) or shared node (`exclude_neighbors`), and `w_tol`. Pair classes from an `[n_bodies, n_bodies]` table. | +| `contact/potential.py` | The Kamensky volume potential as FEBio implements it (`FEContactPotential`): `PotentialParams` (per-class `kc`, `p`, `R_in`, `R_out`, pair multiplicity `scale`), nondimensional force law, pair energy/force kernel, pair Hessian blocks (full or PSD-projected), matrix-free tangent action chained through the point weights, device BSR assembly (`hessian_bsr`, warp.sparse), host triplets and dense for tests, minimum effective distance for the `r_min` guard, reference or current (FEBio) integration weights, Wu 2022 contact area and Zelonis 2026 contact fraction. `from_febio_block` translates a FEBio `contact potential` block, FEBio names unchanged. | +| `contact/enforcement.py` | `ContactPotentialTerm`: the potential behind `contracts.PhysicsTerm` with the residual sign convention (internal + contact - external), a `ContactTangent` operator (apply, apply_transpose, assemble), results, and `energy_and_gradient` as the building block for PyTorch and JAX custom ops. | +| `contact/interface.py` | `ContactInterface` protocol and `ContactInterfaceBase`, the FEBio-style seam for further laws (sliding with friction, sticky, tied); `ContactSet` drives several interfaces as one. | +| `tests/test_contact_potential.py` | Law continuity; force against finite differences of the energy and tangent action against finite differences of the force, in the blend region, in the stiff core, and with radius offsets; assembled symmetry; PSD projection; tape gradient in both weight modes; parameter adjoint against finite differences; exclusion rules; guards for coincident and overlapping points; pair classes; current weights; pair multiplicity; BSR against the matrix-free action; FEBio block translation; FEBio's contact diagnostic check; metrics. FP64. Run on CPU so far; `WARP_FEBIO_TEST_DEVICE=cuda:0` runs the same checks on a GPU, and one graph-capture test runs only there. | +| `examples/contact/point_spacing.py` | The lattice sums behind the point-spacing rule. | + +FEBio's own test suite (`FEBioTest/` on the develop branch) is the reference +for further checks. `FebioDiagnosticTests` applies the check of +`FEContactDiagnostic.cpp` (its two-hex geometry, its two surfaces, contact +stiffness against a finite-difference derivative of the contact residual, pass +below 1e-3 percent) to the contact potential; FEBio's diagnostic itself +exercises a sliding interface. The tangent diagnostics there are the model for +element and material checks as those components arrive. + +## Conventions + +* Distances are evaluated as `|x_j - x_i| - radius_i - radius_j`. With zero radii + the law is FEBio's. A wire on its centerline with `radius = r_w` is a capsule; + for a FEBio-equivalent run set the radius to zero and put `r_w` into `R_in`, + which is what FEBio's edge-to-surface contact potential requires. +* `weight` is the reference-facet Jacobian times the rule weight (area) for + surfaces and segment length times rule weight for lines. `weight_mode="current"` + switches to current Jacobians as FEBio does (`UpdateSurface`); FEBio does not + differentiate the weights and neither does this module in that mode, so the + force is then not the exact energy gradient. The tape and finite-difference + tests apply to the reference mode. `kc` is unscaled, as in FEBio, so it + carries the units that make `weight_i * weight_j * kc / r^p` a force. +* Inside the kernels distances are `s = r / R_out`, so one set of coefficients + serves models in millimetres and in metres (the package convention is SI). +* Pair selection and pair evaluation are separate steps. `build_pairs` (or + `update_pairs` on the term) is called once per Newton iteration in a forward + solve and once at the converged state for a frozen-pairing adjoint. +* Nothing between `build_pairs(sync=False)` and `check_overflow()` touches the + host. Pair search, energy, force and pair Hessian blocks are meant to be + captured in a CUDA graph (`test_newton_body_is_graph_capturable`, GPU only); + `hessian_bsr` has not yet been exercised under capture. If `check_overflow` + returns True the list was incomplete and must be rebuilt. + +## FEBio equivalence: what the source says + +Taken from `FEBioMech/FEContactPotential.cpp` and +`FEEdgeToSurfaceContactPotential.cpp` on the develop branch, not from the papers. + +* Contact points are facet Gauss points (2x2 per quad, 3 per triangle by default; + 16 and 7 with `integration_rule="higher-order"`); the edge-to-surface variant + uses nodal integration on 2-node line elements (FE_LINE2NI: a point at each + node, weight 1). Weights are current Jacobian times rule weight on each side. + `kc` is unscaled. The grid cell size is at least `R_out`; pairs are activated + per element pair; the tangent is the full pair Hessian. +* By default only an element against itself is skipped; `exclude_neighbors` + extends that to element pairs that share a node. `R0_min` (reference distance) + and `w_tol` (cosine between the pair direction and the primary point's current + facet normal) are element-pair activation gates: one Gauss-point pair that + passes activates the whole element pair, which is then summed without + rechecking. `check_intersections` runs an edge-facet test and cuts the step. +* **Where this module differs.** `R0_min` and `w_tol` are applied per point + pair, not per element pair, and `w_tol` passes if either point's normal + passes. FEBio's edge-to-surface variant declares `w_tol` but does not use it; + here it acts through the surface point's normal. `check_intersections` is not + implemented. A facet-level match with FEBio at `w_tol > 0` should therefore + not be expected yet; an element-pair activation mode is the next step for + the reference tier. +* **Pair multiplicity (for Steve's review).** `Update` activates element pairs + from every primary element, and `LoadVector`/`ElementForce` and + `StiffnessMatrix`/`ElementStiffness` add each activated pair to both + elements. When one surface is both primary and secondary (the archived + CardioFEM deck uses `ContactLeaflet` for both), the pair (A, B) appears to be + activated from A and again from B, so every self-contact pair would enter + twice relative to the unordered sum here. `PotentialParams(scale=2)` + reproduces that; `from_febio_block(..., scale=2)` is the switch. Whether + this reading is right, and if so whether it is intended, is a question for + the FEBio team. + +## Open question for review (Steve Maas and all) + +How `kc` should be specified with more than one pair class. With the force and +its slope continuous at `R_in`, the force at the core boundary is +`p kc (R_out - R_in) / (2 R_in^(p+1))`: at fixed `kc` the stiffness scales as +`R_in^-5` for `p = 4`. Absorbing a wire radius into `R_in` (what FEBio's +edge-to-surface potential requires) makes wire-to-wire about 14 times softer +than wire-to-tissue at the same `kc` in the example below; the weight products differ by class +(area by area, length by area, length by length), so `kc` has different units +per class; and in SI the `R_in^5` factor makes hand-picked values unreadable. +The per-point radius offset keeps `R_in` and `R_out` common standoff +parameters, and `kc` can be calibrated per class from a target force at a +target gap through `2 pi g phi(g)` (the same closed form for a point over a +plane, a wire over a plane and a wire crossing a wire). Neither is settled. +In numbers (p = 4, kc = 1, mm): + +| Pair class and convention | R_in | R_out | Force at R_in | kc for the leaflet stiffness | +|---|---|---|---|---| +| Leaflet against leaflet (Wu 2022) | 0.20 | 0.50 | 1,875 | 1.0 | +| Wire against tissue, radius absorbed into R_in (r_w = 0.19, standoff 0.08) | 0.27 | 0.60 | 460 | 4.1 | +| Wire against wire, radius absorbed into R_in | 0.46 | 0.80 | 33 | 57 | +| Wire against tissue, capsule offset 0.19 | 0.20 | 0.50 | 1,875 | 1.0 | +| Wire against wire, capsule offset 0.38 | 0.20 | 0.50 | 1,875 | 1.0 | + +Which convention the reference tier should match, whether FEBio's +edge-to-surface potential should gain a radius term, and whether `kc` should +remain an input or be derived from a target force and gap per class, is for +the group to decide. + +## Rules the solver must apply + +Derived on small test problems and confirmed by the tests and the example: + +* Contact points at most `R_out / 2` apart on both sides, densified independently + of the mechanics quadrature (`rule="lattice"` or `n_per_edge=4`). +* No nodal move larger than `R_out` in one step; a collision check that cuts + the step. The `min_distance` guard against `r_min` is available. +* Full tangent first (`project=False`); the projected tangent is the fallback + when the full one fails to give a descent direction. +* Self-contact exclusion by body and topology (`exclusion="neighbors"`) plus + the reference distance, never the reference distance alone. FEBio's own + default is weaker: only an element against itself is skipped + (`exclusion="element"`), and `w_tol` is what keeps neighboring facets from + repelling each other; `from_febio_block` reproduces that. + +## How this lines up with FEBio, MFEM and the FEBio-MFEM framework + +* FEBio: the `ContactInterface` protocol mirrors `FEContactInterface` (update + the pairing, add to the residual and the stiffness, augment, commit) and the + parameter names are FEBio's, so a `.feb` contact block maps one to one. This + is how Ryan Black's FEBio-MFEM framework (github.com/JolleyLab/FEBioMFEMiFSI) + is organized: FEBio's object model (`FESolver`, `FESurfaceLoad`, domains) + over MFEM numerics. It is cited here for that organization of the mechanics, + not for anything fluid. +* MFEM: `ContactPotentialTerm` has the shape of a `NonlinearForm` (energy, + residual as `Mult`, `linearize` as `GetGradient`), and `ContactTangent` is an + `Operator` with `Mult` and `MultTranspose`, matrix-free by default, assembled + on request (`assemble` returns a BSR matrix for preconditioners or a direct + solve). Partial assembly in the MFEM sense is not attempted. +* Warp: selection (`HashGrid`, pair list) is separate from evaluation so the + evaluation differentiates cleanly on `wp.Tape`; everything in the Newton body + is graph-capturable; the tangent is available as an action and as a + `warp.sparse` BSR matrix. + +## What differentiates, and what does not + +The contract the rest of FEBio-Warp (adjoints, PyTorch, JAX) can rely on +(tests: `PairKernelTests`, `CoreBranchTests`, `DifferentiabilityTests`): + +* In reference-weight mode (the default), energy, nodal force and tangent + action are exact derivatives of one another with respect to the nodal + positions. In `weight_mode="current"` the integration weights are held fixed + in both the residual and the backward pass, as FEBio holds them in its + residual: the tape gradient still equals `residual()`, but the force is then + not the gradient of the energy. +* The contact stiffness table (`kcs`, hence `kc` per class) receives gradients + on the tape. `ContactPotentialTerm.residual_parameter_vjp(state, lam)` returns + `lam^T dR/dkc` per class, the term an equilibrium adjoint needs after solving + `K^T lam = dJ/dx`; verified against finite differences. +* Not differentiated, by design: the pair list (piecewise constant in the + positions; selection is a separate step), `R_in`, `R_out`, `p` and the radius + offsets (they enter through `c1`, `c2` and the nondimensional law and are + treated as fixed model data), and the integration weights in current mode. + Making the radii or `R_in`, `R_out` differentiable would be a contained + change (they are arrays and scalars in the same kernels) if a fit ever needs + them. +* Second derivatives with respect to positions come from the analytic pair + Hessian (`linearize`), not from differentiating the tape twice. + +## Coupling to PyTorch and JAX + +`ContactPotentialTerm.energy_and_gradient(state)` records the energy on a tape +and returns the device gradient, which a `torch.autograd.Function` or +`jax.custom_vjp` can wrap through `wp.to_torch`, `wp.to_jax` and `wp.from_jax` +without copies. Second derivatives come from the analytic pair Hessian +(`linearize().apply` for a Hessian-vector product, `assemble()` for the +matrix), not from a tape of a tape, which Warp does not provide; the frameworks +consume the action as a linear operator for Gauss-Newton, Newton or adjoint +solves. The pair list is selected separately and never differentiated; with +`w_tol = 0` the energy is C2 in the positions, because the potential and its +first two derivatives vanish at `R_out`. + +## Not yet implemented + +* Element-pair activation for `w_tol` and `R0_min`, and `check_intersections`, + from `FEContactPotential` (reference tier only). +* `SlidingContact` (penalty and augmented Lagrangian with Coulomb friction, + `wp.Mesh` closest-point queries), `StickyContact` and `TiedContact`, behind + `ContactInterface`. +* FP32 kernels: the module is FP64; the nondimensional law is the preparation + for an FP32 variant once the linear solve is validated against FP64. + +## Run + +```bash +python -m unittest discover -s tests -v +python examples/contact/point_spacing.py +``` + +## References + +* Kamensky D, Xu F, Lee C-H, Yan J, Bazilevs Y, Hsu M-C. A contact formulation based on a volumetric potential: Application to isogeometric simulations of atrioventricular valves. Comput Methods Appl Mech Eng 2018;330:522-546. doi:10.1016/j.cma.2017.11.007 +* Wu W, Ching S, Maas SA, Lasso A, Sabin P, Weiss JA, Jolley MA. A computational framework for atrioventricular valve modeling using open-source software. J Biomech Eng 2022;144(10):101012. doi:10.1115/1.4054485 +* Wu W, Ching S, Sabin P, Laurence DW, Maas SA, Lasso A, Weiss JA, Jolley MA. The effects of leaflet material properties on the simulated function of regurgitant mitral valves. J Mech Behav Biomed Mater 2023;142:105858. doi:10.1016/j.jmbbm.2023.105858 +* Aslan S, Mangine NR, Laurence DW, Sabin PM, Wu W, Herz C, Unger JS, Maas SA, Gillespie MJ, Weiss JA, Jolley MA. Simulation of transcatheter therapies for atrioventricular valve regurgitation in an open-source finite element simulation framework. Ann Biomed Eng 2026. doi:10.1007/s10439-025-03959-w +* Zelonis CN, Maheshwari J, Wu W, Maas SA, Aslan S, et al. Integrated open-source framework for simulation of transcatheter pulmonary valves in native right ventricular outflow tracts. arXiv:2507.06337 (2026). doi:10.48550/arXiv.2507.06337 +* Maheshwari J, Wu W, Zelonis CN, Maas SA, Sunderland K, et al. Effect of right ventricular outflow tract material properties on simulated transcatheter pulmonary placement. J Mech Behav Biomed Mater 2026. doi:10.1016/j.jmbbm.2026.107642 +* Maas SA, Ellis BJ, Ateshian GA, Weiss JA. FEBio: Finite elements for biomechanics. J Biomech Eng 2012;134(1):011005. doi:10.1115/1.4005694 diff --git a/examples/contact/point_spacing.py b/examples/contact/point_spacing.py new file mode 100644 index 0000000..38dd2d9 --- /dev/null +++ b/examples/contact/point_spacing.py @@ -0,0 +1,99 @@ +"""Why contact points must be at most R_out/2 apart. + +A probe point (radius optional) sits a gap g above a square lattice of contact +points with spacing a. The force it feels, relative to the dense-sampling +continuum value, is reported directly over a lattice point and over the +centre of a lattice cell (a "hole"). At a = R_out the force over a hole is 38 +percent of the continuum value and the force over a point twice it; at +a = R_out/2 both are within 4 percent. Coarse sampling is how a thin strut +passes between contact points. + +Run from the repository root: + python examples/contact/point_spacing.py [--radius 0.0] [--gap-ratio 0.4] +""" + +import argparse + +import numpy as np +import warp as wp + +from warp_febio.contact import ( + ContactPoints, + ContactPotential, + PotentialParams, + node_points, +) + +V = wp.vec3d + + +def probe_force(P, spacing, gap, over_hole, radius, device="cpu", extent=8.0): + """Vertical force on a probe above a lattice, per unit lattice weight density.""" + r_out = P.r_out[0] + n = int(np.ceil(extent * r_out / spacing)) + xs = (np.arange(-n, n + 1)) * spacing + X, Y = np.meshgrid(xs, xs, indexing="ij") + lattice = np.stack([X.ravel(), Y.ravel(), np.zeros(X.size)], axis=1) + shift = 0.5 * spacing if over_hole else 0.0 + probe = np.array([[shift, shift, gap + radius]]) + nodes = np.concatenate([lattice, probe]) + pts = ContactPoints.concatenate( + [ + node_points( + np.arange(len(lattice)), body=0, weight=spacing * spacing + ), # weight = area per point + node_points([len(lattice)], body=1, weight=1.0, radius=radius), + ] + ) + cp = ContactPotential( + pts, + P, + np.zeros((2, 2), dtype=int), + nodes, + len(nodes), + device=device, + grid_dim=128, + ) + x = wp.array(nodes, dtype=V, device=device) + cp.build_pairs(x) + f = wp.zeros(len(nodes), dtype=V, device=device) + cp.energy_force(x, f) + return f.numpy()[-1, 2] + + +def continuum_force(P, gap): + """Dense-sampling limit of the force on a point above a plane of unit weight + density: 2 pi g phi(g).""" + return 2.0 * np.pi * gap * P.phi(gap)[()] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument( + "--radius", type=float, default=0.0, help="probe radius (capsule offset)" + ) + ap.add_argument( + "--gap-ratio", + type=float, + default=0.4, + help="gap / R_out at which the probe sits", + ) + ap.add_argument("--device", default="cpu") + args = ap.parse_args() + + P = PotentialParams(kc=1.0, p=4.0, r_in=0.4, r_out=1.0) + gap = args.gap_ratio * P.r_out[0] + dense = continuum_force(P, gap) + print( + f"gap = {gap:.3f} R_out, probe radius = {args.radius:.3f}; continuum force = {dense:.6e}" + ) + print(f"{'spacing/R_out':>14} {'over point':>12} {'over hole':>12}") + for ratio in (0.2, 0.25, 0.33, 0.4, 0.5, 0.6, 0.75, 0.85, 1.0, 1.25, 1.5): + a = ratio * P.r_out[0] + f_pt = probe_force(P, a, gap, False, args.radius, args.device) / dense + f_hole = probe_force(P, a, gap, True, args.radius, args.device) / dense + print(f"{ratio:14.2f} {f_pt:12.3f} {f_hole:12.3f}") + + +if __name__ == "__main__": + main() diff --git a/src/warp_febio/contact/__init__.py b/src/warp_febio/contact/__init__.py index c660ae4..d1f495b 100644 --- a/src/warp_febio/contact/__init__.py +++ b/src/warp_febio/contact/__init__.py @@ -1 +1,33 @@ -"""Contact components.""" +"""Point-based contact: point sets, pair search, the Kamensky volume potential, +and the PhysicsTerm adapter. See docs/CONTACT.md.""" + +from .points import ( + ContactPoints, + boundary_triangles, + node_points, + quad_facet_points, + segment_points, + tri_facet_points, +) +from .potential import ContactPotential, PotentialParams, from_febio_block +from .search import PairSearch +from .enforcement import ContactPotentialTerm, ContactTangent +from .interface import ContactInterface, ContactInterfaceBase, ContactSet + +__all__ = [ + "ContactPoints", + "boundary_triangles", + "node_points", + "quad_facet_points", + "segment_points", + "tri_facet_points", + "ContactPotential", + "PotentialParams", + "from_febio_block", + "PairSearch", + "ContactPotentialTerm", + "ContactTangent", + "ContactInterface", + "ContactInterfaceBase", + "ContactSet", +] diff --git a/src/warp_febio/contact/enforcement.py b/src/warp_febio/contact/enforcement.py index 6a2e8ff..23cc475 100644 --- a/src/warp_febio/contact/enforcement.py +++ b/src/warp_febio/contact/enforcement.py @@ -1,4 +1,195 @@ -"""Planned component. +"""Contact as a PhysicsTerm: residual, tangent action, committed state. -Evaluate contact residuals, tangents and committed friction state. +``ContactPotentialTerm`` adapts ``potential.ContactPotential`` to the +``contracts.PhysicsTerm`` protocol with the repository's residual sign +convention, internal plus contact minus external: the contact residual is ++dE_c/dx, the negative of the repulsive nodal force. + +State is a ``wp.array(dtype=wp.vec3d)`` of nodal positions. The potential has no +history, so ``commit`` and ``rollback`` do nothing; they exist so that a +frictional law (``sliding.py``, planned) can slot in behind the same interface +with a committed footprint and slip state. + +Pair selection is explicit: call ``update_pairs(state)`` once per Newton +iteration (or per step, for a frozen-pairing adjoint), then ``residual`` and +``linearize`` run over that list without host synchronization. + +Coupling to PyTorch and JAX. ``energy_and_gradient`` is the building block +for a custom op: it records the energy on a ``wp.Tape`` and returns dE/dx on +the device, so a ``torch.autograd.Function`` or a ``jax.custom_vjp`` can wrap +it with zero-copy views (``wp.to_torch``, ``wp.to_jax`` / ``wp.from_jax``). +Second derivatives come from the analytic pair Hessian (``linearize`` gives a +matrix-free Hessian-vector product, ``assemble`` a BSR matrix), not from a +tape of a tape, which Warp does not provide; the frameworks consume the +Hessian action as a linear operator for Gauss-Newton, Newton or adjoint +solves. The pair list is selected separately and never differentiated; the +energy is C2 in the positions because phi and its first two derivatives vanish +at R_out (with ``w_tol > 0`` the normal test makes it discontinuous). """ + +from __future__ import annotations + +import numpy as np +import warp as wp + +from .interface import ContactInterfaceBase +from .points import ContactPoints +from .potential import ContactPotential, PotentialParams + +vec3d = wp.vec3d + + +@wp.kernel +def _axpy(alpha: wp.float64, x: wp.array(dtype=vec3d), y: wp.array(dtype=vec3d)): + i = wp.tid() + y[i] = y[i] + alpha * x[i] + + +class ContactTangent: + """TangentOperator of the contact potential at the state it was linearized at. + + Matrix-free, in the shape of an MFEM Operator (Mult and MultTranspose, no + assembled matrix): the action interpolates nodes to contact points, applies + the stored pair blocks, and scatters back. ``assemble`` gives the BSR + matrix when a preconditioner or direct solver needs one. + """ + + def __init__(self, term: "ContactPotentialTerm", project: bool): + self.term = term + self.project = project + self.height = self.width = 3 * term.potential.n_nodes + self.term.potential.hessian_blocks(project) + + def apply(self, vector: wp.array, out: wp.array) -> None: + self.term.potential.hessian_matvec( + vector, out, project=self.project, rebuild_blocks=False + ) + + def apply_transpose(self, vector: wp.array, out: wp.array) -> None: + # the contact Hessian is symmetric (projected or not) + self.apply(vector, out) + + def assemble(self, dest=None): + """BSR matrix of 3x3 blocks on the device (warp.sparse), for preconditioners.""" + return self.term.potential.hessian_bsr(project=self.project, dest=dest) + + +class ContactPotentialTerm(ContactInterfaceBase): + """Contact potential behind the PhysicsTerm and ContactInterface protocols.""" + + name = "contact_potential" + + def __init__( + self, + points: ContactPoints, + params: PotentialParams, + pair_class: np.ndarray, + ref_node_x: np.ndarray, + n_nodes: int, + exclusion: str = "neighbors", + w_tol: float = 0.0, + weight_mode: str = "reference", + project_tangent: bool = False, + device: str = "cpu", + **search_kwargs, + ): + self.potential = ContactPotential( + points, + params, + pair_class, + ref_node_x, + n_nodes, + exclusion=exclusion, + w_tol=w_tol, + weight_mode=weight_mode, + device=device, + **search_kwargs, + ) + self.project_tangent = project_tangent + self.device = device + self._f = wp.zeros(int(n_nodes), dtype=vec3d, device=device, requires_grad=True) + + def update_pairs(self, state: wp.array, sync: bool = True) -> int: + return self.potential.build_pairs(state, sync=sync) + + def residual(self, state: wp.array, history, out: wp.array) -> None: + """out += dE_c/dx (contact enters the residual with the internal-force sign).""" + self._f.zero_() + self.potential.energy_force(state, self._f) + wp.launch( + _axpy, + dim=self._f.shape[0], + inputs=[wp.float64(-1.0), self._f, out], + device=self.device, + ) + + def energy(self) -> float: + return self.potential.energy_value() + + def energy_and_gradient(self, state: wp.array): + """(E_c as a device scalar array, dE_c/dx as a device array) through wp.Tape. + + ``state`` must have ``requires_grad=True``. The gradient equals the + residual contribution and is returned as a device array that a PyTorch + or JAX custom op can view through Warp interop. In ``weight_mode="current"`` + the weights are held fixed in the backward pass, as in the residual, so + the two agree in both modes. + """ + if not state.requires_grad: + raise ValueError("state must be allocated with requires_grad=True") + pot = self.potential + self._f.zero_() + tape = wp.Tape() + with tape: + E = pot.energy_force(state, self._f) + state.grad.zero_() + tape.backward(E) + grad = wp.clone(state.grad) + tape.zero() + return E, grad + + def residual_parameter_vjp(self, state: wp.array, lam: wp.array) -> dict: + """lam^T dR/dtheta for the contact parameters, through wp.Tape. + + This is the term the equilibrium adjoint needs after solving + K^T lam = dJ/dx. Returns ``{"kc": array over pair classes}`` on the + host; ``R = -f`` so the sign of the force adjoint is flipped. The pair + list and the integration weights are held fixed, as in ``residual``. + """ + pot = self.potential + self._f.zero_() + tape = wp.Tape() + with tape: + pot.energy_force(state, self._f) + self._f.grad.zero_() + wp.launch( + _axpy, + dim=self._f.shape[0], + inputs=[wp.float64(-1.0), lam, self._f.grad], + device=self.device, + ) + tape.backward(grads={self._f: self._f.grad}) + out = {"kc": pot.kc_gradient_from_tables()} + tape.zero() + return out + + def linearize(self, state: wp.array, history) -> ContactTangent: + """Tangent action at ``state`` over the current pair list. + + The points are refreshed from ``state``; the pair list is whatever + ``update_pairs`` last built, which is the frozen-pairing linearization + the equilibrium adjoint wants. + """ + self.potential.search.update_points(state) + return ContactTangent(self, self.project_tangent) + + def results(self) -> dict: + """Point forces and the Wu 2022 contact area per body, after a residual call.""" + pot = self.potential + bodies = np.unique(pot.points.body) + return { + "point_force": pot.point_forces(), + "contact_area": {int(b): pot.contact_area(body=int(b)) for b in bodies}, + "energy": pot.energy_value(), + "n_pairs": pot.search.n_pairs, + } diff --git a/src/warp_febio/contact/interface.py b/src/warp_febio/contact/interface.py new file mode 100644 index 0000000..72a0f26 --- /dev/null +++ b/src/warp_febio/contact/interface.py @@ -0,0 +1,126 @@ +"""Base class for contact interfaces, in the spirit of FEBio's FEContactInterface. + +FEBio organizes contact as interfaces (sliding-elastic, sticky, tied, contact +potential, ...) that each own their surfaces, their search, their enforcement +law and their outputs, behind one set of calls the solver makes: update the +pairing, add to the residual, add to the stiffness, augment, serialize state. +This module gives FEBio-Warp the same seam so that new laws can be added +without touching the solver. + +Every interface implements ``contracts.PhysicsTerm`` plus a pairing update and +a result dictionary. The first implementation is the volume potential +(``ContactPotentialTerm``). Planned next, in the order the targets need them: + +* ``SlidingContact``: gap and normal from a ``wp.Mesh`` closest-point query, + penalty with augmented Lagrangian, Coulomb friction with committed footprint + and slip (FEBio sliding-elastic and edge-to-surface sliding). +* ``StickyContact`` / ``TiedContact``: pair springs created at engagement with + a maximum traction (FEBio sticky, tied-elastic); clip grasp and tines. + +An interface never owns the solver loop. The analysis procedure decides when +``update_pairs`` runs (each Newton iteration for the forward solve, once for a +frozen-pairing adjoint), when ``augment`` runs, and when ``commit`` is called. +""" + +from __future__ import annotations + +from typing import Any, Protocol, runtime_checkable + +import warp as wp + + +@runtime_checkable +class ContactInterface(Protocol): + """What the solver may call on any contact law.""" + + name: str + + def update_pairs(self, state: Any, sync: bool = True) -> int: + """Refresh the candidate pairing for ``state``; return the pair count (or 0 if unknown).""" + ... + + def residual(self, state: Any, history: Any, out: Any) -> None: + """Add the contact contribution with the internal-force sign to ``out``.""" + ... + + def linearize(self, state: Any, history: Any) -> Any: + """Return a TangentOperator (apply, apply_transpose) at ``state``.""" + ... + + def augment(self, state: Any) -> bool: + """Augmented-Lagrangian multiplier update; True when converged or not applicable.""" + ... + + def commit(self, trial_history: Any) -> None: ... + + def rollback(self) -> None: ... + + def results(self) -> dict[str, Any]: + """Named outputs for io/results (gap, traction, contact area, ...).""" + ... + + +class ContactInterfaceBase: + """Defaults shared by the concrete interfaces: no augmentation, no history.""" + + name = "contact" + + def augment(self, state: Any) -> bool: + return True + + def commit(self, trial_history: Any) -> None: + return None + + def rollback(self) -> None: + return None + + def results(self) -> dict[str, Any]: + return {} + + +class ContactSet: + """Several interfaces acting on one state, driven as a unit by the procedure.""" + + def __init__(self, interfaces: list[ContactInterface]): + self.interfaces = list(interfaces) + + def update_pairs(self, state: wp.array, sync: bool = True) -> int: + return sum(ci.update_pairs(state, sync=sync) for ci in self.interfaces) + + def residual(self, state: wp.array, history: Any, out: wp.array) -> None: + for ci in self.interfaces: + ci.residual(state, history, out) + + def linearize(self, state: wp.array, history: Any) -> "_SumTangent": + return _SumTangent([ci.linearize(state, history) for ci in self.interfaces]) + + def augment(self, state: wp.array) -> bool: + return all([ci.augment(state) for ci in self.interfaces]) + + def commit(self, trial_history: Any) -> None: + for ci in self.interfaces: + ci.commit(trial_history) + + def rollback(self) -> None: + for ci in self.interfaces: + ci.rollback() + + def results(self) -> dict[str, Any]: + out = {} + for ci in self.interfaces: + for k, v in ci.results().items(): + out[f"{ci.name}/{k}"] = v + return out + + +class _SumTangent: + def __init__(self, parts): + self.parts = parts + + def apply(self, vector, out) -> None: + for t in self.parts: + t.apply(vector, out) + + def apply_transpose(self, vector, out) -> None: + for t in self.parts: + t.apply_transpose(vector, out) diff --git a/src/warp_febio/contact/points.py b/src/warp_febio/contact/points.py new file mode 100644 index 0000000..67d1bb7 --- /dev/null +++ b/src/warp_febio/contact/points.py @@ -0,0 +1,382 @@ +"""Contact point sets: positions interpolated from nodes through fixed weights. + +A contact point is a node-weighted location on a body. The pair kernels in +``contact/potential.py`` never see an element type; they see positions, an +integration weight, a body id, an optional radius offset and the node list the +point interpolates from. That is what lets one module serve shell Gauss points +(leaflets), facet points of a solid surface (clip arms, a tetrahedral device +frame, a hex vessel wall), points along a cable (chordae) and points along a +beam centerline (a nitinol strut or wire). + +Conventions, following FEBio's FEContactPotential and +FEEdgeToSurfaceContactPotential: + +* ``weight`` is the reference integration weight of the point: reference-facet + Jacobian times rule weight for a surface (an area), segment length times + rule weight for a line. FEBio uses the current Jacobian; the derivative + weights carried here let ``weight_mode="current"`` reproduce that. +* ``area`` is the surface area carried by the point, used for the contact area + metric of Wu 2022 (area over points with nonzero contact force). It is zero + for line points. +* ``radius`` is a per-point offset subtracted from the pair distance, so a wire + of radius r_w on its centerline is treated as a capsule. FEBio has no such + term; set the radius to zero and put the wire radius into R_in for a + FEBio-equivalent run. +* ``body`` groups points for self-contact exclusion; pairs on different bodies + always interact. + +Lengths follow the caller's unit convention (SI inside this package). +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + + +@dataclass +class ContactPoints: + """Node-weighted contact points of one or more bodies. + + Arrays (host, numpy): ``pt_nodes`` [n, K] node ids with -1 in unused slots, + ``pt_w`` [n, K] shape-function weights, ``weight`` [n] (reference + integration weight), ``area`` [n], ``radius`` [n], ``body`` [n] (int32), + ``element`` [n] (int32, the source facet or segment; informational). + + Optional, for the FEBio-equivalent reference tier: ``pt_dw1`` and + ``pt_dw2`` [n, K] are the derivative weights of the two parametric + tangents (one tangent for a line, none for a bare node) and + ``rule_weight`` [n] the rule weight without the Jacobian, so that a + kernel can evaluate the current normal and the current Jacobian-weighted + integration weight the way FEBio does (``FEContactPotential::UpdateSurface``). + """ + + pt_nodes: np.ndarray + pt_w: np.ndarray + weight: np.ndarray + area: np.ndarray + radius: np.ndarray + body: np.ndarray + element: np.ndarray + pt_dw1: np.ndarray | None = None + pt_dw2: np.ndarray | None = None + rule_weight: np.ndarray | None = None + + def __post_init__(self): + for name in ("pt_nodes", "pt_w", "weight", "area", "radius", "body", "element"): + setattr(self, name, np.asarray(getattr(self, name))) + n, K = self.pt_nodes.shape + for name in ("pt_w", "weight", "area", "radius", "body", "element"): + if getattr(self, name).shape[0] != n: + raise ValueError( + f"{name} has {getattr(self, name).shape[0]} rows, expected {n}" + ) + self.pt_nodes = np.ascontiguousarray(self.pt_nodes, dtype=np.int32) + self.pt_w = np.ascontiguousarray(self.pt_w, dtype=np.float64) + self.weight = np.ascontiguousarray(self.weight, dtype=np.float64) + self.area = np.ascontiguousarray(self.area, dtype=np.float64) + self.radius = np.ascontiguousarray(self.radius, dtype=np.float64) + self.body = np.ascontiguousarray(self.body, dtype=np.int32) + self.element = np.ascontiguousarray(self.element, dtype=np.int32) + if self.pt_dw1 is None: + self.pt_dw1 = np.zeros((n, K)) + if self.pt_dw2 is None: + self.pt_dw2 = np.zeros((n, K)) + if self.rule_weight is None: + self.rule_weight = self.weight.copy() + self.pt_dw1 = np.ascontiguousarray(self.pt_dw1, dtype=np.float64) + self.pt_dw2 = np.ascontiguousarray(self.pt_dw2, dtype=np.float64) + self.rule_weight = np.ascontiguousarray(self.rule_weight, dtype=np.float64) + + @property + def count(self) -> int: + return int(self.pt_nodes.shape[0]) + + @property + def nodes_per_point(self) -> int: + return int(self.pt_nodes.shape[1]) + + def positions(self, node_x: np.ndarray) -> np.ndarray: + """Host evaluation of the point positions for a nodal configuration.""" + x = np.zeros((self.count, 3)) + for a in range(self.nodes_per_point): + ok = self.pt_nodes[:, a] >= 0 + x[ok] += self.pt_w[ok, a, None] * node_x[self.pt_nodes[ok, a]] + return x + + @staticmethod + def concatenate(sets: list["ContactPoints"]) -> "ContactPoints": + """Merge point sets that share one node numbering (bodies keep their ids).""" + K = max(s.nodes_per_point for s in sets) + + def pad(a, fill): + out = np.full((a.shape[0], K), fill, dtype=a.dtype) + out[:, : a.shape[1]] = a + return out + + return ContactPoints( + np.concatenate([pad(s.pt_nodes, -1) for s in sets]), + np.concatenate([pad(s.pt_w, 0.0) for s in sets]), + np.concatenate([s.weight for s in sets]), + np.concatenate([s.area for s in sets]), + np.concatenate([s.radius for s in sets]), + np.concatenate([s.body for s in sets]), + np.concatenate([s.element for s in sets]), + np.concatenate([pad(s.pt_dw1, 0.0) for s in sets]), + np.concatenate([pad(s.pt_dw2, 0.0) for s in sets]), + np.concatenate([s.rule_weight for s in sets]), + ) + + +# ----------------------------------------------------------------------------- +# Quadrilateral facets (quad shells, hex faces) +# ----------------------------------------------------------------------------- +def _quad_rule(n_per_edge: int, rule: str): + """Parametric points and weights on [-1, 1]^2 for a quad facet.""" + if rule == "gauss": + g, w = np.polynomial.legendre.leggauss(n_per_edge) + elif rule == "lattice": + # midpoint sub-lattice: n_per_edge^2 equal cells, points at cell centers + g = -1.0 + (2.0 * np.arange(n_per_edge) + 1.0) / n_per_edge + w = np.full(n_per_edge, 2.0 / n_per_edge) + else: + raise ValueError("rule must be 'gauss' or 'lattice'") + r, s = np.meshgrid(g, g, indexing="ij") + wr, ws = np.meshgrid(w, w, indexing="ij") + return r.ravel(), s.ravel(), (wr * ws).ravel() + + +def quad_facet_points( + quads: np.ndarray, + node_x: np.ndarray, + body: int, + n_per_edge: int = 2, + rule: str = "gauss", + radius: float = 0.0, +) -> ContactPoints: + """Points on bilinear Quad4 facets. + + ``n_per_edge=2, rule='gauss'`` is FEBio's default integration rule; + ``n_per_edge=4`` is its ``higher-order`` rule (16 per quad). ``rule='lattice'`` + gives a regular sub-lattice for densification independent of the mechanics + quadrature (Kamensky 2018, Section 4.3). Weights are reference-facet + Jacobian times rule weight; ``area`` equals ``weight``. + """ + quads = np.asarray(quads, dtype=np.int32) + node_x = np.asarray(node_x, dtype=np.float64) + r_all, s_all, w_all = _quad_rule(n_per_edge, rule) + X = node_x[quads] # [nq, 4, 3] + pt_nodes, pt_w, weight, element, dw1, dw2, rule_w = [], [], [], [], [], [], [] + for r, s, w in zip(r_all, s_all, w_all): + N = 0.25 * np.array( + [(1 - r) * (1 - s), (1 + r) * (1 - s), (1 + r) * (1 + s), (1 - r) * (1 + s)] + ) + dNr = 0.25 * np.array([-(1 - s), (1 - s), (1 + s), -(1 + s)]) + dNs = 0.25 * np.array([-(1 - r), -(1 + r), (1 + r), (1 - r)]) + tr = np.einsum("a,qac->qc", dNr, X) + ts = np.einsum("a,qac->qc", dNs, X) + J = np.linalg.norm(np.cross(tr, ts), axis=1) + pt_nodes.append(quads) + pt_w.append(np.tile(N, (len(quads), 1))) + dw1.append(np.tile(dNr, (len(quads), 1))) + dw2.append(np.tile(dNs, (len(quads), 1))) + weight.append(w * J) + rule_w.append(np.full(len(quads), w)) + element.append(np.arange(len(quads), dtype=np.int32)) + weight = np.concatenate(weight) + n = weight.shape[0] + return ContactPoints( + np.concatenate(pt_nodes), + np.concatenate(pt_w), + weight, + weight.copy(), + np.full(n, radius), + np.full(n, body, dtype=np.int32), + np.concatenate(element), + np.concatenate(dw1), + np.concatenate(dw2), + np.concatenate(rule_w), + ) + + +# ----------------------------------------------------------------------------- +# Triangular facets (triangle shells, tet surfaces) +# ----------------------------------------------------------------------------- +def _tri_rule(order: str): + """Barycentric points and weights (summing to 1) on the reference triangle.""" + if order == "1": + return np.array([[1 / 3, 1 / 3, 1 / 3]]), np.array([1.0]) + if order == "3": + return np.array( + [[2 / 3, 1 / 6, 1 / 6], [1 / 6, 2 / 3, 1 / 6], [1 / 6, 1 / 6, 2 / 3]] + ), np.full(3, 1 / 3) + if order == "7": + a, b = 0.059715871789770, 0.470142064105115 + c, d = 0.797426985353087, 0.101286507323456 + pts = np.array( + [ + [1 / 3, 1 / 3, 1 / 3], + [a, b, b], + [b, a, b], + [b, b, a], + [c, d, d], + [d, c, d], + [d, d, c], + ] + ) + w = np.array( + [ + 0.225, + 0.132394152788506, + 0.132394152788506, + 0.132394152788506, + 0.125939180544827, + 0.125939180544827, + 0.125939180544827, + ] + ) + return pts, w + raise ValueError("order must be '1', '3' or '7'") + + +def tri_facet_points( + tris: np.ndarray, + node_x: np.ndarray, + body: int, + order: str = "3", + radius: float = 0.0, +) -> ContactPoints: + """Points on linear Tri3 facets. ``order='7'`` is FEBio's higher-order rule.""" + tris = np.asarray(tris, dtype=np.int32) + node_x = np.asarray(node_x, dtype=np.float64) + bary, w_all = _tri_rule(order) + X = node_x[tris] + area = 0.5 * np.linalg.norm(np.cross(X[:, 1] - X[:, 0], X[:, 2] - X[:, 0]), axis=1) + pt_nodes, pt_w, weight, element, rule_w = [], [], [], [], [] + for N, w in zip(bary, w_all): + pt_nodes.append(tris) + pt_w.append(np.tile(N, (len(tris), 1))) + weight.append(w * area) + rule_w.append(np.full(len(tris), 0.5 * w)) # area = 0.5 |t1 x t2| + element.append(np.arange(len(tris), dtype=np.int32)) + weight = np.concatenate(weight) + n = weight.shape[0] + return ContactPoints( + np.concatenate(pt_nodes), + np.concatenate(pt_w), + weight, + weight.copy(), + np.full(n, radius), + np.full(n, body, dtype=np.int32), + np.concatenate(element), + np.tile([-1.0, 1.0, 0.0], (n, 1)), + np.tile([-1.0, 0.0, 1.0], (n, 1)), + np.concatenate(rule_w), + ) + + +def boundary_triangles(tets: np.ndarray) -> np.ndarray: + """Outward-oriented boundary faces of a Tet4 mesh (faces that appear once).""" + tets = np.asarray(tets, dtype=np.int64) + # faces opposite each vertex, oriented outward for positive-volume tets + faces = np.concatenate( + [ + tets[:, [1, 2, 3]], + tets[:, [0, 3, 2]], + tets[:, [0, 1, 3]], + tets[:, [0, 2, 1]], + ] + ) + key = np.sort(faces, axis=1) + _, idx, counts = np.unique(key, axis=0, return_index=True, return_counts=True) + return faces[idx[counts == 1]].astype(np.int32) + + +# ----------------------------------------------------------------------------- +# Line segments (cables, beam centerlines) +# ----------------------------------------------------------------------------- +def segment_points( + segments: np.ndarray, + node_x: np.ndarray, + body: int, + spacing: float | None = None, + n_per_segment: int | None = None, + radius: float = 0.0, + rule: str = "lattice", +) -> ContactPoints: + """Points along 2-node segments: chordae (radius 0) or beam centerlines. + + Either ``spacing`` (target arc-length spacing, at most R_out/2 is the rule) + or ``n_per_segment``. ``rule='nodal'`` puts one point at each end of the + segment with half its length as weight, which is FEBio's line contact + element (FE_LINE2NI, nodal integration); ``'gauss'`` uses Gauss points; + ``'lattice'`` places points at equal sub-interval midpoints. Weight is + segment length times rule weight; area is zero. The radius is subtracted + from pair distances (capsule). + """ + segments = np.asarray(segments, dtype=np.int32) + node_x = np.asarray(node_x, dtype=np.float64) + length = np.linalg.norm(node_x[segments[:, 1]] - node_x[segments[:, 0]], axis=1) + if rule == "nodal": + if spacing is not None or n_per_segment not in (None, 2): + raise ValueError("rule='nodal' fixes two points per segment") + n_per_segment = 2 + if (spacing is None) == (n_per_segment is None): + raise ValueError("give exactly one of spacing or n_per_segment") + pt_nodes, pt_w, weight, element, rule_w = [], [], [], [], [] + for e, (seg, L) in enumerate(zip(segments, length)): + n = ( + n_per_segment + if n_per_segment is not None + else max(1, int(np.ceil(L / spacing))) + ) + if rule == "nodal": + n = 2 + t = np.array([0.0, 1.0]) + w = np.array([0.5, 0.5]) + elif rule == "gauss": + g, w = np.polynomial.legendre.leggauss(n) + t = 0.5 * (g + 1.0) + w = 0.5 * w + elif rule == "lattice": + t = (np.arange(n) + 0.5) / n + w = np.full(n, 1.0 / n) + else: + raise ValueError("rule must be 'nodal', 'gauss' or 'lattice'") + pt_nodes.append(np.tile(seg, (n, 1))) + pt_w.append(np.stack([1.0 - t, t], axis=1)) + weight.append(w * L) + rule_w.append(w) + element.append(np.full(n, e, dtype=np.int32)) + weight = np.concatenate(weight) + n = weight.shape[0] + return ContactPoints( + np.concatenate(pt_nodes), + np.concatenate(pt_w), + weight, + np.zeros(n), + np.full(n, radius), + np.full(n, body, dtype=np.int32), + np.concatenate(element), + np.tile([-1.0, 1.0], (n, 1)), + np.zeros((n, 2)), + np.concatenate(rule_w), + ) + + +def node_points( + node_ids: np.ndarray, body: int, weight: float = 1.0, radius: float = 0.0 +) -> ContactPoints: + """Nodes used directly as contact points (tests, rigid point clouds).""" + node_ids = np.asarray(node_ids, dtype=np.int32) + n = node_ids.shape[0] + return ContactPoints( + node_ids[:, None], + np.ones((n, 1)), + np.full(n, weight), + np.zeros(n), + np.full(n, radius), + np.full(n, body, dtype=np.int32), + np.arange(n, dtype=np.int32), + ) diff --git a/src/warp_febio/contact/potential.py b/src/warp_febio/contact/potential.py new file mode 100644 index 0000000..ebb7fcb --- /dev/null +++ b/src/warp_febio/contact/potential.py @@ -0,0 +1,715 @@ +"""Volume-potential contact (Kamensky et al., CMAME 2018) over a pair list. + +One energy for every execution tier: + + E_c = sum over kept pairs (i < j) w_i w_j phi(r_ij), r_ij = |x_j - x_i| - rho_i - rho_j + +with the force-separation law FEBio implements in FEContactPotential: + + -phi'(r) = k_c / r^p - c2 r < R_in + = c1 (r - R_out)^2 R_in <= r < R_out + = 0 r >= R_out + +c1 and c2 follow from continuity of the force and its slope at R_in, so the +force is C1 and the energy C2. The optional radius offsets rho turn a point on +a wire centerline into a capsule; with rho = 0 the law is FEBio's. + +Inside the kernels distances are nondimensional, s = r / R_out, so the r^-6 +terms of the Hessian stay in range in FP32 and one set of coefficients serves +models in mm and in m. Parameters are tables indexed by pair class, so +device-to-tissue and device-to-device pairs may differ. + +Pair multiplicity. The sum here runs over unordered pairs (i < j). FEBio's +FEContactPotential activates element pairs from the primary surface and adds +each pair's force to both elements; when one surface is both primary and +secondary (leaflet self-contact in the CardioFEM and Aslan decks) the pair +(A, B) is also activated from B's side, so every self-contact pair enters +twice. ``PotentialParams(scale=2)`` on that pair class reproduces FEBio; +the default is 1. This is flagged for review in docs/CONTACT.md. + +Weights. By default the integration weights are the reference ones carried by +``ContactPoints`` and the force is exactly minus the energy gradient. With +``weight_mode="current"`` the kernels use current Jacobian-weighted weights +as FEBio does; FEBio does not differentiate the weights, and neither does this +module in that mode, so the force is then not the exact gradient of the energy. + +Pair Hessian (Kamensky eq. 26), with d = x_j - x_i, n = d/|d|, r = |d| - rho: + + H = C [ phi''(r) n n^T + (phi'(r) / |d|) (I - n n^T) ] + +Eigenvalues: C phi'' along n (positive under repulsion) and C phi'/|d| across +it (negative). ``project=1`` drops the negative tangential part, which gives a +positive semidefinite tangent with the same equilibrium (the fallback when the +full tangent fails to give a descent direction). +""" + +from __future__ import annotations + +import warnings + +import numpy as np +import warp as wp +import warp.sparse as wps + +from .points import ContactPoints +from .search import PairSearch, interpolate_points, scatter_to_nodes + +f64 = wp.float64 +vec3d = wp.vec3d +mat33d = wp.mat33d + + +# ----------------------------------------------------------------------------- +# Parameters +# ----------------------------------------------------------------------------- +class PotentialParams: + """Parameter table of the contact potential, one row per pair class. + + ``kc``, ``p``, ``r_in``, ``r_out`` are arrays or scalars (broadcast). + ``r_self`` is the reference-distance self-contact exclusion radius (FEBio + ``R0_min``); ``r_min`` the optional hard-core radius used only by the + line-search guard, never by the energy. ``r_self`` defaults to 0, as in + FEBio; set it when ``exclusion`` alone is not enough. ``scale`` is the pair multiplicity + per class (2 reproduces FEBio's same-surface self-contact, see module notes). + """ + + def __init__( + self, kc=1.0, p=4.0, r_in=0.2, r_out=0.5, r_self=None, r_min=0.0, scale=1.0 + ): + kc, p, r_in, r_out, scale = np.broadcast_arrays( + np.atleast_1d(np.asarray(kc, dtype=np.float64)), + np.atleast_1d(np.asarray(p, dtype=np.float64)), + np.atleast_1d(np.asarray(r_in, dtype=np.float64)), + np.atleast_1d(np.asarray(r_out, dtype=np.float64)), + np.atleast_1d(np.asarray(scale, dtype=np.float64)), + ) + if np.any(p < 4.0): + warnings.warn( + "Kamensky 2018: p >= 4 is needed for non-penetration of volumes", + stacklevel=2, + ) + if np.any(r_in <= 0.0) or np.any(r_in >= r_out): + raise ValueError("require 0 < r_in < r_out") + self.kc, self.p, self.r_in, self.r_out, self.scale = ( + kc.copy(), + p.copy(), + r_in.copy(), + r_out.copy(), + scale.copy(), + ) + self.n_classes = int(kc.shape[0]) + self.r_self = float(r_self) if r_self is not None else 0.0 + self.r_min = float(r_min) + self.s_in = self.r_in / self.r_out + # pair multiplicity (FEBio same-surface self-contact: 2) folded into the kernel stiffness + self.kcs = self.scale * self.kc / self.r_out**self.p + s_in = self.s_in + self.c1 = p / (2.0 * (1.0 - s_in) * s_in ** (p + 1.0)) # Kamensky eq. (15) + self.c2 = s_in ** (-p) - self.c1 * (s_in - 1.0) ** 2 # Kamensky eq. (16) + + def device_tables(self, device, requires_grad: bool = False): + """Per-class parameter arrays. With ``requires_grad`` the kernel stiffness + table (index 0, kcs) receives gradients on a wp.Tape, which is what a + parameter adjoint dR/dkc needs; the other tables stay fixed.""" + + def mk(a, g=False): + a = np.asarray(a, dtype=np.float64) + return wp.array(a, dtype=f64, device=device, requires_grad=g) + + return [ + mk(self.kcs, requires_grad), + mk(self.p), + mk(self.s_in), + mk(self.c1), + mk(self.c2), + mk(self.r_out), + ] + + def phi(self, r, cls=0): + """Host evaluation of phi(r) (energy per unit weight product), for checks.""" + s = np.asarray(r, dtype=np.float64) / self.r_out[cls] + p, s_in, c1, c2 = self.p[cls], self.s_in[cls], self.c1[cls], self.c2[cls] + blend = c1 * (1.0 - s_in) ** 3 / 3.0 + G = np.where( + s >= 1.0, + 0.0, + np.where( + s >= s_in, + c1 * (1.0 - s) ** 3 / 3.0, + blend + + (np.power(np.maximum(s, 1e-300), 1.0 - p) - s_in ** (1.0 - p)) + / (p - 1.0) + - c2 * (s_in - s), + ), + ) + return self.r_out[cls] * self.kcs[cls] * G + + def force(self, r, cls=0): + """Host evaluation of -phi'(r), for checks.""" + s = np.asarray(r, dtype=np.float64) / self.r_out[cls] + p, s_in, c1, c2 = self.p[cls], self.s_in[cls], self.c1[cls], self.c2[cls] + g = np.where( + s >= 1.0, + 0.0, + np.where( + s >= s_in, c1 * (s - 1.0) ** 2, np.power(np.maximum(s, 1e-300), -p) - c2 + ), + ) + return self.kcs[cls] * g + + +def from_febio_block(block: dict, scale: float = 1.0): + """Translate a FEBio ``contact type="contact potential"`` block into module options. + + ``block`` holds FEBio's parameter names as keys (strings or numbers, as + parsed from a .feb file): ``kc`` (required; FEBio's default of 0 disables + the interface), ``p``, ``R_in``, ``R_out``, ``R0_min``, ``w_tol``, + ``integration_rule`` (``default`` or ``higher-order``), + ``exclude_neighbors`` (0 or 1). Missing entries take FEBio's defaults. + + Returns ``(params, contact_kwargs, point_rule)``: ``contact_kwargs`` are + keyword arguments of ``ContactPotential`` and ``ContactPotentialTerm`` + (``w_tol``, ``exclusion``, ``weight_mode="current"``); ``point_rule`` is + ``{"quad_n_per_edge": 2 or 4, "tri_order": "3" or "7"}`` for + ``quad_facet_points(n_per_edge=...)`` and ``tri_facet_points(order=...)``. + Pass ``scale=2`` when the block's primary and secondary surfaces are the + same surface (module notes on pair multiplicity). search.py lists where + ``w_tol`` and ``R0_min`` are applied differently from FEBio. + """ + if "kc" not in block: + raise ValueError( + "contact potential block has no kc (FEBio's default 0 disables contact)" + ) + + def get(key, default): + return float(block.get(key, default)) + + params = PotentialParams( + kc=get("kc", 0.0), + p=get("p", 4.0), + r_in=get("R_in", 1.0), + r_out=get("R_out", 2.0), + r_self=get("R0_min", 0.0), + scale=scale, + ) + rule = str(block.get("integration_rule", "default")).strip().lower() + higher = rule in ("higher-order", "1") + contact_kwargs = { + "w_tol": get("w_tol", 0.0), + "exclusion": ( + "neighbors" if int(get("exclude_neighbors", 0)) == 1 else "element" + ), + "weight_mode": "current", + } + point_rule = { + "quad_n_per_edge": 4 if higher else 2, + "tri_order": "7" if higher else "3", + } + return params, contact_kwargs, point_rule + + +# ----------------------------------------------------------------------------- +# Force-separation law in nondimensional form +# g(s) = -phi'(r) / kcs dg(s) = d g / d s +# G(s) = integral_s^1 g(s') ds' so that phi(r) = r_out * kcs * G(s) +# ----------------------------------------------------------------------------- +@wp.func +def g_force(s: f64, p: f64, s_in: f64, c1: f64, c2: f64) -> f64: + if s < s_in: + return wp.pow(s, -p) - c2 + if s < f64(1.0): + return c1 * (s - f64(1.0)) * (s - f64(1.0)) + return f64(0.0) + + +@wp.func +def dg_force(s: f64, p: f64, s_in: f64, c1: f64, c2: f64) -> f64: + if s < s_in: + return -p * wp.pow(s, -p - f64(1.0)) + if s < f64(1.0): + return f64(2.0) * c1 * (s - f64(1.0)) + return f64(0.0) + + +@wp.func +def G_energy(s: f64, p: f64, s_in: f64, c1: f64, c2: f64) -> f64: + if s >= f64(1.0): + return f64(0.0) + blend = c1 * (f64(1.0) - s_in) * (f64(1.0) - s_in) * (f64(1.0) - s_in) / f64(3.0) + if s >= s_in: + return c1 * (f64(1.0) - s) * (f64(1.0) - s) * (f64(1.0) - s) / f64(3.0) + core = (wp.pow(s, f64(1.0) - p) - wp.pow(s_in, f64(1.0) - p)) / ( + p - f64(1.0) + ) - c2 * (s_in - s) + return blend + core + + +# ----------------------------------------------------------------------------- +# Pair kernels +# ----------------------------------------------------------------------------- +@wp.kernel +def pair_energy_force( + pairs: wp.array(dtype=wp.vec2i), + n_pairs: wp.array(dtype=int), + pts: wp.array(dtype=vec3d), + weight: wp.array(dtype=f64), + radius: wp.array(dtype=f64), + body: wp.array(dtype=int), + pair_class: wp.array2d(dtype=int), + kcs: wp.array(dtype=f64), + p: wp.array(dtype=f64), + s_in: wp.array(dtype=f64), + c1: wp.array(dtype=f64), + c2: wp.array(dtype=f64), + r_out: wp.array(dtype=f64), + energy: wp.array(dtype=f64), + f_pts: wp.array(dtype=vec3d), +): + k = wp.tid() + if k >= n_pairs[0]: + return + i = pairs[k][0] + j = pairs[k][1] + c = pair_class[body[i], body[j]] + d = pts[j] - pts[i] + dist = wp.length(d) + r = dist - radius[i] - radius[j] + s = r / r_out[c] + # out of range, or overlapping capsules, where the law is undefined + if s >= f64(1.0) or r <= f64(0.0): + return + C = weight[i] * weight[j] + wp.atomic_add( + energy, 0, C * r_out[c] * kcs[c] * G_energy(s, p[c], s_in[c], c1[c], c2[c]) + ) + fmag = C * kcs[c] * g_force(s, p[c], s_in[c], c1[c], c2[c]) # repulsive + n = d / dist + wp.atomic_add(f_pts, j, fmag * n) + wp.atomic_add(f_pts, i, -fmag * n) + + +@wp.kernel +def pair_hessian_blocks( + pairs: wp.array(dtype=wp.vec2i), + n_pairs: wp.array(dtype=int), + pts: wp.array(dtype=vec3d), + weight: wp.array(dtype=f64), + radius: wp.array(dtype=f64), + body: wp.array(dtype=int), + pair_class: wp.array2d(dtype=int), + kcs: wp.array(dtype=f64), + p: wp.array(dtype=f64), + s_in: wp.array(dtype=f64), + c1: wp.array(dtype=f64), + c2: wp.array(dtype=f64), + r_out: wp.array(dtype=f64), + project: int, + H: wp.array(dtype=mat33d), +): + k = wp.tid() + if k >= n_pairs[0]: + return + i = pairs[k][0] + j = pairs[k][1] + c = pair_class[body[i], body[j]] + d = pts[j] - pts[i] + dist = wp.length(d) + r = dist - radius[i] - radius[j] + s = r / r_out[c] + if s >= f64(1.0) or r <= f64(0.0): + H[k] = mat33d() + return + C = weight[i] * weight[j] + n = d / dist + nn = wp.outer(n, n) + phi1 = -kcs[c] * g_force(s, p[c], s_in[c], c1[c], c2[c]) # phi'(r) + phi2 = -kcs[c] * dg_force(s, p[c], s_in[c], c1[c], c2[c]) / r_out[c] # phi''(r) + Hk = C * phi2 * nn + if project == 0: + Hk = Hk + C * (phi1 / dist) * (wp.identity(n=3, dtype=f64) - nn) + H[k] = Hk + + +@wp.kernel +def hessian_matvec_points( + pairs: wp.array(dtype=wp.vec2i), + n_pairs: wp.array(dtype=int), + H: wp.array(dtype=mat33d), + v_pts: wp.array(dtype=vec3d), + out_pts: wp.array(dtype=vec3d), +): + k = wp.tid() + if k >= n_pairs[0]: + return + i = pairs[k][0] + j = pairs[k][1] + Hdv = H[k] * (v_pts[j] - v_pts[i]) + wp.atomic_add(out_pts, j, Hdv) + wp.atomic_add(out_pts, i, -Hdv) + + +@wp.kernel +def pair_triplets( + pairs: wp.array(dtype=wp.vec2i), + n_pairs: wp.array(dtype=int), + H: wp.array(dtype=mat33d), + pt_nodes: wp.array2d(dtype=int), + pt_w: wp.array2d(dtype=f64), + rows: wp.array(dtype=int), + cols: wp.array(dtype=int), + vals: wp.array(dtype=mat33d), + count: wp.array(dtype=int), +): + """Nodal 3x3 blocks of the contact tangent as COO triplets, 4 K^2 per pair: + (+) ii, (+) jj, (-) ij, (-) ji, each chained through the point weights. + Unused node slots write a zero block at (0, 0), pruned by the BSR build.""" + k = wp.tid() + K = pt_nodes.shape[1] + per_pair = 4 * K * K + if k == 0: + count[0] = wp.min(n_pairs[0], pairs.shape[0]) * per_pair + if k >= n_pairs[0]: + return + i = pairs[k][0] + j = pairs[k][1] + Hk = H[k] + base = k * per_pair + for q in range(4): + pa = i + pb = i + sign = f64(1.0) + if q == 1: + pa = j + pb = j + elif q == 2: + pb = j + sign = f64(-1.0) + elif q == 3: + pa = j + pb = i + sign = f64(-1.0) + for a in range(K): + for b in range(K): + idx = base + (q * K + a) * K + b + na = pt_nodes[pa, a] + nb = pt_nodes[pb, b] + if na >= 0 and nb >= 0: + rows[idx] = na + cols[idx] = nb + vals[idx] = (sign * pt_w[pa, a] * pt_w[pb, b]) * Hk + else: + rows[idx] = 0 + cols[idx] = 0 + vals[idx] = mat33d() + + +@wp.kernel +def min_pair_distance( + pairs: wp.array(dtype=wp.vec2i), + n_pairs: wp.array(dtype=int), + pts: wp.array(dtype=vec3d), + radius: wp.array(dtype=f64), + dmin: wp.array(dtype=f64), +): + k = wp.tid() + if k >= n_pairs[0]: + return + i = pairs[k][0] + j = pairs[k][1] + wp.atomic_min(dmin, 0, wp.length(pts[j] - pts[i]) - radius[i] - radius[j]) + + +# ----------------------------------------------------------------------------- +# Host-side term +# ----------------------------------------------------------------------------- +class ContactPotential: + """Contact potential over a point set: energy, nodal forces, tangent action. + + Everything after ``search.build`` runs over the fixed-capacity pair buffer + with an early exit on the device pair count, so the Newton body can be + captured in a CUDA graph; ``search.check_overflow`` is the only host read. + + Sign convention: ``force`` returns f = -dE_c/dx (repulsive, pushes bodies + apart). The residual convention of ``contracts.PhysicsTerm`` (internal plus + contact minus external) wants +dE_c/dx; ``enforcement.py`` applies the sign. + """ + + def __init__( + self, + points: ContactPoints, + params: PotentialParams, + pair_class: np.ndarray, + ref_node_x: np.ndarray, + n_nodes: int, + exclusion: str = "neighbors", + w_tol: float = 0.0, + weight_mode: str = "reference", + device: str = "cpu", + **search_kwargs, + ): + if weight_mode not in ("reference", "current"): + raise ValueError("weight_mode must be 'reference' or 'current'") + self.points = points + self.params = params + self.device = device + self.n_nodes = int(n_nodes) + self.weight_mode = weight_mode + self.search = PairSearch( + points, + pair_class, + params.r_out, + ref_node_x, + params.r_self, + exclusion=exclusion, + w_tol=w_tol, + device=device, + **search_kwargs, + ) + self.weight = wp.array(points.weight, dtype=f64, device=device) + # kcs carries a gradient buffer so parameter adjoints can flow to it; f_pts + # carries one so that a vector-Jacobian product can be seeded at the forces + self.tables = params.device_tables(device, requires_grad=True) + self.f_pts = wp.zeros( + points.count, dtype=vec3d, device=device, requires_grad=True + ) + self.energy = wp.zeros(1, dtype=f64, device=device, requires_grad=True) + self.dmin = wp.zeros(1, dtype=f64, device=device) + self._trip_rows = self._trip_cols = self._trip_vals = None + self._trip_count = wp.zeros(1, dtype=int, device=device) + self.H = wp.zeros(self.search.capacity, dtype=mat33d, device=device) + self._v_pts = wp.zeros(points.count, dtype=vec3d, device=device) + self._o_pts = wp.zeros(points.count, dtype=vec3d, device=device) + + # --- selection ---------------------------------------------------------- + def build_pairs(self, node_x: wp.array, sync: bool = True) -> int: + n = self.search.build(node_x, sync=sync) + if self.H.shape[0] != self.search.capacity: + self.H = wp.zeros(self.search.capacity, dtype=mat33d, device=self.device) + return n + + def _pair_args(self): + s = self.search + w = s.cur_weight if self.weight_mode == "current" else self.weight + return [ + s.pairs, + s.n_pairs_dev, + s.pts, + w, + s.radius, + s.body, + s.pair_class, + *self.tables, + ] + + # --- evaluation over the current pair list ------------------------------ + def energy_force(self, node_x: wp.array, f_nodes: wp.array) -> wp.array: + """E_c (device scalar) and nodal forces f = -dE_c/dx accumulated into f_nodes. + + Record on a wp.Tape by wrapping the call; ``search.pts`` and ``energy`` + carry gradients. + """ + s = self.search + self.energy.zero_() + self.f_pts.zero_() + if self.weight_mode == "current": + s.update_points(node_x) + else: + wp.launch( + interpolate_points, + dim=s.n_pts, + inputs=[node_x, s.pt_nodes, s.pt_w, s.pts], + device=self.device, + ) + wp.launch( + pair_energy_force, + dim=s.capacity, + inputs=self._pair_args() + [self.energy, self.f_pts], + device=self.device, + ) + wp.launch( + scatter_to_nodes, + dim=s.n_pts, + inputs=[self.f_pts, s.pt_nodes, s.pt_w, f_nodes], + device=self.device, + ) + return self.energy + + def kc_gradient_from_tables(self) -> np.ndarray: + """Chain the tape gradient on the kcs table back to kc per class + (kcs = scale kc / R_out^p). Host array of length n_classes.""" + g_kcs = self.tables[0].grad.numpy() + P = self.params + return g_kcs * P.scale / P.r_out**P.p + + def energy_value(self) -> float: + return float(self.energy.numpy()[0]) + + def hessian_blocks(self, project: bool = False) -> wp.array: + wp.launch( + pair_hessian_blocks, + dim=self.search.capacity, + inputs=self._pair_args() + [1 if project else 0, self.H], + device=self.device, + ) + return self.H + + def hessian_matvec( + self, + v_nodes: wp.array, + out_nodes: wp.array, + project: bool = False, + rebuild_blocks: bool = True, + ): + """out_nodes += K_c v_nodes, matrix-free, chained through the point weights.""" + s = self.search + if rebuild_blocks: + self.hessian_blocks(project) + self._o_pts.zero_() + wp.launch( + interpolate_points, + dim=s.n_pts, + inputs=[v_nodes, s.pt_nodes, s.pt_w, self._v_pts], + device=self.device, + ) + wp.launch( + hessian_matvec_points, + dim=s.capacity, + inputs=[s.pairs, s.n_pairs_dev, self.H, self._v_pts, self._o_pts], + device=self.device, + ) + wp.launch( + scatter_to_nodes, + dim=s.n_pts, + inputs=[self._o_pts, s.pt_nodes, s.pt_w, out_nodes], + device=self.device, + ) + + def hessian_triplets(self, project: bool = False): + """Assembled K_c as host COO triplets (rows, cols, vals) over 3n scalar dofs. + + Host-side and numpy only, for tests and small direct solves; the GPU + paths are the matrix-free action and ``hessian_bsr``. + """ + s = self.search + s.check_overflow() + if s.n_pairs == 0: + z = np.zeros(0) + return z.astype(np.int64), z.astype(np.int64), z + H = self.hessian_blocks(project).numpy()[: s.n_pairs] + pairs = s.pairs.numpy()[: s.n_pairs] + pn, pw, K = self.points.pt_nodes, self.points.pt_w, self.points.nodes_per_point + rows, cols, vals = [], [], [] + for pa, pb, sign in ((0, 0, 1.0), (1, 1, 1.0), (0, 1, -1.0), (1, 0, -1.0)): + ia, ib = pairs[:, pa], pairs[:, pb] + for a in range(K): + na, wa = pn[ia, a], pw[ia, a] + for b in range(K): + nb, wb = pn[ib, b], pw[ib, b] + ok = (na >= 0) & (nb >= 0) + if not ok.any(): + continue + blk = (sign * wa[ok] * wb[ok])[:, None, None] * H[ok] + r0, c0 = 3 * na[ok], 3 * nb[ok] + for u in range(3): + for v in range(3): + rows.append(r0 + u) + cols.append(c0 + v) + vals.append(blk[:, u, v]) + return np.concatenate(rows), np.concatenate(cols), np.concatenate(vals) + + def hessian_dense(self, project: bool = False) -> np.ndarray: + """Dense K_c (3n x 3n) on the host, for tests.""" + n3 = 3 * self.n_nodes + K = np.zeros((n3, n3)) + rows, cols, vals = self.hessian_triplets(project) + np.add.at(K, (rows, cols), vals) + return K + + def hessian_bsr(self, project: bool = False, dest=None): + """Assembled contact tangent as a warp.sparse BSR matrix of 3x3 blocks, + built on the device from the pair list. Pass ``dest`` (from a previous + call) to reuse its storage. Not yet exercised under CUDA graph capture.""" + s = self.search + self.hessian_blocks(project) + K = self.points.nodes_per_point + n_trip = s.capacity * 4 * K * K + if self._trip_rows is None or self._trip_rows.shape[0] != n_trip: + self._trip_rows = wp.zeros(n_trip, dtype=int, device=self.device) + self._trip_cols = wp.zeros(n_trip, dtype=int, device=self.device) + self._trip_vals = wp.zeros(n_trip, dtype=mat33d, device=self.device) + wp.launch( + pair_triplets, + dim=s.capacity, + inputs=[s.pairs, s.n_pairs_dev, self.H, s.pt_nodes, s.pt_w], + outputs=[ + self._trip_rows, + self._trip_cols, + self._trip_vals, + self._trip_count, + ], + device=self.device, + ) + if dest is None: + dest = wps.bsr_zeros( + self.n_nodes, self.n_nodes, block_type=mat33d, device=self.device + ) + wps.bsr_set_from_triplets( + dest, + self._trip_rows, + self._trip_cols, + self._trip_vals, + count=self._trip_count, + ) + return dest + + def min_distance(self, node_x: wp.array) -> float: + """Smallest effective pair distance over the current pair list (r_min guard).""" + s = self.search + wp.launch( + interpolate_points, + dim=s.n_pts, + inputs=[node_x, s.pt_nodes, s.pt_w, s.pts], + device=self.device, + ) + self.dmin.fill_(np.inf) + wp.launch( + min_pair_distance, + dim=s.capacity, + inputs=[s.pairs, s.n_pairs_dev, s.pts, s.radius, self.dmin], + device=self.device, + ) + return float(self.dmin.numpy()[0]) + + # --- metrics ------------------------------------------------------------ + def point_forces(self) -> np.ndarray: + return self.f_pts.numpy() + + def contact_area(self, body: int | None = None) -> float: + """Wu 2022 rule: area of the points with nonzero contact force.""" + f = np.linalg.norm(self.f_pts.numpy(), axis=1) + mask = f > 0.0 + if body is not None: + mask &= self.points.body == body + return float(np.sum(self.points.area[mask])) + + def contact_fraction( + self, body: int, threshold: float, other_body: int, node_x: np.ndarray + ) -> float: + """Zelonis rule: fraction of a body's weight within ``threshold`` of another body + (host evaluation; brute force over the other body's points).""" + x = self.points.positions(np.asarray(node_x)) + a = self.points.body == body + b = self.points.body == other_body + xa, xb = x[a], x[b] + close = np.zeros(xa.shape[0], dtype=bool) + chunk = 2048 + for k in range(0, xa.shape[0], chunk): + d = np.linalg.norm(xa[k : k + chunk, None, :] - xb[None, :, :], axis=2) + d = ( + d + - self.points.radius[a][k : k + chunk, None] + - self.points.radius[b][None, :] + ) + close[k : k + chunk] = d.min(axis=1) < threshold + w = self.points.weight[a] + return float(w[close].sum() / w.sum()) diff --git a/src/warp_febio/contact/search.py b/src/warp_febio/contact/search.py index f54644e..aa79686 100644 --- a/src/warp_febio/contact/search.py +++ b/src/warp_febio/contact/search.py @@ -1,4 +1,448 @@ -"""Planned component. +"""Candidate pair generation for point-based contact. -Generate candidates, closest points, normals and exclusions. +Selection, not physics: which pairs of contact points can interact in the +current configuration. The result is an explicit pair list that the energy, +force and tangent kernels loop over. Keeping selection separate from +evaluation is what makes the evaluation differentiable (the pair set is +piecewise constant in the nodal positions) and what lets the whole Newton body +run without host synchronization. + +Mechanics of the search (Kamensky 2018, Section 3.1; FEBio's uniform grid, +whose cell size is at least R_out): + +* ``wp.HashGrid`` in float64 on the points themselves, cell size equal to the + search radius. +* Two passes, count then fill, with a device-side exclusive scan in between, so + the pair buffer has fixed capacity and overflow is detected by a single + host read at a convenient time. +* A pair (i, j) with i < j is kept when its effective distance + ``|x_j - x_i| - radius_i - radius_j`` is below the outer radius of its pair + class and it is not excluded. + +Exclusion (self-contact): + +* different bodies: never excluded; +* same body and reference distance below ``r_self``: excluded (FEBio ``R0_min``); +* same body and, depending on ``exclusion``: ``"element"`` drops points of the + same source element (FEBio's default: only an element against itself is + skipped, neighbors are left to ``w_tol`` and ``R0_min``); ``"neighbors"`` + drops points whose source elements share a node (FEBio + ``exclude_neighbors``); ``"none"`` applies the reference distance only. + Element ids are per builder call, so give each builder call its own body + when using ``"element"``. + +``w_tol``: a pair is dropped when the cosine between the pair direction and +the current facet normal is below ``w_tol``. Two deliberate differences from +FEBio's FEContactPotential, which matter for a facet-level comparison: FEBio +applies ``w_tol`` and ``R0_min`` as element-pair activation gates (one passing +Gauss-point pair activates the whole element pair, which is then summed +without rechecking) and tests only the primary point's normal; here both are +applied per point pair, and a pair is dropped only when every point of the +pair that has a normal fails the test. FEBio's edge-to-surface variant +declares ``w_tol`` but does not use it; here a wire-to-surface pair is tested +through the surface point's normal. With ``w_tol > 0`` the energy is not +continuous in the positions (a pair in range can be switched by the normal +test); with ``w_tol = 0`` it is C2. + +Not yet implemented from FEBio: ``check_intersections``. """ + +from __future__ import annotations + +import numpy as np +import warp as wp + +from .points import ContactPoints + +f64 = wp.float64 +vec3d = wp.vec3d + + +@wp.kernel +def interpolate_points( + node_x: wp.array(dtype=vec3d), + pt_nodes: wp.array2d(dtype=int), + pt_w: wp.array2d(dtype=f64), + pts: wp.array(dtype=vec3d), +): + i = wp.tid() + x = vec3d() + for a in range(pt_nodes.shape[1]): + n = pt_nodes[i, a] + if n >= 0: + x = x + pt_w[i, a] * node_x[n] + pts[i] = x + + +@wp.kernel +def point_frames( + node_x: wp.array(dtype=vec3d), + pt_nodes: wp.array2d(dtype=int), + pt_w: wp.array2d(dtype=f64), + pt_dw1: wp.array2d(dtype=f64), + pt_dw2: wp.array2d(dtype=f64), + rule_w: wp.array(dtype=f64), + pts: wp.array(dtype=vec3d), + normals: wp.array(dtype=vec3d), + cur_weight: wp.array(dtype=f64), +): + """Position, current unit normal (zero for lines and bare nodes) and current + Jacobian-weighted integration weight of each point, as FEBio's + FEContactPotential::UpdateSurface computes them.""" + i = wp.tid() + x = vec3d() + t1 = vec3d() + t2 = vec3d() + for a in range(pt_nodes.shape[1]): + n = pt_nodes[i, a] + if n >= 0: + xn = node_x[n] + x = x + pt_w[i, a] * xn + t1 = t1 + pt_dw1[i, a] * xn + t2 = t2 + pt_dw2[i, a] * xn + pts[i] = x + l1 = wp.length(t1) + l2 = wp.length(t2) + if l2 > f64(0.0): + nrm = wp.cross(t1, t2) + J = wp.length(nrm) + if J > f64(0.0): + normals[i] = nrm / J + else: # degenerate facet: no usable normal, zero current weight + normals[i] = vec3d() + cur_weight[i] = rule_w[i] * J + elif l1 > f64(0.0): + normals[i] = vec3d() + cur_weight[i] = rule_w[i] * l1 + else: + normals[i] = vec3d() + cur_weight[i] = rule_w[i] + + +@wp.kernel +def scatter_to_nodes( + f_pts: wp.array(dtype=vec3d), + pt_nodes: wp.array2d(dtype=int), + pt_w: wp.array2d(dtype=f64), + f_nodes: wp.array(dtype=vec3d), +): + """Transpose of interpolate_points: accumulate point vectors onto nodes.""" + i = wp.tid() + for a in range(pt_nodes.shape[1]): + n = pt_nodes[i, a] + if n >= 0: + wp.atomic_add(f_nodes, n, pt_w[i, a] * f_pts[i]) + + +@wp.func +def pair_excluded( + i: int, + j: int, + body: wp.array(dtype=int), + element: wp.array(dtype=int), + ref_pts: wp.array(dtype=vec3d), + r_self: f64, + pt_nodes: wp.array2d(dtype=int), + exclusion: int, +) -> bool: + """exclusion: 0 none, 1 same source element, 2 source elements sharing a node.""" + if body[i] != body[j]: + return False + if wp.length(ref_pts[j] - ref_pts[i]) < r_self: + return True + if exclusion == 1: + return element[i] == element[j] + if exclusion == 2: + for a in range(pt_nodes.shape[1]): + na = pt_nodes[i, a] + if na >= 0: + for b in range(pt_nodes.shape[1]): + if pt_nodes[j, b] == na: + return True + return False + + +@wp.func +def pair_active( + i: int, + j: int, + pts: wp.array(dtype=vec3d), + normals: wp.array(dtype=vec3d), + radius: wp.array(dtype=f64), + body: wp.array(dtype=int), + pair_class: wp.array2d(dtype=int), + r_out: wp.array(dtype=f64), + w_tol: f64, +) -> bool: + c = pair_class[body[i], body[j]] + if c < 0: + return False + d = pts[j] - pts[i] + dist = wp.length(d) + if dist <= f64(0.0): # coincident points have no direction; never pair them + return False + if dist - radius[i] - radius[j] >= r_out[c]: + return False + if w_tol > f64(0.0): + e = d / dist + ni = normals[i] + nj = normals[j] + has_i = wp.length_sq(ni) > f64(0.0) + has_j = wp.length_sq(nj) > f64(0.0) + pass_i = has_i and (wp.abs(wp.dot(e, ni)) >= w_tol) + pass_j = has_j and (wp.abs(wp.dot(e, nj)) >= w_tol) + if (has_i or has_j) and not (pass_i or pass_j): + return False + return True + + +@wp.kernel +def count_pairs( + grid: wp.uint64, + pts: wp.array(dtype=vec3d), + normals: wp.array(dtype=vec3d), + ref_pts: wp.array(dtype=vec3d), + radius: wp.array(dtype=f64), + body: wp.array(dtype=int), + element: wp.array(dtype=int), + pair_class: wp.array2d(dtype=int), + r_out: wp.array(dtype=f64), + w_tol: f64, + pt_nodes: wp.array2d(dtype=int), + exclusion: int, + search_radius: f64, + r_self: f64, + counts: wp.array(dtype=int), +): + i = wp.tid() + n = int(0) + q = wp.hash_grid_query(grid, pts[i], search_radius) + j = int(0) + while wp.hash_grid_query_next(q, j): + if j > i: + if pair_active(i, j, pts, normals, radius, body, pair_class, r_out, w_tol): + if not pair_excluded( + i, j, body, element, ref_pts, r_self, pt_nodes, exclusion + ): + n += 1 + counts[i] = n + + +@wp.kernel +def fill_pairs( + grid: wp.uint64, + pts: wp.array(dtype=vec3d), + normals: wp.array(dtype=vec3d), + ref_pts: wp.array(dtype=vec3d), + radius: wp.array(dtype=f64), + body: wp.array(dtype=int), + element: wp.array(dtype=int), + pair_class: wp.array2d(dtype=int), + r_out: wp.array(dtype=f64), + w_tol: f64, + pt_nodes: wp.array2d(dtype=int), + exclusion: int, + search_radius: f64, + r_self: f64, + offsets: wp.array(dtype=int), + pairs: wp.array(dtype=wp.vec2i), +): + i = wp.tid() + k = offsets[i] + cap = pairs.shape[0] + q = wp.hash_grid_query(grid, pts[i], search_radius) + j = int(0) + while wp.hash_grid_query_next(q, j): + if j > i: + if pair_active(i, j, pts, normals, radius, body, pair_class, r_out, w_tol): + if not pair_excluded( + i, j, body, element, ref_pts, r_self, pt_nodes, exclusion + ): + if k < cap: + pairs[k] = wp.vec2i(i, j) + k += 1 + + +@wp.kernel +def total_from_scan( + counts: wp.array(dtype=int), + offsets: wp.array(dtype=int), + n_pairs: wp.array(dtype=int), +): + last = counts.shape[0] - 1 + n_pairs[0] = offsets[last] + counts[last] + + +class PairSearch: + """Device-resident contact points and their current pair list. + + ``points`` defines the point set; ``pair_class`` is a symmetric + [n_bodies, n_bodies] integer table (-1 means the two bodies never + interact); ``r_out`` holds the outer radius of each class. ``ref_node_x`` + is the reference configuration used for the reference-distance exclusion. + ``exclusion`` is ``"element"``, ``"neighbors"`` or ``"none"`` (module + notes). ``grid_dim`` is the hash grid resolution per axis and + ``pairs_per_point`` the initial pair-buffer capacity per point; both are + performance tunables, and the buffer grows on overflow. + """ + + EXCLUSION_MODES = {"none": 0, "element": 1, "neighbors": 2} + + def __init__( + self, + points: ContactPoints, + pair_class: np.ndarray, + r_out: np.ndarray, + ref_node_x: np.ndarray, + r_self: float, + exclusion: str = "neighbors", + w_tol: float = 0.0, + device: str = "cpu", + grid_dim: int = 64, + pairs_per_point: int = 48, + ): + self.points = points + self.device = device + self.n_pts = points.count + if exclusion not in self.EXCLUSION_MODES: + raise ValueError("exclusion must be 'none', 'element' or 'neighbors'") + self.exclusion = self.EXCLUSION_MODES[exclusion] + self.r_self = float(r_self) + self.w_tol = float(w_tol) + pair_class = np.asarray(pair_class, dtype=np.int32) + r_out = np.asarray(r_out, dtype=np.float64) + if pair_class.ndim != 2 or pair_class.shape[0] != pair_class.shape[1]: + raise ValueError("pair_class must be a square [n_bodies, n_bodies] table") + if not np.array_equal(pair_class, pair_class.T): + raise ValueError("pair_class must be symmetric: pairs are stored unordered") + if points.body.max() >= pair_class.shape[0]: + raise ValueError("a body id exceeds the pair_class table") + if pair_class.max() >= r_out.shape[0]: + raise ValueError("a pair class exceeds the parameter table") + + self.pt_nodes = wp.array(points.pt_nodes, dtype=int, device=device) + self.pt_w = wp.array(points.pt_w, dtype=f64, device=device) + self.pt_dw1 = wp.array(points.pt_dw1, dtype=f64, device=device) + self.pt_dw2 = wp.array(points.pt_dw2, dtype=f64, device=device) + self.rule_w = wp.array(points.rule_weight, dtype=f64, device=device) + self.radius = wp.array(points.radius, dtype=f64, device=device) + self.body = wp.array(points.body, dtype=int, device=device) + self.element = wp.array(points.element, dtype=int, device=device) + self.pair_class = wp.array(pair_class, dtype=int, device=device) + self.r_out = wp.array(r_out, dtype=f64, device=device) + + # pts carries a gradient buffer so the energy can be recorded on a tape + self.pts = wp.zeros(self.n_pts, dtype=vec3d, device=device, requires_grad=True) + self.normals = wp.zeros(self.n_pts, dtype=vec3d, device=device) + self.cur_weight = wp.zeros(self.n_pts, dtype=f64, device=device) + self.counts = wp.zeros(self.n_pts, dtype=int, device=device) + self.offsets = wp.zeros(self.n_pts, dtype=int, device=device) + self.n_pairs_dev = wp.zeros(1, dtype=int, device=device) + self.capacity = int(pairs_per_point * self.n_pts) + self.pairs = wp.zeros(self.capacity, dtype=wp.vec2i, device=device) + self.grid = wp.HashGrid(grid_dim, grid_dim, grid_dim, device=device, dtype=f64) + # every pair whose effective distance can be below r_out must be in reach + self.search_radius = float(r_out.max() + 2.0 * points.radius.max()) + self.n_pairs = 0 + + ref_x = wp.array( + np.asarray(ref_node_x, dtype=np.float64), dtype=vec3d, device=device + ) + self.ref_pts = wp.zeros(self.n_pts, dtype=vec3d, device=device) + wp.launch( + interpolate_points, + dim=self.n_pts, + inputs=[ref_x, self.pt_nodes, self.pt_w], + outputs=[self.ref_pts], + device=device, + ) + + def update_points(self, node_x: wp.array): + """Positions, current normals and current weights for ``node_x``.""" + wp.launch( + point_frames, + dim=self.n_pts, + inputs=[ + node_x, + self.pt_nodes, + self.pt_w, + self.pt_dw1, + self.pt_dw2, + self.rule_w, + ], + outputs=[self.pts, self.normals, self.cur_weight], + device=self.device, + ) + + def _selection_args(self): + return [ + self.grid.id, + self.pts, + self.normals, + self.ref_pts, + self.radius, + self.body, + self.element, + self.pair_class, + self.r_out, + f64(self.w_tol), + self.pt_nodes, + self.exclusion, + f64(self.search_radius), + f64(self.r_self), + ] + + def build(self, node_x: wp.array, sync: bool = True) -> int: + """Enumerate the pairs of configuration ``node_x``. + + With ``sync=True`` the pair count is read back and the buffer regrown + and refilled on overflow. With ``sync=False`` nothing touches the host; + call ``check_overflow`` later (once per step is enough) and rebuild if + it returns True, since an overflowed list is incomplete. + """ + self.update_points(node_x) + self.grid.build(self.pts, self.search_radius) + sel = self._selection_args() + wp.launch( + count_pairs, + dim=self.n_pts, + inputs=sel, + outputs=[self.counts], + device=self.device, + ) + wp.utils.array_scan(self.counts, self.offsets, inclusive=False) + wp.launch( + total_from_scan, + dim=1, + inputs=[self.counts, self.offsets], + outputs=[self.n_pairs_dev], + device=self.device, + ) + wp.launch( + fill_pairs, + dim=self.n_pts, + inputs=sel + [self.offsets], + outputs=[self.pairs], + device=self.device, + ) + if sync and self.check_overflow(): + return self.build(node_x, sync=True) + return self.n_pairs + + def check_overflow(self) -> bool: + """Host read of the pair count. On overflow the buffer is regrown, the + device count is reset to zero so that no kernel consumes the incomplete + list, and True is returned: the caller must build again.""" + self.n_pairs = int(self.n_pairs_dev.numpy()[0]) + if self.n_pairs > self.capacity: + self.capacity = int(1.5 * self.n_pairs) + 16 + self.pairs = wp.zeros(self.capacity, dtype=wp.vec2i, device=self.device) + self.n_pairs_dev.zero_() + self.n_pairs = 0 + return True + return False + + def pair_array(self) -> np.ndarray: + """Host copy of the current pairs, [n_pairs, 2].""" + self.check_overflow() + return self.pairs.numpy()[: self.n_pairs].copy() diff --git a/tests/test_contact_potential.py b/tests/test_contact_potential.py new file mode 100644 index 0000000..f80986d --- /dev/null +++ b/tests/test_contact_potential.py @@ -0,0 +1,866 @@ +"""Checks for the contact potential: law, derivatives, tape, exclusion, capsules. + +Synthetic geometry, FP64. Runs on the device named by the environment +variable WARP_FEBIO_TEST_DEVICE (default "cpu"); set it to "cuda:0" to run +the same checks on a GPU. Tolerances are stated at each assertion. +""" + +import os +import unittest + +import numpy as np +import warp as wp + +from warp_febio.contact import ( + from_febio_block, + ContactInterface, + ContactPoints, + ContactPotential, + ContactPotentialTerm, + ContactSet, + PotentialParams, + node_points, + quad_facet_points, + segment_points, +) + +wp.init() +DEVICE = os.environ.get("WARP_FEBIO_TEST_DEVICE", "cpu") +vec3d = wp.vec3d + + +def quad_plate(nx, ny, size, z, offset=(0.0, 0.0), node0=0): + """Flat Quad4 plate in the plane z = const; returns nodes [n,3], quads [m,4].""" + xs = np.linspace(-size / 2, size / 2, nx + 1) + offset[0] + ys = np.linspace(-size / 2, size / 2, ny + 1) + offset[1] + X, Y = np.meshgrid(xs, ys, indexing="ij") + nodes = np.stack([X.ravel(), Y.ravel(), np.full(X.size, z)], axis=1) + quads = [] + for i in range(nx): + for j in range(ny): + n00 = i * (ny + 1) + j + quads.append([n00, n00 + (ny + 1), n00 + (ny + 1) + 1, n00 + 1]) + return nodes, np.asarray(quads, dtype=np.int32) + node0 + + +def two_plates(gap, nx=4, size=1.0, n_per_edge=2, rule="gauss"): + """Two plates facing each other, a gap apart, as two bodies.""" + n_lo, q_lo = quad_plate(nx, nx, size, 0.0) + n_hi, q_hi = quad_plate(nx, nx, size, gap, offset=(0.013, -0.021), node0=len(n_lo)) + nodes = np.concatenate([n_lo, n_hi]) + pts = ContactPoints.concatenate( + [ + quad_facet_points(q_lo, nodes, body=0, n_per_edge=n_per_edge, rule=rule), + quad_facet_points(q_hi, nodes, body=1, n_per_edge=n_per_edge, rule=rule), + ] + ) + return nodes, pts + + +def wp_nodes(nodes, requires_grad=False): + return wp.array( + np.asarray(nodes, dtype=np.float64), + dtype=vec3d, + device=DEVICE, + requires_grad=requires_grad, + ) + + +class ForceLawTests(unittest.TestCase): + def test_force_is_c1_and_energy_vanishes_at_r_out(self): + P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5) + e = 1e-7 + f_in = P.force(P.r_in[0] - e) + f_out = P.force(P.r_in[0] + e) + self.assertAlmostEqual(f_in / f_out, 1.0, places=5) + slope_in = (P.force(P.r_in[0]) - P.force(P.r_in[0] - e)) / e + slope_out = (P.force(P.r_in[0] + e) - P.force(P.r_in[0])) / e + self.assertAlmostEqual(slope_in / slope_out, 1.0, places=4) + self.assertEqual(P.phi(P.r_out[0]), 0.0) + self.assertEqual(P.force(P.r_out[0]), 0.0) + # phi' = -force by finite differences across the blend region + r = 0.35 + dphi = (P.phi(r + e) - P.phi(r - e)) / (2 * e) + self.assertAlmostEqual(-dphi / P.force(r), 1.0, places=6) + + def test_parameter_table_broadcasts(self): + P = PotentialParams(kc=[1.0, 2.0], p=4.0, r_in=0.2, r_out=[0.5, 0.5]) + self.assertEqual(P.n_classes, 2) + self.assertAlmostEqual( + P.force(0.15, cls=1) / P.force(0.15, cls=0), 2.0, places=12 + ) + Q = PotentialParams(kc=1.0, p=4.0, r_in=[0.2, 0.3], r_out=0.5) + # each class is continuous at its own R_in (the c1, c2 of that class) + for cls in (0, 1): + e = 1e-7 + self.assertAlmostEqual( + Q.force(Q.r_in[cls] - e, cls) / Q.force(Q.r_in[cls] + e, cls), + 1.0, + places=5, + ) + + +class PairKernelTests(unittest.TestCase): + def setUp(self): + self.P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5) + self.nodes, self.pts = two_plates(gap=0.3) + self.n = len(self.nodes) + self.cp = ContactPotential( + self.pts, + self.P, + np.array([[0, 0], [0, 0]]), + self.nodes, + self.n, + device=DEVICE, + ) + self.x = wp_nodes(self.nodes) + self.cp.build_pairs(self.x) + self.assertGreater(self.cp.search.n_pairs, 0) + + def energy_and_force(self, nodes): + f = wp.zeros(self.n, dtype=vec3d, device=DEVICE) + self.cp.energy_force(wp_nodes(nodes), f) + return self.cp.energy_value(), f.numpy() + + def test_force_matches_energy_gradient(self): + E0, f0 = self.energy_and_force(self.nodes) + self.assertGreater(E0, 0.0) + rng = np.random.default_rng(0) + direction = rng.standard_normal(self.nodes.shape) + h = 1e-6 + Ep, _ = self.energy_and_force(self.nodes + h * direction) + Em, _ = self.energy_and_force(self.nodes - h * direction) + dE_fd = (Ep - Em) / (2 * h) + dE_an = -np.sum(f0 * direction) + self.assertAlmostEqual(dE_fd / dE_an, 1.0, places=8) + + def test_hessian_action_matches_force_derivative(self): + rng = np.random.default_rng(1) + v = rng.standard_normal(self.nodes.shape) + h = 1e-6 + _, fp = self.energy_and_force(self.nodes + h * v) + _, fm = self.energy_and_force(self.nodes - h * v) + Kv_fd = -(fp - fm) / (2 * h) # K = d(-f)/dx = d2E/dx2 + self.energy_and_force(self.nodes) + out = wp.zeros(self.n, dtype=vec3d, device=DEVICE) + self.cp.hessian_matvec(wp_nodes(v), out, project=False) + Kv = out.numpy() + rel = np.linalg.norm(Kv - Kv_fd) / np.linalg.norm(Kv_fd) + self.assertLess(rel, 1e-7) + # assembled matrix agrees with the action and is symmetric + K = self.cp.hessian_dense(project=False) + self.assertLess( + np.linalg.norm(K @ v.ravel() - Kv.ravel()) / np.linalg.norm(Kv), 1e-12 + ) + self.assertLess(np.abs(K - K.T).max() / np.abs(K).max(), 1e-12) + + def test_projected_tangent_is_positive_semidefinite(self): + self.energy_and_force(self.nodes) + K_full = self.cp.hessian_dense(project=False) + K_proj = self.cp.hessian_dense(project=True) + lam_full = np.linalg.eigvalsh(K_full) + lam_proj = np.linalg.eigvalsh(K_proj) + self.assertLess(lam_full.min(), -1e-6 * np.abs(lam_full).max()) + self.assertGreater(lam_proj.min(), -1e-10 * np.abs(lam_proj).max()) + + def test_tape_gradient_equals_force(self): + x = wp_nodes(self.nodes, requires_grad=True) + f = wp.zeros(self.n, dtype=vec3d, device=DEVICE) + tape = wp.Tape() + with tape: + E = self.cp.energy_force(x, f) + tape.backward(E) + g = x.grad.numpy() + f = f.numpy() + self.assertLess(np.linalg.norm(g + f) / np.linalg.norm(f), 1e-12) + + def test_term_residual_sign_and_tangent(self): + term = ContactPotentialTerm( + self.pts, + self.P, + np.array([[0, 0], [0, 0]]), + self.nodes, + self.n, + device=DEVICE, + ) + term.update_pairs(self.x) + R = wp.zeros(self.n, dtype=vec3d, device=DEVICE) + term.residual(self.x, None, R) + _, f = self.energy_and_force(self.nodes) + self.assertLess(np.linalg.norm(R.numpy() + f) / np.linalg.norm(f), 1e-12) + T = term.linearize(self.x, None) + v = np.random.default_rng(2).standard_normal(self.nodes.shape) + out = wp.zeros(self.n, dtype=vec3d, device=DEVICE) + T.apply(wp_nodes(v), out) + ref = wp.zeros(self.n, dtype=vec3d, device=DEVICE) + self.cp.hessian_matvec(wp_nodes(v), ref, project=False) + self.assertLess( + np.linalg.norm(out.numpy() - ref.numpy()) / np.linalg.norm(ref.numpy()), + 1e-12, + ) + # tape gradient through the term equals the residual (custom-op building block) + xg = wp_nodes(self.nodes, requires_grad=True) + E, g = term.energy_and_gradient(xg) + self.assertLess( + np.linalg.norm(g.numpy() - R.numpy()) / np.linalg.norm(R.numpy()), 1e-12 + ) + self.assertAlmostEqual(float(E.numpy()[0]) / term.energy(), 1.0, places=12) + # the term satisfies the generic interface and composes in a ContactSet + self.assertIsInstance(term, ContactInterface) + cs = ContactSet([term]) + cs.update_pairs(self.x) + R2 = wp.zeros(self.n, dtype=vec3d, device=DEVICE) + cs.residual(self.x, None, R2) + self.assertLess(np.linalg.norm(R2.numpy() - R.numpy()), 1e-14) + self.assertIn("contact_potential/contact_area", cs.results()) + + +class CapsuleDerivativeTests(unittest.TestCase): + """Force and Hessian consistency with nonzero radius offsets (the capsule path).""" + + def test_capsule_force_and_hessian_match_finite_differences(self): + P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5) + nodes, pts = two_plates(gap=0.45) + pts.radius[pts.body == 1] = 0.08 + pts.radius[pts.body == 0] = 0.03 + n = len(nodes) + cp = ContactPotential( + pts, P, np.zeros((2, 2), dtype=int), nodes, n, device=DEVICE + ) + cp.build_pairs(wp_nodes(nodes)) + self.assertGreater(cp.search.n_pairs, 0) + + def ef(x_np): + f = wp.zeros(n, dtype=vec3d, device=DEVICE) + cp.energy_force(wp_nodes(x_np), f) + return cp.energy_value(), f.numpy() + + rng = np.random.default_rng(5) + d = rng.standard_normal(nodes.shape) + h = 1e-6 + Ep, fp = ef(nodes + h * d) + Em, fm = ef(nodes - h * d) + E0, f0 = ef(nodes) + self.assertAlmostEqual(((Ep - Em) / (2 * h)) / (-np.sum(f0 * d)), 1.0, places=8) + out = wp.zeros(n, dtype=vec3d, device=DEVICE) + cp.hessian_matvec(wp_nodes(d), out, project=False) + Kd_fd = -(fp - fm) / (2 * h) + self.assertLess( + np.linalg.norm(out.numpy() - Kd_fd) / np.linalg.norm(Kd_fd), 1e-7 + ) + + +class CoreBranchTests(unittest.TestCase): + """Derivative checks with pairs inside the stiff core (r < R_in).""" + + def test_force_and_hessian_in_the_core(self): + P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5) + nodes, pts = two_plates(gap=0.15) + n = len(nodes) + cp = ContactPotential( + pts, P, np.zeros((2, 2), dtype=int), nodes, n, device=DEVICE + ) + cp.build_pairs(wp_nodes(nodes)) + self.assertLess(cp.min_distance(wp_nodes(nodes)), P.r_in[0]) + + def ef(x_np): + f = wp.zeros(n, dtype=vec3d, device=DEVICE) + cp.energy_force(wp_nodes(x_np), f) + return cp.energy_value(), f.numpy() + + d = np.random.default_rng(11).standard_normal(nodes.shape) + h = 1e-7 + Ep, fp = ef(nodes + h * d) + Em, fm = ef(nodes - h * d) + _, f0 = ef(nodes) + # central differences: relative agreement to 1e-7 (force) and 1e-6 (tangent action) + self.assertLess(abs(((Ep - Em) / (2 * h)) / (-np.sum(f0 * d)) - 1.0), 1e-7) + out = wp.zeros(n, dtype=vec3d, device=DEVICE) + cp.hessian_matvec(wp_nodes(d), out, project=False) + Kd_fd = -(fp - fm) / (2 * h) + self.assertLess( + np.linalg.norm(out.numpy() - Kd_fd) / np.linalg.norm(Kd_fd), 1e-6 + ) + + +class GuardTests(unittest.TestCase): + def test_coincident_and_overlapping_points_do_not_poison_the_sum(self): + P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5) + # nodes 0 and 1 coincide (different bodies); node 2 overlaps node 0's capsule + nodes = np.array([[0.0, 0, 0], [0.0, 0, 0], [0.05, 0, 0], [0.3, 0, 0]]) + pts = ContactPoints.concatenate( + [node_points([0], body=0, radius=0.1), node_points([1, 2, 3], body=1)] + ) + cp = ContactPotential( + pts, P, np.zeros((2, 2), dtype=int), nodes, 4, device=DEVICE + ) + cp.build_pairs(wp_nodes(nodes)) + f = wp.zeros(4, dtype=vec3d, device=DEVICE) + cp.energy_force(wp_nodes(nodes), f) + self.assertTrue(np.all(np.isfinite(f.numpy()))) + self.assertTrue(np.isfinite(cp.energy_value())) + self.assertGreater( + f.numpy()[3, 0], 0.0 + ) # the one valid pair (0, 3) still repels + + def test_asymmetric_pair_class_is_rejected(self): + P = PotentialParams(kc=[1.0, 1.0], p=4.0, r_in=0.2, r_out=0.5) + nodes = np.array([[0.0, 0, 0], [0.3, 0, 0]]) + pts = ContactPoints.concatenate( + [node_points([0], body=0), node_points([1], body=1)] + ) + with self.assertRaises(ValueError): + ContactPotential( + pts, P, np.array([[0, 1], [0, 0]]), nodes, 2, device=DEVICE + ) + + def test_febio_block_requires_kc(self): + with self.assertRaises(ValueError): + from_febio_block({"R_in": 0.2, "R_out": 0.5}) + + +class ExclusionTests(unittest.TestCase): + def pairs_for(self, nodes, ref_nodes, body, exclusion, pt_nodes=None, r_self=0.75): + n = len(nodes) + if pt_nodes is None: + pts = ContactPoints.concatenate( + [node_points(np.where(body == b)[0], body=b) for b in np.unique(body)] + ) + else: + pts = pt_nodes + P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5, r_self=r_self) + nb = int(pts.body.max()) + 1 + cp = ContactPotential( + pts, + P, + np.zeros((nb, nb), dtype=int), + ref_nodes, + n, + exclusion=exclusion, + device=DEVICE, + ) + cp.build_pairs(wp_nodes(nodes)) + return cp.search.pair_array() + + def test_same_body_close_in_reference_is_excluded(self): + ref = np.array([[0.0, 0, 0], [0.3, 0, 0]]) + self.assertEqual(len(self.pairs_for(ref, ref, np.array([0, 0]), "none")), 0) + + def test_different_bodies_always_interact(self): + ref = np.array([[0.0, 0, 0], [0.3, 0, 0]]) + self.assertEqual(len(self.pairs_for(ref, ref, np.array([0, 1]), "none")), 1) + + def test_same_body_far_in_reference_interacts_when_folded(self): + ref = np.array([[0.0, 0, 0], [5.0, 0, 0]]) + cur = np.array([[0.0, 0, 0], [0.3, 0, 0]]) + self.assertEqual(len(self.pairs_for(cur, ref, np.array([0, 0]), "none")), 1) + + def test_shared_node_points_are_excluded_by_topology(self): + # two points on facets that share node 1, far apart in the reference, + # brought within r_out in the current configuration + ref = np.array([[0.0, 0, 0], [5.0, 0, 0], [10.0, 0, 0]]) + cur = np.array([[0.0, 0, 0], [0.2, 0, 0], [0.4, 0, 0]]) + pt_nodes = np.array([[0, 1], [1, 2]]) + pt_w = np.array([[0.5, 0.5], [0.5, 0.5]]) + pts = ContactPoints( + pt_nodes, + pt_w, + np.ones(2), + np.ones(2), + np.zeros(2), + np.zeros(2, dtype=np.int32), + np.arange(2, dtype=np.int32), + ) + self.assertEqual( + len(self.pairs_for(cur, ref, None, "neighbors", pt_nodes=pts, r_self=0.01)), + 0, + ) + # two points of one facet, 0.4 apart in the current configuration + same = ContactPoints( + np.array([[0, 1], [0, 1]]), + np.array([[0.9, 0.1], [0.1, 0.9]]), + np.ones(2), + np.ones(2), + np.zeros(2), + np.zeros(2, dtype=np.int32), + np.zeros(2, dtype=np.int32), + ) + cur2 = np.array([[0.0, 0, 0], [0.5, 0, 0], [10.0, 0, 0]]) + self.assertEqual( + len(self.pairs_for(cur2, ref, None, "element", pt_nodes=same, r_self=0.01)), + 0, + ) + self.assertEqual( + len(self.pairs_for(cur2, ref, None, "none", pt_nodes=same, r_self=0.01)), 1 + ) + self.assertEqual( + len(self.pairs_for(cur, ref, None, "element", pt_nodes=pts, r_self=0.01)), 1 + ) + + def test_pair_class_minus_one_disables_a_body_pair(self): + ref = np.array([[0.0, 0, 0], [0.3, 0, 0]]) + pts = ContactPoints.concatenate( + [node_points([0], body=0), node_points([1], body=1)] + ) + P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5) + cp = ContactPotential( + pts, P, np.array([[0, -1], [-1, 0]]), ref, 2, device=DEVICE + ) + cp.build_pairs(wp_nodes(ref)) + self.assertEqual(len(cp.search.pair_array()), 0) + + +class CapsuleAndClassTests(unittest.TestCase): + def point_pair_force( + self, d, radius_a, radius_b, kc_table=(1.0,), pair_class=((0, 0), (0, 0)) + ): + nodes = np.array([[0.0, 0, 0], [0.0, 0, d]]) + pts = ContactPoints.concatenate( + [ + node_points([0], body=0, radius=radius_a), + node_points([1], body=1, radius=radius_b), + ] + ) + P = PotentialParams(kc=np.array(kc_table), p=4.0, r_in=0.2, r_out=0.5) + cp = ContactPotential(pts, P, np.array(pair_class), nodes, 2, device=DEVICE) + cp.build_pairs(wp_nodes(nodes)) + f = wp.zeros(2, dtype=vec3d, device=DEVICE) + cp.energy_force(wp_nodes(nodes), f) + return f.numpy()[1, 2], cp.energy_value() + + def test_radius_offsets_shift_the_law_exactly(self): + f0, E0 = self.point_pair_force(0.30, 0.0, 0.0) + f1, E1 = self.point_pair_force(0.30 + 0.1 + 0.15, 0.1, 0.15) + self.assertAlmostEqual(f1 / f0, 1.0, places=12) + self.assertAlmostEqual(E1 / E0, 1.0, places=12) + self.assertGreater(f0, 0.0) + + def test_pair_class_selects_parameters(self): + f_a, _ = self.point_pair_force( + 0.30, 0.0, 0.0, kc_table=(1.0, 3.0), pair_class=((0, 0), (0, 0)) + ) + f_b, _ = self.point_pair_force( + 0.30, 0.0, 0.0, kc_table=(1.0, 3.0), pair_class=((0, 1), (1, 0)) + ) + self.assertAlmostEqual(f_b / f_a, 3.0, places=12) + + def test_crossing_wires_repel_through_their_radii(self): + """Two perpendicular wires of radius r_w: the law acts on the surface gap.""" + r_w, L = 0.05, 2.0 + P = PotentialParams(kc=1.0, p=4.0, r_in=0.1, r_out=0.25) + + # wire 0 along x at z = 0, wire 1 along y at height h (nodes 0,1 and 2,3) + def nodes_at(h): + return np.array( + [[-L / 2, 0, 0], [L / 2, 0, 0], [0, -L / 2, h], [0, L / 2, h]] + ) + + ref = nodes_at(1.0) + pts = ContactPoints.concatenate( + [ + segment_points( + np.array([[0, 1]]), ref, body=0, spacing=P.r_out[0] / 4, radius=r_w + ), + segment_points( + np.array([[2, 3]]), ref, body=1, spacing=P.r_out[0] / 4, radius=r_w + ), + ] + ) + cp = ContactPotential( + pts, P, np.zeros((2, 2), dtype=int), ref, 4, device=DEVICE + ) + + def vertical_force(h): + x = wp_nodes(nodes_at(h)) + cp.build_pairs(x) + f = wp.zeros(4, dtype=vec3d, device=DEVICE) + cp.energy_force(x, f) + return f.numpy()[2:, 2].sum() + + # the force is repulsive and grows monotonically as the wires approach + gaps = np.array([0.9, 0.7, 0.5, 0.3]) * P.r_out[0] + forces = np.array([vertical_force(2 * r_w + g) for g in gaps]) + self.assertTrue(np.all(forces > 0.0)) + self.assertTrue(np.all(np.diff(forces) > 0.0)) + # no interaction beyond 2 r_w + R_out, and the reported gap excludes the radii + self.assertEqual(vertical_force(2 * r_w + 1.01 * P.r_out[0]), 0.0) + h = 2 * r_w + 0.5 * P.r_out[0] + vertical_force(h) + dmin = cp.min_distance( + wp_nodes(nodes_at(h)) + ) # sampled points straddle the crossing + self.assertGreaterEqual(dmin, 0.5 * P.r_out[0]) + self.assertLess(dmin, 0.5 * P.r_out[0] + 0.01) + + +class SegmentRuleTests(unittest.TestCase): + def test_nodal_rule_matches_febio_line_element(self): + nodes = np.array([[0.0, 0, 0], [2.0, 0, 0]]) + pts = segment_points(np.array([[0, 1]]), nodes, body=0, rule="nodal") + self.assertEqual(pts.count, 2) + np.testing.assert_allclose(pts.positions(nodes), nodes) + np.testing.assert_allclose(pts.weight, [1.0, 1.0]) # half the length each + lat = segment_points(np.array([[0, 1]]), nodes, body=0, spacing=0.5) + self.assertEqual(lat.count, 4) + self.assertAlmostEqual(lat.weight.sum(), 2.0) + + +class MetricTests(unittest.TestCase): + def test_contact_area_and_fraction(self): + P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5) + nodes, pts = two_plates(gap=0.3, nx=4, size=1.0) + cp = ContactPotential( + pts, P, np.zeros((2, 2), dtype=int), nodes, len(nodes), device=DEVICE + ) + x = wp_nodes(nodes) + cp.build_pairs(x) + f = wp.zeros(len(nodes), dtype=vec3d, device=DEVICE) + cp.energy_force(x, f) + area0 = cp.contact_area(body=0) + self.assertGreater( + area0, 0.5 + ) # most of a unit plate is within r_out of the other + self.assertLessEqual(area0, 1.0 + 1e-12) + self.assertAlmostEqual(cp.contact_fraction(0, 0.5, 1, nodes), area0, places=12) + self.assertEqual(cp.contact_fraction(0, 0.1, 1, nodes), 0.0) + + +class ReferenceTierTests(unittest.TestCase): + """FEBio semantics that the reference tier switches on.""" + + def setUp(self): + self.P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5) + self.nodes, self.pts = two_plates(gap=0.3) + self.n = len(self.nodes) + + def test_w_tol_drops_oblique_pairs(self): + cp = ContactPotential( + self.pts, + self.P, + np.zeros((2, 2), dtype=int), + self.nodes, + self.n, + w_tol=0.6, + device=DEVICE, + ) + n06 = cp.build_pairs(wp_nodes(self.nodes)) + counts = [] + for w_tol in (0.0, 0.8, 0.99): + cp = ContactPotential( + self.pts, + self.P, + np.zeros((2, 2), dtype=int), + self.nodes, + self.n, + w_tol=w_tol, + device=DEVICE, + ) + counts.append(cp.build_pairs(wp_nodes(self.nodes))) + # w_tol = 0.6 (the Aslan value) removes the in-plane same-plate pairs and keeps + # every plate-to-plate pair; larger values start dropping oblique plate-to-plate pairs + self.assertGreater(counts[0], n06) + self.assertGreater(n06, counts[1]) + self.assertGreater(counts[0], counts[1]) + self.assertGreater(counts[1], counts[2]) + self.assertGreater(counts[2], 0) + + def test_current_weights_track_the_deformed_area(self): + cp_ref = ContactPotential( + self.pts, + self.P, + np.zeros((2, 2), dtype=int), + self.nodes, + self.n, + device=DEVICE, + ) + cp_cur = ContactPotential( + self.pts, + self.P, + np.zeros((2, 2), dtype=int), + self.nodes, + self.n, + weight_mode="current", + device=DEVICE, + ) + # undeformed: identical + f_ref, f_cur = wp.zeros(self.n, dtype=vec3d, device=DEVICE), wp.zeros( + self.n, dtype=vec3d, device=DEVICE + ) + x = wp_nodes(self.nodes) + cp_ref.build_pairs(x) + cp_ref.energy_force(x, f_ref) + cp_cur.build_pairs(x) + cp_cur.energy_force(x, f_cur) + self.assertLess(np.linalg.norm(f_ref.numpy() - f_cur.numpy()), 1e-12) + # stretch both plates in-plane by 10%: current weights scale by 1.21 per side + stretched = self.nodes.copy() + stretched[:, :2] *= 1.1 + x2 = wp_nodes(stretched) + f_ref.zero_() + f_cur.zero_() + cp_ref.build_pairs(x2) + cp_ref.energy_force(x2, f_ref) + cp_cur.build_pairs(x2) + cp_cur.energy_force(x2, f_cur) + ratio = np.linalg.norm(f_cur.numpy()) / np.linalg.norm(f_ref.numpy()) + self.assertAlmostEqual(ratio, 1.21 * 1.21, places=6) + + def test_scale_two_doubles_the_pair_force(self): + P2 = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5, scale=2.0) + f1, f2 = wp.zeros(self.n, dtype=vec3d, device=DEVICE), wp.zeros( + self.n, dtype=vec3d, device=DEVICE + ) + x = wp_nodes(self.nodes) + for P, f in ((self.P, f1), (P2, f2)): + cp = ContactPotential( + self.pts, + P, + np.zeros((2, 2), dtype=int), + self.nodes, + self.n, + device=DEVICE, + ) + cp.build_pairs(x) + cp.energy_force(x, f) + self.assertAlmostEqual( + np.linalg.norm(f2.numpy()) / np.linalg.norm(f1.numpy()), 2.0, places=12 + ) + + +class FebioBlockTests(unittest.TestCase): + def test_cardiofem_block_round_trips(self): + # the archived CardioFEM contact block (examples/cardiofem_valve/febio_cases.json) + block = { + "kc": 2.0, + "p": 4.0, + "R_in": 0.2, + "R_out": 0.5, + "R0_min": 0.0, + "w_tol": 0.6, + } + P, kw, rule = from_febio_block(block, scale=2.0) # primary == secondary surface + self.assertEqual(P.n_classes, 1) + self.assertAlmostEqual(P.kc[0], 2.0) + self.assertAlmostEqual(P.r_in[0], 0.2) + self.assertAlmostEqual(P.r_out[0], 0.5) + self.assertAlmostEqual(P.scale[0], 2.0) + self.assertEqual( + kw, {"w_tol": 0.6, "exclusion": "element", "weight_mode": "current"} + ) + self.assertEqual(rule, {"quad_n_per_edge": 2, "tri_order": "3"}) + nodes, pts = two_plates(gap=0.3, n_per_edge=rule["quad_n_per_edge"]) + cp = ContactPotential( + pts, P, np.zeros((2, 2), dtype=int), nodes, len(nodes), device=DEVICE, **kw + ) + self.assertGreater(cp.build_pairs(wp_nodes(nodes)), 0) + _, kw2, rule2 = from_febio_block( + {**block, "integration_rule": "higher-order", "exclude_neighbors": 1} + ) + self.assertEqual(kw2["exclusion"], "neighbors") + self.assertEqual(rule2, {"quad_n_per_edge": 4, "tri_order": "7"}) + + +class AssemblyTests(unittest.TestCase): + def test_bsr_assembly_matches_matrix_free_action(self): + import warp.sparse as wps + + P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5) + nodes, pts = two_plates(gap=0.3) + n = len(nodes) + cp = ContactPotential( + pts, P, np.zeros((2, 2), dtype=int), nodes, n, device=DEVICE + ) + x = wp_nodes(nodes) + cp.build_pairs(x) + f = wp.zeros(n, dtype=vec3d, device=DEVICE) + cp.energy_force(x, f) + A = cp.hessian_bsr(project=False) + v = np.random.default_rng(3).standard_normal(nodes.shape) + y = wps.bsr_mv(A, wp_nodes(v)) + ref = wp.zeros(n, dtype=vec3d, device=DEVICE) + cp.hessian_matvec(wp_nodes(v), ref, project=False) + self.assertLess( + np.linalg.norm(y.numpy() - ref.numpy()) / np.linalg.norm(ref.numpy()), 1e-12 + ) + # reuse of the destination matrix + A2 = cp.hessian_bsr(project=True, dest=A) + y2 = wps.bsr_mv(A2, wp_nodes(v)) + ref.zero_() + cp.hessian_matvec(wp_nodes(v), ref, project=True) + self.assertLess( + np.linalg.norm(y2.numpy() - ref.numpy()) / np.linalg.norm(ref.numpy()), + 1e-12, + ) + + @unittest.skipUnless( + wp.get_cuda_device_count() > 0, "CUDA graph capture needs a GPU" + ) + def test_newton_body_is_graph_capturable(self): + device = "cuda:0" + P = PotentialParams(kc=1.0, p=4.0, r_in=0.2, r_out=0.5) + nodes, pts = two_plates(gap=0.3) + n = len(nodes) + cp = ContactPotential( + pts, P, np.zeros((2, 2), dtype=int), nodes, n, device=device + ) + x = wp.array(nodes, dtype=vec3d, device=device) + f = wp.zeros(n, dtype=vec3d, device=device) + cp.build_pairs(x) # warm up and size the buffers + with wp.ScopedCapture(device=device) as capture: + cp.build_pairs(x, sync=False) + cp.energy_force(x, f) + cp.hessian_blocks(project=False) + wp.capture_launch(capture.graph) + wp.synchronize_device(device) + self.assertFalse(cp.search.check_overflow()) + self.assertGreater(np.linalg.norm(f.numpy()), 0.0) + + +class FebioDiagnosticTests(unittest.TestCase): + """Same check as FEBio's contact diagnostic (FEBioTest/FEContactDiagnostic.cpp). + + FEBio builds two unit hex elements whose facing surfaces overlap by eps = 0.5, + assembles the contact stiffness of a sliding interface, differentiates the + contact residual by finite differences node by node, and passes when the + largest entry-wise difference is below 1e-3 percent. Here the geometry, + the two surfaces and the pass criterion are FEBio's; the law is the + contact potential on 2x2 Gauss points, and the differences are central. + """ + + def test_two_hex_contact_stiffness_matches_residual_derivative(self): + eps = 0.5 + nodes = np.array( + [ + [0, 0, 0], + [1, 0, 0], + [1, 1, 0], + [0, 1, 0], + [0, 0, 1], + [1, 0, 1], + [1, 1, 1], + [0, 1, 1], + [0, 0, 1 - eps], + [1, 0, 1 - eps], + [1, 1, 1 - eps], + [0, 1, 1 - eps], + [0, 0, 2 - eps], + [1, 0, 2 - eps], + [1, 1, 2 - eps], + [0, 1, 2 - eps], + ], + dtype=np.float64, + ) + primary = np.array([[4, 5, 6, 7]]) # top face of element 1 (FEBio ms) + secondary = np.array([[11, 10, 9, 8]]) # bottom face of element 2 (FEBio ss) + pts = ContactPoints.concatenate( + [ + quad_facet_points(primary, nodes, body=0, n_per_edge=2), + quad_facet_points(secondary, nodes, body=1, n_per_edge=2), + ] + ) + P = PotentialParams(kc=1.0, p=4.0, r_in=0.4, r_out=1.0) + n = len(nodes) + cp = ContactPotential( + pts, P, np.zeros((2, 2), dtype=int), nodes, n, device=DEVICE + ) + + def residual(x_np): + f = wp.zeros(n, dtype=vec3d, device=DEVICE) + cp.energy_force(wp_nodes(x_np), f) + return -f.numpy().ravel() # contact residual = dE/dx + + cp.build_pairs(wp_nodes(nodes)) + self.assertGreater(cp.search.n_pairs, 0) + K0 = cp.hessian_dense(project=False) + K1 = np.zeros_like(K0) + dx = 1e-6 + for j in range(3 * n): + xp = nodes.copy().ravel() + xp[j] += dx + xm = nodes.copy().ravel() + xm[j] -= dx + K1[:, j] = (residual(xp.reshape(-1, 3)) - residual(xm.reshape(-1, 3))) / ( + 2 * dx + ) + denom = np.abs(K0) + denom[denom < 1e-15] = 1.0 + kmax_percent = 100.0 * np.max(np.abs(K1 - K0) / denom) + self.assertLess(kmax_percent, 1e-3) + + +class DifferentiabilityTests(unittest.TestCase): + """What differentiates, in both weight modes, and the parameter adjoint.""" + + def setUp(self): + self.P = PotentialParams(kc=[1.0, 2.0], p=4.0, r_in=0.2, r_out=0.5) + self.nodes, self.pts = two_plates(gap=0.3) + self.n = len(self.nodes) + self.pair_class = np.array([[0, 1], [1, 0]]) + + def term(self, weight_mode): + t = ContactPotentialTerm( + self.pts, + self.P, + self.pair_class, + self.nodes, + self.n, + weight_mode=weight_mode, + device=DEVICE, + ) + t.update_pairs(wp_nodes(self.nodes)) + return t + + def test_tape_gradient_equals_residual_in_both_weight_modes(self): + for mode in ("reference", "current"): + t = self.term(mode) + R = wp.zeros(self.n, dtype=vec3d, device=DEVICE) + t.residual(wp_nodes(self.nodes), None, R) + _, g = t.energy_and_gradient(wp_nodes(self.nodes, requires_grad=True)) + self.assertLess( + np.linalg.norm(g.numpy() - R.numpy()) / np.linalg.norm(R.numpy()), + 1e-12, + mode, + ) + + def test_parameter_adjoint_matches_finite_differences(self): + t = self.term("reference") + rng = np.random.default_rng(7) + lam = rng.standard_normal(self.nodes.shape) + g = t.residual_parameter_vjp(wp_nodes(self.nodes), wp_nodes(lam))["kc"] + self.assertEqual(g.shape, (2,)) + # finite differences over kc of class 1 (the plate-to-plate class) + h = 1e-6 + + def lam_R(kc1): + P = PotentialParams(kc=[1.0, kc1], p=4.0, r_in=0.2, r_out=0.5) + tt = ContactPotentialTerm( + self.pts, P, self.pair_class, self.nodes, self.n, device=DEVICE + ) + tt.update_pairs(wp_nodes(self.nodes)) + R = wp.zeros(self.n, dtype=vec3d, device=DEVICE) + tt.residual(wp_nodes(self.nodes), None, R) + return np.sum(lam * R.numpy()) + + fd = (lam_R(2.0 + h) - lam_R(2.0 - h)) / (2 * h) + self.assertAlmostEqual(g[1] / fd, 1.0, places=8) + + def test_energy_is_linear_in_kc_through_the_tape(self): + t = self.term("reference") + x = wp_nodes(self.nodes, requires_grad=True) + E, _ = t.energy_and_gradient(x) + pot = t.potential + tape = wp.Tape() + f = wp.zeros(self.n, dtype=vec3d, device=DEVICE, requires_grad=True) + with tape: + E2 = pot.energy_force(x, f) + tape.backward(E2) + g_kc = pot.kc_gradient_from_tables() + # E is linear in kc per class: sum_c kc_c dE/dkc_c = E (kc = [1, 2]) + self.assertAlmostEqual( + (g_kc[0] * 1.0 + g_kc[1] * 2.0) / float(E2.numpy()[0]), 1.0, places=10 + ) + tape.zero() + + +if __name__ == "__main__": + unittest.main()