From 45f11201a78cdb1f7d2f433ef859ae5928f5d589 Mon Sep 17 00:00:00 2001 From: Audun Arnesen Nyhus Date: Tue, 10 Nov 2026 23:22:50 +0100 Subject: [PATCH 1/3] Drive one-way solid submodels and recover Q4 stresses at their physical stations --- .github/workflows/ci.yml | 16 + docs/SOLID_SUBMODEL.md | 113 ++++ src/anysolver/results.py | 114 +++- src/anysolver/solid_submodel.py | 930 ++++++++++++++++++++++++++++ tests/test_nodal_stress_recovery.py | 8 +- tests/test_q4_nodal_stress_order.py | 233 +++++++ tests/test_solid_submodel.py | 696 +++++++++++++++++++++ 7 files changed, 2101 insertions(+), 9 deletions(-) create mode 100644 docs/SOLID_SUBMODEL.md create mode 100644 src/anysolver/solid_submodel.py create mode 100644 tests/test_q4_nodal_stress_order.py create mode 100644 tests/test_solid_submodel.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 638d1f02d..73b6a412b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -119,6 +119,22 @@ jobs: .ecosystem/ANYmesh .ecosystem/ANYfileIO - run: python -m pip install ./packages/results - run: python -m pip install -e ".[dev,numba]" + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + if: matrix.shard-index == 0 && matrix.subshard-index == 0 + with: + repository: audunarn/ANYsolid + ref: 06f3276d9207376316502aca651c3455db984104 + path: .ecosystem/ANYsolid + persist-credentials: false + - name: One-way shell-driven solid and stress recovery + if: matrix.shard-index == 0 && matrix.subshard-index == 0 + env: + OMP_NUM_THREADS: '1' + OPENBLAS_NUM_THREADS: '1' + run: | + python -m pip install ".ecosystem/ANYsolid[skfem]" + python -c "import anysolid.backend, skfem" + python -m pytest -q tests/test_solid_submodel.py tests/test_q4_nodal_stress_order.py tests/test_nodal_stress_recovery.py - name: Install Windows process-supervision dependency if: runner.os == 'Windows' run: python -m pip install pywin32 diff --git a/docs/SOLID_SUBMODEL.md b/docs/SOLID_SUBMODEL.md new file mode 100644 index 000000000..bb9ceb0f9 --- /dev/null +++ b/docs/SOLID_SUBMODEL.md @@ -0,0 +1,113 @@ +# One-way shell -> solid submodel (`anysolver.solid_submodel`) + +A converged **linear** shell solution drives the cut boundary of a prepared ANYsolid +`PreparedSolid` (linear tetrahedra, P1 or P2). The solid is solved once; nothing is fed +back to the shell. This is the one-way mechanics only: it does not import a regional +mesher (the host supplies `locate`), and it is not the held two-way workflow. + +```python +from anysolver.solid_submodel import solve_shell_driven_solid + +result = solve_shell_driven_solid( + fe_model, source_u, prepared, + cut_groups=["cut_a", "cut_b"], # boundary (or node) groups, every coefficient driven + locate=locate, # world point (3,) -> iterable of (element_id, natural) + skin_tractions={"skin": (0.0, 0.0, -1.0e6)}, # external group -> global traction vector + cancel=None, # None | callable() -> bool | object with is_set() +) +``` + +## Source field + +* Admitted shells are the exact classes of `submodel_transfer` (qualified Q4, + `NativeParityE4PLS3V2DShellElement`); any other shell in the model refuses the source. + Q4 facets must be planar and strictly convex, V2D triangles non-degenerate with a + facet-normal reference normal. +* `source_u` must be finite, have one entry per model DOF, and satisfy every support, + constraint equation and element coupling row of the model (`SOURCE_CONSTRAINT_INCONSISTENT`). +* `locate(x)` receives a world coordinate `ndarray (3,)` and returns `(element_id, natural)` + pairs on the shell **reference midsurface**: Q4 `(xi, eta)` in `[-1, 1]^2`, V2D `(r, s)` with + `N = (1-r-s, r, s)`. Geometry ownership (projection, tolerance, which side) stays with the + host. Several hits (a shared edge/corner) are all evaluated and must agree to + `1e-8` of the source field scale, else `LOCATE_HITS_DISAGREE`. +* Physical displacement at the actual target `x` (all three components, not a reference-surface + value): with `p = sum_i N_i X_i`, `u_ref = sum_i N_i u_i`, `theta_bar = sum_i N_i theta_i`, + `u(x) = u_ref + theta_bar x (x - p)`. The whole displacement is transported from `p` to `x` + once, so the face/thickness offset of the target is counted exactly once and a varying + rotation field (including drilling `theta_z`) does not displace the midsurface (`x = p`). +* V2D transverse term. The normal component of `u_ref` is replaced by the element's own MIN3 + dead-pressure interpolation `w` (`compute_native_pressure_density`, which owns the node + permutation and the physical-director chart): `u_ref += (w_MIN3 - n . u_ref) n`, with `n` the + reference normal; then the transport above is applied. Hand-checked at the centroid of a + unit right triangle: `w = x*y` gives `1/9` (interpolated nodal `w` is `0`), `w = x^2` gives + `1/9` (interpolated nodal `w` is `1/3`). The Q4 needs no correction: its bilinear + translation reproduces the twist `w = x*y` exactly on a rectangle. The correction magnitude is + reported (`diagnostics["source"]["v2d_transverse_correction_max"]`). + +## Solid solve + +* **All** DOFs of every cut group are prescribed: vertices and, for P2, edge midsides. A DOF + shared by several groups (edges/corners) is prescribed once; the number of duplicates is + `diagnostics["constraints"]["duplicate_dof_count"]`. Each cut group must carry all three + components at each of its locations. +* The prescribed set must remove every rigid mode of the solid (`prepared.rigid_modes()`); + otherwise `UNDERCONSTRAINED` (e.g. a single driven vertex). +* Single-case constrained statics on the free block with symmetric Jacobi scaling, sparse LU and one + refinement step. Certified only if the scaled backward error is `<= 1e-10`, the 1-norm condition + estimate `<= 1e12` and `kappa * eta <= 1e-6`; otherwise `SOLVE_UNCERTIFIED` / `POOR_CONDITIONING`. + Non-positive free diagonals or a singular factorization give `SOLVE_SINGULAR`; non-finite values + `SOLVE_NONFINITE`. +* `skin_tractions` maps an external boundary group (not a cut group, sharing no facet with one) to a + constant global traction vector, applied with `prepared.traction`. + +## Result + +`SolidSubmodelResult`: + +| field | meaning | +| --- | --- | +| `coefficients` | all solid coefficients (cut values prescribed) | +| `nodal_displacements` | `(N, 3)`, aligned to `prepared.mesh.node_ids` | +| `recovery` | `prepared.recover(coefficients)` (true element quadrature) | +| `interface_force`, `interface_moment` | force and moment, global frame, **about the origin**, that the driven boundary exerts on the solid: `r = K q - f` on the prescribed DOFs, `F = sum r_i e_c`, `M = sum x_i x r_i e_c` | +| `skin_force`, `skin_moment` | same resultants of the applied skin load; `interface + skin = 0` | +| `group_resultants` | per cut group `GroupResultant(force, moment, dof_count, shared_dof_count)` | +| `shared_attribution`, `attribution_rule` | DOF -> groups sharing it; a shared DOF's reaction is split **equally** among its groups (`equal_split_among_groups_sharing_the_dof`), so group resultants add up to the total | +| `prescribed_dofs`, `prescribed_values`, `reactions` | the driven set, its values and its reactions | +| `diagnostics` | `certification` (backward error, condition, `kappa*eta`, thresholds, rigid-mode singular values), `residual` (free-block residual, force/moment balance, attribution closure), `constraints`, `source` (hit spread, correction, offsets, element kinds, constraint rows checked), `prepared`, `skin` | + +The interface resultants are work-conjugate to the coefficient DOFs, so they are exact for rigid +translation and rotation of P1/P2; they are generalized nodal forces, not a traction field. The +force/moment balance and free-block residual are checked against the internal-force magnitude +`|K||q|` and refuse with `EQUILIBRIUM_VIOLATED` above `1e-6`. + +## Failure and cancellation + +All refusals raise `SolidSubmodelError` with a stable `code` (`SOURCE_*`, `LOCATE_*`, +`PREPARED_*`, `CUT_GROUP_INVALID`, `SKIN_INVALID`, `UNDERCONSTRAINED`, `SOLVE_*`, +`POOR_CONDITIONING`, `EQUILIBRIUM_VIOLATED`, `RECOVERY_FAILED`, `CANCEL_INVALID`) and `details`. +`cancel` is polled before every stage and for every driven location; a trip raises +`SolidSubmodelCancelled` (`code == "CANCELLED"`) and returns nothing. No input is mutated. + +## Limits + +* Linear statics only; small strain; one load case; no contact, no nonlinear shell or solid. +* Constant isotropic solid material and tet4/P1-P2 as `PreparedSolid` provides; only constant + skin tractions. +* The shell-to-solid transport is kinematic (displacement and rotation of the reference surface); + it does not model through-thickness warping, transverse-shear distribution or a stress transfer. + St. Venant decay: the cut must lie where the shell field is smooth and away from the region of + interest. +* V2D transverse correction is the MIN3 interpolation of the element, valid for planar triangles; + non-planar Q4 or V2D facets are refused. `locate` must return reference-midsurface points: for + every hit (primary and shared) the target must lie on the element's reference normal line through + `p`. The tangential residual `|(x - p) - n n.(x - p)|` must not exceed + `1e-7 * (largest node-to-node distance of the element) + 64 eps * (largest coordinate magnitude of + the element nodes and target)`, else `LOCATE_TANGENTIAL_MISMATCH` (details: `element_id`, `target`, + `natural`, `reference_point`, `tangential_residual`, `allowed`). The signed normal offset is not + limited (any face/thickness offset is admissible), and the allowance is independent of unrelated + point distances. +* The sign convention of `interface_*` is the force on the solid; the force on the shell is the + negative, and no shell reaction is computed or applied (one-way). +* Hit agreement across a nonconforming V2D/Q4 interface can legitimately exceed the `1e-8` + tolerance and then refuses; this is deliberate. diff --git a/src/anysolver/results.py b/src/anysolver/results.py index 06c208f1d..a021fef4a 100644 --- a/src/anysolver/results.py +++ b/src/anysolver/results.py @@ -523,7 +523,9 @@ def _cached_gauss_to_node_extrapolation( return None P_gauss = _polynomial_basis(gauss_points, num_gauss) P_nodes = _polynomial_basis(node_natural, num_gauss) - coefficients, *_ = np.linalg.lstsq(P_gauss, np.eye(num_gauss), rcond=None) + coefficients, _, rank, _ = np.linalg.lstsq(P_gauss, np.eye(num_gauss), rcond=None) + if rank != P_gauss.shape[1]: + raise ValueError("stress stations do not span the recovery polynomial basis") operator = P_nodes @ coefficients operator.setflags(write=False) return operator @@ -542,6 +544,67 @@ def _gauss_to_node_extrapolation(element: Any) -> Optional[np.ndarray]: ) +def _operator_for_returned_rows( + element: Any, + stresses: Mapping[str, Any], + keys: Any, +) -> np.ndarray: + """Return the node-extrapolation operator for the rows actually returned. + + Formulations that report ``natural_point_coordinates`` (e.g. the qualified + planar Q4, whose default rows follow its stiffness-station order rather + than ``element.gauss_points``) define the physical location of each row. + The operator is then built from those coordinates. Without that field the + rows are taken to follow ``element.gauss_points`` (legacy contract). + Inconsistent row counts or coordinates are refused, never reinterpreted. + """ + + row_counts = {np.asarray(stresses[key], dtype=float).reshape(-1).shape[0] for key in keys} + if len(row_counts) != 1: + raise ValueError( + f"element {getattr(element, 'element_id', '?')} returned stress fields " + f"with inconsistent row counts {sorted(row_counts)}" + ) + rows = row_counts.pop() + declared = stresses.get("natural_point_coordinates") + if declared is None: + operator = _gauss_to_node_extrapolation(element) + if operator is None or operator.shape[1] != rows: + raise ValueError( + f"element {getattr(element, 'element_id', '?')} returned {rows} stress rows " + "that do not match its integration-point layout" + ) + return operator + points = np.asarray(declared, dtype=float) + if points.ndim != 2 or points.shape != (rows, 2) or not np.all(np.isfinite(points)): + raise ValueError( + f"element {getattr(element, 'element_id', '?')} natural_point_coordinates " + f"shape {points.shape} is inconsistent with {rows} stress rows" + ) + if np.unique(np.round(points, 12), axis=0).shape[0] != rows: + raise ValueError( + f"element {getattr(element, 'element_id', '?')} natural_point_coordinates " + "contain duplicate stations" + ) + if _qualified_s3_barycentric_extrapolation(element) is not None: + # The S3 operator also carries quadrature weights tied to its own rule. + native = _gauss_to_node_extrapolation(element) + if not np.array_equal(points, np.asarray(element.gauss_points, dtype=float)): + raise ValueError( + "qualified S3 natural_point_coordinates differ from its recovery stations" + ) + return native + operator = _cached_gauss_to_node_extrapolation( + int(getattr(element, "num_nodes", 0)), + tuple(float(value) for value in points.reshape(-1)), + ) + if operator is None: + raise ValueError( + f"element {getattr(element, 'element_id', '?')} has no nodal recovery operator" + ) + return operator + + def _von_mises_surface(components: Dict[str, float], suffix: str) -> float: sxx = components[f"global_xx_{suffix}"] syy = components[f"global_yy_{suffix}"] @@ -557,6 +620,47 @@ def _von_mises_surface(components: Dict[str, float], suffix: str) -> float: ) +def _global_displacement_vector(model: "FEModel", displacements: Any) -> np.ndarray: + """Validate the model-level (global) displacement vector. + + ``Element._get_element_displacements`` treats any vector whose length equals + the element DOF count as already element-local. A one-element model's + global vector has exactly that length, so model-level callers must gather + explicitly instead of relying on the length heuristic. + """ + + u = np.asarray(displacements, dtype=float) + if u.ndim != 1: + raise ValueError( + f"global displacement vector must be one-dimensional; got shape {u.shape}" + ) + if not np.all(np.isfinite(u)): + raise ValueError("global displacement vector must be finite") + expected = model.mesh.dof_manager.total_dofs + if u.size != expected: + raise ValueError(f"global displacement vector has length {u.size}; the model has {expected} DOFs") + return u + + +def _gather_element_displacements( + model: "FEModel", element: Any, global_u: np.ndarray +) -> np.ndarray: + """Gather global displacements into the element's own DOF (connectivity) order.""" + + mapping = np.asarray(element.get_dof_mapping(model.mesh), dtype=np.intp) + if mapping.size != element.total_dofs: + raise ValueError( + f"element {getattr(element, 'element_id', '?')} maps {mapping.size} " + f"global DOFs but has {element.total_dofs} element DOFs" + ) + if mapping.size and (int(mapping.min()) < 0 or int(mapping.max()) >= global_u.size): + raise IndexError( + f"element {getattr(element, 'element_id', '?')} requires global DOF " + f"outside a displacement vector of length {global_u.size}" + ) + return global_u[mapping] + + def recover_nodal_stresses( model: "FEModel", displacements: np.ndarray, @@ -593,6 +697,7 @@ def recover_nodal_stresses( context="recover_nodal_stresses", element_ids=selected_ids, ) + global_u = _global_displacement_vector(model, displacements) node_sums: Dict[int, Dict[str, float]] = {} node_counts: Dict[int, int] = {} element_nodal: Dict[int, Dict[str, np.ndarray]] = {} @@ -602,15 +707,16 @@ def recover_nodal_stresses( continue if not isinstance(element, ShellElement): continue - operator = _gauss_to_node_extrapolation(element) - if operator is None: + if _gauss_to_node_extrapolation(element) is None: skipped.append(int(element_id)) continue material = model.get_material(element.material_name) - stresses = element.compute_stresses(model.mesh, displacements, material, return_global=True) + element_u = _gather_element_displacements(model, element, global_u) + stresses = element.compute_stresses(model.mesh, element_u, material, return_global=True) if any(key not in stresses for key in keys): skipped.append(int(element_id)) continue + operator = _operator_for_returned_rows(element, stresses, keys) nodal_values = {key: operator @ np.asarray(stresses[key], dtype=float).reshape(-1) for key in keys} element_nodal[int(element_id)] = nodal_values for local_index, node_id in enumerate(element.node_ids): diff --git a/src/anysolver/solid_submodel.py b/src/anysolver/solid_submodel.py new file mode 100644 index 000000000..fb630bc2d --- /dev/null +++ b/src/anysolver/solid_submodel.py @@ -0,0 +1,930 @@ +"""One-way connected linear shell -> solid submodel mechanics. + +A converged linear shell solution drives the cut boundary of a prepared solid +region (ANYsolid ``PreparedSolid``). The solid is solved once, with every +coefficient on the cut groups prescribed from the shell field, and the result is +reported with its interface resultants and certification diagnostics. Nothing is +fed back to the shell (no two-way coupling), and no regional mesher is imported: +the host supplies the correspondence through ``locate``. + +Mechanics (see ``docs/SOLID_SUBMODEL.md`` for the limits): + +* Source admission is the exact-class allow-list of ``submodel_transfer`` (the + qualified Q4 and the S3 V2D triangle), planar elements only. +* At a target world point ``x`` with reference point ``p = sum_i N_i X_i`` the + physical 3-component displacement is ``u(x) = u_ref + theta_bar x (x - p)``, + where ``u_ref = sum_i N_i u_i`` and ``theta_bar = sum_i N_i theta_i`` are the + interpolated translation and rotation. The whole displacement is transported + from ``p`` to ``x`` once; nodal rotations are never transported against + per-node lever arms (that would displace the midsurface under varying rotations). +* For the V2D triangle the component of ``u_ref`` along the reference normal is + replaced by the full interior MIN3 transverse displacement ``w`` taken from the + element's own dead-pressure operator (``compute_native_pressure_density``), then + the result is transported once as above. Native node permutation and the + physical director conventions stay with the element. +* Every DOF of every cut group (vertices and P2 edge midpoints) is prescribed, + shared DOFs once. The constrained linear static problem is solved on the free + block with a symmetric Jacobi scaling, one refinement step, a backward-error and + a condition certificate, and an equilibrium check. + +Failures raise :class:`SolidSubmodelError` (or :class:`SolidSubmodelCancelled`) +with a stable ``code``; nothing is returned for a refused or cancelled solve. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple + +import numpy as np +from scipy import sparse +from scipy.sparse.linalg import LinearOperator, onenormest, splu + +from . import submodel_transfer as _transfer + +__all__ = [ + "SolidSubmodelError", + "SolidSubmodelCancelled", + "ShellDisplacement", + "GroupResultant", + "SolidSubmodelResult", + "ATTRIBUTION_RULE", + "evaluate_shell_displacement", + "solve_shell_driven_solid", +] + +_EPS = float(np.finfo(float).eps) +_TINY = float(np.finfo(float).tiny) +#: Natural-coordinate overshoot tolerated from the host's inverse mapping. +_NATURAL_TOL = 1.0e-8 +#: Planarity / degeneracy tolerances of a source element (relative to its size). +_PLANAR_TOL = 1.0e-8 +_AREA_TOL = 1.0e-9 +#: Tangential target-to-located-point residual: fraction of the element length plus roundoff +#: (``_TANGENTIAL_EPS_FACTOR`` machine epsilons of the coordinate magnitude). +_TANGENTIAL_RTOL = 1.0e-7 +_TANGENTIAL_EPS_FACTOR = 64.0 +#: Alternative hits must agree to this fraction of the source field scale. +_HIT_AGREE_RTOL = 1.0e-8 +#: Source constraint rows must hold to this fraction of their operands. +_SOURCE_CONSTRAINT_RTOL = 1.0e-9 +#: V2D density must reproduce the element's own shape functions on its translations. +_DENSITY_TOL = 1.0e-10 +#: Same backward-error limit as the linear static path / submodel_transfer. +_BACKWARD_ERROR_LIMIT = 1.0e-10 +_CONDITION_LIMIT = 1.0e12 +_ERROR_BOUND_LIMIT = 1.0e-6 +_RIGID_RANK_RATIO = 1.0e-8 +_BALANCE_LIMIT = 1.0e-6 +_SYMMETRY_RTOL = 1.0e-10 +ATTRIBUTION_RULE = "equal_split_among_groups_sharing_the_dof" + + +class SolidSubmodelError(ValueError): + """A typed, fail-closed refusal of the shell->solid submodel.""" + + def __init__(self, code: str, message: str, *, details: Optional[Mapping[str, Any]] = None): + super().__init__(f"{code}: {message}") + self.code = code + self.details = dict(details or {}) + + +class SolidSubmodelCancelled(SolidSubmodelError): + """The caller cancelled the operation; no result exists.""" + + def __init__(self, where: str = ""): + super().__init__("CANCELLED", f"cancelled{' at ' + where if where else ''}", details={"where": where}) + + +def _error(code: str, message: str, **details: Any) -> SolidSubmodelError: + return SolidSubmodelError(code, message, details=details) + + +# ---------------------------------------------------------------------- +# cancellation +# ---------------------------------------------------------------------- +def _cancel_probe(cancel: Any) -> Optional[Callable[[], bool]]: + if cancel is None: + return None + is_set = getattr(cancel, "is_set", None) + if callable(is_set): + return lambda: bool(is_set()) + if callable(cancel): + return lambda: bool(cancel()) + raise _error("CANCEL_INVALID", "cancel must be None, a callable returning a flag, or an object with is_set()") + + +def _check_cancel(probe: Optional[Callable[[], bool]], where: str) -> None: + if probe is not None and probe(): + raise SolidSubmodelCancelled(where) + + +# ---------------------------------------------------------------------- +# shell source +# ---------------------------------------------------------------------- +@dataclass(frozen=True) +class ShellDisplacement: + """Physical displacement of the shell at one target point.""" + + value: np.ndarray # (3,) global frame, from the first hit + hit_spread: float # largest |difference| between agreeing hits + hits: int + transverse_correction: float # V2D MIN3 normal correction (0 for the Q4) + normal_offset: float # (target - reference point) . reference normal of the first hit + director_offset: float # same, along the element's physical director + element_ids: Tuple[int, ...] + + +@dataclass +class _ElementData: + element: Any + kind: str # "q4" or "v2d" + node_ids: Tuple[int, ...] + X: np.ndarray # (n, 3) nodal reference coordinates + U: np.ndarray # (n, 6) nodal translations + rotations + normal: np.ndarray # (3,) unit reference normal + director: np.ndarray # (3,) unit physical director + length: float = 0.0 # largest node-to-node distance (admitted element length) + coordinate_scale: float = 0.0 # largest |nodal coordinate| (roundoff scale) + + +class _Source: + """Validated shell model + displacement vector, evaluated at physical points.""" + + def __init__(self, model: Any, source_u: Any): + mesh = getattr(model, "mesh", None) + if ( + mesh is None + or not isinstance(getattr(mesh, "elements", None), Mapping) + or not isinstance(getattr(mesh, "nodes", None), Mapping) + or getattr(mesh, "dof_manager", None) is None + or not callable(getattr(mesh, "get_node", None)) + ): + raise _error("SOURCE_INVALID", "fe_model does not expose mesh.elements / mesh.nodes / mesh.dof_manager") + try: + total = int(mesh.dof_manager.total_dofs) + except (AttributeError, TypeError, ValueError) as error: + raise _error("SOURCE_INVALID", "fe_model has no usable DOF manager") from error + try: + u = np.asarray(source_u, dtype=float) + except (TypeError, ValueError) as error: + raise _error("SOURCE_INVALID", "source displacement vector is not numeric") from error + if u.shape != (total,): + raise _error("SOURCE_INVALID", f"source displacement has shape {u.shape}, model has {total} DOFs") + if not np.all(np.isfinite(u)): + raise _error("SOURCE_INVALID", "source displacement vector is not finite") + try: + _transfer._require_target_shells(model) + except _transfer.SubmodelTransferError as error: + raise _error("SOURCE_ELEMENT_NOT_ADMITTED", str(error), **error.details) from error + self.model = model + self.mesh = mesh + self.u = u.copy() + self.q4_type, self.v2d_type = _transfer.admitted_transfer_element_types() + self._cache: Dict[int, _ElementData] = {} + coords = np.array([np.asarray(node.coords(), dtype=float) for node in mesh.nodes.values()]).reshape(-1, 3) + self.extent = float(np.linalg.norm(coords.max(axis=0) - coords.min(axis=0))) if coords.size else 0.0 + translations, rotations = [], [] + for node_id in mesh.nodes: + dofs = mesh.dof_manager.get_node_dofs(int(node_id)) + if len(dofs) == 6: + six = u[list(dofs)] + translations.append(np.max(np.abs(six[:3]))) + rotations.append(np.max(np.abs(six[3:]))) + self.scale = max( + max(translations, default=0.0), max(rotations, default=0.0) * self.extent, 0.0 + ) + self._check_constraints() + + # -- constraint consistency ------------------------------------------------ + def _check_constraints(self) -> None: + try: + rows = _transfer._physical_rows(self.model) + except Exception as error: # constraint enumeration is owned by the model + raise _error("SOURCE_CONSTRAINT_CHECK_FAILED", f"cannot enumerate model constraints: {error}") from error + total = self.u.size + worst = 0.0 + for kind, origin, terms, value in rows: + if any(not (0 <= dof < total) for dof in terms): + raise _error("SOURCE_CONSTRAINT_INCONSISTENT", f"{kind} {origin!r} references an unknown DOF") + action = sum(coef * self.u[dof] for dof, coef in terms.items()) + operand = sum(abs(coef * self.u[dof]) for dof, coef in terms.items()) + abs(value) + allowed = _SOURCE_CONSTRAINT_RTOL * (operand + self.scale) + 16.0 * _EPS * operand + violation = abs(action - value) + worst = max(worst, violation / (allowed + _TINY)) + if not np.isfinite(violation) or violation > allowed: + raise _error( + "SOURCE_CONSTRAINT_INCONSISTENT", + f"source displacement violates {kind} {origin!r} by {violation:.3e} (allowed {allowed:.3e})", + kind=kind, origin=origin, violation=float(violation), allowed=float(allowed), + ) + self.constraint_rows = len(rows) + + # -- element admission ----------------------------------------------------- + def element_data(self, element_id: int) -> _ElementData: + cached = self._cache.get(element_id) + if cached is not None: + return cached + element = self.mesh.elements.get(element_id) + if element is None: + raise _error("SOURCE_ELEMENT_MISSING", f"source element {element_id} is not in the model", + element_id=element_id) + if type(element) is self.q4_type: + kind = "q4" + elif type(element) is self.v2d_type: + kind = "v2d" + else: + raise _error("SOURCE_ELEMENT_NOT_ADMITTED", + f"element {element_id} is {type(element).__name__}; admitted shells: " + f"{self.q4_type.__name__}, {self.v2d_type.__name__}", element_id=element_id) + node_ids = tuple(int(n) for n in element.node_ids) + expected = 4 if kind == "q4" else 3 + if len(node_ids) != expected or len(set(node_ids)) != expected: + raise _error("SOURCE_ELEMENT_INVALID", f"element {element_id} has malformed connectivity", + element_id=element_id) + try: + X = np.array([np.asarray(self.mesh.get_node(n).coords(), dtype=float) for n in node_ids]) + except (AttributeError, TypeError, ValueError) as error: + raise _error("SOURCE_ELEMENT_INVALID", f"element {element_id} references a missing node") from error + if X.shape != (expected, 3) or not np.all(np.isfinite(X)): + raise _error("SOURCE_ELEMENT_INVALID", f"element {element_id} has invalid node coordinates", + element_id=element_id) + U = np.empty((expected, 6)) + for row, n in enumerate(node_ids): + dofs = list(self.mesh.dof_manager.get_node_dofs(n)) + if len(dofs) != 6: + raise _error("SOURCE_ELEMENT_INVALID", f"node {n} of element {element_id} has no six DOFs", + element_id=element_id) + U[row] = self.u[dofs] + if kind == "q4": + normal = _check_planar_quad(X, element_id) + director = normal.copy() + else: + normal, director = self._check_triangle(element, element_id, X) + length = float(max(np.linalg.norm(X[i] - X[j]) for i in range(expected) for j in range(i + 1, expected))) + data = _ElementData(element, kind, node_ids, X, U, normal, director, length, + float(np.max(np.abs(X)))) + self._cache[element_id] = data + return data + + def _check_triangle(self, element: Any, element_id: int, X: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + scale = max(float(np.max(np.linalg.norm(X - X.mean(axis=0), axis=1))), _TINY) + cross = np.cross(X[1] - X[0], X[2] - X[0]) + if float(np.linalg.norm(cross)) <= _AREA_TOL * scale * scale: + raise _error("SOURCE_ELEMENT_INVALID", f"V2D element {element_id} is degenerate", element_id=element_id) + try: + normal = np.array(element.reference_normal, dtype=float).reshape(3) + polarity = float(element.director_polarity) + except (AttributeError, TypeError, ValueError) as error: + raise _error("SOURCE_ELEMENT_INVALID", f"V2D element {element_id} has no reference normal / director", + element_id=element_id) from error + if not np.all(np.isfinite(normal)) or abs(float(np.linalg.norm(normal)) - 1.0) > 1.0e-8: + raise _error("SOURCE_ELEMENT_INVALID", f"V2D element {element_id} reference normal is not a unit vector", + element_id=element_id) + if abs(abs(float(normal @ cross)) - float(np.linalg.norm(cross))) > 1.0e-8 * float(np.linalg.norm(cross)): + raise _error("SOURCE_ELEMENT_INVALID", f"V2D element {element_id} is not planar with its reference normal", + element_id=element_id) + if polarity not in (-1.0, 1.0): + raise _error("SOURCE_ELEMENT_INVALID", f"V2D element {element_id} director polarity is not +-1", + element_id=element_id) + return normal, polarity * normal + + # -- evaluation ------------------------------------------------------------ + def _weights(self, data: _ElementData, natural: np.ndarray, element_id: int) -> np.ndarray: + r, s = float(natural[0]), float(natural[1]) + if data.kind == "q4": + inside = abs(r) <= 1.0 + _NATURAL_TOL and abs(s) <= 1.0 + _NATURAL_TOL + else: + inside = r >= -_NATURAL_TOL and s >= -_NATURAL_TOL and r + s <= 1.0 + _NATURAL_TOL + if not inside: + raise _error("LOCATE_NATURAL_OUTSIDE", + f"natural coordinates {(r, s)} lie outside element {element_id}", + element_id=element_id, natural=(r, s)) + try: + weights = np.asarray(_transfer.element_interpolation_weights(data.element, (r, s)), dtype=float).reshape(-1) + except _transfer.SubmodelTransferError as error: + raise _error("SOURCE_ELEMENT_INVALID", str(error), element_id=element_id) from error + if ( + weights.shape != (len(data.node_ids),) + or not np.all(np.isfinite(weights)) + or abs(float(weights.sum()) - 1.0) > 1.0e-12 + ): + raise _error("SOURCE_ELEMENT_INVALID", f"element {element_id} returned malformed interpolation weights", + element_id=element_id) + return weights + + def hit_value(self, element_id: int, natural: np.ndarray, target: np.ndarray) -> Tuple[np.ndarray, float, float, float]: + """Displacement at ``target`` through one hit: (value, correction, normal_offset, director_offset).""" + + data = self.element_data(element_id) + weights = self._weights(data, natural, element_id) + # Displacement of the reference point p = sum N_i X_i: interpolated translation. The + # rotation is interpolated too and transported ONCE, from p to the target, below. + reference_point = weights @ data.X + offset = target - reference_point + # The target must lie on the element's reference normal line through p: only the signed + # normal offset (any thickness) is admissible; the in-plane part is a locator error. The + # allowance is scaled by the admitted element length and by the coordinate magnitude + # (roundoff), never by the distance to unrelated points. + tangential = float(np.linalg.norm(offset - float(data.normal @ offset) * data.normal)) + coordinate_scale = max(data.coordinate_scale, float(np.max(np.abs(target)))) + allowed = _TANGENTIAL_RTOL * data.length + _TANGENTIAL_EPS_FACTOR * _EPS * coordinate_scale + if not np.isfinite(tangential) or tangential > allowed: + raise _error( + "LOCATE_TANGENTIAL_MISMATCH", + f"target {target.tolist()} is {tangential:.3e} from the normal line through the located point " + f"of element {element_id} (allowed {allowed:.3e})", + element_id=element_id, target=target.tolist(), natural=(float(natural[0]), float(natural[1])), + reference_point=reference_point.tolist(), tangential_residual=tangential, allowed=float(allowed), + ) + translation = weights @ data.U[:, :3] + rotation = weights @ data.U[:, 3:] + correction = 0.0 + if data.kind == "v2d": + try: + density, _area = data.element.compute_native_pressure_density( + self.mesh, np.array([[float(natural[0]), float(natural[1])]]) + ) + except Exception as error: # element-owned geometry / scope guards + raise _error("SOURCE_ELEMENT_INVALID", + f"V2D element {element_id} rejected its transverse operator: {error}", + element_id=element_id) from error + density = np.asarray(density, dtype=float).reshape(-1) + if density.shape != (18,) or not np.all(np.isfinite(density)): + raise _error("SOURCE_ELEMENT_INVALID", f"V2D element {element_id} transverse operator is malformed", + element_id=element_id) + translational = np.array([density[6 * k:6 * k + 3] for k in range(3)]) + if float(np.max(np.abs(translational - weights[:, None] * data.normal[None, :]))) > _DENSITY_TOL: + raise _error("SOURCE_ELEMENT_INVALID", + f"V2D element {element_id} transverse operator disagrees with its node order / normal", + element_id=element_id) + w_min3 = float(density @ data.U.reshape(-1)) + # Exact native normal displacement at the reference point replaces the normal + # component of the interpolated translation (in-plane components untouched). + correction = w_min3 - float(data.normal @ translation) + translation = translation + correction * data.normal + value = translation + np.cross(rotation, offset) + if not (np.all(np.isfinite(value)) and np.isfinite(correction)): + raise _error("SOURCE_NONFINITE", f"displacement through element {element_id} is not finite", + element_id=element_id) + return value, correction, float(data.normal @ offset), float(data.director @ offset) + + def displacement(self, target: np.ndarray, hits: Sequence[Tuple[int, np.ndarray]]) -> ShellDisplacement: + first: Optional[Tuple[np.ndarray, float, float, float]] = None + spread = 0.0 + tolerance = _HIT_AGREE_RTOL * self.scale + for element_id, natural in hits: + result = self.hit_value(element_id, natural, target) + if first is None: + first = result + continue + difference = float(np.max(np.abs(result[0] - first[0]))) + spread = max(spread, difference) + if difference > tolerance: + raise _error( + "LOCATE_HITS_DISAGREE", + f"hits at {target.tolist()} disagree by {difference:.3e} (allowed {tolerance:.3e})", + target=target.tolist(), difference=difference, allowed=tolerance, + ) + assert first is not None + return ShellDisplacement(first[0].copy(), spread, len(hits), first[1], first[2], first[3], + tuple(int(e) for e, _n in hits)) + + +def _check_planar_quad(X: np.ndarray, element_id: int) -> np.ndarray: + center = X.mean(axis=0) + scale = max(float(np.max(np.linalg.norm(X - center, axis=1))), _TINY) + normal = np.cross(X[2] - X[0], X[3] - X[1]) + area2 = float(np.linalg.norm(normal)) + if area2 <= _AREA_TOL * scale * scale: + raise _error("SOURCE_ELEMENT_INVALID", f"Q4 element {element_id} is degenerate", element_id=element_id) + normal = normal / area2 + if float(np.max(np.abs((X - center) @ normal))) > _PLANAR_TOL * scale: + raise _error("SOURCE_ELEMENT_INVALID", + f"Q4 element {element_id} is warped; only planar facets are admitted", element_id=element_id) + for i in range(4): + turn = float(np.cross(X[(i + 1) % 4] - X[i], X[(i + 2) % 4] - X[(i + 1) % 4]) @ normal) + if turn <= _AREA_TOL * scale * scale: + raise _error("SOURCE_ELEMENT_INVALID", + f"Q4 element {element_id} is not strictly convex (corner {i})", element_id=element_id) + return normal + + +def _hits_from_locate(locate: Callable[[np.ndarray], Iterable[Any]], target: np.ndarray) -> List[Tuple[int, np.ndarray]]: + try: + raw = locate(target.copy()) + except SolidSubmodelError: + raise + except Exception as error: + raise _error("LOCATE_FAILED", f"locate raised {type(error).__name__}: {error}", + target=target.tolist()) from error + try: + pairs = list(raw) + except TypeError as error: + raise _error("LOCATE_INVALID", "locate must return an iterable of (element_id, natural) pairs") from error + if not pairs: + raise _error("LOCATE_MISS", f"no source element found for target {target.tolist()}", target=target.tolist()) + hits: List[Tuple[int, np.ndarray]] = [] + for pair in pairs: + try: + element_id, natural = pair + except (TypeError, ValueError) as error: + raise _error("LOCATE_INVALID", "each locate hit must be an (element_id, natural) pair") from error + if isinstance(element_id, (bool, np.bool_)) or not isinstance(element_id, (int, np.integer)): + raise _error("LOCATE_INVALID", f"element id {element_id!r} is not an integer") + try: + coordinates = np.asarray(natural, dtype=float).reshape(-1) + except (TypeError, ValueError) as error: + raise _error("LOCATE_INVALID", "natural coordinates are not numeric") from error + if coordinates.shape != (2,) or not np.all(np.isfinite(coordinates)): + raise _error("LOCATE_INVALID", "natural coordinates must be two finite numbers") + hits.append((int(element_id), coordinates)) + return hits + + +def evaluate_shell_displacement( + fe_model: Any, + source_u: Any, + hits: Iterable[Tuple[int, Sequence[float]]], + target: Sequence[float], +) -> ShellDisplacement: + """Physical displacement of the shell at ``target`` through ``hits``. + + ``hits`` are ``(source_element_id, natural_coordinates)`` pairs; several hits + must agree. The model and source vector are validated exactly as for + :func:`solve_shell_driven_solid`. + """ + + source = _Source(fe_model, source_u) + try: + x = np.asarray(target, dtype=float).reshape(-1) + except (TypeError, ValueError) as error: + raise _error("TARGET_INVALID", "target is not numeric") from error + if x.shape != (3,) or not np.all(np.isfinite(x)): + raise _error("TARGET_INVALID", "target must be a finite 3-vector") + return source.displacement(x, _hits_from_locate(lambda _x: hits, x)) + + +# ---------------------------------------------------------------------- +# prepared solid validation +# ---------------------------------------------------------------------- +@dataclass +class _Prepared: + ndof: int + coordinates: np.ndarray # (ndof, 3) + components: np.ndarray # (ndof,) + order: int + + +def _validate_prepared(prepared: Any) -> _Prepared: + for name in ("assemble_linear", "boundary_dofs", "traction", "recover", "rigid_modes", "trace"): + if not callable(getattr(prepared, name, None)): + raise _error("PREPARED_INVALID", f"prepared solid lacks the {name}() interface") + order = getattr(prepared, "order", None) + if isinstance(order, (bool, np.bool_)) or order not in (1, 2): + raise _error("PREPARED_INVALID", "prepared solid order must be 1 or 2") + ndof = getattr(prepared, "ndof", None) + if isinstance(ndof, (bool, np.bool_)) or not isinstance(ndof, (int, np.integer)) or ndof <= 0: + raise _error("PREPARED_INVALID", "prepared solid ndof must be a positive integer") + ndof = int(ndof) + try: + coordinates = np.asarray(prepared.coefficient_coordinates, dtype=float) + components = np.asarray(prepared.coefficient_components) + except (AttributeError, TypeError, ValueError) as error: + raise _error("PREPARED_INVALID", "coefficient coordinates/components are unavailable") from error + if coordinates.shape != (ndof, 3) or not np.all(np.isfinite(coordinates)): + raise _error("PREPARED_INVALID", f"coefficient_coordinates must be finite ({ndof}, 3)") + if components.shape != (ndof,) or components.dtype.kind not in "iu" or not np.all(np.isin(components, (0, 1, 2))): + raise _error("PREPARED_INVALID", f"coefficient_components must be integers 0..2 of shape ({ndof},)") + components = components.astype(np.int64) + keyed = np.column_stack([coordinates, components]) + if len(np.unique(keyed, axis=0)) != ndof: + raise _error("PREPARED_INVALID", "coefficient (coordinate, component) pairs are not unique") + mesh = getattr(prepared, "mesh", None) + try: + node_ids = np.asarray(mesh.node_ids) + node_coordinates = np.asarray(mesh.coordinates, dtype=float) + groups = mesh.boundary_groups + node_groups = mesh.node_groups + except (AttributeError, TypeError, ValueError) as error: + raise _error("PREPARED_INVALID", "prepared solid mesh lacks node_ids/coordinates/groups") from error + if ( + node_ids.ndim != 1 + or node_coordinates.shape != (node_ids.size, 3) + or not np.all(np.isfinite(node_coordinates)) + or not isinstance(groups, Mapping) + or not isinstance(node_groups, Mapping) + ): + raise _error("PREPARED_INVALID", "prepared solid mesh arrays are malformed") + return _Prepared(ndof, coordinates, components, int(order)) + + +def _group_dofs(prepared: Any, info: _Prepared, name: str) -> np.ndarray: + try: + raw = prepared.boundary_dofs(name) + except (ValueError, KeyError, TypeError) as error: + raise _error("CUT_GROUP_INVALID", f"cut group {name!r} is not usable: {error}", group=name) from error + dofs = np.asarray(raw) + if dofs.ndim != 1 or dofs.dtype.kind not in "iu" or dofs.size == 0: + raise _error("CUT_GROUP_INVALID", f"cut group {name!r} yields no DOF index array", group=name) + dofs = dofs.astype(np.int64) + if dofs.min() < 0 or dofs.max() >= info.ndof or len(np.unique(dofs)) != dofs.size: + raise _error("CUT_GROUP_INVALID", f"cut group {name!r} has out-of-range or repeated DOFs", group=name) + locations: Dict[bytes, int] = {} + for d in dofs: + key = info.coordinates[d].tobytes() + locations[key] = locations.get(key, 0) + 1 + if any(count != 3 for count in locations.values()): + raise _error("CUT_GROUP_INVALID", + f"cut group {name!r} does not carry all three components at every location", group=name) + return np.sort(dofs) + + +def _resultant(coordinates: np.ndarray, components: np.ndarray, values: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """Work-conjugate force and moment about the origin of nodal values on (x, component) DOFs.""" + + vectors = np.zeros((components.size, 3)) + vectors[np.arange(components.size), components] = values + return vectors.sum(axis=0), np.cross(coordinates, vectors).sum(axis=0) + + +# ---------------------------------------------------------------------- +# result +# ---------------------------------------------------------------------- +@dataclass(frozen=True) +class GroupResultant: + """Resultant of the interface forces attributed to one cut group.""" + + name: str + force: np.ndarray # (3,) global, force the shell boundary exerts on the solid + moment: np.ndarray # (3,) global, about the origin + dof_count: int + shared_dof_count: int + + +@dataclass(frozen=True) +class SolidSubmodelResult: + """Result of a certified one-way shell->solid solve. + + ``interface_force`` / ``interface_moment`` are the force and moment (global + frame, moment about the origin) that the driven cut boundary exerts on the + solid: the constraint reactions ``r = K q - f`` on the prescribed DOFs. With + free skins they balance the skin load resultants (``skin_force``, + ``skin_moment``): ``interface + skin = 0``. + """ + + coefficients: np.ndarray + nodal_displacements: np.ndarray # (N, 3), aligned to prepared.mesh.node_ids + recovery: Any + interface_force: np.ndarray + interface_moment: np.ndarray + group_resultants: Dict[str, GroupResultant] + shared_attribution: Dict[int, Tuple[str, ...]] + attribution_rule: str + prescribed_dofs: np.ndarray + prescribed_values: np.ndarray + reactions: np.ndarray # aligned with prescribed_dofs + skin_force: np.ndarray + skin_moment: np.ndarray + diagnostics: Dict[str, Any] = field(default_factory=dict) + + +def _nodal_displacements(prepared: Any, info: _Prepared, q: np.ndarray) -> np.ndarray: + coordinates = np.asarray(prepared.mesh.coordinates, dtype=float) + lookup: Dict[bytes, Dict[int, int]] = {} + for d in range(info.ndof): + lookup.setdefault(info.coordinates[d].tobytes(), {})[int(info.components[d])] = d + nodal = np.empty((coordinates.shape[0], 3)) + for row, x in enumerate(coordinates): + entry = lookup.get(np.ascontiguousarray(x).tobytes()) + if entry is None or set(entry) != {0, 1, 2}: + break + nodal[row] = [q[entry[0]], q[entry[1]], q[entry[2]]] + else: + return nodal + # Vertices are not coefficient locations bit-for-bit: interpolate through the trace operator. + try: + values = sparse.csr_matrix(prepared.trace(coordinates)) @ q + except ValueError as error: + raise _error("PREPARED_INVALID", f"nodal displacements cannot be evaluated: {error}") from error + return np.asarray(values, dtype=float).reshape(-1, 3) + + +def _validated_cut_groups(cut_groups: Any) -> List[str]: + if isinstance(cut_groups, (str, bytes)) or not isinstance(cut_groups, (list, tuple)): + raise _error("CUT_GROUP_INVALID", "cut_groups must be a list or tuple of group names") + names = list(cut_groups) + if not names: + raise _error("CUT_GROUP_INVALID", "at least one cut group is required") + if any(not isinstance(n, str) or not n for n in names) or len(set(names)) != len(names): + raise _error("CUT_GROUP_INVALID", "cut group names must be distinct non-empty strings") + return names + + +def _validated_skin(prepared: Any, info: _Prepared, skin_tractions: Any, cut_names: Sequence[str]) -> List[Tuple[str, np.ndarray]]: + if skin_tractions is None: + return [] + if not isinstance(skin_tractions, Mapping): + raise _error("SKIN_INVALID", "skin_tractions must be a mapping group -> global traction vector") + groups = prepared.mesh.boundary_groups + out: List[Tuple[str, np.ndarray]] = [] + for name, vector in skin_tractions.items(): + if not isinstance(name, str) or name not in groups: + raise _error("SKIN_INVALID", f"skin group {name!r} is not an external boundary group", group=name) + if name in cut_names: + raise _error("SKIN_INVALID", f"skin group {name!r} is also a cut group", group=name) + try: + traction = np.asarray(vector, dtype=float).reshape(-1) + except (TypeError, ValueError) as error: + raise _error("SKIN_INVALID", f"traction of {name!r} is not numeric", group=name) from error + if traction.shape != (3,) or not np.all(np.isfinite(traction)): + raise _error("SKIN_INVALID", f"traction of {name!r} must be a finite 3-vector", group=name) + for cut in cut_names: + if cut in groups and np.intersect1d(np.asarray(groups[name]), np.asarray(groups[cut])).size: + raise _error("SKIN_INVALID", f"skin group {name!r} shares facets with cut group {cut!r}", group=name) + out.append((name, traction)) + return out + + +# ---------------------------------------------------------------------- +# solve +# ---------------------------------------------------------------------- +def solve_shell_driven_solid( + fe_model: Any, + source_u: Any, + prepared: Any, + *, + cut_groups: Sequence[str], + locate: Callable[[np.ndarray], Iterable[Tuple[int, Sequence[float]]]], + skin_tractions: Optional[Mapping[str, Sequence[float]]] = None, + cancel: Any = None, +) -> SolidSubmodelResult: + """Drive a prepared solid from a linear shell solution and solve it once. + + Parameters + ---------- + fe_model, source_u: + The converged linear shell model and its global displacement vector. The + vector must satisfy every support, equation and coupling row of the model. + prepared: + ANYsolid ``PreparedSolid`` (P1 or P2). + cut_groups: + Boundary (or node) group names whose coefficients are all prescribed. + locate: + ``locate(x)`` takes a world coordinate ``ndarray (3,)`` and returns an + iterable of ``(source_element_id, natural_coordinates)`` pairs on the shell + reference midsurface (the Q4 uses ``(xi, eta)`` in ``[-1, 1]^2``, the V2D + ``(r, s)`` with ``N = (1-r-s, r, s)``). Several hits must agree. + skin_tractions: + ``{external boundary group: global traction vector}``. + cancel: + ``None``, a callable returning a flag, or an object with ``is_set()``. + """ + + probe = _cancel_probe(cancel) + _check_cancel(probe, "start") + if not callable(locate): + raise _error("LOCATE_INVALID", "locate must be callable") + info = _validate_prepared(prepared) + names = _validated_cut_groups(cut_groups) + skin = _validated_skin(prepared, info, skin_tractions, names) + source = _Source(fe_model, source_u) + + # -- cut DOFs -------------------------------------------------------------- + group_dofs: Dict[str, np.ndarray] = {} + owners: Dict[int, List[str]] = {} + for name in names: + _check_cancel(probe, f"cut group {name}") + dofs = _group_dofs(prepared, info, name) + group_dofs[name] = dofs + for d in dofs: + owners.setdefault(int(d), []).append(name) + prescribed = np.array(sorted(owners), dtype=np.int64) + listed = sum(len(v) for v in group_dofs.values()) + duplicates = listed - prescribed.size + + # -- driven values --------------------------------------------------------- + cache: Dict[bytes, ShellDisplacement] = {} + values = np.empty(prescribed.size) + spread_max = 0.0 + correction_max = 0.0 + offset_max = 0.0 + hits_max = 0 + element_counts: Dict[str, int] = {} + for position, d in enumerate(prescribed): + _check_cancel(probe, "evaluating the shell field") + x = info.coordinates[d] + key = x.tobytes() + shell = cache.get(key) + if shell is None: + shell = source.displacement(x.copy(), _hits_from_locate(locate, x)) + cache[key] = shell + spread_max = max(spread_max, shell.hit_spread) + correction_max = max(correction_max, abs(shell.transverse_correction)) + offset_max = max(offset_max, abs(shell.normal_offset)) + hits_max = max(hits_max, shell.hits) + for eid in shell.element_ids: + kind = source.element_data(eid).kind + element_counts[kind] = element_counts.get(kind, 0) + 1 + values[position] = shell.value[info.components[d]] + if not np.all(np.isfinite(values)): + raise _error("SOURCE_NONFINITE", "driven values are not finite") + + # -- operator and loads ---------------------------------------------------- + _check_cancel(probe, "assembling the solid operator") + try: + K = sparse.csr_matrix(prepared.assemble_linear(), dtype=float) + except (ValueError, TypeError) as error: + raise _error("PREPARED_OPERATOR_INVALID", f"assemble_linear failed: {error}") from error + if K.shape != (info.ndof, info.ndof) or not np.all(np.isfinite(K.data)): + raise _error("PREPARED_OPERATOR_INVALID", "the linear operator is not a finite square matrix of ndof") + k_norm = float(abs(K).max()) if K.nnz else 0.0 + if k_norm == 0.0 or float(abs(K - K.T).max()) > _SYMMETRY_RTOL * k_norm: + raise _error("PREPARED_OPERATOR_INVALID", "the linear operator is zero or not symmetric") + f = np.zeros(info.ndof) + for name, traction in skin: + _check_cancel(probe, f"skin traction {name}") + try: + load = np.asarray(prepared.traction(name, traction), dtype=float) + except ValueError as error: + raise _error("SKIN_INVALID", f"traction of {name!r} failed: {error}", group=name) from error + if load.shape != (info.ndof,) or not np.all(np.isfinite(load)): + raise _error("SKIN_INVALID", f"traction load of {name!r} is malformed", group=name) + f += load + + # -- support check: the prescribed set must remove every rigid mode -------- + _check_cancel(probe, "rigid-mode check") + try: + modes = np.asarray(prepared.rigid_modes(), dtype=float) + except (ValueError, TypeError) as error: + raise _error("PREPARED_INVALID", f"rigid_modes failed: {error}") from error + if modes.ndim != 2 or modes.shape[0] != info.ndof or not np.all(np.isfinite(modes)): + raise _error("PREPARED_INVALID", "rigid_modes must be a finite (ndof, 6m) array") + singular_values = np.linalg.svd(modes[prescribed], compute_uv=False) + if singular_values.size < modes.shape[1] or singular_values[-1] <= _RIGID_RANK_RATIO * max(singular_values[0], _TINY): + raise _error( + "UNDERCONSTRAINED", + "the prescribed cut DOFs leave a rigid-body mode of the solid free " + f"(smallest/largest rigid-mode singular value {singular_values[-1] / max(singular_values[0], _TINY):.3e})", + singular_values=singular_values.tolist(), + ) + + # -- constrained static solve --------------------------------------------- + _check_cancel(probe, "factorization") + free = np.setdiff1d(np.arange(info.ndof), prescribed) + q = np.zeros(info.ndof) + q[prescribed] = values + eta = 0.0 + kappa = 1.0 + refinements = 0 + if free.size: + K_f = K[free][:, free].tocsc() + rhs = f[free] - K[free][:, prescribed] @ values + diagonal = K_f.diagonal() + if not np.all(np.isfinite(diagonal)) or np.any(diagonal <= 0.0): + raise _error("SOLVE_SINGULAR", "the free block has a non-positive diagonal (singular or mechanism)") + d = 1.0 / np.sqrt(diagonal) + D = sparse.diags(d) + scaled = sparse.csc_matrix(D @ K_f @ D) + scaled_rhs = d * rhs + try: + lu = splu(scaled) + except RuntimeError as error: + raise _error("SOLVE_SINGULAR", f"the free block is singular: {error}") from error + y = lu.solve(scaled_rhs) + _check_cancel(probe, "refinement") + y = y + lu.solve(scaled_rhs - scaled @ y) + refinements = 1 + if not np.all(np.isfinite(y)): + raise _error("SOLVE_NONFINITE", "the constrained solve produced non-finite coefficients") + residual = scaled @ y - scaled_rhs + denominator = float(abs(scaled).sum(axis=1).max()) * float(np.max(np.abs(y), initial=0.0)) \ + + float(np.max(np.abs(scaled_rhs), initial=0.0)) + eta = float(np.max(np.abs(residual), initial=0.0) / denominator) if denominator > 0.0 else 0.0 + _check_cancel(probe, "condition estimate") + m = scaled.shape[0] + if m > 1: + inverse = LinearOperator((m, m), matvec=lu.solve, rmatvec=lambda v: lu.solve(v, trans="T"), dtype=float) + kappa = float(abs(scaled).sum(axis=0).max()) * float(onenormest(inverse)) + if not (np.isfinite(eta) and np.isfinite(kappa)): + raise _error("SOLVE_NONFINITE", "the solve certificate is not finite") + if kappa > _CONDITION_LIMIT: + raise _error("POOR_CONDITIONING", f"estimated condition number {kappa:.3e} exceeds {_CONDITION_LIMIT:.0e}", + kappa=kappa) + if eta > _BACKWARD_ERROR_LIMIT: + raise _error("SOLVE_UNCERTIFIED", f"scaled backward error {eta:.3e} exceeds {_BACKWARD_ERROR_LIMIT:.0e}", + eta=eta) + if kappa * eta > _ERROR_BOUND_LIMIT: + raise _error("SOLVE_UNCERTIFIED", f"kappa*eta = {kappa * eta:.3e} exceeds {_ERROR_BOUND_LIMIT:.0e}", + eta=eta, kappa=kappa) + q[free] = d * y + if not np.all(np.isfinite(q)): + raise _error("SOLVE_NONFINITE", "coefficients are not finite") + + # -- reactions and resultants --------------------------------------------- + _check_cancel(probe, "reactions") + r = K @ q - f + reactions = r[prescribed] + coords = info.coordinates + comps = info.components + free_scale = float(np.max(np.abs(abs(K)[free] @ np.abs(q) + np.abs(f[free])), initial=0.0)) if free.size else 0.0 + free_residual = float(np.max(np.abs(r[free]), initial=0.0)) + free_ratio = free_residual / (free_scale + _TINY) + interface_force, interface_moment = _resultant(coords[prescribed], comps[prescribed], reactions) + loaded = np.flatnonzero(f) + skin_force, skin_moment = _resultant(coords[loaded], comps[loaded], f[loaded]) if loaded.size else (np.zeros(3), np.zeros(3)) + # Scale by the magnitude of the internal forces that cancel (|K||q|) and the loads, so a + # rigid or unloaded solve compares roundoff with the operator scale, not with itself. + magnitude = np.asarray(abs(K) @ np.abs(q)).reshape(-1) + np.abs(f) + force_scale = float(np.sum(magnitude)) + moment_scale = float(np.sum(np.linalg.norm(coords, axis=1) * magnitude)) + force_balance = float(np.linalg.norm(interface_force + skin_force)) / (force_scale + _TINY) + moment_balance = float(np.linalg.norm(interface_moment + skin_moment)) / (moment_scale + _TINY) + if not (np.isfinite(force_balance) and np.isfinite(moment_balance)) or max(force_balance, moment_balance, free_ratio) > _BALANCE_LIMIT: + raise _error( + "EQUILIBRIUM_VIOLATED", + f"force/moment/free-residual balance {force_balance:.3e}/{moment_balance:.3e}/{free_ratio:.3e} " + f"exceeds {_BALANCE_LIMIT:.0e}", + force_balance=force_balance, moment_balance=moment_balance, free_ratio=free_ratio, + ) + + group_results: Dict[str, GroupResultant] = {} + shared = {d_: tuple(g) for d_, g in owners.items() if len(g) > 1} + for name in names: + dofs = group_dofs[name] + position = np.searchsorted(prescribed, dofs) + weight = np.array([1.0 / len(owners[int(d_)]) for d_ in dofs]) + force, moment = _resultant(coords[dofs], comps[dofs], reactions[position] * weight) + group_results[name] = GroupResultant( + name, force, moment, int(dofs.size), int(sum(1 for d_ in dofs if int(d_) in shared)) + ) + closure_force = np.sum([g.force for g in group_results.values()], axis=0) - interface_force + closure_moment = np.sum([g.moment for g in group_results.values()], axis=0) - interface_moment + + _check_cancel(probe, "recovery") + try: + recovery = prepared.recover(q) + except ValueError as error: + raise _error("RECOVERY_FAILED", f"prepared.recover rejected the coefficients: {error}") from error + nodal = _nodal_displacements(prepared, info, q) + _check_cancel(probe, "finish") + + diagnostics = { + "certification": { + "certified": True, + "scaled_backward_error": eta, + "condition_estimate": kappa, + "error_bound_estimate": kappa * eta, + "refinement_steps": refinements, + "backward_error_limit": _BACKWARD_ERROR_LIMIT, + "condition_limit": _CONDITION_LIMIT, + "error_bound_limit": _ERROR_BOUND_LIMIT, + "rigid_mode_singular_values": singular_values.tolist(), + }, + "residual": { + "free_residual_inf": free_residual, + "free_residual_ratio": free_ratio, + "force_balance_ratio": force_balance, + "moment_balance_ratio": moment_balance, + "balance_limit": _BALANCE_LIMIT, + "attribution_closure_force": closure_force, + "attribution_closure_moment": closure_moment, + }, + "constraints": { + "cut_groups": tuple(names), + "prescribed_dofs": int(prescribed.size), + "free_dofs": int(free.size), + "listed_group_dofs": int(listed), + "duplicate_dof_count": int(duplicates), + "shared_dof_count": len(shared), + }, + "source": { + "locations": len(cache), + "hits_max": hits_max, + "hit_spread_max": spread_max, + "v2d_transverse_correction_max": correction_max, + "normal_offset_max": offset_max, + "element_kinds": dict(element_counts), + "constraint_rows_checked": source.constraint_rows, + "scale": source.scale, + }, + "prepared": {"order": info.order, "ndof": info.ndof}, + "skin": {name: traction.tolist() for name, traction in skin}, + } + return SolidSubmodelResult( + coefficients=q, + nodal_displacements=nodal, + recovery=recovery, + interface_force=interface_force, + interface_moment=interface_moment, + group_resultants=group_results, + shared_attribution=shared, + attribution_rule=ATTRIBUTION_RULE, + prescribed_dofs=prescribed, + prescribed_values=values, + reactions=reactions, + skin_force=skin_force, + skin_moment=skin_moment, + diagnostics=diagnostics, + ) diff --git a/tests/test_nodal_stress_recovery.py b/tests/test_nodal_stress_recovery.py index ba4527653..5b4bd283f 100644 --- a/tests/test_nodal_stress_recovery.py +++ b/tests/test_nodal_stress_recovery.py @@ -102,11 +102,9 @@ def test_recovery_and_native_q4_stresses_converge_toward_fine_mesh_value() -> No raw_coarse, recovered_coarse = _panel_case(4) raw_medium, recovered_medium = _panel_case(8) - # Formulation-native mixed resultants need not make nodal averaging a - # one-sided increase on the coarsest grid. Require both raw and recovered - # sequences to approach the fine recovered value, and require smoothing to - # improve the resolved medium grid without asserting a legacy stress bias. + # Gauss and nodal maxima sample different physical locations. Each sequence + # converges toward the resolved peak. Pointwise precision is checked separately + # against manufactured stresses and cyclic permutations of the same physical nodes. assert abs(raw_medium - reference) < abs(raw_coarse - reference) assert abs(recovered_medium - reference) < abs(recovered_coarse - reference) - assert abs(recovered_medium - reference) < abs(raw_medium - reference) assert recovered_medium == pytest.approx(reference, rel=0.075) diff --git a/tests/test_q4_nodal_stress_order.py b/tests/test_q4_nodal_stress_order.py new file mode 100644 index 000000000..85a2c8e43 --- /dev/null +++ b/tests/test_q4_nodal_stress_order.py @@ -0,0 +1,233 @@ +"""Q4 nodal stress recovery must pair rows with the stations they came from. + +The qualified planar Q4 returns stress rows in its stiffness-station order +(``[--, +-, ++, -+]``) and reports that order in ``natural_point_coordinates``, +while ``element.gauss_points`` is tensor ordered (``[--, +-, -+, ++]``). +The first group exercises the production consumer helper with manufactured, +asymmetric fields. The second group drives ``recover_nodal_stresses`` on a +one-element production model: the global displacement vector of a one-element +model has exactly the element DOF count, so the model-level caller must gather +it into connectivity order itself. +""" + +from types import SimpleNamespace + +import numpy as np +import pytest + +from anysolver.elements import create_shell_element +from anysolver.fe_core import FEModel +from anysolver.results import _operator_for_returned_rows, recover_nodal_stresses + +G = 1.0 / np.sqrt(3.0) +STIFFNESS_ORDER = np.array([[-G, -G], [G, -G], [G, G], [-G, G]]) +TENSOR_ORDER = np.array([[-G, -G], [G, -G], [-G, G], [G, G]]) +NODES = np.array([[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]]) +KEYS = ("global_xx_top", "global_xx_bot") + + +def _field(points, scale=1.0): + r, s = points[:, 0], points[:, 1] + return scale * (2.0 + 3.0 * r - 5.0 * s + 7.0 * r * s) + + +def _element(): + return SimpleNamespace(element_id=1, num_nodes=4, gauss_points=TENSOR_ORDER) + + +def _stresses(points, declared=True): + out = {"global_xx_top": _field(points), "global_xx_bot": _field(points, -2.0)} + if declared: + out["natural_point_coordinates"] = points.copy() + return out + + +def test_declared_stiffness_order_recovers_exact_nodal_field(): + stresses = _stresses(STIFFNESS_ORDER) + operator = _operator_for_returned_rows(_element(), stresses, KEYS) + np.testing.assert_allclose(operator @ stresses["global_xx_top"], _field(NODES), rtol=0, atol=1e-13) + np.testing.assert_allclose(operator @ stresses["global_xx_bot"], _field(NODES, -2.0), rtol=0, atol=1e-13) + + +def test_legacy_gauss_point_layout_unchanged_without_declared_coordinates(): + stresses = _stresses(TENSOR_ORDER, declared=False) + operator = _operator_for_returned_rows(_element(), stresses, KEYS) + np.testing.assert_allclose(operator @ stresses["global_xx_top"], _field(NODES), rtol=0, atol=1e-13) + + +def test_old_pairing_would_have_been_wrong(): + rows = _field(STIFFNESS_ORDER) + wrong = _operator_for_returned_rows(_element(), _stresses(TENSOR_ORDER, declared=False), KEYS) @ rows + assert not np.allclose(wrong, _field(NODES), atol=1e-6) + + +@pytest.mark.parametrize("shift", range(4)) +def test_cyclic_station_permutation_gives_same_nodal_values(shift): + points = np.roll(STIFFNESS_ORDER, shift, axis=0) + stresses = _stresses(points) + operator = _operator_for_returned_rows(_element(), stresses, KEYS) + np.testing.assert_allclose(operator @ stresses["global_xx_top"], _field(NODES), rtol=0, atol=1e-13) + + +def test_inconsistent_rows_are_refused(): + element = _element() + bad_shape = _stresses(STIFFNESS_ORDER) + bad_shape["natural_point_coordinates"] = STIFFNESS_ORDER[:3] + with pytest.raises(ValueError, match="inconsistent"): + _operator_for_returned_rows(element, bad_shape, KEYS) + duplicate = _stresses(STIFFNESS_ORDER) + duplicate["natural_point_coordinates"] = np.vstack((STIFFNESS_ORDER[:3], STIFFNESS_ORDER[:1])) + with pytest.raises(ValueError, match="duplicate"): + _operator_for_returned_rows(element, duplicate, KEYS) + ragged = _stresses(STIFFNESS_ORDER) + ragged["global_xx_bot"] = ragged["global_xx_bot"][:3] + with pytest.raises(ValueError, match="row counts"): + _operator_for_returned_rows(element, ragged, KEYS) + nonfinite = _stresses(STIFFNESS_ORDER) + nonfinite["natural_point_coordinates"][0, 0] = np.nan + with pytest.raises(ValueError, match="inconsistent"): + _operator_for_returned_rows(element, nonfinite, KEYS) + + +# --------------------------------------------------------------------------- +# One-element production model through recover_nodal_stresses +# --------------------------------------------------------------------------- + +E_MOD = 210.0e9 +NU = 0.3 +SKEW_COORDS = np.array( + [[0.0, 0.0, 0.0], [1.35, 0.08, 0.0], [1.08, 0.95, 0.0], [-0.18, 1.12, 0.0]] +) +CYCLIC_CONNECTIVITIES = [[1, 2, 3, 4], [4, 1, 2, 3], [3, 4, 1, 2], [2, 3, 4, 1]] + + +def _rotation(): + def rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + def ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + def rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + return rz(np.radians(30.0)) @ ry(np.radians(-25.0)) @ rx(np.radians(40.0)) + + +def _one_element_model(connectivity, coords): + model = FEModel("one_element") + model.add_material("steel", E_MOD, NU) + for node_id, coord in enumerate(coords, start=1): + model.add_node(node_id, *(float(v) for v in coord)) + model.add_element(1, create_shell_element(1, list(connectivity), "steel", thickness=0.01)) + return model + + +def _physical_field(model, coords, rotation): + """Asymmetric in-plane strain plus an oblique rigid motion, in global axes. + + Returns the global displacement vector (indexed by each node's own DOFs, + independent of element connectivity) and the exact global stress tensor. + """ + a, b, c = 1.2e-4, -0.4e-4, 0.35e-4 + local_strain = np.array([[a, c, 0.0], [c, b, 0.0], [0.0, 0.0, 0.0]]) + strain = rotation @ local_strain @ rotation.T + normal = rotation[:, 2] + projector = np.eye(3) - np.outer(normal, normal) + omega = np.array([2.0e-4, -1.5e-4, 3.0e-4]) + translation = np.array([1.0e-4, -2.0e-4, 0.5e-4]) + + dofs = {node_id: model.mesh.get_node(node_id).dofs for node_id in range(1, 5)} + u = np.zeros(1 + max(max(d) for d in dofs.values())) + for node_id, coord in enumerate(coords, start=1): + x = np.asarray(coord, dtype=float) + base = list(dofs[node_id]) + u[base[:3]] = translation + strain @ x + np.cross(omega, x) + u[base[3:6]] = omega + + shear_modulus = E_MOD / (2.0 * (1.0 + NU)) + lam = E_MOD * NU / (1.0 - NU**2) + stress = 2.0 * shear_modulus * strain + lam * np.trace(strain) * projector + return u, stress + + +_COMPONENT_INDEX = {"xx": (0, 0), "yy": (1, 1), "zz": (2, 2), "xy": (0, 1), "yz": (1, 2), "xz": (0, 2)} + + +@pytest.mark.parametrize("connectivity", CYCLIC_CONNECTIVITIES) +def test_one_element_recovery_matches_physical_stress_for_cyclic_connectivity(connectivity): + rotation = _rotation() + coords = SKEW_COORDS @ rotation.T + model = _one_element_model(connectivity, coords) + u, expected = _physical_field(model, coords, rotation) + scale = E_MOD * 1.2e-4 # stress scale of the imposed strain, Pa + + recovered = recover_nodal_stresses(model, u) + + assert recovered["skipped_element_ids"] == [] + assert sorted(recovered["nodal"]) == [1, 2, 3, 4] + for node_id, values in recovered["nodal"].items(): + for surface in ("top", "bot"): + for component, index in _COMPONENT_INDEX.items(): + assert values[f"global_{component}_{surface}"] == pytest.approx( + expected[index], rel=0.0, abs=1.0e-8 * scale + ), (connectivity, node_id, surface, component) + + +def test_one_element_recovery_is_invariant_under_cyclic_connectivity(): + rotation = _rotation() + coords = SKEW_COORDS @ rotation.T + scale = E_MOD * 1.2e-4 + results = [] + for connectivity in CYCLIC_CONNECTIVITIES: + model = _one_element_model(connectivity, coords) + u, _ = _physical_field(model, coords, rotation) + results.append(recover_nodal_stresses(model, u)["nodal"]) + for other in results[1:]: + for node_id, reference in results[0].items(): + for key, value in reference.items(): + assert other[node_id][key] == pytest.approx(value, rel=0.0, abs=1.0e-8 * scale) + + +def test_raw_compute_stresses_keeps_element_local_convention_for_full_length_vector(): + """A raw element-length vector is element-ordered input, as before.""" + rotation = _rotation() + coords = SKEW_COORDS @ rotation.T + scale = E_MOD * 1.2e-4 + + identity = _one_element_model([1, 2, 3, 4], coords) + u, expected = _physical_field(identity, coords, rotation) + material = identity.get_material("steel") + raw = identity.mesh.get_element(1).compute_stresses(identity.mesh, u, material, return_global=True) + assert np.max(np.abs(raw["global_xx_top"] - expected[0, 0])) < 1.0e-8 * scale + + permuted = _one_element_model([4, 1, 2, 3], coords) + element = permuted.mesh.get_element(1) + node_order_raw = element.compute_stresses(permuted.mesh, u, material, return_global=True) + gather = np.asarray(element.get_dof_mapping(permuted.mesh), dtype=int) + element_order = element.compute_stresses(permuted.mesh, u[gather], material, return_global=True) + # Node-ordered input to the raw API is interpreted as element-local, hence wrong... + assert np.max(np.abs(node_order_raw["global_xx_top"] - expected[0, 0])) > 1.0e-3 * scale + # ...while explicitly gathered element-order input is physical. + assert np.max(np.abs(element_order["global_xx_top"] - expected[0, 0])) < 1.0e-8 * scale + + +def test_recover_nodal_stresses_rejects_malformed_global_vector(): + rotation = _rotation() + coords = SKEW_COORDS @ rotation.T + model = _one_element_model([4, 1, 2, 3], coords) + u, _ = _physical_field(model, coords, rotation) + with pytest.raises(ValueError): + recover_nodal_stresses(model, u.reshape(-1, 1)) + with pytest.raises((ValueError, IndexError)): + recover_nodal_stresses(model, u[:-6]) + + +def test_collinear_q4_stations_cannot_recover_a_bilinear_stress(): + points = np.array([[-.9, 0.], [-.3, 0.], [.3, 0.], [.9, 0.]]) + with pytest.raises(ValueError, match="span the recovery polynomial"): + _operator_for_returned_rows(_element(), {"natural_point_coordinates": points, + **{key: _field(points) for key in KEYS}}, KEYS) diff --git a/tests/test_solid_submodel.py b/tests/test_solid_submodel.py new file mode 100644 index 000000000..ea820906e --- /dev/null +++ b/tests/test_solid_submodel.py @@ -0,0 +1,696 @@ +"""One-way shell -> solid submodel (docs/SOLID_SUBMODEL.md). + +Oracles are closed-form: rigid and affine fields that both the shell and the P1/P2 solid +reproduce exactly (so the solid must return them), hand-derived MIN3 / bilinear values at a +centroid, and global equilibrium of the signed interface resultants. No result is compared +with another run of the same code. Needs the optional ANYsolid scikit-fem backend. +""" + +from __future__ import annotations + +import functools +import itertools + +import numpy as np +import pytest + +pytest.importorskip("skfem") +anysolid_backend = pytest.importorskip("anysolid.backend") +from anysolid.mesh import SolidMesh # noqa: E402 + +from anysolver.e4_pl_s3_v2d_element import NativeParityE4PLS3V2DShellElement # noqa: E402 +from anysolver.elements import ShellElement, create_shell_element # noqa: E402 +from anysolver.fe_core import FEModel # noqa: E402 +from anysolver import BoundaryCondition # noqa: E402 +from anysolver.solid_submodel import ( # noqa: E402 + ATTRIBUTION_RULE, + SolidSubmodelCancelled, + SolidSubmodelError, + evaluate_shell_displacement, + solve_shell_driven_solid, +) +from anysolver.submodel_transfer import element_interpolation_weights # noqa: E402 + +E, NU, T = 210.0e9, 0.3, 0.01 +LZ = 0.2 +ALL = ["xmin", "xmax", "ymin", "ymax", "zmin", "zmax"] +LATERAL_AND_BOTTOM = ["xmin", "xmax", "ymin", "ymax", "zmin"] + + +# ---------------------------------------------------------------------- +# fixtures: shell plate [0,1]^2 at z=0, solid box [0,1]^2 x [-LZ/2, LZ/2] +# ---------------------------------------------------------------------- +def shell_plate(n=2, *, triangles=False, membrane=False): + model = FEModel("solid-submodel") + model.add_material("steel", E, NU, density=7850.0) + grid, node = {}, 1 + for j in range(n + 1): + for i in range(n + 1): + model.add_node(node, i / n, j / n, 0.0) + grid[i, j] = node + node += 1 + element = 1 + for j in range(n): + for i in range(n): + a, b, c, d = grid[i, j], grid[i + 1, j], grid[i + 1, j + 1], grid[i, j + 1] + if triangles: + for ids in ((a, b, c), (a, c, d)): + model.add_element(element, NativeParityE4PLS3V2DShellElement( + element, ids, "steel", thickness=T, reference_normal=(0.0, 0.0, 1.0))) + element += 1 + else: + model.add_element(element, create_shell_element(element, [a, b, c, d], "steel", thickness=T)) + element += 1 + if membrane: + model.add_boundary_condition(BoundaryCondition( + name="membrane", node_ids=sorted(grid.values()), dof_constraints={"uz": 0.0, "rx": 0.0, "ry": 0.0})) + return model + + +def coords(model, node): + return np.asarray(model.mesh.get_node(node).coords(), dtype=float) + + +def nodal_vector(model, field): + u = np.zeros(model.mesh.dof_manager.total_dofs) + for node_id in model.mesh.nodes: + u[model.mesh.dof_manager.get_node_dofs(node_id)] = field(coords(model, node_id)) + return u + + +def affine(x, omega=2.0e-4): + return np.array([1.0e-4 * x[0] + (2.5e-5 - omega) * x[1], (2.5e-5 + omega) * x[0] - 3.0e-5 * x[1], + 0.0, 0.0, 0.0, omega]) + + +A_RIGID = np.array([1.0e-3, -2.0e-3, 3.0e-3]) +OM_RIGID = np.array([1.0e-3, -5.0e-4, 2.0e-3]) + + +def rigid(x): + return np.concatenate([A_RIGID + np.cross(OM_RIGID, x), OM_RIGID]) + + +def zero(_x): + return np.zeros(6) + + +def make_locate(model): + """Exact inverse of the (affine) element maps of the plate, by the elements' own weights.""" + + records = [] + for element_id, element in sorted(model.mesh.elements.items()): + X = np.array([coords(model, n) for n in element.node_ids]) + p0 = element_interpolation_weights(element, (0.0, 0.0)) @ X + pa = element_interpolation_weights(element, (1.0, 0.0)) @ X + pb = element_interpolation_weights(element, (0.0, 1.0)) @ X + records.append((element_id, len(element.node_ids) == 3, p0, np.column_stack([pa - p0, pb - p0])[:2])) + + def locate(x): + hits = [] + for element_id, triangle, p0, A in records: + natural = np.linalg.solve(A, (x - p0)[:2]) + if triangle: + inside = natural.min() >= -1e-9 and natural.sum() <= 1.0 + 1e-9 + else: + inside = np.abs(natural).max() <= 1.0 + 1e-9 + if inside: + hits.append((element_id, tuple(float(v) for v in natural))) + return hits + + return locate + + +def box_mesh(n=2, nz=2, *, node_groups=None): + xs = np.linspace(0.0, 1.0, n + 1) + zs = np.linspace(-LZ / 2, LZ / 2, nz + 1) + index = lambda i, j, k: (k * (n + 1) + j) * (n + 1) + i # noqa: E731 + points = np.array([(xs[i], xs[j], zs[k]) for k in range(nz + 1) for j in range(n + 1) for i in range(n + 1)]) + cells = [] + for k, j, i in itertools.product(range(nz), range(n), range(n)): + for permutation in itertools.permutations(range(3)): + current, ids = [i, j, k], [index(i, j, k)] + for axis in permutation: + current[axis] += 1 + ids.append(index(*current)) + volume = np.linalg.det(points[ids[1:]] - points[ids[0]]) + if volume < 0.0: + ids[2], ids[3] = ids[3], ids[2] + cells.append(ids) + base = SolidMesh(points, cells) + groups = {} + for name, axis, value in (("xmin", 0, 0.0), ("xmax", 0, 1.0), ("ymin", 1, 0.0), ("ymax", 1, 1.0), + ("zmin", 2, -LZ / 2), ("zmax", 2, LZ / 2)): + mask = np.array([np.allclose(points[f][:, axis], value) for f in base.boundary_facets]) + groups[name] = base.boundary_ids[mask] + return SolidMesh(points, cells, boundary_facets=base.boundary_facets, boundary_ids=base.boundary_ids, + boundary_groups=groups, node_groups=node_groups) + + +@functools.lru_cache(maxsize=None) +def solid(order): + return anysolid_backend.prepare(box_mesh(), {"elastic_modulus": E, "poisson_ratio": NU}, order=order) + + +@functools.lru_cache(maxsize=None) +def solid_with_corner_node(): + return anysolid_backend.prepare(box_mesh(node_groups={"pt": [0]}), + {"elastic_modulus": E, "poisson_ratio": NU}, order=1) + + +class Proxy: + """Composition wrapper (PreparedSolid is immutable) overriding selected attributes.""" + + def __init__(self, base, **override): + self._base = base + self._override = override + + def __getattr__(self, name): + if name in self.__dict__.get("_override", {}): + return self._override[name] + return getattr(self._base, name) + + +def drive(order, field, groups=ALL, *, triangles=False, skin=None, cancel=None, prepared=None): + shell = shell_plate(2, triangles=triangles) + return solve_shell_driven_solid( + shell, nodal_vector(shell, field), prepared or solid(order), cut_groups=groups, + locate=make_locate(shell), skin_tractions=skin, cancel=cancel) + + +def code_of(call): + with pytest.raises(SolidSubmodelError) as info: + call() + return info.value.code + + +# ---------------------------------------------------------------------- +# independent rigid / affine P1 and P2 +# ---------------------------------------------------------------------- +@pytest.mark.parametrize("order", [1, 2]) +@pytest.mark.parametrize("triangles", [False, True]) +def test_rigid_shell_field_is_reproduced_with_zero_strain_and_interface_resultants(order, triangles): + result = drive(order, rigid, triangles=triangles) + prepared = solid(order) + expected = np.array([(A_RIGID + np.cross(OM_RIGID, x))[c] for x, c in + zip(prepared.coefficient_coordinates, prepared.coefficient_components)]) + assert np.max(np.abs(result.coefficients - expected)) <= 1.0e-12 + assert np.max(np.abs(result.recovery.strain)) <= 1.0e-12 + scale = E * 1.0e-3 + assert np.linalg.norm(result.interface_force) <= 1.0e-9 * scale + assert np.linalg.norm(result.interface_moment) <= 1.0e-9 * scale + cert = result.diagnostics["certification"] + assert cert["certified"] and cert["scaled_backward_error"] <= 1.0e-10 + expected_nodal = np.array([A_RIGID + np.cross(OM_RIGID, x) for x in prepared.mesh.coordinates]) + assert result.nodal_displacements.shape == (len(prepared.mesh.node_ids), 3) + assert np.max(np.abs(result.nodal_displacements - expected_nodal)) <= 1.0e-12 + + +@pytest.mark.parametrize("order", [1, 2]) +@pytest.mark.parametrize("triangles", [False, True]) +def test_affine_shell_field_gives_uniform_strain_and_stress(order, triangles): + result = drive(order, affine, triangles=triangles) + prepared = solid(order) + expected_u = np.array([affine(x)[c] for x, c in + zip(prepared.coefficient_coordinates, prepared.coefficient_components)]) + assert np.max(np.abs(result.coefficients - expected_u)) <= 1.0e-12 + eps = np.array([[1.0e-4, 2.5e-5, 0.0], [2.5e-5, -3.0e-5, 0.0], [0.0, 0.0, 0.0]]) + assert np.max(np.abs(result.recovery.strain - eps)) <= 1.0e-12 + lam = E * NU / ((1 + NU) * (1 - 2 * NU)) + mu = E / (2 * (1 + NU)) + sigma = lam * np.trace(eps) * np.eye(3) + 2 * mu * eps + assert np.max(np.abs(result.recovery.stress - sigma)) <= 1.0e-8 * np.max(np.abs(sigma)) + # A closed, uniformly stressed body: the interface resultant is zero but the faces carry load. + assert np.linalg.norm(result.interface_force) <= 1.0e-8 * np.max(np.abs(sigma)) + assert result.group_resultants["xmax"].force[0] > 0.0 > result.group_resultants["xmin"].force[0] + + +@pytest.mark.parametrize("order", [1, 2]) +def test_every_cut_dof_including_p2_midsides_is_driven_and_shared_dofs_are_deduplicated(order): + result = drive(order, affine) + prepared = solid(order) + union = np.unique(np.concatenate([prepared.boundary_dofs(g) for g in ALL])) + assert np.array_equal(result.prescribed_dofs, union) + total_listed = sum(len(prepared.boundary_dofs(g)) for g in ALL) + constraints = result.diagnostics["constraints"] + assert constraints["duplicate_dof_count"] == total_listed - union.size > 0 + assert constraints["prescribed_dofs"] == union.size + if order == 2: + vertices = len(prepared.mesh.coordinates) + assert prepared.ndof > 3 * vertices # midside coefficients exist and are all in the union + assert result.attribution_rule == ATTRIBUTION_RULE + assert result.shared_attribution + for dof, owners in result.shared_attribution.items(): + assert len(owners) >= 2 and set(owners) <= set(ALL) and dof in union + assert all(dof in prepared.boundary_dofs(g) for g in owners) + force = sum(g.force for g in result.group_resultants.values()) + moment = sum(g.moment for g in result.group_resultants.values()) + scale = np.max(np.abs(result.reactions)) + assert np.max(np.abs(force - result.interface_force)) <= 1.0e-9 * scale + assert np.max(np.abs(moment - result.interface_moment)) <= 1.0e-9 * scale + assert sum(g.shared_dof_count for g in result.group_resultants.values()) > 0 + + +# ---------------------------------------------------------------------- +# signed loads +# ---------------------------------------------------------------------- +@pytest.mark.parametrize("order", [1, 2]) +@pytest.mark.parametrize("traction", [(0.0, 0.0, -1.0e6), (2.0e5, -3.0e5, 5.0e5)]) +def test_skin_traction_is_balanced_by_the_signed_interface_resultants(order, traction): + t = np.asarray(traction) + result = drive(order, zero, LATERAL_AND_BOTTOM, skin={"zmax": t}) + centroid = np.array([0.5, 0.5, LZ / 2]) # unit-area top face + assert np.max(np.abs(result.skin_force - t)) <= 1.0e-9 * np.linalg.norm(t) + assert np.max(np.abs(result.interface_force + t)) <= 1.0e-8 * np.linalg.norm(t) + moment = np.cross(centroid, t) + assert np.max(np.abs(result.skin_moment - moment)) <= 1.0e-9 * np.linalg.norm(moment) + assert np.max(np.abs(result.interface_moment + moment)) <= 1.0e-8 * np.linalg.norm(moment) + # Reversing the load reverses the field and every resultant (linearity, sign). + reverse = drive(order, zero, LATERAL_AND_BOTTOM, skin={"zmax": -t}) + assert np.max(np.abs(reverse.coefficients + result.coefficients)) <= 1.0e-9 * np.max(np.abs(result.coefficients)) + assert np.max(np.abs(reverse.interface_force + result.interface_force)) <= 1.0e-8 * np.linalg.norm(t) + assert result.diagnostics["residual"]["force_balance_ratio"] <= 1.0e-6 + + +def _top_centre(prepared): + centre = [i for i, x in enumerate(prepared.mesh.coordinates) if np.allclose(x, (0.5, 0.5, LZ / 2))] + assert len(centre) == 1 + return centre[0] + + +def test_pressure_like_traction_has_physical_sign_work_balance_and_reversal(): + # Evidence solver-solid-01 (kept): the former assertion |ux| < 1e-6 |uz| at the top centre failed + # on this Kuhn mesh (ux ~ 8.04e-8 vs |uz| ~ 6.70e-7). Kuhn tetrahedra are not mirror-symmetric + # about x = 0.5, so a zero lateral displacement is not guaranteed; that assertion was invalid. + prepared = solid(1) + load = np.array([0.0, 0.0, -1.0e6]) + result = drive(1, zero, LATERAL_AND_BOTTOM, skin={"zmax": load}) + centre = _top_centre(prepared) + assert result.nodal_displacements[centre, 2] < 0.0 # moves in the loaded direction + top = [i for i, x in enumerate(prepared.mesh.coordinates) if np.isclose(x[2], LZ / 2)] + assert np.mean(result.nodal_displacements[top, 2]) < 0.0 + # External work f.q equals twice the strain energy q.K.q (zero prescribed values) and is positive. + f = np.asarray(prepared.traction("zmax", load)) + q = result.coefficients + work = float(f @ q) + energy2 = float(q @ (prepared.assemble_linear() @ q)) + assert work > 0.0 and energy2 > 0.0 + assert work == pytest.approx(energy2, rel=1.0e-6) + # Balance from the total applied load (unit-area face), independent of the solver's own sums. + assert np.max(np.abs(result.skin_force - load)) <= 1.0e-9 * np.linalg.norm(load) + summed = np.array([result.reactions[prepared.coefficient_components[result.prescribed_dofs] == c].sum() + for c in range(3)]) + assert np.max(np.abs(summed + load)) <= 1.0e-8 * np.linalg.norm(load) + # Reversal flips the displacement, the work keeps its sign. + reverse = drive(1, zero, LATERAL_AND_BOTTOM, skin={"zmax": -load}) + assert reverse.nodal_displacements[centre, 2] > 0.0 + assert np.max(np.abs(reverse.coefficients + q)) <= 1.0e-9 * np.max(np.abs(q)) + assert float(-f @ reverse.coefficients) == pytest.approx(work, rel=1.0e-6) + + +def test_vertical_load_is_symmetric_under_the_x_y_swap_of_the_kuhn_mesh(): + # The Kuhn subdivision (all six axis permutations per cell) is invariant under x <-> y, so the + # top-centre lateral displacement must have equal x and y components. (It is not mirror + # symmetric under x -> 1 - x, hence no zero-ux claim.) + prepared = solid(1) + result = drive(1, zero, LATERAL_AND_BOTTOM, skin={"zmax": (0.0, 0.0, -1.0e6)}) + ux, uy, uz = result.nodal_displacements[_top_centre(prepared)] + assert abs(ux - uy) <= 1.0e-5 * abs(uz) + + +# ---------------------------------------------------------------------- +# bending / rotation correction (hand-derived centroid values) +# ---------------------------------------------------------------------- +AMP = 1.0e-3 + + +def single(element_factory, nodes, rows): + model = FEModel("single") + model.add_material("steel", E, NU, density=7850.0) + for node, xyz in enumerate(nodes, start=1): + model.add_node(node, *xyz) + model.add_element(1, element_factory(tuple(range(1, len(nodes) + 1)))) + u = np.zeros(model.mesh.dof_manager.total_dofs) + for node, six in enumerate(rows, start=1): + u[model.mesh.dof_manager.get_node_dofs(node)] = AMP * np.asarray(six, dtype=float) + return model, u + + +def triangle(rows): + return single( + lambda ids: NativeParityE4PLS3V2DShellElement(1, ids, "steel", thickness=T, reference_normal=(0.0, 0.0, 1.0)), + [(0, 0, 0), (1, 0, 0), (0, 1, 0)], rows) + + +def test_v2d_min3_twist_correction_at_the_centroid(): + # w = x*y: nodal w = 0, rotations (theta_x, theta_y) = (w_y, -w_x). Exact w(1/3,1/3) = 1/9. + model, u = triangle([(0,) * 6, (0, 0, 0, 1, 0, 0), (0, 0, 0, 0, -1, 0)]) + value = evaluate_shell_displacement(model, u, [(1, (1 / 3, 1 / 3))], (1 / 3, 1 / 3, 0.0)) + assert value.value[2] == pytest.approx(AMP / 9, rel=1e-12) + # The interpolated nodal w is 0: the MIN3 term replaces it by 1/9. + assert value.transverse_correction == pytest.approx(AMP / 9, rel=1e-12) + assert np.max(np.abs(value.value[:2])) <= 1e-18 + + +def test_v2d_min3_curvature_correction_at_the_centroid(): + # w = x^2: nodal w = (0, 1, 0), theta_y = -w_x = (0, -2, 0). Exact 1/9; interpolated nodal w 1/3. + model, u = triangle([(0,) * 6, (0, 0, 1, 0, -2, 0), (0,) * 6]) + value = evaluate_shell_displacement(model, u, [(1, (1 / 3, 1 / 3))], (1 / 3, 1 / 3, 0.0)) + assert value.value[2] == pytest.approx(AMP / 9, rel=1e-12) + assert value.transverse_correction == pytest.approx(-2 * AMP / 9, rel=1e-12) + + +def test_v2d_transverse_term_leaves_the_normal_offset_rotation_transport(): + # Constant nodal rotation about x (zero translations), target 5 mm above the reference + # point: the lever arm to every node is (x - X_i), so the displacement is theta x (x - p) + # = theta x (0, 0, 0.005) and the MIN3 correction (sum l_i = 0) vanishes. + model, u = triangle([(0, 0, 0, 1, 0, 0)] * 3) + value = evaluate_shell_displacement(model, u, [(1, (0.2, 0.3))], (0.2, 0.3, 0.005)) + expected = AMP * np.cross([1.0, 0.0, 0.0], [0.0, 0.0, 0.005]) + assert np.max(np.abs(value.value - expected)) <= 1e-15 + assert value.transverse_correction == pytest.approx(0.0, abs=1e-18) + assert value.normal_offset == pytest.approx(0.005) + + +def quad(rows): + return single( + lambda ids: create_shell_element(1, list(ids), "steel", thickness=T), + [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], rows) + + +def reference_point(model): + element = model.mesh.elements[1] + natural = (0.0, 0.0) if len(element.node_ids) == 4 else (1 / 3, 1 / 3) + X = np.array([coords(model, n) for n in element.node_ids]) + return natural, element_interpolation_weights(element, natural) @ X + + +def test_q4_varying_drilling_rotation_does_not_displace_the_midsurface_centre(): + # theta_z = 1 only at the origin node: the centre translation and the centre in-plane + # displacement are exactly zero (interpolated translation 0, lever arm 0). + model, u = quad([(0, 0, 0, 0, 0, 1), (0,) * 6, (0,) * 6, (0,) * 6]) + natural, centre = reference_point(model) + value = evaluate_shell_displacement(model, u, [(1, natural)], centre) + assert np.array_equal(value.value[:2], np.zeros(2)) + assert value.normal_offset == 0.0 + + +def test_v2d_varying_drilling_rotation_does_not_displace_the_midsurface_centroid(): + model, u = triangle([(0, 0, 0, 0, 0, 1), (0,) * 6, (0,) * 6]) + natural, centroid = reference_point(model) + value = evaluate_shell_displacement(model, u, [(1, natural)], centroid) + assert np.array_equal(value.value[:2], np.zeros(2)) + + +def test_q4_signed_face_offset_with_varying_bending(): + # Mean translation (1,1,1) and mean rotation (1,1,1) (nodal values 4x on three nodes). + rows = [(4, 0, 0, 4, 0, 0), (0, 4, 0, 0, 4, 0), (0, 0, 4, 0, 0, 4), (0,) * 6] + model, u = quad(rows) + natural, centre = reference_point(model) + for h in (0.005, -0.005, 0.0): + value = evaluate_shell_displacement(model, u, [(1, natural)], centre + [0.0, 0.0, h]) + # u = u_ref + theta_bar x (0, 0, h) = (1 + h, 1 - h, 1) + assert np.max(np.abs(value.value - AMP * np.array([1.0 + h, 1.0 - h, 1.0]))) <= 1e-15 + assert value.normal_offset == pytest.approx(h) + + +def test_v2d_signed_face_offset_with_varying_bending(): + # Mean in-plane translation (1,1) and mean rotation (1,1,1); the normal part is the MIN3 w. + rows = [(3, 0, 0, 3, 0, 0), (0, 3, 0, 0, 3, 0), (0, 0, 0, 0, 0, 3)] + model, u = triangle(rows) + natural, centroid = reference_point(model) + mid = evaluate_shell_displacement(model, u, [(1, natural)], centroid) + for h in (0.005, -0.005): + value = evaluate_shell_displacement(model, u, [(1, natural)], centroid + [0.0, 0.0, h]) + assert np.max(np.abs(value.value[:2] - AMP * np.array([1.0 + h, 1.0 - h]))) <= 1e-15 + assert value.value[2] == pytest.approx(mid.value[2], abs=1e-18) # (theta x e_z) has no z part + assert value.normal_offset == pytest.approx(h) + assert np.max(np.abs(mid.value[:2] - AMP)) <= 1e-15 + + +def test_q4_represents_twist_exactly_without_correction(): + # Unit square, w = x*y: centre value 1/4 through the nodal transport alone. + model, u = single( + lambda ids: create_shell_element(1, list(ids), "steel", thickness=T), + [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], + [(0,) * 6, (0, 0, 0, 1, 0, 0), (0, 0, 1, 1, -1, 0), (0, 0, 0, 0, -1, 0)]) + value = evaluate_shell_displacement(model, u, [(1, (0.0, 0.0))], (0.5, 0.5, 0.0)) + assert value.value[2] == pytest.approx(AMP / 4, rel=1e-12) + assert value.transverse_correction == 0.0 + + +# ---------------------------------------------------------------------- +# refusals: source, locate, prepared, solve +# ---------------------------------------------------------------------- +def test_source_refusals(): + plate = shell_plate(1) + u = nodal_vector(plate, rigid) + bad = u.copy() + bad[0] = np.nan + hits = [(1, (0.0, 0.0))] + target = (0.5, 0.5, 0.0) + assert code_of(lambda: evaluate_shell_displacement(plate, bad, hits, target)) == "SOURCE_INVALID" + assert code_of(lambda: evaluate_shell_displacement(plate, u[:-1], hits, target)) == "SOURCE_INVALID" + assert code_of(lambda: evaluate_shell_displacement(object(), u, hits, target)) == "SOURCE_INVALID" + assert code_of(lambda: evaluate_shell_displacement(plate, u, [(99, (0.0, 0.0))], target)) == "SOURCE_ELEMENT_MISSING" + + legacy = FEModel("legacy") + legacy.add_material("steel", E, NU, density=7850.0) + for node, xyz in enumerate([(0, 0, 0), (1, 0, 0), (0, 1, 0)], start=1): + legacy.add_node(node, *xyz) + legacy.add_element(1, ShellElement(1, [1, 2, 3], "steel", thickness=T)) + assert code_of(lambda: evaluate_shell_displacement( + legacy, np.zeros(18), [(1, (0.2, 0.2))], (0.2, 0.2, 0.0))) == "SOURCE_ELEMENT_NOT_ADMITTED" + + warped = FEModel("warped") + warped.add_material("steel", E, NU, density=7850.0) + for node, xyz in enumerate([(0, 0, 0), (1, 0, 0), (1, 1, 0.3), (0, 1, 0)], start=1): + warped.add_node(node, *xyz) + warped.add_element(1, create_shell_element(1, [1, 2, 3, 4], "steel", thickness=T)) + assert code_of(lambda: evaluate_shell_displacement( + warped, np.zeros(24), [(1, (0.0, 0.0))], (0.5, 0.5, 0.0))) == "SOURCE_ELEMENT_INVALID" + + +def test_inconsistently_constrained_source_is_refused(): + plate = shell_plate(1, membrane=True) # uz = rx = ry = 0 supports + code = code_of(lambda: evaluate_shell_displacement( + plate, nodal_vector(plate, rigid), [(1, (0.0, 0.0))], (0.5, 0.5, 0.0))) + assert code == "SOURCE_CONSTRAINT_INCONSISTENT" + # A field that honours the supports is accepted. + ok = evaluate_shell_displacement(plate, nodal_vector(plate, affine), [(1, (0.0, 0.0))], (0.5, 0.5, 0.0)) + assert np.all(np.isfinite(ok.value)) + + +def test_locate_hits_must_agree_and_lie_inside(): + plate = shell_plate(2) + rng = np.random.default_rng(3) + u = rng.normal(scale=1.0e-3, size=plate.mesh.dof_manager.total_dofs) + target = (0.25, 0.25, 0.0) + # Conforming Q4s share both translations and rotations along their entire edge. + shared = evaluate_shell_displacement(plate, u, [(1, (1., 0.)), (2, (-1., 0.))], (.5, .25, 0.)) + assert shared.hits == 2 and shared.hit_spread <= 1e-15 + # An overlapping, disconnected sheet can have a different physical displacement. + duplicate = shell_plate(1) + for node in range(1, 5): + duplicate.add_node(node + 4, *coords(duplicate, node)) + duplicate.add_element(2, create_shell_element(2, [5, 6, 8, 7], "steel", thickness=T)) + separate = np.zeros(duplicate.mesh.dof_manager.total_dofs) + for node in range(5, 9): + separate[duplicate.mesh.dof_manager.get_node_dofs(node)[0]] = 0.01 + assert code_of(lambda: evaluate_shell_displacement( + duplicate, separate, [(1, (0., 0.)), (2, (0., 0.))], (.5, .5, 0.))) == "LOCATE_HITS_DISAGREE" + assert code_of(lambda: evaluate_shell_displacement( + plate, u, [(1, (1.5, 0.0))], target)) == "LOCATE_NATURAL_OUTSIDE" + # Conforming hits on a shared edge of a smooth field agree and are reported. + smooth = nodal_vector(plate, rigid) + both = evaluate_shell_displacement(plate, smooth, [(1, (1.0, 0.0)), (2, (-1.0, 0.0))], (0.5, 0.25, 0.0)) + assert both.hits == 2 and both.hit_spread <= 1.0e-15 + + +def _rotation(axis, angle): + axis = np.asarray(axis, dtype=float) + axis = axis / np.linalg.norm(axis) + K = np.array([[0.0, -axis[2], axis[1]], [axis[2], 0.0, -axis[0]], [-axis[1], axis[0], 0.0]]) + return np.eye(3) + np.sin(angle) * K + (1.0 - np.cos(angle)) * (K @ K) + + +def _tilted(triangle_element, shift=(0.0, 0.0, 0.0)): + """Unit facet rotated out of the xy plane (and shifted); returns model, u, unit normal, centre.""" + + R = _rotation((1.0, 2.0, 0.5), 0.7) + normal = R @ np.array([0.0, 0.0, 1.0]) + shift = np.asarray(shift, dtype=float) + local = [(0, 0, 0), (1, 0, 0), (0, 1, 0)] if triangle_element else [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)] + nodes = [tuple(R @ np.asarray(p, dtype=float) + shift) for p in local] + if triangle_element: + # Use the effective facet built from the stored world coordinates. At a large + # origin, subtracting rounded points perturbs the nominal analytic director. + normal = np.cross(np.subtract(nodes[1], nodes[0]), np.subtract(nodes[2], nodes[0])) + normal /= np.linalg.norm(normal) + factory = lambda ids: NativeParityE4PLS3V2DShellElement( # noqa: E731 + 1, ids, "steel", thickness=T, reference_normal=tuple(normal)) + else: + factory = lambda ids: create_shell_element(1, list(ids), "steel", thickness=T) # noqa: E731 + rng = np.random.default_rng(11) + model, u = single(factory, nodes, rng.normal(size=(len(nodes), 6))) + return model, u, normal + + +@pytest.mark.parametrize("triangle_element", [False, True]) +@pytest.mark.parametrize("shift", [(0.0, 0.0, 0.0), (1.0e6, -2.0e6, 3.0e6)]) +def test_tilted_large_coordinate_signed_normal_offset_is_admitted_and_tangential_forgery_refused( + triangle_element, shift): + model, u, normal = _tilted(triangle_element, shift) + natural, centre = reference_point(model) + tangent = np.cross(normal, [0.0, 0.0, 1.0]) + tangent /= np.linalg.norm(tangent) + # Any signed normal offset (thickness-like or large) stays admissible and finite. + for h in (0.0, 0.005, -0.005, 0.3, -2.0): + value = evaluate_shell_displacement(model, u, [(1, natural)], centre + h * normal) + assert np.all(np.isfinite(value.value)) + assert value.normal_offset == pytest.approx(h, abs=1.0e-6) + # A tangential displacement of the target far above roundoff is a forged pairing. + for sign in (1.0, -1.0): + for lateral in (1.0e-3, 2.0): + with pytest.raises(SolidSubmodelError) as info: + evaluate_shell_displacement( + model, u, [(1, natural)], centre + 0.005 * normal + sign * lateral * tangent) + assert info.value.code == "LOCATE_TANGENTIAL_MISMATCH" + assert info.value.details["tangential_residual"] == pytest.approx(lateral, rel=1.0e-3) + assert info.value.details["allowed"] < 1.0e-6 * max(1.0, abs(shift[0]) / 1.0e6) + + +def test_tangential_forgery_is_refused_for_primary_and_shared_hits_through_the_public_evaluator(): + plate = shell_plate(2) + u = nodal_vector(plate, rigid) + # Valid natural point of element 2, but 0.5 away tangentially from the target. + assert code_of(lambda: evaluate_shell_displacement( + plate, u, [(2, (0.0, 0.0))], (0.25, 0.25, 0.0))) == "LOCATE_TANGENTIAL_MISMATCH" + # Target 2 m from a perfectly valid natural point of element 1. + assert code_of(lambda: evaluate_shell_displacement( + plate, u, [(1, (0.0, 0.0))], (2.25, 0.25, 0.0))) == "LOCATE_TANGENTIAL_MISMATCH" + # Honest primary hit, forged shared (second / third) hit: the rigid field would make the + # values agree, so only the geometric check can refuse it. + honest = [(1, (1.0, 0.0)), (2, (-1.0, 0.0))] + target = (0.5, 0.25, 0.0) + assert evaluate_shell_displacement(plate, u, honest, target).hits == 2 + assert code_of(lambda: evaluate_shell_displacement( + plate, u, honest + [(4, (0.0, 0.0))], target)) == "LOCATE_TANGENTIAL_MISMATCH" + assert code_of(lambda: evaluate_shell_displacement( + plate, u, [honest[0], (2, (0.0, 0.0))], target)) == "LOCATE_TANGENTIAL_MISMATCH" + # The refusal carries the diagnostic. + with pytest.raises(SolidSubmodelError) as info: + evaluate_shell_displacement(plate, u, [(2, (0.0, 0.0))], (0.25, 0.25, 0.0)) + assert info.value.details["element_id"] == 2 + assert info.value.details["tangential_residual"] == pytest.approx(0.5) + assert info.value.details["allowed"] < 1.0e-6 + # Large signed normal offsets over the honest correspondence remain admissible. + for h in (0.005, -0.005, 0.5): + assert evaluate_shell_displacement(plate, u, [(1, (0.0, 0.0))], (0.25, 0.25, h)).normal_offset \ + == pytest.approx(h) + + +def test_forged_locator_is_refused_by_the_solve(): + shell = shell_plate(2) + u = nodal_vector(shell, rigid) + honest = make_locate(shell) + + def forged(x): + hits = list(honest(x)) + if np.allclose(x, (0.0, 0.0, 0.0)): + return [(2, (0.0, 0.0))] # valid natural point, 0.75 m away tangentially + return hits + + assert code_of(lambda: solve_shell_driven_solid( + shell, u, solid(1), cut_groups=ALL, locate=forged)) == "LOCATE_TANGENTIAL_MISMATCH" + + +def test_locate_failures(): + shell = shell_plate(2) + u = nodal_vector(shell, zero) + run = lambda locate: solve_shell_driven_solid( # noqa: E731 + shell, u, solid(1), cut_groups=["xmin"], locate=locate) + assert code_of(lambda: run(lambda x: [])) == "LOCATE_MISS" + assert code_of(lambda: run(lambda x: 7)) == "LOCATE_INVALID" + assert code_of(lambda: run(lambda x: [(True, (0.0, 0.0))])) == "LOCATE_INVALID" + assert code_of(lambda: run(lambda x: [(1, (np.nan, 0.0))])) == "LOCATE_INVALID" + + def boom(x): + raise RuntimeError("host failure") + + assert code_of(lambda: run(boom)) == "LOCATE_FAILED" + + +def test_prepared_and_argument_refusals(): + shell = shell_plate(2) + u = nodal_vector(shell, zero) + locate = make_locate(shell) + run = lambda prepared, **kw: solve_shell_driven_solid( # noqa: E731 + shell, u, prepared, cut_groups=kw.pop("cut_groups", ["xmin"]), locate=locate, **kw) + prepared = solid(1) + assert code_of(lambda: run(object())) == "PREPARED_INVALID" + bad_components = prepared.coefficient_components.copy() + bad_components[0] = 5 + assert code_of(lambda: run(Proxy(prepared, coefficient_components=bad_components))) == "PREPARED_INVALID" + assert code_of(lambda: run(prepared, cut_groups=["nope"])) == "CUT_GROUP_INVALID" + assert code_of(lambda: run(prepared, cut_groups=[])) == "CUT_GROUP_INVALID" + assert code_of(lambda: run(prepared, cut_groups="xmin")) == "CUT_GROUP_INVALID" + assert code_of(lambda: run(prepared, cut_groups=["xmin", "xmin"])) == "CUT_GROUP_INVALID" + assert code_of(lambda: run(prepared, skin_tractions={"xmin": (0, 0, 1)})) == "SKIN_INVALID" # also a cut group + assert code_of(lambda: run(prepared, skin_tractions={"nope": (0, 0, 1)})) == "SKIN_INVALID" + assert code_of(lambda: run(prepared, skin_tractions={"zmax": (0, 0, np.inf)})) == "SKIN_INVALID" + assert code_of(lambda: run(prepared, skin_tractions={"zmax": (0, 0)})) == "SKIN_INVALID" + assert code_of(lambda: run(prepared, cancel=42)) == "CANCEL_INVALID" + assert code_of(lambda: solve_shell_driven_solid( + shell, u, prepared, cut_groups=["xmin"], locate="not callable")) == "LOCATE_INVALID" + + +def test_singular_and_nonfinite_operators_are_refused(): + # A single driven vertex leaves rigid rotations free. + prepared = solid_with_corner_node() + shell = shell_plate(2) + code = code_of(lambda: solve_shell_driven_solid( + shell, nodal_vector(shell, zero), prepared, cut_groups=["pt"], locate=make_locate(shell))) + assert code == "UNDERCONSTRAINED" + + base = solid(1) + interior = next(i for i, x in enumerate(base.coefficient_coordinates) if np.allclose(x, (0.5, 0.5, 0.0))) + K = base.assemble_linear().tolil() + K[interior, :] = 0.0 + K[:, interior] = 0.0 + assert code_of(lambda: drive(1, zero, prepared=Proxy(base, assemble_linear=lambda: K.tocsr()))) == "SOLVE_SINGULAR" + + nan_K = base.assemble_linear() + nan_K.data[0] = np.nan + assert code_of(lambda: drive(1, zero, prepared=Proxy(base, assemble_linear=lambda: nan_K))) \ + == "PREPARED_OPERATOR_INVALID" + + +def test_cancellation_returns_no_result(): + with pytest.raises(SolidSubmodelCancelled): + drive(1, rigid, cancel=lambda: True) + + class Flag: + def __init__(self): + self.value = False + + def is_set(self): + return self.value + + flag = Flag() + flag.value = True + with pytest.raises(SolidSubmodelCancelled): + drive(1, rigid, cancel=flag) + + calls = {"n": 0} + + def late(): + calls["n"] += 1 + return calls["n"] > 25 # after the cut groups are resolved, while evaluating the shell field + + with pytest.raises(SolidSubmodelCancelled) as info: + drive(1, rigid, cancel=late) + assert info.value.code == "CANCELLED" and calls["n"] > 25 + # An un-triggered probe changes nothing. + result = drive(1, rigid, cancel=lambda: False) + assert result.diagnostics["certification"]["certified"] From 95c6a8d32070ec011f8e32d96d6f100829371dc9 Mon Sep 17 00:00:00 2001 From: Audun Arnesen Nyhus Date: Tue, 10 Nov 2026 23:36:35 +0100 Subject: [PATCH 2/3] Exercise the rejected S3 source through the public legacy factory --- tests/test_solid_submodel.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_solid_submodel.py b/tests/test_solid_submodel.py index ea820906e..bdb025b5d 100644 --- a/tests/test_solid_submodel.py +++ b/tests/test_solid_submodel.py @@ -19,7 +19,7 @@ from anysolid.mesh import SolidMesh # noqa: E402 from anysolver.e4_pl_s3_v2d_element import NativeParityE4PLS3V2DShellElement # noqa: E402 -from anysolver.elements import ShellElement, create_shell_element # noqa: E402 +from anysolver.elements import create_shell_element # noqa: E402 from anysolver.fe_core import FEModel # noqa: E402 from anysolver import BoundaryCondition # noqa: E402 from anysolver.solid_submodel import ( # noqa: E402 @@ -458,7 +458,7 @@ def test_source_refusals(): legacy.add_material("steel", E, NU, density=7850.0) for node, xyz in enumerate([(0, 0, 0), (1, 0, 0), (0, 1, 0)], start=1): legacy.add_node(node, *xyz) - legacy.add_element(1, ShellElement(1, [1, 2, 3], "steel", thickness=T)) + legacy.add_element(1, create_shell_element(1, [1, 2, 3], "steel", thickness=T, formulation="legacy-s3")) assert code_of(lambda: evaluate_shell_displacement( legacy, np.zeros(18), [(1, (0.2, 0.2))], (0.2, 0.2, 0.0))) == "SOURCE_ELEMENT_NOT_ADMITTED" From adb0d6ac775d5c266a083e4ffa1bd86b6e7b6ea2 Mon Sep 17 00:00:00 2001 From: Audun Arnesen Nyhus Date: Wed, 11 Nov 2026 00:04:39 +0100 Subject: [PATCH 3/3] Bind the guarded ANYsolid checkout in the CI dependency contract --- tests/test_anyfileio_version_compatibility.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/tests/test_anyfileio_version_compatibility.py b/tests/test_anyfileio_version_compatibility.py index 7114a7238..ad04be99a 100644 --- a/tests/test_anyfileio_version_compatibility.py +++ b/tests/test_anyfileio_version_compatibility.py @@ -403,6 +403,7 @@ def test_workflows_pin_compatibility_graph_and_actions() -> None: "ebbe0e3b500a3f0cfcc62059c3dac4b0ac178b6c", "b6f7cf466865b1c4c34b8e5511ace97d00290f6c", "32f3bb65e3843d6fd7af6c4fdf76ce472a7f6555", + "06f3276d9207376316502aca651c3455db984104", } assert set(re.findall(r"\b[0-9a-f]{40}\b", publish)) == { "11d5960a326750d5838078e36cf38b85af677262", @@ -434,8 +435,20 @@ def action_sequence(block: str) -> list[str]: assert action_sequence(job_block(ci, "license")) == [checkout_ref, setup_ref] assert action_sequence(job_block(ci, "resolver")) == [checkout_ref, setup_ref] + pytest_block = job_block(ci, "pytest") + assert action_sequence(pytest_block) == [checkout_ref] * 5 + [setup_ref, checkout_ref] + solid_condition = " if: matrix.shard-index == 0 && matrix.subshard-index == 0\n" + assert pytest_block.count(solid_condition) == 2 + solid_checkout = ( + f" - uses: {checkout_ref}\n" + solid_condition + + " with:\n" + " repository: audunarn/ANYsolid\n" + " ref: 06f3276d9207376316502aca651c3455db984104\n" + " path: .ecosystem/ANYsolid\n" + " persist-credentials: false\n" + ) + assert pytest_block.count(solid_checkout) == 1 for name in ( - "pytest", "anymesher-compatibility", "anyfileio-compatibility", "wheel", @@ -549,7 +562,6 @@ def action_sequence(block: str) -> list[str]: block = job_block(ci, name) assert checkout_pattern.findall(block) == current_checkouts assert block.count(checkout_ref) == 5 - pytest_block = job_block(ci, "pytest") numba_block = job_block(ci, "numba") numba_test_install = 'python -m pip install -e ".[dev,numba]"' assert pytest_block.count(numba_test_install) == 1