Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
818b85d
[docs] Add the LinearSmallStrainFEMForceField notebook
th-skam Oct 12, 2026
a0cdd9e
[verification] Add the LinearSmallStrainFEMForceField/Quadratic1D case
th-skam Oct 12, 2026
a80e971
[verification] Add the LinearSmallStrainFEMForceField/Quadratic2D_Qua…
th-skam Oct 12, 2026
061d27d
[verification] Add the LinearSmallStrainFEMForceField/Quadratic2D_Tri…
th-skam Oct 12, 2026
e0f0e67
[verification] Add the LinearSmallStrainFEMForceField/Quadratic3D_Hex…
th-skam Oct 12, 2026
3e6ffb0
[verification] Add the LinearSmallStrainFEMForceField/Quadratic3D_Tet…
th-skam Oct 12, 2026
7d23399
[verification] Add the LinearSmallStrainFEMForceField/Quartic2D_Quad …
th-skam Oct 12, 2026
4ea2d77
[verification] Add the LinearSmallStrainFEMForceField/Quartic2D_Tri case
th-skam Oct 12, 2026
fb9e2ea
[verification] Add the LinearSmallStrainFEMForceField/Quartic3D_Hexa …
th-skam Oct 12, 2026
f450011
[verification] Add the LinearSmallStrainFEMForceField/Quartic3D_Tetra…
th-skam Oct 12, 2026
1580ae9
[verification] Add the LinearSmallStrainFEMForceField/Trigonometric1D…
th-skam Oct 12, 2026
6316c82
[verification] Add the LinearSmallStrainFEMForceField/Trigonometric2D…
th-skam Oct 12, 2026
dc39ed2
[verification] Add the LinearSmallStrainFEMForceField/Trigonometric2D…
th-skam Oct 12, 2026
260fc11
[verification] Add the LinearSmallStrainFEMForceField/Trigonometric2D…
th-skam Oct 12, 2026
7bb3148
[verification] Add the LinearSmallStrainFEMForceField/Trigonometric2D…
th-skam Oct 12, 2026
b05781d
[verification] Add the LinearSmallStrainFEMForceField/Trigonometric2D…
th-skam Oct 12, 2026
24725ee
[verification] Add the LinearSmallStrainFEMForceField/Trigonometric3D…
th-skam Oct 12, 2026
6fc75da
[verification] Add the LinearSmallStrainFEMForceField/Trigonometric3D…
th-skam Oct 12, 2026
42f37f9
[verification] Add the LinearSmallStrainFEMForceField/Trigonometric3D…
th-skam Oct 12, 2026
11a306c
[verification] Add the LinearSmallStrainFEMForceField/Trigonometric3D…
th-skam Oct 12, 2026
738f9ed
[docs] Update README
th-skam Oct 12, 2026
3bb3970
[validation] Adjust to new integration schemes
th-skam Nov 6, 2026
3cc29df
[all] Ignore validation results
th-skam Oct 12, 2026
36efe75
[fenics] Add the dolfinx grid meshes
th-skam Oct 12, 2026
ba51165
[fenics] Export the grid meshes
th-skam Oct 12, 2026
76e9c99
[fenics] Add the fenics package
th-skam Oct 12, 2026
9f52632
[sofa] Share the controllers with the validation suite
th-skam Oct 12, 2026
5aa79d0
[validation] Add the validation package
th-skam Oct 12, 2026
17252b9
[validation] Add the study package
th-skam Oct 12, 2026
6cb82b5
[validation] Add the comparison metrics
th-skam Oct 12, 2026
2f3ca74
[validation] Add the validation study
th-skam Oct 12, 2026
d6c9229
[validation] Add the validation runner
th-skam Oct 12, 2026
0276bda
[docs] Introduce the validation suite in the README
th-skam Oct 12, 2026
6758a2a
[validation] Add the LinearSmallStrainFEMForceField/1D/DistributedAxi…
th-skam Oct 12, 2026
4256daf
[validation] Add the LinearSmallStrainFEMForceField/2D/AxialCompressi…
th-skam Oct 12, 2026
f3afd09
[validation] Add the LinearSmallStrainFEMForceField/2D/DistributedTra…
th-skam Oct 12, 2026
fb5c3c2
[validation] Add the LinearSmallStrainFEMForceField/2D/ThreePointBend…
th-skam Oct 12, 2026
e1ffda5
[validation] Add the LinearSmallStrainFEMForceField/3D/AxialCompressi…
th-skam Oct 12, 2026
1b49ed6
[validation] Add the LinearSmallStrainFEMForceField/3D/DistributedTra…
th-skam Oct 12, 2026
79e6559
[validation] Add the LinearSmallStrainFEMForceField/3D/ThreePointBend…
th-skam Oct 12, 2026
1f10dd5
[docs] Add LinearSmallStrainFEMForceField doc
th-skam Oct 12, 2026
168b73b
[validation] Store solutions as well
th-skam Oct 12, 2026
e2b3a57
[validation] Make 3-point bending symmetric
th-skam Oct 12, 2026
922b100
[validation] Update linear doc
th-skam Oct 12, 2026
24afe0b
[docs] Add a generic validation doc
th-skam Oct 12, 2026
a6555c2
[validation] Improve plotting functionality
th-skam Oct 12, 2026
9fbc951
[common] Make force field and solver addition functions static and sh…
th-skam Oct 12, 2026
96bd52a
[validation] Axial compression on a circular beam
th-skam Oct 12, 2026
c1d5dcd
[validation] Add Circular beam transverse traction case
th-skam Oct 12, 2026
3e01121
[validation] Circular beam under torsion
th-skam Oct 12, 2026
36eb7a9
[validation] Increase loads to make solutions visible
th-skam Oct 12, 2026
1d193ad
[validation] Remove all reference solutions from FEniCS
th-skam Oct 12, 2026
07ad93e
[validation] Make plots in deformed shape
th-skam Oct 12, 2026
42ff309
[docs] Update IntroductionValidation.ipynb
th-skam Oct 12, 2026
bc43a6e
[docs] Update LineaerSmallStrainFEMForceField.ipynb
th-skam Oct 12, 2026
c227685
[validation] Re-generate references
th-skam Oct 12, 2026
7e0e10e
[verification] Adjust to integration schemes
th-skam Nov 6, 2026
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@

