Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
213 changes: 213 additions & 0 deletions docs/CONTACT.md

Large diffs are not rendered by default.

99 changes: 99 additions & 0 deletions examples/contact/point_spacing.py
Original file line number Diff line number Diff line change
@@ -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()
34 changes: 33 additions & 1 deletion src/warp_febio/contact/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
195 changes: 193 additions & 2 deletions src/warp_febio/contact/enforcement.py
Original file line number Diff line number Diff line change
@@ -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,
}
Loading
Loading