zero-mech 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {zero_mech-0.2.0/src/zero_mech.egg-info → zero_mech-0.3.0}/PKG-INFO +1 -1
  2. {zero_mech-0.2.0 → zero_mech-0.3.0}/pyproject.toml +2 -2
  3. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech/__init__.py +7 -1
  4. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech/active.py +38 -0
  5. zero_mech-0.3.0/src/zero_mech/material.py +160 -0
  6. zero_mech-0.3.0/src/zero_mech/thick_wall.py +398 -0
  7. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech/ventricle.py +12 -6
  8. {zero_mech-0.2.0 → zero_mech-0.3.0/src/zero_mech.egg-info}/PKG-INFO +1 -1
  9. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech.egg-info/SOURCES.txt +3 -0
  10. {zero_mech-0.2.0 → zero_mech-0.3.0}/tests/test_experiments.py +31 -0
  11. zero_mech-0.3.0/tests/test_material.py +140 -0
  12. zero_mech-0.3.0/tests/test_thick_wall.py +221 -0
  13. zero_mech-0.2.0/src/zero_mech/material.py +0 -91
  14. {zero_mech-0.2.0 → zero_mech-0.3.0}/LICENSE +0 -0
  15. {zero_mech-0.2.0 → zero_mech-0.3.0}/README.md +0 -0
  16. {zero_mech-0.2.0 → zero_mech-0.3.0}/setup.cfg +0 -0
  17. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech/atoms.py +0 -0
  18. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech/compressibility.py +0 -0
  19. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech/experiments.py +0 -0
  20. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech/model.py +0 -0
  21. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech/viscosity.py +0 -0
  22. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech.egg-info/dependency_links.txt +0 -0
  23. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech.egg-info/entry_points.txt +0 -0
  24. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech.egg-info/not-zip-safe +0 -0
  25. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech.egg-info/requires.txt +0 -0
  26. {zero_mech-0.2.0 → zero_mech-0.3.0}/src/zero_mech.egg-info/top_level.txt +0 -0
  27. {zero_mech-0.2.0 → zero_mech-0.3.0}/tests/test_ventricle.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zero_mech
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A zero-dimensional mechanics solver
5
5
  Author-email: Henrik Finsberg <henriknf@simula.no>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "zero_mech"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "A zero-dimensional mechanics solver"
9
9
  authors = [{name = "Henrik Finsberg", email = "henriknf@simula.no"}]
10
10
  license = {text = "MIT"}
@@ -158,7 +158,7 @@ tag = true
158
158
  sign_tags = false
159
159
  tag_name = "v{new_version}"
160
160
  tag_message = "Bump version: {current_version} → {new_version}"
161
- current_version = "0.2.0"
161
+ current_version = "0.3.0"
162
162
 
163
163
 
164
164
  [[tool.bumpversion.files]]
@@ -4,9 +4,11 @@ from . import compressibility
4
4
  from . import model
5
5
  from .model import Model
6
6
  from . import active
7
- from .active import ActiveStress
7
+ from .active import ActiveStress, StretchActiveStress
8
8
  from . import ventricle
9
9
  from .ventricle import SphericalVentricle, TriSeg
10
+ from . import thick_wall
11
+ from .thick_wall import ThickCylinder, ThickSphere
10
12
 
11
13
 