# a run's own output
verification/results/

# a validation run's own output
validation/**/results/
22 changes: 18 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,35 @@
# Verification-Validation
Initially funded by TIRREX, this repository proposes a framework for verification and validation. It relies on both manufactured solutions and comparison with alternative simulation technologies. This work therefore proves the reliability and compliance of the SOFA models & algorithms.

## Verification
## Verification and validation

**Verification** uses the method of manufactured solutions: an exact displacement is chosen, the
loads that produce it are derived, and SOFA solves the problem on a sequence of refined meshes.
The error must shrink at the rate the discretisation predicts. Covered force fields:
- `LinearSmallStrainFEMForceField`
- `LinearSmallStrainFEMForceField` [`verification/docs/LinearSmallStrainFEMForceField.ipynb`](verification/docs/LinearSmallStrainFEMForceField.ipynb)

To get started, read [`verification/docs/IntroductionMMS.ipynb`](verification/docs/IntroductionMMS.ipynb): it presents the method and builds one verification study step by step, from the manufactured solution to the input file the suite runs.

**Validation** compares SOFA against reference results computed with FEniCS, and against an
analytic solution where one exists. Covered force fields:
- `LinearSmallStrainFEMForceField`

## Layout

```
common/ shared code: geometry and SOFA helpers
common/ code shared by both suites: geometry, SOFA and FEniCS helpers
verification/ the verification suite
cases/<Component>/**.json one test case per file
validation/ the validation suite
cases/<Component>/<dim>D/<Case>/ sofa_scene.py, fenics_scene.py, case.json,
reference_solution.json, analytic_solution.py (optional)
```

## Requirements

- SOFA with SofaPython3
- numpy, sympy, matplotlib
- FEniCSx (dolfinx, petsc4py, mpi4py), only to regenerate validation references with `--fenics`