12
14
  __all__ = [
@@ -17,7 +19,11 @@ __all__ = [
17
19
  "Model",
18
20
  "active",
19
21
  "ActiveStress",
22
+ "StretchActiveStress",
20
23
  "ventricle",
21
24
  "SphericalVentricle",
22
25
  "TriSeg",
26
+ "thick_wall",
27
+ "ThickCylinder",
28
+ "ThickSphere",
23
29
  ]
@@ -12,6 +12,10 @@ class ActiveStress(AbstractStrainEnergy):
12
12
  Piola-Kirchhoff stress it adds is :math:`T_a \\, f_0 \\otimes f_0`. For a
13
13
  fibre stretch :math:`\\lambda` the first Piola-Kirchhoff stress along the
14
14
  fibre is :math:`T_a \\lambda` and the Cauchy stress :math:`T_a \\lambda^2 / J`.
15
+
16
+ This is the ``invariant`` formulation of ``pulse.ActiveStress``. See
17
+ :class:`StretchActiveStress` for the ``stretch`` formulation, whose stress
18
+ is smaller by a factor of :math:`\\lambda`.
15
19
  """
16
20
 
17
21
  Ta: sp.Symbol = sp.Symbol("Ta")
@@ -30,6 +34,40 @@ class ActiveStress(AbstractStrainEnergy):
30
34
  return "Ta / 2 * (I4f - 1)"
31
35
 
32
36
 
37
+ @dataclass(slots=True, frozen=True)
38
+ class StretchActiveStress(AbstractStrainEnergy):
39
+ """An active tension along the fibres that is a nominal stress, as a strain energy.
40
+
41
+ The energy is :math:`T_a (\\lambda - 1)`, with :math:`\\lambda = \\sqrt{I_{4f}}`
42
+ the fibre stretch, so that the second Piola-Kirchhoff stress it adds is
43
+ :math:`\\frac{T_a}{\\lambda} f_0 \\otimes f_0` and the first Piola-Kirchhoff
44
+ stress is :math:`T_a \\, F f_0 \\otimes f_0 / |F f_0|`. The force per unit
45
+ reference area along the fibre is therefore :math:`T_a` at any stretch, and the
46
+ Cauchy stress along the fibre is :math:`T_a \\lambda / J`.
47
+
48
+ This is the ``stretch`` formulation of ``pulse.ActiveStress``, the normalisation
49
+ of Regazzoni and Quarteroni (2021), under which the active stiffness of a
50
+ force-generation model and its tension refer to the same stretch.
51
+ :class:`ActiveStress` is the ``invariant`` formulation, whose stress is larger
52
+ by a factor of :math:`\\lambda`.
53
+ """
54
+
55
+ Ta: sp.Symbol = sp.Symbol("Ta")
56
+ f0: sp.Matrix = field(default_factory=lambda: sp.Matrix([1, 0, 0]))
57
+
58
+ def strain_energy(self, F: sp.Matrix) -> sp.Expr:
59
+ f = F @ self.f0
60
+ I4f = f.T.dot(f)
61
+ return self.Ta * (sp.sqrt(I4f) - 1)
62
+
63
+ def default_parameters(self):
64
+ return {self.Ta: 0.0}
65
+
66
+ @staticmethod
67
+ def str() -> str:
68
+ return "Ta * (sqrt(I4f) - 1)"
69
+
70
+
33
71
  @dataclass(slots=True, frozen=True)
34
72
  class ActiveStrain:
35
73
  γ: sp.Symbol = sp.Symbol("γ")
@@ -0,0 +1,160 @@
1
+ import logging
2
+ from dataclasses import dataclass, field
3
+ import sympy as sp
4
+ from mpmath.libmp import prec_to_dps
5
+ from sympy.printing.numpy import NumPyPrinter
6
+ from sympy.printing.pycode import MpmathPrinter
7
+
8
+ from .atoms import AbstractStrainEnergy
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ @dataclass(slots=True, frozen=True)
14
+ class NeoHookean(AbstractStrainEnergy):
15
+ mu: sp.Symbol = sp.Symbol("mu")
16
+
17
+ def strain_energy(self, F: sp.Matrix) -> sp.Expr:
18
+ C = F.T @ F
19
+ I1 = sp.trace(C)
20
+ return self.mu / 2 * (I1 - 3)
21
+
22
+ def default_parameters(self):
23
+ return {self.mu: 15.0}
24
+
25
+ @staticmethod
26
+ def str() -> str:
27
+ return "μ / 2 * (I1 - 3)"
28
+
29
+
30
+ # class LinearElastic(AbstractStrainEnergy):
31
+ # mu: sp.Symbol = sp.Symbol("mu")
32
+ # lmbda: sp.Symbol = sp.Symbol("lmbda")
33
+
34
+ # def strain_energy(self, F: sp.Matrix) -> sp.Expr:
35
+ # C = F.T @ F
36
+ # I1 = sp.trace(C)
37
+
38
+
39
+ #: Below this magnitude an exponent ``b`` of :class:`HolzapfelOgden` is taken as zero, as in pulse
40
+ B_ZERO = 1e-10
41
+
42
+
43
+ class expm1_div(sp.Function):
44
+ """``(exp(b x) - 1) / b``, continued by its limit ``x`` where ``|b| <= B_ZERO``.
45
+
46
+ Called as ``expm1_div(b, x)``. A function rather than a ``Piecewise`` in ``b``, so
47
+ that expressions stay free of conditions on the parameters: ``sympy.solve`` cannot
48
+ convert a solution whose ``Piecewise`` conditions combine into an ``And`` to floats.
49
+ With a number for ``b`` it evaluates to ``x`` or to the exponential expression. Its
50
+ derivative in ``x`` is ``exp(b x)``, regular at ``b = 0``, and it lambdifies to
51
+ ``expm1`` with a switch that does not divide by zero.
52
+ """
53
+
54
+ nargs = 2
55
+
56
+ @classmethod
57
+ def eval(cls, b, x):
58
+ if b.is_Number:
59
+ if abs(b) <= B_ZERO:
60
+ return x
61
+ return (sp.exp(b * x) - 1) / b
62
+ return None
63
+
64
+ def fdiff(self, argindex=1):
65
+ b, x = self.args
66
+ if argindex == 1:
67
+ return (x * sp.exp(b * x) - self) / b
68
+ if argindex == 2:
69
+ return sp.exp(b * x)
70
+ raise sp.ArgumentIndexError(self, argindex)
71
+
72
+ def _eval_evalf(self, prec):
73
+ dps = prec_to_dps(prec)
74
+ return self.func(*(arg.evalf(dps) for arg in self.args))
75
+
76
+ def _pythoncode(self, printer):
77
+ b, x = (printer._print(arg) for arg in self.args)
78
+ if isinstance(printer, NumPyPrinter):
79
+ np = printer._module
80
+ where = printer._module_format(f"{np}.where")
81
+ abs_ = printer._module_format(f"{np}.abs")
82
+ expm1 = printer._module_format(f"{np}.expm1")
83
+ nonzero = f"{abs_}({b}) > {B_ZERO!r}"
84
+ safe_b = f"{where}({nonzero}, {b}, 1.0)"
85
+ return f"{where}({nonzero}, {expm1}(({b})*({x}))/{safe_b}, {x})"
86
+ module = "mpmath" if isinstance(printer, MpmathPrinter) else "math"
87
+ expm1 = printer._module_format(f"{module}.expm1")
88
+ return f"(({expm1}(({b})*({x}))/({b})) if abs({b}) > {B_ZERO!r} else ({x}))"
89
+
90
+ # The name of the printing method differs between the printers that lambdify uses
91
+ _numpycode = _cupycode = _jaxcode = _lambdacode = _mpmathcode = _pythoncode
92
+
93
+
94
+ @dataclass(slots=True, frozen=True)
95
+ class HolzapfelOgden(AbstractStrainEnergy):
96
+ """The Holzapfel-Ogden model.
97
+
98
+ Each term is :math:`\\frac{a}{2 b} (e^{b x} - 1)`. Where an exponent :math:`b`
99
+ is zero (:math:`|b|` at most :data:`B_ZERO`) the term is its limit
100
+ :math:`\\frac{a}{2} x`, as in pulse, so that a parameter set with ``b_s = 0`` and
101
+ ``a_s = 0``, such as pulse's ``transversely_isotropic_parameters()``, can be used
102
+ as it is. A term whose :math:`a` is zero vanishes either way. The terms are
103
+ written with :class:`expm1_div`, which evaluates to the familiar expression once
104
+ :math:`b` is a number.
105
+ """
106
+
107
+ a: sp.Symbol = sp.Symbol("a")
108
+ b: sp.Symbol = sp.Symbol("b")
109
+ a_f: sp.Symbol = sp.Symbol("a_f")
110
+ b_f: sp.Symbol = sp.Symbol("b_f")
111
+ a_s: sp.Symbol = sp.Symbol("a_s")
112
+ b_s: sp.Symbol = sp.Symbol("b_s")
113
+ a_fs: sp.Symbol = sp.Symbol("a_fs")
114
+ b_fs: sp.Symbol = sp.Symbol("b_fs")
115
+ f0: sp.Matrix = field(default_factory=lambda: sp.Matrix([1, 0, 0]))
116
+ s0: sp.Matrix = field(default_factory=lambda: sp.Matrix([0, 1, 0]))
117
+ use_heaviside: bool = False
118
+
119
+ def strain_energy(self, F: sp.Matrix) -> sp.Expr:
120
+ C = F.T @ F
121
+
122
+ I1 = sp.trace(C)
123
+ logger.debug(f"I1: {I1}")
124
+ I4f = self.f0.dot(C * self.f0)
125
+ logger.debug(f"I4f: {I4f}")
126
+ I4s = self.s0.dot(C * self.s0)
127
+ logger.debug(f"I4s: {I4s}")
128
+ I8fs = self.f0.dot(C * self.s0)
129
+ logger.debug(f"I8fs: {I8fs}")
130
+
131
+ I4fm1 = I4f - 1 if not self.use_heaviside else sp.Piecewise((0.0, I4f < 1), (I4f - 1, True))
132
+ I4sm1 = I4s - 1 if not self.use_heaviside else sp.Piecewise((0.0, I4s < 1), (I4s - 1, True))
133
+
134
+ return (
135
+ self.a / 2 * expm1_div(self.b, I1 - 3)
136
+ + self.a_f / 2 * expm1_div(self.b_f, I4fm1**2)
137
+ + self.a_s / 2 * expm1_div(self.b_s, I4sm1**2)
138
+ + self.a_fs / 2 * expm1_div(self.b_fs, I8fs**2)
139
+ )
140
+
141
+ def default_parameters(self):
142
+ return {
143
+ self.a: 0.059,
144
+ self.b: 8.023,
145
+ self.a_f: 18.472,
146
+ self.b_f: 16.026,
147
+ self.a_s: 2.481,
148
+ self.b_s: 11.120,
149
+ self.a_fs: 0.216,
150
+ self.b_fs: 11.436,
151
+ }
152
+
153
+ @staticmethod
154
+ def str() -> str:
155
+ return (
156
+ "(a / (2 * b)) * (exp(b * (I1 - 3)) - 1) + "
157
+ "(a_f / (2 * b_f)) * (exp(b_f * H(I4f - 1)**2) - 1) + "
158
+ "(a_s / (2 * b_s)) * (exp(b_s * H(I4s - 1)**2) - 1) + "
159
+ "(a_fs / (2 * b_fs)) * (exp(b_fs * I8fs**2) - 1)"
160
+ )
@@ -0,0 +1,398 @@
1
+ """Thick walls: a cylinder and a sphere, solved exactly.
2
+
3
+ The ventricles of :mod:`zero_mech.ventricle` reduce the wall to a single stretch,
4
+ an approximation whose error grows with the thickness of the wall. The classes
5
+ here do not. For an incompressible wall whose deformation keeps the symmetry of
6
+ its geometry, the deformation is known in closed form, and radial equilibrium
7
+ gives the cavity pressure as one integral through the wall. That is the solution
8
+ of the full three-dimensional problem, so it can serve as a reference for a finite
9
+ element solver, for instance on a mesh of a quarter of an annulus or an eighth of
10
+ a sphere. The integral is computed by Gauss-Legendre quadrature in the reference
11
+ radius.
12
+
13
+ Cylinder
14
+ --------
15
+
16
+ An incompressible tube in plane strain (no axial stretch), with inner and outer
17
+ radii :math:`R_i` and :math:`R_o` when unloaded. Each cross-section stays
18
+ circular, so a point at radius :math:`R` moves to
19
+
20
+ .. math::
21
+ r(R)^2 = r_i^2 + R^2 - R_i^2, \\qquad \\lambda = \\frac{r}{R},
22
+
23
+ with :math:`\\lambda` the circumferential stretch, :math:`1/\\lambda` the radial
24
+ one and 1 the axial one. With :math:`\\hat\\psi(\\lambda)` the strain energy at
25
+ that deformation, :math:`\\sigma_{\\theta\\theta} - \\sigma_{rr} = \\lambda \\,
26
+ d\\hat\\psi/d\\lambda`, and radial equilibrium with a traction-free outer surface
27
+ gives the inner pressure
28
+
29
+ .. math::
30
+ p = \\int_{r_i}^{r_o} (\\sigma_{\\theta\\theta} - \\sigma_{rr}) \\frac{dr}{r}
31
+ = \\int_{R_i}^{R_o} \\lambda \\frac{d\\hat\\psi}{d\\lambda} \\frac{R}{r^2} \\, dR.
32
+
33
+ This is exact when the stress is diagonal in the radial, circumferential and
34
+ axial directions: an isotropic material, or one whose fibre and sheet directions
35
+ lie along those directions. Circumferential fibres may carry an active stress, so
36
+ the tube can contract, with an active tension that varies through the wall.
37
+
38
+ Sphere
39
+ ------
40
+
41
+ A point at radius :math:`R` moves to :math:`r(R)^3 = r_i^3 + R^3 - R_i^3`, with
42
+ the stretch :math:`\\lambda = r / R` in both directions of the wall plane and
43
+ :math:`\\lambda^{-2}` through it (:func:`zero_mech.experiments.equibiaxial`).
44
+ With :math:`\\hat\\psi(\\lambda)` the strain energy at that deformation,
45
+ :math:`\\sigma_{\\theta\\theta} + \\sigma_{\\phi\\phi} - 2 \\sigma_{rr} = \\lambda
46
+ \\, d\\hat\\psi/d\\lambda`, and
47
+
48
+ .. math::
49
+ p = \\int_{r_i}^{r_o} (\\sigma_{\\theta\\theta} + \\sigma_{\\phi\\phi} - 2 \\sigma_{rr})
50
+ \\frac{dr}{r}
51
+ = \\int_{R_i}^{R_o} \\lambda \\frac{d\\hat\\psi}{d\\lambda} \\frac{R^2}{r^3} \\, dR.
52
+
53
+ The deformation is spherically symmetric only if the material is isotropic in the
54
+ wall plane (:math:`\\sigma_{\\theta\\theta} = \\sigma_{\\phi\\phi}`). The sphere
55
+ therefore takes no fibres, sheets or active stress along a direction of the wall
56
+ plane: no single direction is tangent to a sphere everywhere. It is a reference
57
+ for a passive wall that is isotropic in its plane.
58
+
59
+ Common to both
60
+ --------------
61
+
62
+ The argument of the methods is the cavity volume: :math:`\\frac{4}{3} \\pi r_i^3`
63
+ for the sphere and, for the cylinder, the volume per unit length,
64
+ :math:`\\pi r_i^2`. Lengths can be in any unit, and pressures come out in the unit
65
+ of the material parameters.
66
+
67
+ A parameter of the model can be given one value per quadrature point (an array
68
+ shaped like :attr:`ThickCylinder.R`), to vary through the wall. An active tension
69
+ computed from the stretch :meth:`ThickCylinder.stretch` of each point is one
70
+ example.
71
+
72
+ The quadrature converges exponentially for a smooth integrand, and the default
73
+ number of points then gives round-off accuracy. The integrand has a kink where a
74
+ stretch crosses a switch of the material inside the wall, such as the heaviside
75
+ function of :class:`zero_mech.material.HolzapfelOgden` with
76
+ ``use_heaviside=True``. The convergence is then algebraic, so check the result
77
+ with more points.
78
+
79
+ References
80
+ ----------
81
+ Ogden RW (1984). Non-linear Elastic Deformations. Ellis Horwood, Chichester.
82
+ """
83
+
84
+ from __future__ import annotations
85
+
86
+ import math
87
+ from typing import Any, Callable, Mapping, Sequence
88
+
89
+ import sympy as sp
90
+
91
+ from .model import Model
92
+ from .ventricle import _Ventricle
93
+
94
+ try:
95
+ import numpy as _np
96
+ except ImportError: # pragma: no cover
97
+ _np = None # type: ignore[assignment]
98
+
99
+ __all__ = ["ThickCylinder", "ThickSphere"]
100
+
101
+ #: Stretches at which the symmetry of the stress is checked
102
+ _CHECK_STRETCHES = (0.8, 0.95, 1.05, 1.25)
103
+
104
+
105
+ class _ThickWall(_Ventricle):
106
+ """What the cylinder and the sphere share. ``_n`` is 2 for the cylinder and 3 for the
107
+ sphere: the cavity volume is ``_c * r_i**_n``, and ``r**_n - R**_n`` is the same at
108
+ every point of the wall."""
109
+
110
+ _n: int
111
+ _c: float
112
+
113
+ def _setup(
114
+ self,
115
+ model: Model | None,
116
+ Ri: float,
117
+ Ro: float,
118
+ diagonal: Callable[[sp.Symbol], Sequence[sp.Expr]],
119
+ parameters: Mapping[Any, Any] | None,
120
+ num_points: int,
121
+ ) -> None:
122
+ if _np is None: # pragma: no cover
123
+ raise ImportError("The thick walls need numpy")
124
+ if not 0 < Ri < Ro:
125
+ raise ValueError(f"The radii must satisfy 0 < Ri < Ro, got Ri = {Ri} and Ro = {Ro}")
126
+ if int(num_points) < 1:
127
+ raise ValueError(f"num_points must be positive, got {num_points}")
128
+ self.model = model if model is not None else Model()
129
+ if self.model.compressibility.is_compressible():
130
+ raise ValueError("The wall must be incompressible")
131
+
132
+ self.Ri = float(Ri)
133
+ self.Ro = float(Ro)
134
+ x, w = _np.polynomial.legendre.leggauss(int(num_points))
135
+ #: Reference radii of the quadrature points through the wall
136
+ self.R = 0.5 * (self.Ro - self.Ri) * x + 0.5 * (self.Ro + self.Ri)
137
+ #: Quadrature weights of the points :attr:`R`
138
+ self.weights = 0.5 * (self.Ro - self.Ri) * w
139
+ #: Cavity volume of the unloaded wall
140
+ self.V0 = self.volume(self.Ri)
141
+
142
+ n = self._n
143
+ lmbda = sp.Symbol("λ", real=True, positive=True)
144
+ F = sp.diag(*diagonal(lmbda))
145
+ # lmbda dpsi/dlmbda: sigma_tt - sigma_rr (cylinder), sigma_tt + sigma_pp - 2 sigma_rr
146
+ # (sphere). The pressure of an incompressible model drops out, since J = 1.
147
+ stress = lmbda * sp.diff(self.model.strain_energy(F), lmbda)
148
+ self._R = sp.Symbol("R", real=True, positive=True)
149
+ self._ri = sp.Symbol("r_i", real=True, positive=True)
150
+ r = (self._ri**n + self._R**n - sp.Float(self.Ri) ** n) ** sp.Rational(1, n)
151
+ #: The integrand of the pressure, :math:`p = \\int_{R_i}^{R_o} f \\, dR`, in the
152
+ #: reference radius ``R``, the deformed inner radius ``r_i`` and the parameters
153
+ #: of the model
154
+ self.integrand_expr = stress.subs(lmbda, r / self._R) * self._R ** (n - 1) / r**n
155
+ dintegrand = sp.diff(self.integrand_expr, self._ri)
156
+
157
+ self._set_parameters(parameters, (self.integrand_expr, dintegrand), (self._R, self._ri))
158
+ args = (self._R, self._ri, *self._parameter_symbols)
159
+ self._integrand: Callable[..., Any] = sp.lambdify(args, self.integrand_expr, "numpy")
160
+ self._dintegrand: Callable[..., Any] = sp.lambdify(args, dintegrand, "numpy")
161
+ self._build_symmetry_check(lmbda, self.model.first_piola_kirchhoff(F))
162
+ self._check_symmetry(self._defaults)
163
+
164
+ def _symmetry_violations(self, P: sp.Matrix) -> list[sp.Expr]:
165
+ """Expressions that must vanish for the deformation to be symmetric: the
166
+ off-diagonal entries of the stress."""
167
+ return [P[i, j] for i in range(3) for j in range(3) if i != j]
168
+
169
+ _symmetry_error: str
170
+
171
+ def _build_symmetry_check(self, lmbda: sp.Symbol, P: sp.Matrix) -> None:
172
+ p = getattr(self.model.compressibility, "p", None)
173
+ zero = {p: 0} if p is not None else {}
174
+ exprs = [e.subs(zero) for e in self._symmetry_violations(P)]
175
+ diagonal = [P[i, i].subs(zero) for i in range(3)]
176
+ symbols = set().union(*(e.free_symbols for e in exprs + diagonal)) - {lmbda}
177
+ self._check_symbols = sorted(symbols, key=lambda s: s.name)
178
+ self._num_violations = len(exprs)
179
+ self._check: Callable[..., Any] = sp.lambdify(
180
+ (lmbda, *self._check_symbols), [*exprs, *diagonal], "numpy"
181
+ )
182
+
183
+ def _check_symmetry(self, values: Mapping[str, Any]) -> None:
184
+ """Raise if, at these parameter values, the stress of the model breaks the symmetry
185
+ that the deformation assumes."""
186
+ stretches = _np.array(_CHECK_STRETCHES).reshape(-1, 1)
187
+ args = [values.get(s.name, 1.0) for s in self._check_symbols]
188
+ with _np.errstate(all="ignore"):
189
+ results = [_np.max(_np.abs(v)) for v in self._check(stretches, *args)]
190
+ violation = max(results[: self._num_violations])
191
+ scale = max(results[self._num_violations :])
192
+ if not violation <= 1e-12 * max(scale, 1.0):
193
+ raise ValueError(self._symmetry_error)
194
+
195
+ def _values(self, parameters: Mapping[Any, Any] | None) -> list[Any]:
196
+ if parameters:
197
+ self._check_symmetry({**self._defaults, **self._checked(parameters)})
198
+ return super()._values(parameters)
199
+
200
+ def _value(self, name: str, value: Any) -> Any:
201
+ """A float, or one value per point of the wall."""
202
+ if _np.ndim(value) == 0:
203
+ return float(value)
204
+ values = _np.asarray(value, dtype=float)
205
+ if values.shape != self.R.shape:
206
+ raise ValueError(
207
+ f"A parameter given through the wall needs one value per point, shape "
208
+ f"{self.R.shape}; {name} has shape {values.shape}"
209
+ )
210
+ return values
211
+
212
+ def variables(self) -> dict[str, sp.Symbol]:
213
+ """The symbols of the integrand (``R``, ``r_i``) and of the model, by name."""
214
+ return {self._R.name: self._R, self._ri.name: self._ri, **self.model.variables()}
215
+
216
+ # ------------------------------------------------------------------
217
+ # Kinematics
218
+ # ------------------------------------------------------------------
219
+
220
+ def volume(self, ri):
221
+ """Cavity volume at the deformed inner radius ``ri``."""
222
+ return self._c * ri**self._n
223
+
224
+ def inner_radius(self, V):
225
+ """Deformed inner radius at the cavity volume ``V``."""
226
+ return (V / self._c) ** (1 / self._n)
227
+
228
+ def radius(self, V):
229
+ """Deformed radius of each point :attr:`R` at the cavity volume ``V``, with the
230
+ points along the last axis."""
231
+ ri = self.inner_radius(_np.asarray(V, dtype=float))[..., None]
232
+ return (ri**self._n + self.R**self._n - self.Ri**self._n) ** (1 / self._n)
233
+
234
+ def stretch(self, V):
235
+ """Stretch of the wall at each point :attr:`R`, along the last axis. Circumferential
236
+ for the cylinder; in both directions of the wall plane for the sphere."""
237
+ return self.radius(V) / self.R
238
+
239
+ # ------------------------------------------------------------------
240
+ # Pressure
241
+ # ------------------------------------------------------------------
242
+
243
+ def pressure(self, V, parameters: Mapping[Any, Any] | None = None):
244
+ """Cavity pressure, with a traction-free outer surface.
245
+
246
+ Parameters
247
+ ----------
248
+ V : float or array
249
+ Cavity volume (per unit length, for the cylinder).
250
+ parameters : mapping, optional
251
+ Model parameters to override for this call, by name or by symbol: a
252
+ float, or an array of one value per point :attr:`R`.
253
+ """
254
+ ri = self.inner_radius(_np.asarray(V, dtype=float))[..., None]
255
+ f = self._integrand(self.R, ri, *self._values(parameters))
256
+ return _np.sum(self.weights * f, axis=-1)
257
+
258
+ def stiffness(self, V, parameters: Mapping[Any, Any] | None = None):
259
+ """Derivative of the cavity pressure with respect to the cavity volume, at fixed
260
+ parameters. Arguments as for :meth:`pressure`."""
261
+ V = _np.asarray(V, dtype=float)
262
+ ri = self.inner_radius(V)
263
+ df = self._dintegrand(self.R, ri[..., None], *self._values(parameters))
264
+ # V = c ri^n, so dri/dV = ri / (n V)
265
+ return _np.sum(self.weights * df, axis=-1) * ri / (self._n * V)
266
+
267
+
268
+ def _axes(radial_axis: int, axial_axis: int | None = None) -> None:
269
+ given = [radial_axis] if axial_axis is None else [radial_axis, axial_axis]
270
+ if any(a not in (0, 1, 2) for a in given) or len(set(given)) != len(given):
271
+ raise ValueError(f"The axes must be distinct and 0, 1 or 2, got {given}")
272
+
273
+
274
+ class ThickCylinder(_ThickWall):
275
+ """A thick-walled tube in plane strain, solved exactly.
276
+
277
+ Parameters
278
+ ----------
279
+ model : zero_mech.Model, optional
280
+ The material of the wall, incompressible. Its stress must be diagonal in
281
+ the radial, circumferential and axial directions, so its fibre and sheet
282
+ directions, if any, must lie along those axes. By default a neo-Hookean
283
+ material.
284
+ Ri, Ro : float
285
+ Inner and outer radius of the unloaded tube, ``0 < Ri < Ro``.
286
+ radial_axis, axial_axis : int, optional
287
+ The axes of the model that are radial and axial, by default 1 and 2. The
288
+ third is circumferential, which by default is axis 0, the default fibre
289
+ direction of the materials.
290
+ parameters : mapping, optional
291
+ Values for the parameters of the model, by name or by symbol: a float, or
292
+ an array of one value per point :attr:`R`. Those not given take the
293
+ defaults of the model's parts.
294
+ num_points : int, optional
295
+ Number of Gauss-Legendre points through the wall, by default 100.
296
+
297
+ Notes
298
+ -----
299
+ The volumes of the methods are per unit length: :math:`\\pi r_i^2` for an
300
+ inner radius :math:`r_i`. A quarter of an annulus of height :math:`H` holds a
301
+ quarter of :math:`\\pi r_i^2 H`. The constructor raises ``ValueError`` if, at
302
+ the parameters it is given, the stress breaks the symmetry of the tube.
303
+ """
304
+
305
+ _n = 2
306
+ _c = math.pi
307
+ _symmetry_error = (
308
+ "The stress of the model is not diagonal in the radial, circumferential and axial "
309
+ "directions, so the tube does not deform symmetrically. Its fibre and sheet directions "
310
+ "must lie along the axes of the tube."
311
+ )
312
+
313
+ def __init__(
314
+ self,
315
+ model: Model | None = None,
316
+ Ri: float = 1.0,
317
+ Ro: float = 1.5,
318
+ radial_axis: int = 1,
319
+ axial_axis: int = 2,
320
+ parameters: Mapping[Any, Any] | None = None,
321
+ num_points: int = 100,
322
+ ) -> None:
323
+ _axes(radial_axis, axial_axis)
324
+ self.radial_axis = radial_axis
325
+ self.axial_axis = axial_axis
326
+ (self.circumferential_axis,) = {0, 1, 2} - {radial_axis, axial_axis}
327
+
328
+ def diagonal(lmbda: sp.Symbol) -> list[sp.Expr]:
329
+ d: list[sp.Expr] = [lmbda, lmbda, lmbda]
330
+ d[radial_axis] = 1 / lmbda
331
+ d[axial_axis] = sp.S.One
332
+ return d
333
+
334
+ self._setup(model, Ri, Ro, diagonal, parameters, num_points)
335
+
336
+
337
+ class ThickSphere(_ThickWall):
338
+ """A thick-walled sphere, solved exactly.
339
+
340
+ Parameters
341
+ ----------
342
+ model : zero_mech.Model, optional
343
+ The material of the wall, incompressible and isotropic in the wall plane.
344
+ By default a neo-Hookean material.
345
+ Ri, Ro : float
346
+ Inner and outer radius of the unloaded sphere, ``0 < Ri < Ro``.
347
+ radial_axis : int, optional
348
+ The axis of the model that is radial, by default 2.
349
+ parameters : mapping, optional
350
+ Values for the parameters of the model, by name or by symbol: a float, or
351
+ an array of one value per point :attr:`R`. Those not given take the
352
+ defaults of the model's parts.
353
+ num_points : int, optional
354
+ Number of Gauss-Legendre points through the wall, by default 100.
355
+
356
+ Notes
357
+ -----
358
+ The constructor raises ``ValueError`` if, at the parameters it is given, the
359
+ stress differs between the two directions of the wall plane. A material with
360
+ fibres in the wall plane, such as
361
+ :class:`zero_mech.material.HolzapfelOgden` with ``a_f > 0``, does, and so does
362
+ an active stress along one direction. Compare
363
+ :class:`zero_mech.SphericalVentricle`, which approximates the same sphere by a
364
+ single stretch.
365
+ """
366
+
367
+ _n = 3
368
+ _c = 4 * math.pi / 3
369
+ _symmetry_error = (
370
+ "The stress of the model is not the same in the two directions of the wall plane, or "
371
+ "not diagonal, so the sphere does not deform spherically symmetrically. The model must "
372
+ "be isotropic in the wall plane: no fibres, sheets or active stress along a direction "
373
+ "of that plane."
374
+ )
375
+
376
+ def __init__(
377
+ self,
378
+ model: Model | None = None,
379
+ Ri: float = 1.0,
380
+ Ro: float = 1.5,
381
+ radial_axis: int = 2,
382
+ parameters: Mapping[Any, Any] | None = None,
383
+ num_points: int = 100,
384
+ ) -> None:
385
+ _axes(radial_axis)
386
+ self.radial_axis = radial_axis
387
+ self._in_plane = sorted({0, 1, 2} - {radial_axis})
388
+
389
+ def diagonal(lmbda: sp.Symbol) -> list[sp.Expr]:
390
+ d: list[sp.Expr] = [lmbda, lmbda, lmbda]
391
+ d[radial_axis] = lmbda**-2
392
+ return d
393
+
394
+ self._setup(model, Ri, Ro, diagonal, parameters, num_points)
395
+
396
+ def _symmetry_violations(self, P: sp.Matrix) -> list[sp.Expr]:
397
+ a, b = self._in_plane
398
+ return [*super()._symmetry_violations(P), P[a, a] - P[b, b]]
@@ -33,6 +33,10 @@ with :math:`T_a` an active tension along the fibres (a Cauchy stress).
33
33
  an active part, and pass the active tension to the methods; the classes
34
34
  warn otherwise.
35
35
 
36
+ The one-fibre model is an approximation whose error grows with the thickness of
37
+ the wall. For the exact solution of a thick-walled sphere or tube, to compare with
38
+ or to verify a finite element solver against, see :mod:`zero_mech.thick_wall`.
39
+
36
40
  Spherical ventricle
37
41
  -------------------
38
42
 
@@ -141,10 +145,8 @@ except ImportError: # pragma: no cover
141
145
  _quiet = contextlib.nullcontext
142
146
 
143
147
 
144
- def _by_name(parameters: Mapping[Any, float]) -> dict[str, float]:
145
- return {
146
- (k.name if isinstance(k, sp.Symbol) else str(k)): float(v) for k, v in parameters.items()
147
- }
148
+ def _by_name(parameters: Mapping[Any, Any]) -> dict[str, Any]:
149
+ return {(k.name if isinstance(k, sp.Symbol) else str(k)): v for k, v in parameters.items()}
148
150
 
149
151
 
150
152
  def _default_parameters(model: Model) -> dict[str, float]:
@@ -152,7 +154,7 @@ def _default_parameters(model: Model) -> dict[str, float]:
152
154
  for part in (model.material, model.compressibility, model.active):
153
155
  get = getattr(part, "default_parameters", None)
154
156
  if get is not None:
155
- defaults.update(_by_name(get()))
157
+ defaults.update({k: float(v) for k, v in _by_name(get()).items()})
156
158
  return defaults
157
159
 
158
160
 
@@ -208,9 +210,13 @@ class _Ventricle(Atom):
208
210
  if missing:
209
211
  raise ValueError(f"No value for the model parameters {missing}")
210
212
 
213
+ def _value(self, name: str, value: Any) -> Any:
214
+ """The value of a parameter as the ventricle takes it: a float."""
215
+ return float(value)
216
+
211
217
  def _checked(self, parameters: Mapping[Any, float]) -> dict[str, float]:
212
218
  """``parameters`` by name, after checking that each is a parameter of the model."""
213
- given = _by_name(parameters)
219
+ given = {name: self._value(name, v) for name, v in _by_name(parameters).items()}
214
220
  unknown = set(given) - self._known
215
221
  if unknown:
216
222
  raise KeyError(f"Unknown parameters {sorted(unknown)}; known: {sorted(self._known)}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zero_mech
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A zero-dimensional mechanics solver
5
5
  Author-email: Henrik Finsberg <henriknf@simula.no>
6
6
  License: MIT
@@ -8,6 +8,7 @@ src/zero_mech/compressibility.py
8
8
  src/zero_mech/experiments.py
9
9
  src/zero_mech/material.py
10
10
  src/zero_mech/model.py
11
+ src/zero_mech/thick_wall.py
11
12
  src/zero_mech/ventricle.py
12
13
  src/zero_mech/viscosity.py
13
14
  src/zero_mech.egg-info/PKG-INFO
@@ -18,4 +19,6 @@ src/zero_mech.egg-info/not-zip-safe
18
19
  src/zero_mech.egg-info/requires.txt
19
20
  src/zero_mech.egg-info/top_level.txt
20
21
  tests/test_experiments.py
22
+ tests/test_material.py
23
+ tests/test_thick_wall.py
21
24
  tests/test_ventricle.py
@@ -112,3 +112,34 @@ def test_active_stress_is_the_second_piola_kirchhoff_stress_along_the_fibre():
112
112
  S = sp.simplify(F.inv() @ P)
113
113
  assert sp.simplify(S - act.Ta * f0 @ f0.T) == sp.zeros(3, 3)
114
114
  assert act.str() == "Ta / 2 * (I4f - 1)"
115
+
116
+
117
+ def test_stretch_active_stress_is_a_nominal_stress_along_the_fibre():
118
+ F = zero_mech.experiments.full_matrix().F
119
+ f0 = sp.Matrix([1, 0, 0])
120
+ act = zero_mech.StretchActiveStress(f0=f0)
121
+ P = sp.Matrix(3, 3, lambda i, j: sp.diff(act.strain_energy(F), F[i, j]))
122
+ S = sp.simplify(F.inv() @ P)
123
+ I4f = (F @ f0).dot(F @ f0)
124
+ assert sp.simplify(S - act.Ta / sp.sqrt(I4f) * f0 @ f0.T) == sp.zeros(3, 3)
125
+ assert act.str() == "Ta * (sqrt(I4f) - 1)"
126
+
127
+
128
+ @pytest.mark.parametrize("axis", range(3))
129
+ def test_stretch_active_stress_in_uniaxial_tension(axis):
130
+ # The force per reference area along the fibre is Ta at any stretch, smaller than that of
131
+ # ActiveStress by a factor of the stretch
132
+ f0 = sp.Matrix([0, 0, 0])
133
+ f0[axis] = 1
134
+ experiment = zero_mech.experiments.uniaxial_tension(axis=axis)
135
+ lmbda = experiment["λ"]
136
+ stretch = zero_mech.Model(active=zero_mech.StretchActiveStress(f0=f0))
137
+ invariant = zero_mech.Model(active=zero_mech.ActiveStress(f0=f0))
138
+ P_stretch = stretch.first_piola_kirchhoff(experiment.F)
139
+ P_invariant = invariant.first_piola_kirchhoff(experiment.F)
140
+ passive = zero_mech.Model().first_piola_kirchhoff(experiment.F)
141
+ Ta = stretch["Ta"]
142
+ assert equal(P_stretch[axis, axis] - passive[axis, axis], Ta)
143
+ assert equal(P_invariant[axis, axis] - passive[axis, axis], Ta * lmbda)
144
+ for i in set(range(3)) - {axis}:
145
+ assert equal(P_stretch[i, i], passive[i, i])
@@ -0,0 +1,140 @@
1
+ import numpy as np
2
+ import pytest
3
+ import sympy as sp
4
+
5
+ import zero_mech
6
+ from zero_mech.material import expm1_div
7
+
8
+ #: A deformation with every invariant of Holzapfel-Ogden away from its rest value
9
+ F_VALUES = sp.Matrix([[1.15, 0.1, 0.05], [0.08, 0.95, 0.02], [0.03, 0.06, 0.93]])
10
+
11
+
12
+ def energy(parameters, use_heaviside=True):
13
+ material = zero_mech.material.HolzapfelOgden(use_heaviside=use_heaviside)
14
+ return float(
15
+ material.strain_energy(F_VALUES).xreplace(
16
+ {getattr(material, k): v for k, v in parameters.items()}
17
+ )
18
+ )
19
+
20
+
21
+ def invariants():
22
+ f0, s0 = sp.Matrix([1, 0, 0]), sp.Matrix([0, 1, 0])
23
+ C = F_VALUES.T @ F_VALUES
24
+ return (
25
+ float(sp.trace(C)),
26
+ float(f0.dot(C @ f0)),
27
+ float(s0.dot(C @ s0)),
28
+ float(f0.dot(C @ s0)),
29
+ )
30
+
31
+
32
+ A = dict(a=2.0, a_f=3.0, a_s=4.0, a_fs=5.0)
33
+
34
+
35
+ def test_holzapfel_ogden_with_zero_exponents_is_the_limit():
36
+ I1, I4f, I4s, I8fs = invariants()
37
+ assert I4f > 1 and I4s < 1 # so that the heaviside of the sheet term switches it off
38
+ zero = {**A, "b": 0.0, "b_f": 0.0, "b_s": 0.0, "b_fs": 0.0}
39
+ expected = A["a"] / 2 * (I1 - 3) + A["a_f"] / 2 * (I4f - 1) ** 2 + A["a_fs"] / 2 * I8fs**2
40
+ assert energy(zero) == pytest.approx(expected, rel=1e-14)
41
+ without_heaviside = expected + A["a_s"] / 2 * (I4s - 1) ** 2
42
+ assert energy(zero, use_heaviside=False) == pytest.approx(without_heaviside, rel=1e-14)
43
+
44
+
45
+ def test_holzapfel_ogden_is_continuous_in_its_exponents():
46
+ for b in ("b", "b_f", "b_s", "b_fs"):
47
+ zero = {**A, "b": 1.0, "b_f": 1.0, "b_s": 1.0, "b_fs": 1.0, b: 0.0}
48
+ small = {**zero, b: 1e-7}
49
+ assert energy(small, use_heaviside=False) == pytest.approx(
50
+ energy(zero, use_heaviside=False), rel=1e-6
51
+ )
52
+
53
+
54
+ def test_pulse_transversely_isotropic_parameters_give_a_finite_stress():
55
+ # a_s = b_s = a_fs = b_fs = 0, which divided zero by zero before the limit was taken
56
+ parameters = dict(a=2.280, b=9.726, a_f=1.685, b_f=15.779, a_s=0.0, b_s=0.0, a_fs=0.0, b_fs=0.0)
57
+ model = zero_mech.Model(material=zero_mech.material.HolzapfelOgden(use_heaviside=True))
58
+ experiment = zero_mech.experiments.uniaxial_tension(lmbda=sp.Float(1.1))
59
+ P = model.first_piola_kirchhoff(experiment.F).xreplace(
60
+ {model[k]: v for k, v in parameters.items()} | {model["p"]: 0.0}
61
+ )
62
+ values = np.array(P.evalf(), dtype=float)
63
+ assert np.all(np.isfinite(values))
64
+ # The same as dropping the two terms by any positive exponent
65
+ reference = model.first_piola_kirchhoff(experiment.F).xreplace(
66
+ {model[k]: v for k, v in parameters.items()}
67
+ | {model["p"]: 0.0, model["b_s"]: 1.0, model["b_fs"]: 1.0}
68
+ )
69
+ assert np.allclose(values, np.array(reference.evalf(), dtype=float), rtol=1e-14, atol=0)
70
+
71
+
72
+ def test_holzapfel_ogden_lambdifies_with_zero_exponents():
73
+ material = zero_mech.material.HolzapfelOgden()
74
+ symbols = [material.a, material.b, material.a_f, material.b_f]
75
+ f = sp.lambdify(
76
+ symbols,
77
+ material.strain_energy(F_VALUES).xreplace(
78
+ {material.a_s: 0.0, material.b_s: 0.0, material.a_fs: 0.0, material.b_fs: 0.0}
79
+ ),
80
+ "numpy",
81
+ )
82
+ I1, I4f, *_ = invariants()
83
+ with np.errstate(all="raise"):
84
+ value = f(2.0, 0.0, 3.0, 0.0)
85
+ assert value == pytest.approx(1.0 * (I1 - 3) + 1.5 * (I4f - 1) ** 2)
86
+
87
+
88
+ def test_holzapfel_ogden_stress_lambdifies_cleanly_with_zero_exponents():
89
+ material = zero_mech.material.HolzapfelOgden()
90
+ model = zero_mech.Model(material=material)
91
+ P = model.first_piola_kirchhoff(F_VALUES).xreplace({model["p"]: 0.0})
92
+ symbols = [model[k] for k in ("a", "b", "a_f", "b_f", "a_s", "b_s", "a_fs", "b_fs")]
93
+ f = sp.lambdify(symbols, P, "numpy")
94
+ with np.errstate(all="raise"):
95
+ values = np.array(f(2.0, 0.0, 3.0, 0.0, 4.0, 0.0, 5.0, 0.0), dtype=float)
96
+ assert np.all(np.isfinite(values))
97
+
98
+
99
+ def test_holzapfel_ogden_str_names_the_sheet_invariant():
100
+ assert "exp(b_s * H(I4s - 1)**2)" in zero_mech.material.HolzapfelOgden.str()
101
+
102
+
103
+ def test_holzapfel_ogden_lambdifies_with_math_and_zero_exponents():
104
+ material = zero_mech.material.HolzapfelOgden()
105
+ symbols = [material.a, material.b, material.a_f, material.b_f]
106
+ f = sp.lambdify(
107
+ symbols,
108
+ material.strain_energy(F_VALUES).xreplace(
109
+ {material.a_s: 0.0, material.b_s: 0.0, material.a_fs: 0.0, material.b_fs: 0.0}
110
+ ),
111
+ "math",
112
+ )
113
+ I1, I4f, *_ = invariants()
114
+ assert f(2.0, 0.0, 3.0, 0.0) == pytest.approx(1.0 * (I1 - 3) + 1.5 * (I4f - 1) ** 2)
115
+ assert f(2.0, 1.0, 3.0, 2.0) == pytest.approx(
116
+ energy(
117
+ {**A, "b": 1.0, "b_f": 2.0, "a_s": 0.0, "a_fs": 0.0, "b_s": 1.0, "b_fs": 1.0},
118
+ use_heaviside=False,
119
+ )
120
+ )
121
+
122
+
123
+ def test_holzapfel_ogden_with_a_number_for_b_is_the_plain_exponential():
124
+ material = zero_mech.material.HolzapfelOgden()
125
+ x = sp.Symbol("x")
126
+ term = expm1_div(material.b, x)
127
+ assert term.subs(material.b, 2) == (sp.exp(2 * x) - 1) / 2
128
+ assert term.subs(material.b, 0) == x
129
+ # A negative exponent keeps the exponential, which is exact there too
130
+ assert term.subs(material.b, -1) == 1 - sp.exp(-x)
131
+ assert sp.diff(term, x) == sp.exp(material.b * x)
132
+
133
+
134
+ def test_solve_for_the_pressure_in_simple_shear():
135
+ # A Piecewise in b made sympy.solve fail to convert its solution to floats
136
+ model = zero_mech.Model(material=zero_mech.material.HolzapfelOgden())
137
+ experiment = zero_mech.experiments.simple_shear(plane="fs")
138
+ P = model.first_piola_kirchhoff(experiment.F)
139
+ (p,) = sp.solve(P[0, 0], model["p"])
140
+ assert not p.has(sp.Piecewise)
@@ -0,0 +1,221 @@
1
+ import math
2
+
3
+ import numpy as np
4
+ import pytest
5
+ import sympy as sp
6
+
7
+ import zero_mech
8
+ from zero_mech import ThickCylinder, ThickSphere
9
+
10
+ MU = 15.0 # the default of NeoHookean
11
+ RI, RO = 1.0, 1.5
12
+
13
+ #: Holzapfel-Ogden as in pulse's transversely_isotropic_parameters(), in kPa
14
+ TRANSVERSELY_ISOTROPIC = dict(
15
+ a=2.280, b=9.726, a_f=1.685, b_f=15.779, a_s=0.0, b_s=0.0, a_fs=0.0, b_fs=0.0
16
+ )
17
+
18
+
19
+ def contracting_wall():
20
+ """Holzapfel-Ogden with circumferential fibres (axis 0) and radial sheets (axis 1),
21
+ the default axes of ThickCylinder, and an active stress along the fibres."""
22
+ return zero_mech.Model(
23
+ material=zero_mech.material.HolzapfelOgden(use_heaviside=True),
24
+ active=zero_mech.StretchActiveStress(),
25
+ )
26
+
27
+
28
+ def stretches(wall, V):
29
+ """The stretch at the inner and the outer surface, from the incompressibility."""
30
+ n = 2 if isinstance(wall, ThickCylinder) else 3
31
+ ri = wall.inner_radius(V)
32
+ ro = (ri**n + wall.Ro**n - wall.Ri**n) ** (1 / n)
33
+ return ri / wall.Ri, ro / wall.Ro
34
+
35
+
36
+ @pytest.mark.parametrize("ratio", [0.6, 0.9, 1.2, 2.0, 4.0])
37
+ def test_neo_hookean_cylinder_closed_form(ratio):
38
+ # p = mu (ln(li / lo) - 1 / (2 li^2) + 1 / (2 lo^2)), li and lo the inner and outer stretch
39
+ cylinder = ThickCylinder(Ri=RI, Ro=RO)
40
+ V = ratio * cylinder.V0
41
+ li, lo = stretches(cylinder, V)
42
+ exact = MU * (math.log(li / lo) - 1 / (2 * li**2) + 1 / (2 * lo**2))
43
+ assert cylinder.pressure(V) == pytest.approx(exact, rel=1e-12, abs=1e-12)
44
+
45
+
46
+ @pytest.mark.parametrize("ratio", [0.6, 0.9, 1.2, 2.0, 4.0])
47
+ def test_neo_hookean_sphere_closed_form(ratio):
48
+ # p = mu (2 / lo + 1 / (2 lo^4) - 2 / li - 1 / (2 li^4))
49
+ sphere = ThickSphere(Ri=RI, Ro=RO)
50
+ V = ratio * sphere.V0
51
+ li, lo = stretches(sphere, V)
52
+ exact = MU * (2 / lo + 1 / (2 * lo**4) - 2 / li - 1 / (2 * li**4))
53
+ assert sphere.pressure(V) == pytest.approx(exact, rel=1e-12, abs=1e-12)
54
+
55
+
56
+ @pytest.mark.parametrize("cls", [ThickCylinder, ThickSphere])
57
+ def test_unloaded_wall_has_no_pressure(cls):
58
+ wall = cls(Ri=RI, Ro=RO)
59
+ assert wall.pressure(wall.V0) == pytest.approx(0.0, abs=1e-13)
60
+ assert np.allclose(wall.stretch(wall.V0), 1.0)
61
+
62
+
63
+ @pytest.mark.parametrize("cls, n", [(ThickCylinder, 2), (ThickSphere, 3)])
64
+ def test_kinematics(cls, n):
65
+ wall = cls(Ri=2.0, Ro=3.0, num_points=7)
66
+ assert wall.V0 == pytest.approx(wall._c * 2.0**n)
67
+ V = np.array([0.5, 1.0, 3.0]) * wall.V0
68
+ assert np.allclose(wall.volume(wall.inner_radius(V)), V)
69
+ r = wall.radius(V)
70
+ assert r.shape == (3, 7)
71
+ # Incompressible: r^n - R^n is the same at every point, the change of the cavity
72
+ assert np.allclose(r**n - wall.R**n, (wall.inner_radius(V) ** n - 2.0**n)[:, None])
73
+ assert np.allclose(wall.stretch(V), r / wall.R)
74
+ assert np.all((wall.R > 2.0) & (wall.R < 3.0))
75
+ assert np.sum(wall.weights) == pytest.approx(1.0)
76
+
77
+
78
+ def test_pressure_accepts_arrays_of_volumes():
79
+ cylinder = ThickCylinder(Ri=RI, Ro=RO)
80
+ V = np.array([0.8, 1.5, 2.5]) * cylinder.V0
81
+ assert np.allclose(cylinder.pressure(V), [cylinder.pressure(v) for v in V], rtol=1e-14)
82
+
83
+
84
+ @pytest.mark.parametrize("ratio", [0.8, 1.3])
85
+ def test_active_stress_of_a_cylinder(ratio):
86
+ # Circumferential fibres add their Cauchy stress to sigma_tt - sigma_rr. For
87
+ # StretchActiveStress that is Ta lmbda, so p_a = Ta int dR / r = Ta ln((Ro + ro) / (Ri + ri));
88
+ # for ActiveStress it is Ta lmbda^2, so p_a = Ta int dR / R = Ta ln(Ro / Ri), at any volume
89
+ Ta = 7.0
90
+ stretch = ThickCylinder(zero_mech.Model(active=zero_mech.StretchActiveStress()), RI, RO)
91
+ invariant = ThickCylinder(zero_mech.Model(active=zero_mech.ActiveStress()), RI, RO)
92
+ V = ratio * stretch.V0
93
+ li, lo = stretches(stretch, V)
94
+ p_stretch = stretch.pressure(V, parameters={"Ta": Ta}) - stretch.pressure(V)
95
+ p_invariant = invariant.pressure(V, parameters={"Ta": Ta}) - invariant.pressure(V)
96
+ assert p_stretch == pytest.approx(Ta * math.log((RO * (1 + lo)) / (RI * (1 + li))), rel=1e-12)
97
+ assert p_invariant == pytest.approx(Ta * math.log(RO / RI), rel=1e-12)
98
+
99
+
100
+ def test_parameters_can_vary_through_the_wall():
101
+ cylinder = ThickCylinder(zero_mech.Model(active=zero_mech.StretchActiveStress()), RI, RO)
102
+ V = 0.9 * cylinder.V0
103
+ uniform = np.full(cylinder.R.shape, 7.0)
104
+ assert cylinder.pressure(V, parameters={"Ta": uniform}) == pytest.approx(
105
+ cylinder.pressure(V, parameters={"Ta": 7.0}), rel=1e-14
106
+ )
107
+ # p_a = int Ta(R) lmbda R / r^2 dR = int Ta(R) / r dR
108
+ Ta = 10.0 * (cylinder.R - RI)
109
+ active = cylinder.pressure(V, parameters={"Ta": Ta}) - cylinder.pressure(V)
110
+ assert active == pytest.approx(np.sum(cylinder.weights * Ta / cylinder.radius(V)), rel=1e-12)
111
+ through_constructor = ThickCylinder(cylinder.model, RI, RO, parameters={"Ta": Ta})
112
+ assert through_constructor.pressure(V) == pytest.approx(cylinder.pressure(V, {"Ta": Ta}))
113
+
114
+
115
+ def test_a_parameter_through_the_wall_needs_a_value_per_point():
116
+ cylinder = ThickCylinder(zero_mech.Model(active=zero_mech.StretchActiveStress()), RI, RO)
117
+ with pytest.raises(ValueError, match="one value per point"):
118
+ cylinder.pressure(cylinder.V0, parameters={"Ta": np.ones(3)})
119
+ with pytest.raises(ValueError, match="one value per point"):
120
+ ThickCylinder(cylinder.model, RI, RO, parameters={"Ta": np.ones(3)})
121
+
122
+
123
+ @pytest.mark.parametrize("Ta", [0.0, 30.0])
124
+ def test_stiffness_is_the_derivative_of_the_pressure(Ta):
125
+ cylinder = ThickCylinder(contracting_wall(), RI, RO, parameters=TRANSVERSELY_ISOTROPIC)
126
+ sphere = ThickSphere(Ri=RI, Ro=RO)
127
+ for wall, parameters in ((cylinder, {"Ta": Ta}), (sphere, None)):
128
+ V, h = np.array([0.9, 1.2, 1.6]) * wall.V0, 1e-6
129
+ slope = (
130
+ wall.pressure(V * (1 + h), parameters) - wall.pressure(V * (1 - h), parameters)
131
+ ) / (2 * h * V)
132
+ assert np.allclose(wall.stiffness(V, parameters), slope, rtol=1e-6)
133
+
134
+
135
+ def test_thin_sphere_is_the_spherical_ventricle():
136
+ # The one-fibre model of SphericalVentricle is exact in the limit of a thin wall: the
137
+ # difference is first order in the thickness
138
+ differences = []
139
+ for h0 in (1e-2, 1e-3):
140
+ sphere = ThickSphere(Ri=1.0, Ro=1.0 + h0)
141
+ ventricle = zero_mech.SphericalVentricle.from_radius(1.0, h0)
142
+ V = 1.5 * sphere.V0
143
+ differences.append(abs(ventricle.pressure(V) / sphere.pressure(V) - 1))
144
+ assert differences[1] < 2e-3
145
+ assert differences[0] / differences[1] == pytest.approx(10, rel=0.1)
146
+
147
+
148
+ def test_quadrature_of_a_smooth_integrand_converges_to_round_off():
149
+ model = contracting_wall()
150
+ coarse = ThickCylinder(model, RI, RO, parameters=TRANSVERSELY_ISOTROPIC, num_points=60)
151
+ fine = ThickCylinder(model, RI, RO, parameters=TRANSVERSELY_ISOTROPIC, num_points=240)
152
+ V = 1.2 * coarse.V0 # the fibres are stretched everywhere, so the heaviside does not switch
153
+ assert np.all(coarse.stretch(V) > 1)
154
+ assert coarse.pressure(V) == pytest.approx(fine.pressure(V), rel=1e-13)
155
+
156
+
157
+ def test_holzapfel_ogden_with_fibres_in_the_wall_plane_is_refused_by_the_sphere():
158
+ model = zero_mech.Model(material=zero_mech.material.HolzapfelOgden(use_heaviside=True))
159
+ with pytest.raises(ValueError, match="wall plane"):
160
+ ThickSphere(model, RI, RO, parameters=TRANSVERSELY_ISOTROPIC)
161
+ # Without the fibre term, or with the fibres through the wall, it is symmetric
162
+ ThickSphere(model, RI, RO, parameters={**TRANSVERSELY_ISOTROPIC, "a_f": 0.0})
163
+ ThickSphere(model, RI, RO, radial_axis=0, parameters=TRANSVERSELY_ISOTROPIC)
164
+
165
+
166
+ def test_an_active_stress_along_the_wall_plane_is_refused_by_the_sphere():
167
+ sphere = ThickSphere(zero_mech.Model(active=zero_mech.StretchActiveStress()), RI, RO)
168
+ assert sphere.pressure(sphere.V0) == pytest.approx(0.0, abs=1e-13) # Ta defaults to 0
169
+ with pytest.raises(ValueError, match="wall plane"):
170
+ sphere.pressure(sphere.V0, parameters={"Ta": 1.0})
171
+ with pytest.raises(ValueError, match="wall plane"):
172
+ sphere.stiffness(sphere.V0, parameters={"Ta": 1.0})
173
+
174
+
175
+ def test_fibres_off_the_axes_are_refused_by_the_cylinder():
176
+ helix = sp.Matrix([math.cos(0.5), 0, math.sin(0.5)])
177
+ material = zero_mech.material.HolzapfelOgden(use_heaviside=True, f0=helix)
178
+ with pytest.raises(ValueError, match="axes of the tube"):
179
+ ThickCylinder(zero_mech.Model(material=material), RI, RO, parameters=TRANSVERSELY_ISOTROPIC)
180
+
181
+
182
+ @pytest.mark.parametrize(
183
+ "kwargs",
184
+ [dict(Ri=0.0), dict(Ri=1.5, Ro=1.0), dict(num_points=0), dict(radial_axis=3)],
185
+ )
186
+ def test_rejects_bad_geometry(kwargs):
187
+ with pytest.raises(ValueError):
188
+ ThickSphere(**kwargs)
189
+
190
+
191
+ def test_cylinder_rejects_equal_axes():
192
+ with pytest.raises(ValueError, match="distinct"):
193
+ ThickCylinder(radial_axis=2, axial_axis=2)
194
+
195
+
196
+ def test_rejects_a_compressible_wall():
197
+ model = zero_mech.Model(compressibility=zero_mech.compressibility.Compressible1())
198
+ with pytest.raises(ValueError, match="incompressible"):
199
+ ThickCylinder(model)
200
+
201
+
202
+ def test_unknown_parameter_names_are_rejected():
203
+ with pytest.raises(KeyError, match="typo_mu"):
204
+ ThickCylinder(parameters={"typo_mu": 3.0})
205
+ sphere = ThickSphere()
206
+ with pytest.raises(KeyError, match="typo_mu"):
207
+ sphere.pressure(5.0, parameters={"typo_mu": 3.0})
208
+
209
+
210
+ def test_parameters_and_symbols():
211
+ cylinder = ThickCylinder(parameters={"mu": 30.0})
212
+ assert cylinder.parameters == {"mu": 30.0}
213
+ reference = ThickCylinder()
214
+ V = 1.4 * cylinder.V0
215
+ assert cylinder.pressure(V) == pytest.approx(2 * reference.pressure(V))
216
+ assert cylinder.pressure(V, parameters={cylinder.model["mu"]: 15.0}) == pytest.approx(
217
+ reference.pressure(V)
218
+ )
219
+ assert {"R", "r_i", "mu"} <= set(cylinder.variables())
220
+ assert cylinder.integrand_expr.free_symbols == {cylinder["R"], cylinder["r_i"], cylinder["mu"]}
221
+ assert cylinder.circumferential_axis == 0
@@ -1,91 +0,0 @@
1
- import logging
2
- from dataclasses import dataclass, field
3
- import sympy as sp
4
-
5
- from .atoms import AbstractStrainEnergy
6
-
7
- logger = logging.getLogger(__name__)
8
-
9
-
10
- @dataclass(slots=True, frozen=True)
11
- class NeoHookean(AbstractStrainEnergy):
12
- mu: sp.Symbol = sp.Symbol("mu")
13
-
14
- def strain_energy(self, F: sp.Matrix) -> sp.Expr:
15
- C = F.T @ F
16
- I1 = sp.trace(C)
17
- return self.mu / 2 * (I1 - 3)
18
-
19
- def default_parameters(self):
20
- return {self.mu: 15.0}
21
-
22
- @staticmethod
23
- def str() -> str:
24
- return "μ / 2 * (I1 - 3)"
25
-
26
-
27
- # class LinearElastic(AbstractStrainEnergy):
28
- # mu: sp.Symbol = sp.Symbol("mu")
29
- # lmbda: sp.Symbol = sp.Symbol("lmbda")
30
-
31
- # def strain_energy(self, F: sp.Matrix) -> sp.Expr:
32
- # C = F.T @ F
33
- # I1 = sp.trace(C)
34
-
35
-
36
- @dataclass(slots=True, frozen=True)
37
- class HolzapfelOgden(AbstractStrainEnergy):
38
- a: sp.Symbol = sp.Symbol("a")
39
- b: sp.Symbol = sp.Symbol("b")
40
- a_f: sp.Symbol = sp.Symbol("a_f")
41
- b_f: sp.Symbol = sp.Symbol("b_f")
42
- a_s: sp.Symbol = sp.Symbol("a_s")
43
- b_s: sp.Symbol = sp.Symbol("b_s")
44
- a_fs: sp.Symbol = sp.Symbol("a_fs")
45
- b_fs: sp.Symbol = sp.Symbol("b_fs")
46
- f0: sp.Matrix = field(default_factory=lambda: sp.Matrix([1, 0, 0]))
47
- s0: sp.Matrix = field(default_factory=lambda: sp.Matrix([0, 1, 0]))
48
- use_heaviside: bool = False
49
-
50
- def strain_energy(self, F: sp.Matrix) -> sp.Expr:
51
- C = F.T @ F
52
-
53
- I1 = sp.trace(C)
54
- logger.debug(f"I1: {I1}")
55
- I4f = self.f0.dot(C * self.f0)
56
- logger.debug(f"I4f: {I4f}")
57
- I4s = self.s0.dot(C * self.s0)
58
- logger.debug(f"I4s: {I4s}")
59
- I8fs = self.f0.dot(C * self.s0)
60
- logger.debug(f"I8fs: {I8fs}")
61
-
62
- I4fm1 = I4f - 1 if not self.use_heaviside else sp.Piecewise((0.0, I4f < 1), (I4f - 1, True))
63
- I4sm1 = I4s - 1 if not self.use_heaviside else sp.Piecewise((0.0, I4s < 1), (I4s - 1, True))
64
-
65
- return (
66
- (self.a / (2 * self.b)) * (sp.exp(self.b * (I1 - 3)) - 1)
67
- + (self.a_f / (2 * self.b_f)) * (sp.exp(self.b_f * I4fm1**2) - 1)
68
- + (self.a_s / (2 * self.b_s)) * (sp.exp(self.b_s * I4sm1**2) - 1)
69
- + (self.a_fs / (2 * self.b_fs)) * (sp.exp(self.b_fs * I8fs**2) - 1)
70
- )
71
-
72
- def default_parameters(self):
73
- return {
74
- self.a: 0.059,
75
- self.b: 8.023,
76
- self.a_f: 18.472,
77
- self.b_f: 16.026,
78
- self.a_s: 2.481,
79
- self.b_s: 11.120,
80
- self.a_fs: 0.216,
81
- self.b_fs: 11.436,
82
- }
83
-
84
- @staticmethod
85
- def str() -> str:
86
- return (
87
- "(a / (2 * b)) * (exp(b * (I1 - 3)) - 1) + "
88
- "(a_f / (2 * b_f)) * (exp(b_f * H(I4f - 1)**2) - 1) + "
89
- "(a_s / (2 * b_s)) * (exp(b_s * H(I4f - 1)**2) - 1) + "
90
- "(a_fs / (2 * b_fs)) * (exp(b_fs * I8fs**2) - 1)"
91
- )
File without changes
File without changes
File without changes