## Running

Expand All @@ -31,7 +39,13 @@ python verification/run.py --all # every test case, then one summ
python verification/run.py --clean # delete previous results
```

Results are written to `verification/results/`.
```bash
python validation/run.py <path-to-case-folder> # one case
python validation/run.py --all # every case
python validation/run.py --all --fenics # regenerate the FEniCS references first
```

Results are written to `verification/results/` and `validation/results/`.

To inspect one mesh of a case in the SOFA GUI, the runner also acts as a SOFA scene file:

Expand Down
1 change: 1 addition & 0 deletions common/fenics/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .prefabs import GridMesh, BarMesh, BeamMesh
1 change: 1 addition & 0 deletions common/fenics/prefabs/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .grid import GridMesh, BarMesh, BeamMesh
133 changes: 133 additions & 0 deletions common/fenics/prefabs/grid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
"""FEniCS (dolfinx) meshes built from tool-agnostic Geometry."""

import basix.ufl
import numpy as np
import ufl
from dolfinx import mesh as dmesh
from mpi4py import MPI


class GridMesh:
"""A dolfinx mesh built from a Grid geometry, matching its extents and cell resolution.

dolfinx renumbers a mesh's nodes on construction, so a direct comparison with a SOFA solution
is not readily available. `inverse` undoes this remap allowing the comparison to happen.
The inversion only holds for a degree-1 Lagrange space, where each DOF is one mesh node.
"""

def __init__(self, geometry, resolution):
self.geometry = geometry
self.resolution = resolution
self.inverse = None

def build(self, comm=MPI.COMM_WORLD):
raise NotImplementedError


class BarMesh(GridMesh):
"""A 1D interval mesh matching a Bar1D geometry."""

def build(self, comm=MPI.COMM_WORLD):
cells = self.resolution[0] - 1
mesh = dmesh.create_interval(comm, cells, [0.0, self.geometry.length])
self.inverse = np.argsort(mesh.geometry.input_global_indices)
return mesh


class BeamMesh(GridMesh):
"""A dolfinx mesh matching a Beam2D or Beam3D geometry, as SOFA would mesh it: quadrilaterals
or triangles in 2D, hexahedra or tetrahedra in 3D.

The nodes are ordered i + nx*(j + ny*k) like SOFA's RegularGridTopology (2D: i + nx*j). In 2D,
each quad splits in two triangles along a diagonal; with `swapping`, this diagonal alternates
per quad in a checkerboard pattern, else every quad splits the same way. In 3D, each
hexahedron splits into 6 tets, following SOFA's Hexa2TetraTopologicalMapping: with `swapping`,
a cell's corners are mirrored along X/Y/Z depending on its grid position before the tet
pattern is applied; without it, every hexahedron splits the same way.
"""

# SOFA's Hexahedron corner convention (n0..n7) and edge/tet patterns, from
# sofa::geometry::Hexahedron and Hexa2TetraTopologicalMapping.cpp.
SOFA_CORNERS = ((0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1))
X_EDGES = ((0, 1), (4, 5), (3, 2), (7, 6))
Y_EDGES = ((4, 7), (5, 6), (1, 2), (0, 3))
Z_EDGES = ((4, 0), (5, 1), (6, 2), (7, 3))
NON_SWAPPED = ((0, 5, 1, 6), (0, 1, 3, 6), (1, 3, 6, 2), (6, 3, 0, 7), (6, 7, 0, 5), (7, 5, 4, 0))
SWAPPED = ((0, 5, 6, 1), (0, 1, 6, 3), (1, 3, 2, 6), (6, 3, 7, 0), (6, 7, 5, 0), (7, 5, 0, 4))
# Hex cells need corners in basix's (0,0,0)..(1,1,1) lexicographic order, not SOFA's.
BASIX_ORDER = (0, 1, 3, 2, 4, 5, 7, 6)

def __init__(self, geometry, resolution, element='quad', swapping=True):
super().__init__(geometry, resolution)
self.element = element
self.swapping = swapping

def build(self, comm=MPI.COMM_WORLD):
if self.geometry.dim == 2:
nx, ny = self.resolution[0], self.resolution[1]
dx, dy = self.geometry.length / (nx - 1), self.geometry.width / (ny - 1)

def node(i, j):
return i + nx * j

points = np.array([[i * dx, j * dy] for j in range(ny) for i in range(nx)])

cells = []
for j in range(ny - 1):
for i in range(nx - 1):
p0, p1, p2, p3 = node(i, j), node(i + 1, j), node(i + 1, j + 1), node(i, j + 1)
if self.element == 'quad':
cells.append([p0, p1, p3, p2])
else:
if self.swapping and (i ^ j) & 1:
cells += [[p0, p1, p3], [p2, p3, p1]]
else:
cells += [[p1, p2, p0], [p3, p0, p2]]

cell_type = "quadrilateral" if self.element == 'quad' else "triangle"
cell_element = basix.ufl.element("Lagrange", cell_type, 1, shape=(2,))
mesh = dmesh.create_mesh(comm, np.array(cells), points, ufl.Mesh(cell_element))
self.inverse = np.argsort(mesh.geometry.input_global_indices)
return mesh

nx, ny, nz = self.resolution[0], self.resolution[1], self.resolution[2]
dx, dy, dz = (self.geometry.length / (nx - 1), self.geometry.width / (ny - 1),
self.geometry.height / (nz - 1))

def node(i, j, k):
return i + nx * (j + ny * k)

points = np.array([[i * dx, j * dy, k * dz]
for k in range(nz) for j in range(ny) for i in range(nx)])

cells = []
for k in range(nz - 1):
for j in range(ny - 1):
for i in range(nx - 1):
corners = [node(i + di, j + dj, k + dk) for di, dj, dk in self.SOFA_CORNERS]
if self.element == 'hexa':
cells.append([corners[c] for c in self.BASIX_ORDER])
continue

swapped = False
if self.swapping:
if i % 2 == 0:
for v0, v1 in self.X_EDGES:
corners[v0], corners[v1] = corners[v1], corners[v0]
swapped = not swapped
if j % 2 == 1:
for v0, v1 in self.Y_EDGES:
corners[v0], corners[v1] = corners[v1], corners[v0]
swapped = not swapped
if k % 2 == 1:
for v0, v1 in self.Z_EDGES:
corners[v0], corners[v1] = corners[v1], corners[v0]
swapped = not swapped
pattern = self.SWAPPED if swapped else self.NON_SWAPPED
cells += [[corners[c] for c in tet] for tet in pattern]

cell_type = "hexahedron" if self.element == 'hexa' else "tetrahedron"
cell_element = basix.ufl.element("Lagrange", cell_type, 1, shape=(3,))
mesh = dmesh.create_mesh(comm, np.array(cells), points, ufl.Mesh(cell_element))
self.inverse = np.argsort(mesh.geometry.input_global_indices)
return mesh
2 changes: 1 addition & 1 deletion common/sofa/controllers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Post-init SOFA controllers."""
"""Post-init SOFA controllers shared by both suites."""

import Sofa.Core

Expand Down
6 changes: 4 additions & 2 deletions common/sofa/prefabs/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@ def __init__(self, *args, configs=None, geometry=None, **kwargs):
def mechanical_node(self):
raise NotImplementedError

def add_force_field(self, node, config, material, template):
@staticmethod
def add_force_field(node, config, material, template):
"""The *FEMForceField component under test, its Data merged from `config` and `material`"""
node.addObject(config['type'], name='fem', template=template, topology='@topology',
**params(material), **params(config))

def add_solvers(self, node, config):
@staticmethod
def add_solvers(node, config):
"""Linear solver (+ preconditioner) + integration scheme."""

# Linear Solver & Preconditioner (optional)
Expand Down
Empty file added validation/__init__.py
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""Analytic solution for DistributedAxialLoad: a bar under a uniform distributed axial load.

u(x) = q/E * (length*x - x^2/2), for a bar clamped at x=0, free at x=length, under a uniform
axial body force q per unit length.
"""


def displacement(x, case):
length = case['geometry']['length']
young_modulus = case['material']['youngModulus']
load = case['load']['magnitude']
return load / young_modulus * (length * x - x ** 2 / 2)
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"geometry": { "type": "Bar1D", "length": 1.0 },
"element": "edge",
"material": { "type": "LinearElastic", "youngModulus": 1e6, "poissonRatio": 0.3 },
"forceField": { "type": "LinearSmallStrainFEMForceField" },
"solvers": {
"integration": { "type": "StaticEquilibriumIntegrationScheme", "maxNbIterationsNewton": 1,
"residualThreshold": 0 },
"linearSolver": { "type": "SparseLDLSolver", "template": "CompressedRowSparseMatrixd" }
},
"mesh": { "resolution": [10, 1, 1] },
"load": { "type": "distributedAxial", "magnitude": 400000.0 },
"tolerance": { "rms": 1e-10 },
"toleranceAnalytic": { "rms": 1e-10 }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import json
import os
import sys

CASE_DIR = os.path.dirname(os.path.abspath(__file__))
REPO_ROOT = os.path.abspath(os.path.join(CASE_DIR, *[os.pardir] * 5))
for path in (CASE_DIR, REPO_ROOT):
if path not in sys.path:
sys.path.insert(0, path)

import numpy as np
import ufl
from dolfinx import default_scalar_type, fem
from dolfinx.fem.petsc import LinearProblem

from common.fenics import BarMesh
from common.geometry import Bar1D

PETSC_OPTIONS = {'ksp_type': 'preonly', 'pc_type': 'lu'}


def build(case):
geometry = Bar1D(length=case['geometry']['length'])
grid = BarMesh(geometry, case['mesh']['resolution'])
domain = grid.build()
V = fem.functionspace(domain, ("Lagrange", 1))

# 1D axial stiffness: lambda + 2*mu collapses to E exactly (poissonRatio is inert in 1D).
stiffness = fem.Constant(domain, default_scalar_type(case['material']['youngModulus']))
load = fem.Constant(domain, default_scalar_type(case['load']['magnitude']))

u, v = ufl.TrialFunction(V), ufl.TestFunction(V)
a = stiffness * ufl.inner(ufl.grad(u), ufl.grad(v)) * ufl.dx
L = load * v * ufl.dx

clamped = fem.locate_dofs_geometrical(V, lambda x: np.isclose(x[0], 0.0))
bc = fem.dirichletbc(default_scalar_type(0.0), clamped, V)

return grid, V, a, L, bc


def solve(case):
grid, V, a, L, bc = build(case)

problem = LinearProblem(a, L, bcs=[bc], petsc_options=PETSC_OPTIONS)
solution = problem.solve()

x = V.tabulate_dof_coordinates()[:, 0]
return x[grid.inverse], solution.x.array[grid.inverse]


def main(case):
x, u = solve(case)

reference_file = os.path.join(CASE_DIR, 'reference_solution.json')
if os.path.exists(reference_file):
with open(reference_file) as f:
reference = json.load(f)
else:
reference = {}
reference.setdefault(case['element'], {})['fenics'] = {'x': x.tolist(), 'u': u.tolist()}
with open(reference_file, 'w') as f:
json.dump(reference, f)

print(f"{case['element']}: solved {len(x)} nodes")


if __name__ == '__main__':
with open(os.path.join(CASE_DIR, 'case.json')) as f:
whole_case = json.load(f)

for sub_case in ([whole_case] if 'geometry' in whole_case else whole_case.values()):
main(sub_case)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"edge": {"fenics": {"x": [0.0, 0.1111111111111111, 0.2222222222222222, 0.3333333333333333, 0.4444444444444444, 0.5555555555555556, 0.6666666666666666, 0.7777777777777777, 0.8888888888888888, 1.0], "u": [0.0, 0.0419753086419752, 0.07901234567901212, 0.11111111111111079, 0.13827160493827118, 0.16049382716049332, 0.1777777777777772, 0.19012345679012285, 0.19753086419753024, 0.1999999999999994]}}}
Loading