ZTWHHH commited on
Commit
ef76aa4
·
verified ·
1 Parent(s): dd1d319

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. evalkit_internvl/lib/libcrypto.so.3 +3 -0
  3. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/__init__.cpython-310.pyc +0 -0
  4. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/hydrogen.cpython-310.pyc +0 -0
  5. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/matrices.cpython-310.pyc +0 -0
  6. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/paulialgebra.cpython-310.pyc +0 -0
  7. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/pring.cpython-310.pyc +0 -0
  8. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/qho_1d.cpython-310.pyc +0 -0
  9. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/secondquant.cpython-310.pyc +0 -0
  10. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/sho.cpython-310.pyc +0 -0
  11. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/wigner.cpython-310.pyc +0 -0
  12. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__init__.py +53 -0
  13. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/__init__.cpython-310.pyc +0 -0
  14. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/_mixin.cpython-310.pyc +0 -0
  15. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/activation.cpython-310.pyc +0 -0
  16. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/curve.cpython-310.pyc +0 -0
  17. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/musculotendon.cpython-310.pyc +0 -0
  18. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/_mixin.py +53 -0
  19. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/activation.py +869 -0
  20. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/curve.py +1763 -0
  21. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/musculotendon.py +1424 -0
  22. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__init__.py +0 -0
  23. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  24. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_activation.cpython-310.pyc +0 -0
  25. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_curve.cpython-310.pyc +0 -0
  26. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_mixin.cpython-310.pyc +0 -0
  27. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_musculotendon.cpython-310.pyc +0 -0
  28. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_activation.py +348 -0
  29. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_curve.py +1784 -0
  30. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_mixin.py +48 -0
  31. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_musculotendon.py +837 -0
  32. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-310.pyc +0 -0
  33. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/cable.cpython-310.pyc +0 -0
  34. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  35. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-310.pyc +0 -0
  36. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/control/__init__.py +16 -0
  37. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/control/control_plots.py +978 -0
  38. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/control/lti.py +0 -0
  39. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/control/tests/__init__.py +0 -0
  40. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/control/tests/test_control_plots.py +299 -0
  41. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/__init__.py +0 -0
  42. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/__init__.cpython-310.pyc +0 -0
  43. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/gamma_matrices.cpython-310.pyc +0 -0
  44. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/gamma_matrices.py +716 -0
  45. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/tests/__init__.py +0 -0
  46. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  47. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/test_gamma_matrices.cpython-310.pyc +0 -0
  48. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/tests/test_gamma_matrices.py +427 -0
  49. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/optics/__init__.py +38 -0
  50. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/__init__.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -1607,3 +1607,4 @@ evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/tokenizat
1607
  evalkit_internvl/lib/python3.10/site-packages/safetensors/_safetensors_rust.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1608
  evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1609
  evalkit_cambrian/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.so.12.1 filter=lfs diff=lfs merge=lfs -text
 
 
1607
  evalkit_internvl/lib/python3.10/site-packages/safetensors/_safetensors_rust.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1608
  evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1609
  evalkit_cambrian/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.so.12.1 filter=lfs diff=lfs merge=lfs -text
1610
+ evalkit_internvl/lib/libcrypto.so.3 filter=lfs diff=lfs merge=lfs -text
evalkit_internvl/lib/libcrypto.so.3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6def00ad4b209f9d5080358805e1228b5050747cc9f41921c3c87d58c27acda0
3
+ size 5172040
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (416 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/hydrogen.cpython-310.pyc ADDED
Binary file (7.36 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/matrices.cpython-310.pyc ADDED
Binary file (3.63 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/paulialgebra.cpython-310.pyc ADDED
Binary file (6.14 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/pring.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/qho_1d.cpython-310.pyc ADDED
Binary file (2.42 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/secondquant.cpython-310.pyc ADDED
Binary file (83.8 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/sho.cpython-310.pyc ADDED
Binary file (2.8 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__pycache__/wigner.cpython-310.pyc ADDED
Binary file (38 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Biomechanics extension for SymPy.
2
+
3
+ Includes biomechanics-related constructs which allows users to extend multibody
4
+ models created using `sympy.physics.mechanics` into biomechanical or
5
+ musculoskeletal models involding musculotendons and activation dynamics.
6
+
7
+ """
8
+
9
+ from .activation import (
10
+ ActivationBase,
11
+ FirstOrderActivationDeGroote2016,
12
+ ZerothOrderActivation,
13
+ )
14
+ from .curve import (
15
+ CharacteristicCurveCollection,
16
+ CharacteristicCurveFunction,
17
+ FiberForceLengthActiveDeGroote2016,
18
+ FiberForceLengthPassiveDeGroote2016,
19
+ FiberForceLengthPassiveInverseDeGroote2016,
20
+ FiberForceVelocityDeGroote2016,
21
+ FiberForceVelocityInverseDeGroote2016,
22
+ TendonForceLengthDeGroote2016,
23
+ TendonForceLengthInverseDeGroote2016,
24
+ )
25
+ from .musculotendon import (
26
+ MusculotendonBase,
27
+ MusculotendonDeGroote2016,
28
+ MusculotendonFormulation,
29
+ )
30
+
31
+
32
+ __all__ = [
33
+ # Musculotendon characteristic curve functions
34
+ 'CharacteristicCurveCollection',
35
+ 'CharacteristicCurveFunction',
36
+ 'FiberForceLengthActiveDeGroote2016',
37
+ 'FiberForceLengthPassiveDeGroote2016',
38
+ 'FiberForceLengthPassiveInverseDeGroote2016',
39
+ 'FiberForceVelocityDeGroote2016',
40
+ 'FiberForceVelocityInverseDeGroote2016',
41
+ 'TendonForceLengthDeGroote2016',
42
+ 'TendonForceLengthInverseDeGroote2016',
43
+
44
+ # Activation dynamics classes
45
+ 'ActivationBase',
46
+ 'FirstOrderActivationDeGroote2016',
47
+ 'ZerothOrderActivation',
48
+
49
+ # Musculotendon classes
50
+ 'MusculotendonBase',
51
+ 'MusculotendonDeGroote2016',
52
+ 'MusculotendonFormulation',
53
+ ]
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.23 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/_mixin.cpython-310.pyc ADDED
Binary file (1.71 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/activation.cpython-310.pyc ADDED
Binary file (25.8 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/curve.cpython-310.pyc ADDED
Binary file (55.4 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/musculotendon.cpython-310.pyc ADDED
Binary file (52.3 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/_mixin.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mixin classes for sharing functionality between unrelated classes.
2
+
3
+ This module is named with a leading underscore to signify to users that it's
4
+ "private" and only intended for internal use by the biomechanics module.
5
+
6
+ """
7
+
8
+
9
+ __all__ = ['_NamedMixin']
10
+
11
+
12
+ class _NamedMixin:
13
+ """Mixin class for adding `name` properties.
14
+
15
+ Valid names, as will typically be used by subclasses as a suffix when
16
+ naming automatically-instantiated symbol attributes, must be nonzero length
17
+ strings.
18
+
19
+ Attributes
20
+ ==========
21
+
22
+ name : str
23
+ The name identifier associated with the instance. Must be a string of
24
+ length at least 1.
25
+
26
+ """
27
+
28
+ @property
29
+ def name(self) -> str:
30
+ """The name associated with the class instance."""
31
+ return self._name
32
+
33
+ @name.setter
34
+ def name(self, name: str) -> None:
35
+ if hasattr(self, '_name'):
36
+ msg = (
37
+ f'Can\'t set attribute `name` to {repr(name)} as it is '
38
+ f'immutable.'
39
+ )
40
+ raise AttributeError(msg)
41
+ if not isinstance(name, str):
42
+ msg = (
43
+ f'Name {repr(name)} passed to `name` was of type '
44
+ f'{type(name)}, must be {str}.'
45
+ )
46
+ raise TypeError(msg)
47
+ if name in {''}:
48
+ msg = (
49
+ f'Name {repr(name)} is invalid, must be a nonzero length '
50
+ f'{type(str)}.'
51
+ )
52
+ raise ValueError(msg)
53
+ self._name = name
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/activation.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Activation dynamics for musclotendon models.
2
+
3
+ Musculotendon models are able to produce active force when they are activated,
4
+ which is when a chemical process has taken place within the muscle fibers
5
+ causing them to voluntarily contract. Biologically this chemical process (the
6
+ diffusion of :math:`\textrm{Ca}^{2+}` ions) is not the input in the system,
7
+ electrical signals from the nervous system are. These are termed excitations.
8
+ Activation dynamics, which relates the normalized excitation level to the
9
+ normalized activation level, can be modeled by the models present in this
10
+ module.
11
+
12
+ """
13
+
14
+ from abc import ABC, abstractmethod
15
+ from functools import cached_property
16
+
17
+ from sympy.core.symbol import Symbol
18
+ from sympy.core.numbers import Float, Integer, Rational
19
+ from sympy.functions.elementary.hyperbolic import tanh
20
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix, zeros
21
+ from sympy.physics.biomechanics._mixin import _NamedMixin
22
+ from sympy.physics.mechanics import dynamicsymbols
23
+
24
+
25
+ __all__ = [
26
+ 'ActivationBase',
27
+ 'FirstOrderActivationDeGroote2016',
28
+ 'ZerothOrderActivation',
29
+ ]
30
+
31
+
32
+ class ActivationBase(ABC, _NamedMixin):
33
+ """Abstract base class for all activation dynamics classes to inherit from.
34
+
35
+ Notes
36
+ =====
37
+
38
+ Instances of this class cannot be directly instantiated by users. However,
39
+ it can be used to created custom activation dynamics types through
40
+ subclassing.
41
+
42
+ """
43
+
44
+ def __init__(self, name):
45
+ """Initializer for ``ActivationBase``."""
46
+ self.name = str(name)
47
+
48
+ # Symbols
49
+ self._e = dynamicsymbols(f"e_{name}")
50
+ self._a = dynamicsymbols(f"a_{name}")
51
+
52
+ @classmethod
53
+ @abstractmethod
54
+ def with_defaults(cls, name):
55
+ """Alternate constructor that provides recommended defaults for
56
+ constants."""
57
+ pass
58
+
59
+ @property
60
+ def excitation(self):
61
+ """Dynamic symbol representing excitation.
62
+
63
+ Explanation
64
+ ===========
65
+
66
+ The alias ``e`` can also be used to access the same attribute.
67
+
68
+ """
69
+ return self._e
70
+
71
+ @property
72
+ def e(self):
73
+ """Dynamic symbol representing excitation.
74
+
75
+ Explanation
76
+ ===========
77
+
78
+ The alias ``excitation`` can also be used to access the same attribute.
79
+
80
+ """
81
+ return self._e
82
+
83
+ @property
84
+ def activation(self):
85
+ """Dynamic symbol representing activation.
86
+
87
+ Explanation
88
+ ===========
89
+
90
+ The alias ``a`` can also be used to access the same attribute.
91
+
92
+ """
93
+ return self._a
94
+
95
+ @property
96
+ def a(self):
97
+ """Dynamic symbol representing activation.
98
+
99
+ Explanation
100
+ ===========
101
+
102
+ The alias ``activation`` can also be used to access the same attribute.
103
+
104
+ """
105
+ return self._a
106
+
107
+ @property
108
+ @abstractmethod
109
+ def order(self):
110
+ """Order of the (differential) equation governing activation."""
111
+ pass
112
+
113
+ @property
114
+ @abstractmethod
115
+ def state_vars(self):
116
+ """Ordered column matrix of functions of time that represent the state
117
+ variables.
118
+
119
+ Explanation
120
+ ===========
121
+
122
+ The alias ``x`` can also be used to access the same attribute.
123
+
124
+ """
125
+ pass
126
+
127
+ @property
128
+ @abstractmethod
129
+ def x(self):
130
+ """Ordered column matrix of functions of time that represent the state
131
+ variables.
132
+
133
+ Explanation
134
+ ===========
135
+
136
+ The alias ``state_vars`` can also be used to access the same attribute.
137
+
138
+ """
139
+ pass
140
+
141
+ @property
142
+ @abstractmethod
143
+ def input_vars(self):
144
+ """Ordered column matrix of functions of time that represent the input
145
+ variables.
146
+
147
+ Explanation
148
+ ===========
149
+
150
+ The alias ``r`` can also be used to access the same attribute.
151
+
152
+ """
153
+ pass
154
+
155
+ @property
156
+ @abstractmethod
157
+ def r(self):
158
+ """Ordered column matrix of functions of time that represent the input
159
+ variables.
160
+
161
+ Explanation
162
+ ===========
163
+
164
+ The alias ``input_vars`` can also be used to access the same attribute.
165
+
166
+ """
167
+ pass
168
+
169
+ @property
170
+ @abstractmethod
171
+ def constants(self):
172
+ """Ordered column matrix of non-time varying symbols present in ``M``
173
+ and ``F``.
174
+
175
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
176
+ has been used instead of ``Symbol`` for a constant then that attribute
177
+ will not be included in the matrix returned by this property. This is
178
+ because the primary use of this property attribute is to provide an
179
+ ordered sequence of the still-free symbols that require numeric values
180
+ during code generation.
181
+
182
+ Explanation
183
+ ===========
184
+
185
+ The alias ``p`` can also be used to access the same attribute.
186
+
187
+ """
188
+ pass
189
+
190
+ @property
191
+ @abstractmethod
192
+ def p(self):
193
+ """Ordered column matrix of non-time varying symbols present in ``M``
194
+ and ``F``.
195
+
196
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
197
+ has been used instead of ``Symbol`` for a constant then that attribute
198
+ will not be included in the matrix returned by this property. This is
199
+ because the primary use of this property attribute is to provide an
200
+ ordered sequence of the still-free symbols that require numeric values
201
+ during code generation.
202
+
203
+ Explanation
204
+ ===========
205
+
206
+ The alias ``constants`` can also be used to access the same attribute.
207
+
208
+ """
209
+ pass
210
+
211
+ @property
212
+ @abstractmethod
213
+ def M(self):
214
+ """Ordered square matrix of coefficients on the LHS of ``M x' = F``.
215
+
216
+ Explanation
217
+ ===========
218
+
219
+ The square matrix that forms part of the LHS of the linear system of
220
+ ordinary differential equations governing the activation dynamics:
221
+
222
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
223
+
224
+ """
225
+ pass
226
+
227
+ @property
228
+ @abstractmethod
229
+ def F(self):
230
+ """Ordered column matrix of equations on the RHS of ``M x' = F``.
231
+
232
+ Explanation
233
+ ===========
234
+
235
+ The column matrix that forms the RHS of the linear system of ordinary
236
+ differential equations governing the activation dynamics:
237
+
238
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
239
+
240
+ """
241
+ pass
242
+
243
+ @abstractmethod
244
+ def rhs(self):
245
+ """
246
+
247
+ Explanation
248
+ ===========
249
+
250
+ The solution to the linear system of ordinary differential equations
251
+ governing the activation dynamics:
252
+
253
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
254
+
255
+ """
256
+ pass
257
+
258
+ def __eq__(self, other):
259
+ """Equality check for activation dynamics."""
260
+ if type(self) != type(other):
261
+ return False
262
+ if self.name != other.name:
263
+ return False
264
+ return True
265
+
266
+ def __repr__(self):
267
+ """Default representation of activation dynamics."""
268
+ return f'{self.__class__.__name__}({self.name!r})'
269
+
270
+
271
+ class ZerothOrderActivation(ActivationBase):
272
+ """Simple zeroth-order activation dynamics mapping excitation to
273
+ activation.
274
+
275
+ Explanation
276
+ ===========
277
+
278
+ Zeroth-order activation dynamics are useful in instances where you want to
279
+ reduce the complexity of your musculotendon dynamics as they simple map
280
+ exictation to activation. As a result, no additional state equations are
281
+ introduced to your system. They also remove a potential source of delay
282
+ between the input and dynamics of your system as no (ordinary) differential
283
+ equations are involed.
284
+
285
+ """
286
+
287
+ def __init__(self, name):
288
+ """Initializer for ``ZerothOrderActivation``.
289
+
290
+ Parameters
291
+ ==========
292
+
293
+ name : str
294
+ The name identifier associated with the instance. Must be a string
295
+ of length at least 1.
296
+
297
+ """
298
+ super().__init__(name)
299
+
300
+ # Zeroth-order activation dynamics has activation equal excitation so
301
+ # overwrite the symbol for activation with the excitation symbol.
302
+ self._a = self._e
303
+
304
+ @classmethod
305
+ def with_defaults(cls, name):
306
+ """Alternate constructor that provides recommended defaults for
307
+ constants.
308
+
309
+ Explanation
310
+ ===========
311
+
312
+ As this concrete class doesn't implement any constants associated with
313
+ its dynamics, this ``classmethod`` simply creates a standard instance
314
+ of ``ZerothOrderActivation``. An implementation is provided to ensure
315
+ a consistent interface between all ``ActivationBase`` concrete classes.
316
+
317
+ """
318
+ return cls(name)
319
+
320
+ @property
321
+ def order(self):
322
+ """Order of the (differential) equation governing activation."""
323
+ return 0
324
+
325
+ @property
326
+ def state_vars(self):
327
+ """Ordered column matrix of functions of time that represent the state
328
+ variables.
329
+
330
+ Explanation
331
+ ===========
332
+
333
+ As zeroth-order activation dynamics simply maps excitation to
334
+ activation, this class has no associated state variables and so this
335
+ property return an empty column ``Matrix`` with shape (0, 1).
336
+
337
+ The alias ``x`` can also be used to access the same attribute.
338
+
339
+ """
340
+ return zeros(0, 1)
341
+
342
+ @property
343
+ def x(self):
344
+ """Ordered column matrix of functions of time that represent the state
345
+ variables.
346
+
347
+ Explanation
348
+ ===========
349
+
350
+ As zeroth-order activation dynamics simply maps excitation to
351
+ activation, this class has no associated state variables and so this
352
+ property return an empty column ``Matrix`` with shape (0, 1).
353
+
354
+ The alias ``state_vars`` can also be used to access the same attribute.
355
+
356
+ """
357
+ return zeros(0, 1)
358
+
359
+ @property
360
+ def input_vars(self):
361
+ """Ordered column matrix of functions of time that represent the input
362
+ variables.
363
+
364
+ Explanation
365
+ ===========
366
+
367
+ Excitation is the only input in zeroth-order activation dynamics and so
368
+ this property returns a column ``Matrix`` with one entry, ``e``, and
369
+ shape (1, 1).
370
+
371
+ The alias ``r`` can also be used to access the same attribute.
372
+
373
+ """
374
+ return Matrix([self._e])
375
+
376
+ @property
377
+ def r(self):
378
+ """Ordered column matrix of functions of time that represent the input
379
+ variables.
380
+
381
+ Explanation
382
+ ===========
383
+
384
+ Excitation is the only input in zeroth-order activation dynamics and so
385
+ this property returns a column ``Matrix`` with one entry, ``e``, and
386
+ shape (1, 1).
387
+
388
+ The alias ``input_vars`` can also be used to access the same attribute.
389
+
390
+ """
391
+ return Matrix([self._e])
392
+
393
+ @property
394
+ def constants(self):
395
+ """Ordered column matrix of non-time varying symbols present in ``M``
396
+ and ``F``.
397
+
398
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
399
+ has been used instead of ``Symbol`` for a constant then that attribute
400
+ will not be included in the matrix returned by this property. This is
401
+ because the primary use of this property attribute is to provide an
402
+ ordered sequence of the still-free symbols that require numeric values
403
+ during code generation.
404
+
405
+ Explanation
406
+ ===========
407
+
408
+ As zeroth-order activation dynamics simply maps excitation to
409
+ activation, this class has no associated constants and so this property
410
+ return an empty column ``Matrix`` with shape (0, 1).
411
+
412
+ The alias ``p`` can also be used to access the same attribute.
413
+
414
+ """
415
+ return zeros(0, 1)
416
+
417
+ @property
418
+ def p(self):
419
+ """Ordered column matrix of non-time varying symbols present in ``M``
420
+ and ``F``.
421
+
422
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
423
+ has been used instead of ``Symbol`` for a constant then that attribute
424
+ will not be included in the matrix returned by this property. This is
425
+ because the primary use of this property attribute is to provide an
426
+ ordered sequence of the still-free symbols that require numeric values
427
+ during code generation.
428
+
429
+ Explanation
430
+ ===========
431
+
432
+ As zeroth-order activation dynamics simply maps excitation to
433
+ activation, this class has no associated constants and so this property
434
+ return an empty column ``Matrix`` with shape (0, 1).
435
+
436
+ The alias ``constants`` can also be used to access the same attribute.
437
+
438
+ """
439
+ return zeros(0, 1)
440
+
441
+ @property
442
+ def M(self):
443
+ """Ordered square matrix of coefficients on the LHS of ``M x' = F``.
444
+
445
+ Explanation
446
+ ===========
447
+
448
+ The square matrix that forms part of the LHS of the linear system of
449
+ ordinary differential equations governing the activation dynamics:
450
+
451
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
452
+
453
+ As zeroth-order activation dynamics have no state variables, this
454
+ linear system has dimension 0 and therefore ``M`` is an empty square
455
+ ``Matrix`` with shape (0, 0).
456
+
457
+ """
458
+ return Matrix([])
459
+
460
+ @property
461
+ def F(self):
462
+ """Ordered column matrix of equations on the RHS of ``M x' = F``.
463
+
464
+ Explanation
465
+ ===========
466
+
467
+ The column matrix that forms the RHS of the linear system of ordinary
468
+ differential equations governing the activation dynamics:
469
+
470
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
471
+
472
+ As zeroth-order activation dynamics have no state variables, this
473
+ linear system has dimension 0 and therefore ``F`` is an empty column
474
+ ``Matrix`` with shape (0, 1).
475
+
476
+ """
477
+ return zeros(0, 1)
478
+
479
+ def rhs(self):
480
+ """Ordered column matrix of equations for the solution of ``M x' = F``.
481
+
482
+ Explanation
483
+ ===========
484
+
485
+ The solution to the linear system of ordinary differential equations
486
+ governing the activation dynamics:
487
+
488
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
489
+
490
+ As zeroth-order activation dynamics have no state variables, this
491
+ linear has dimension 0 and therefore this method returns an empty
492
+ column ``Matrix`` with shape (0, 1).
493
+
494
+ """
495
+ return zeros(0, 1)
496
+
497
+
498
+ class FirstOrderActivationDeGroote2016(ActivationBase):
499
+ r"""First-order activation dynamics based on De Groote et al., 2016 [1]_.
500
+
501
+ Explanation
502
+ ===========
503
+
504
+ Gives the first-order activation dynamics equation for the rate of change
505
+ of activation with respect to time as a function of excitation and
506
+ activation.
507
+
508
+ The function is defined by the equation:
509
+
510
+ .. math::
511
+
512
+ \frac{da}{dt} = \left(\frac{\frac{1}{2} + a0}{\tau_a \left(\frac{1}{2}
513
+ + \frac{3a}{2}\right)} + \frac{\left(\frac{1}{2}
514
+ + \frac{3a}{2}\right) \left(\frac{1}{2} - a0\right)}{\tau_d}\right)
515
+ \left(e - a\right)
516
+
517
+ where
518
+
519
+ .. math::
520
+
521
+ a0 = \frac{\tanh{\left(b \left(e - a\right) \right)}}{2}
522
+
523
+ with constant values of :math:`tau_a = 0.015`, :math:`tau_d = 0.060`, and
524
+ :math:`b = 10`.
525
+
526
+ References
527
+ ==========
528
+
529
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
530
+ of direct collocation optimal control problem formulations for
531
+ solving the muscle redundancy problem, Annals of biomedical
532
+ engineering, 44(10), (2016) pp. 2922-2936
533
+
534
+ """
535
+
536
+ def __init__(self,
537
+ name,
538
+ activation_time_constant=None,
539
+ deactivation_time_constant=None,
540
+ smoothing_rate=None,
541
+ ):
542
+ """Initializer for ``FirstOrderActivationDeGroote2016``.
543
+
544
+ Parameters
545
+ ==========
546
+ activation time constant : Symbol | Number | None
547
+ The value of the activation time constant governing the delay
548
+ between excitation and activation when excitation exceeds
549
+ activation.
550
+ deactivation time constant : Symbol | Number | None
551
+ The value of the deactivation time constant governing the delay
552
+ between excitation and activation when activation exceeds
553
+ excitation.
554
+ smoothing_rate : Symbol | Number | None
555
+ The slope of the hyperbolic tangent function used to smooth between
556
+ the switching of the equations where excitation exceed activation
557
+ and where activation exceeds excitation. The recommended value to
558
+ use is ``10``, but values between ``0.1`` and ``100`` can be used.
559
+
560
+ """
561
+ super().__init__(name)
562
+
563
+ # Symbols
564
+ self.activation_time_constant = activation_time_constant
565
+ self.deactivation_time_constant = deactivation_time_constant
566
+ self.smoothing_rate = smoothing_rate
567
+
568
+ @classmethod
569
+ def with_defaults(cls, name):
570
+ r"""Alternate constructor that will use the published constants.
571
+
572
+ Explanation
573
+ ===========
574
+
575
+ Returns an instance of ``FirstOrderActivationDeGroote2016`` using the
576
+ three constant values specified in the original publication.
577
+
578
+ These have the values:
579
+
580
+ :math:`tau_a = 0.015`
581
+ :math:`tau_d = 0.060`
582
+ :math:`b = 10`
583
+
584
+ """
585
+ tau_a = Float('0.015')
586
+ tau_d = Float('0.060')
587
+ b = Float('10.0')
588
+ return cls(name, tau_a, tau_d, b)
589
+
590
+ @property
591
+ def activation_time_constant(self):
592
+ """Delay constant for activation.
593
+
594
+ Explanation
595
+ ===========
596
+
597
+ The alias ```tau_a`` can also be used to access the same attribute.
598
+
599
+ """
600
+ return self._tau_a
601
+
602
+ @activation_time_constant.setter
603
+ def activation_time_constant(self, tau_a):
604
+ if hasattr(self, '_tau_a'):
605
+ msg = (
606
+ f'Can\'t set attribute `activation_time_constant` to '
607
+ f'{repr(tau_a)} as it is immutable and already has value '
608
+ f'{self._tau_a}.'
609
+ )
610
+ raise AttributeError(msg)
611
+ self._tau_a = Symbol(f'tau_a_{self.name}') if tau_a is None else tau_a
612
+
613
+ @property
614
+ def tau_a(self):
615
+ """Delay constant for activation.
616
+
617
+ Explanation
618
+ ===========
619
+
620
+ The alias ``activation_time_constant`` can also be used to access the
621
+ same attribute.
622
+
623
+ """
624
+ return self._tau_a
625
+
626
+ @property
627
+ def deactivation_time_constant(self):
628
+ """Delay constant for deactivation.
629
+
630
+ Explanation
631
+ ===========
632
+
633
+ The alias ``tau_d`` can also be used to access the same attribute.
634
+
635
+ """
636
+ return self._tau_d
637
+
638
+ @deactivation_time_constant.setter
639
+ def deactivation_time_constant(self, tau_d):
640
+ if hasattr(self, '_tau_d'):
641
+ msg = (
642
+ f'Can\'t set attribute `deactivation_time_constant` to '
643
+ f'{repr(tau_d)} as it is immutable and already has value '
644
+ f'{self._tau_d}.'
645
+ )
646
+ raise AttributeError(msg)
647
+ self._tau_d = Symbol(f'tau_d_{self.name}') if tau_d is None else tau_d
648
+
649
+ @property
650
+ def tau_d(self):
651
+ """Delay constant for deactivation.
652
+
653
+ Explanation
654
+ ===========
655
+
656
+ The alias ``deactivation_time_constant`` can also be used to access the
657
+ same attribute.
658
+
659
+ """
660
+ return self._tau_d
661
+
662
+ @property
663
+ def smoothing_rate(self):
664
+ """Smoothing constant for the hyperbolic tangent term.
665
+
666
+ Explanation
667
+ ===========
668
+
669
+ The alias ``b`` can also be used to access the same attribute.
670
+
671
+ """
672
+ return self._b
673
+
674
+ @smoothing_rate.setter
675
+ def smoothing_rate(self, b):
676
+ if hasattr(self, '_b'):
677
+ msg = (
678
+ f'Can\'t set attribute `smoothing_rate` to {b!r} as it is '
679
+ f'immutable and already has value {self._b!r}.'
680
+ )
681
+ raise AttributeError(msg)
682
+ self._b = Symbol(f'b_{self.name}') if b is None else b
683
+
684
+ @property
685
+ def b(self):
686
+ """Smoothing constant for the hyperbolic tangent term.
687
+
688
+ Explanation
689
+ ===========
690
+
691
+ The alias ``smoothing_rate`` can also be used to access the same
692
+ attribute.
693
+
694
+ """
695
+ return self._b
696
+
697
+ @property
698
+ def order(self):
699
+ """Order of the (differential) equation governing activation."""
700
+ return 1
701
+
702
+ @property
703
+ def state_vars(self):
704
+ """Ordered column matrix of functions of time that represent the state
705
+ variables.
706
+
707
+ Explanation
708
+ ===========
709
+
710
+ The alias ``x`` can also be used to access the same attribute.
711
+
712
+ """
713
+ return Matrix([self._a])
714
+
715
+ @property
716
+ def x(self):
717
+ """Ordered column matrix of functions of time that represent the state
718
+ variables.
719
+
720
+ Explanation
721
+ ===========
722
+
723
+ The alias ``state_vars`` can also be used to access the same attribute.
724
+
725
+ """
726
+ return Matrix([self._a])
727
+
728
+ @property
729
+ def input_vars(self):
730
+ """Ordered column matrix of functions of time that represent the input
731
+ variables.
732
+
733
+ Explanation
734
+ ===========
735
+
736
+ The alias ``r`` can also be used to access the same attribute.
737
+
738
+ """
739
+ return Matrix([self._e])
740
+
741
+ @property
742
+ def r(self):
743
+ """Ordered column matrix of functions of time that represent the input
744
+ variables.
745
+
746
+ Explanation
747
+ ===========
748
+
749
+ The alias ``input_vars`` can also be used to access the same attribute.
750
+
751
+ """
752
+ return Matrix([self._e])
753
+
754
+ @property
755
+ def constants(self):
756
+ """Ordered column matrix of non-time varying symbols present in ``M``
757
+ and ``F``.
758
+
759
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
760
+ has been used instead of ``Symbol`` for a constant then that attribute
761
+ will not be included in the matrix returned by this property. This is
762
+ because the primary use of this property attribute is to provide an
763
+ ordered sequence of the still-free symbols that require numeric values
764
+ during code generation.
765
+
766
+ Explanation
767
+ ===========
768
+
769
+ The alias ``p`` can also be used to access the same attribute.
770
+
771
+ """
772
+ constants = [self._tau_a, self._tau_d, self._b]
773
+ symbolic_constants = [c for c in constants if not c.is_number]
774
+ return Matrix(symbolic_constants) if symbolic_constants else zeros(0, 1)
775
+
776
+ @property
777
+ def p(self):
778
+ """Ordered column matrix of non-time varying symbols present in ``M``
779
+ and ``F``.
780
+
781
+ Explanation
782
+ ===========
783
+
784
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
785
+ has been used instead of ``Symbol`` for a constant then that attribute
786
+ will not be included in the matrix returned by this property. This is
787
+ because the primary use of this property attribute is to provide an
788
+ ordered sequence of the still-free symbols that require numeric values
789
+ during code generation.
790
+
791
+ The alias ``constants`` can also be used to access the same attribute.
792
+
793
+ """
794
+ constants = [self._tau_a, self._tau_d, self._b]
795
+ symbolic_constants = [c for c in constants if not c.is_number]
796
+ return Matrix(symbolic_constants) if symbolic_constants else zeros(0, 1)
797
+
798
+ @property
799
+ def M(self):
800
+ """Ordered square matrix of coefficients on the LHS of ``M x' = F``.
801
+
802
+ Explanation
803
+ ===========
804
+
805
+ The square matrix that forms part of the LHS of the linear system of
806
+ ordinary differential equations governing the activation dynamics:
807
+
808
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
809
+
810
+ """
811
+ return Matrix([Integer(1)])
812
+
813
+ @property
814
+ def F(self):
815
+ """Ordered column matrix of equations on the RHS of ``M x' = F``.
816
+
817
+ Explanation
818
+ ===========
819
+
820
+ The column matrix that forms the RHS of the linear system of ordinary
821
+ differential equations governing the activation dynamics:
822
+
823
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
824
+
825
+ """
826
+ return Matrix([self._da_eqn])
827
+
828
+ def rhs(self):
829
+ """Ordered column matrix of equations for the solution of ``M x' = F``.
830
+
831
+ Explanation
832
+ ===========
833
+
834
+ The solution to the linear system of ordinary differential equations
835
+ governing the activation dynamics:
836
+
837
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
838
+
839
+ """
840
+ return Matrix([self._da_eqn])
841
+
842
+ @cached_property
843
+ def _da_eqn(self):
844
+ HALF = Rational(1, 2)
845
+ a0 = HALF * tanh(self._b * (self._e - self._a))
846
+ a1 = (HALF + Rational(3, 2) * self._a)
847
+ a2 = (HALF + a0) / (self._tau_a * a1)
848
+ a3 = a1 * (HALF - a0) / self._tau_d
849
+ activation_dynamics_equation = (a2 + a3) * (self._e - self._a)
850
+ return activation_dynamics_equation
851
+
852
+ def __eq__(self, other):
853
+ """Equality check for ``FirstOrderActivationDeGroote2016``."""
854
+ if type(self) != type(other):
855
+ return False
856
+ self_attrs = (self.name, self.tau_a, self.tau_d, self.b)
857
+ other_attrs = (other.name, other.tau_a, other.tau_d, other.b)
858
+ if self_attrs == other_attrs:
859
+ return True
860
+ return False
861
+
862
+ def __repr__(self):
863
+ """Representation of ``FirstOrderActivationDeGroote2016``."""
864
+ return (
865
+ f'{self.__class__.__name__}({self.name!r}, '
866
+ f'activation_time_constant={self.tau_a!r}, '
867
+ f'deactivation_time_constant={self.tau_d!r}, '
868
+ f'smoothing_rate={self.b!r})'
869
+ )
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/curve.py ADDED
@@ -0,0 +1,1763 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementations of characteristic curves for musculotendon models."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from sympy.core.expr import UnevaluatedExpr
6
+ from sympy.core.function import ArgumentIndexError, Function
7
+ from sympy.core.numbers import Float, Integer
8
+ from sympy.functions.elementary.exponential import exp, log
9
+ from sympy.functions.elementary.hyperbolic import cosh, sinh
10
+ from sympy.functions.elementary.miscellaneous import sqrt
11
+ from sympy.printing.precedence import PRECEDENCE
12
+
13
+
14
+ __all__ = [
15
+ 'CharacteristicCurveCollection',
16
+ 'CharacteristicCurveFunction',
17
+ 'FiberForceLengthActiveDeGroote2016',
18
+ 'FiberForceLengthPassiveDeGroote2016',
19
+ 'FiberForceLengthPassiveInverseDeGroote2016',
20
+ 'FiberForceVelocityDeGroote2016',
21
+ 'FiberForceVelocityInverseDeGroote2016',
22
+ 'TendonForceLengthDeGroote2016',
23
+ 'TendonForceLengthInverseDeGroote2016',
24
+ ]
25
+
26
+
27
+ class CharacteristicCurveFunction(Function):
28
+ """Base class for all musculotendon characteristic curve functions."""
29
+
30
+ @classmethod
31
+ def eval(cls):
32
+ msg = (
33
+ f'Cannot directly instantiate {cls.__name__!r}, instances of '
34
+ f'characteristic curves must be of a concrete subclass.'
35
+
36
+ )
37
+ raise TypeError(msg)
38
+
39
+ def _print_code(self, printer):
40
+ """Print code for the function defining the curve using a printer.
41
+
42
+ Explanation
43
+ ===========
44
+
45
+ The order of operations may need to be controlled as constant folding
46
+ the numeric terms within the equations of a musculotendon
47
+ characteristic curve can sometimes results in a numerically-unstable
48
+ expression.
49
+
50
+ Parameters
51
+ ==========
52
+
53
+ printer : Printer
54
+ The printer to be used to print a string representation of the
55
+ characteristic curve as valid code in the target language.
56
+
57
+ """
58
+ return printer._print(printer.parenthesize(
59
+ self.doit(deep=False, evaluate=False), PRECEDENCE['Atom'],
60
+ ))
61
+
62
+ _ccode = _print_code
63
+ _cupycode = _print_code
64
+ _cxxcode = _print_code
65
+ _fcode = _print_code
66
+ _jaxcode = _print_code
67
+ _lambdacode = _print_code
68
+ _mpmathcode = _print_code
69
+ _octave = _print_code
70
+ _pythoncode = _print_code
71
+ _numpycode = _print_code
72
+ _scipycode = _print_code
73
+
74
+
75
+ class TendonForceLengthDeGroote2016(CharacteristicCurveFunction):
76
+ r"""Tendon force-length curve based on De Groote et al., 2016 [1]_.
77
+
78
+ Explanation
79
+ ===========
80
+
81
+ Gives the normalized tendon force produced as a function of normalized
82
+ tendon length.
83
+
84
+ The function is defined by the equation:
85
+
86
+ $fl^T = c_0 \exp{c_3 \left( \tilde{l}^T - c_1 \right)} - c_2$
87
+
88
+ with constant values of $c_0 = 0.2$, $c_1 = 0.995$, $c_2 = 0.25$, and
89
+ $c_3 = 33.93669377311689$.
90
+
91
+ While it is possible to change the constant values, these were carefully
92
+ selected in the original publication to give the characteristic curve
93
+ specific and required properties. For example, the function produces no
94
+ force when the tendon is in an unstrained state. It also produces a force
95
+ of 1 normalized unit when the tendon is under a 5% strain.
96
+
97
+ Examples
98
+ ========
99
+
100
+ The preferred way to instantiate :class:`TendonForceLengthDeGroote2016` is using
101
+ the :meth:`~.with_defaults` constructor because this will automatically
102
+ populate the constants within the characteristic curve equation with the
103
+ floating point values from the original publication. This constructor takes
104
+ a single argument corresponding to normalized tendon length. We'll create a
105
+ :class:`~.Symbol` called ``l_T_tilde`` to represent this.
106
+
107
+ >>> from sympy import Symbol
108
+ >>> from sympy.physics.biomechanics import TendonForceLengthDeGroote2016
109
+ >>> l_T_tilde = Symbol('l_T_tilde')
110
+ >>> fl_T = TendonForceLengthDeGroote2016.with_defaults(l_T_tilde)
111
+ >>> fl_T
112
+ TendonForceLengthDeGroote2016(l_T_tilde, 0.2, 0.995, 0.25,
113
+ 33.93669377311689)
114
+
115
+ It's also possible to populate the four constants with your own values too.
116
+
117
+ >>> from sympy import symbols
118
+ >>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
119
+ >>> fl_T = TendonForceLengthDeGroote2016(l_T_tilde, c0, c1, c2, c3)
120
+ >>> fl_T
121
+ TendonForceLengthDeGroote2016(l_T_tilde, c0, c1, c2, c3)
122
+
123
+ You don't just have to use symbols as the arguments, it's also possible to
124
+ use expressions. Let's create a new pair of symbols, ``l_T`` and
125
+ ``l_T_slack``, representing tendon length and tendon slack length
126
+ respectively. We can then represent ``l_T_tilde`` as an expression, the
127
+ ratio of these.
128
+
129
+ >>> l_T, l_T_slack = symbols('l_T l_T_slack')
130
+ >>> l_T_tilde = l_T/l_T_slack
131
+ >>> fl_T = TendonForceLengthDeGroote2016.with_defaults(l_T_tilde)
132
+ >>> fl_T
133
+ TendonForceLengthDeGroote2016(l_T/l_T_slack, 0.2, 0.995, 0.25,
134
+ 33.93669377311689)
135
+
136
+ To inspect the actual symbolic expression that this function represents,
137
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
138
+ argument ``evaluate=False`` as this will keep the expression in its
139
+ canonical form and won't simplify any constants.
140
+
141
+ >>> fl_T.doit(evaluate=False)
142
+ -0.25 + 0.2*exp(33.93669377311689*(l_T/l_T_slack - 0.995))
143
+
144
+ The function can also be differentiated. We'll differentiate with respect
145
+ to l_T using the ``diff`` method on an instance with the single positional
146
+ argument ``l_T``.
147
+
148
+ >>> fl_T.diff(l_T)
149
+ 6.787338754623378*exp(33.93669377311689*(l_T/l_T_slack - 0.995))/l_T_slack
150
+
151
+ References
152
+ ==========
153
+
154
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
155
+ of direct collocation optimal control problem formulations for
156
+ solving the muscle redundancy problem, Annals of biomedical
157
+ engineering, 44(10), (2016) pp. 2922-2936
158
+
159
+ """
160
+
161
+ @classmethod
162
+ def with_defaults(cls, l_T_tilde):
163
+ r"""Recommended constructor that will use the published constants.
164
+
165
+ Explanation
166
+ ===========
167
+
168
+ Returns a new instance of the tendon force-length function using the
169
+ four constant values specified in the original publication.
170
+
171
+ These have the values:
172
+
173
+ $c_0 = 0.2$
174
+ $c_1 = 0.995$
175
+ $c_2 = 0.25$
176
+ $c_3 = 33.93669377311689$
177
+
178
+ Parameters
179
+ ==========
180
+
181
+ l_T_tilde : Any (sympifiable)
182
+ Normalized tendon length.
183
+
184
+ """
185
+ c0 = Float('0.2')
186
+ c1 = Float('0.995')
187
+ c2 = Float('0.25')
188
+ c3 = Float('33.93669377311689')
189
+ return cls(l_T_tilde, c0, c1, c2, c3)
190
+
191
+ @classmethod
192
+ def eval(cls, l_T_tilde, c0, c1, c2, c3):
193
+ """Evaluation of basic inputs.
194
+
195
+ Parameters
196
+ ==========
197
+
198
+ l_T_tilde : Any (sympifiable)
199
+ Normalized tendon length.
200
+ c0 : Any (sympifiable)
201
+ The first constant in the characteristic equation. The published
202
+ value is ``0.2``.
203
+ c1 : Any (sympifiable)
204
+ The second constant in the characteristic equation. The published
205
+ value is ``0.995``.
206
+ c2 : Any (sympifiable)
207
+ The third constant in the characteristic equation. The published
208
+ value is ``0.25``.
209
+ c3 : Any (sympifiable)
210
+ The fourth constant in the characteristic equation. The published
211
+ value is ``33.93669377311689``.
212
+
213
+ """
214
+ pass
215
+
216
+ def _eval_evalf(self, prec):
217
+ """Evaluate the expression numerically using ``evalf``."""
218
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
219
+
220
+ def doit(self, deep=True, evaluate=True, **hints):
221
+ """Evaluate the expression defining the function.
222
+
223
+ Parameters
224
+ ==========
225
+
226
+ deep : bool
227
+ Whether ``doit`` should be recursively called. Default is ``True``.
228
+ evaluate : bool.
229
+ Whether the SymPy expression should be evaluated as it is
230
+ constructed. If ``False``, then no constant folding will be
231
+ conducted which will leave the expression in a more numerically-
232
+ stable for values of ``l_T_tilde`` that correspond to a sensible
233
+ operating range for a musculotendon. Default is ``True``.
234
+ **kwargs : dict[str, Any]
235
+ Additional keyword argument pairs to be recursively passed to
236
+ ``doit``.
237
+
238
+ """
239
+ l_T_tilde, *constants = self.args
240
+ if deep:
241
+ hints['evaluate'] = evaluate
242
+ l_T_tilde = l_T_tilde.doit(deep=deep, **hints)
243
+ c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
244
+ else:
245
+ c0, c1, c2, c3 = constants
246
+
247
+ if evaluate:
248
+ return c0*exp(c3*(l_T_tilde - c1)) - c2
249
+
250
+ return c0*exp(c3*UnevaluatedExpr(l_T_tilde - c1)) - c2
251
+
252
+ def fdiff(self, argindex=1):
253
+ """Derivative of the function with respect to a single argument.
254
+
255
+ Parameters
256
+ ==========
257
+
258
+ argindex : int
259
+ The index of the function's arguments with respect to which the
260
+ derivative should be taken. Argument indexes start at ``1``.
261
+ Default is ``1``.
262
+
263
+ """
264
+ l_T_tilde, c0, c1, c2, c3 = self.args
265
+ if argindex == 1:
266
+ return c0*c3*exp(c3*UnevaluatedExpr(l_T_tilde - c1))
267
+ elif argindex == 2:
268
+ return exp(c3*UnevaluatedExpr(l_T_tilde - c1))
269
+ elif argindex == 3:
270
+ return -c0*c3*exp(c3*UnevaluatedExpr(l_T_tilde - c1))
271
+ elif argindex == 4:
272
+ return Integer(-1)
273
+ elif argindex == 5:
274
+ return c0*(l_T_tilde - c1)*exp(c3*UnevaluatedExpr(l_T_tilde - c1))
275
+
276
+ raise ArgumentIndexError(self, argindex)
277
+
278
+ def inverse(self, argindex=1):
279
+ """Inverse function.
280
+
281
+ Parameters
282
+ ==========
283
+
284
+ argindex : int
285
+ Value to start indexing the arguments at. Default is ``1``.
286
+
287
+ """
288
+ return TendonForceLengthInverseDeGroote2016
289
+
290
+ def _latex(self, printer):
291
+ """Print a LaTeX representation of the function defining the curve.
292
+
293
+ Parameters
294
+ ==========
295
+
296
+ printer : Printer
297
+ The printer to be used to print the LaTeX string representation.
298
+
299
+ """
300
+ l_T_tilde = self.args[0]
301
+ _l_T_tilde = printer._print(l_T_tilde)
302
+ return r'\operatorname{fl}^T \left( %s \right)' % _l_T_tilde
303
+
304
+
305
+ class TendonForceLengthInverseDeGroote2016(CharacteristicCurveFunction):
306
+ r"""Inverse tendon force-length curve based on De Groote et al., 2016 [1]_.
307
+
308
+ Explanation
309
+ ===========
310
+
311
+ Gives the normalized tendon length that produces a specific normalized
312
+ tendon force.
313
+
314
+ The function is defined by the equation:
315
+
316
+ ${fl^T}^{-1} = frac{\log{\frac{fl^T + c_2}{c_0}}}{c_3} + c_1$
317
+
318
+ with constant values of $c_0 = 0.2$, $c_1 = 0.995$, $c_2 = 0.25$, and
319
+ $c_3 = 33.93669377311689$. This function is the exact analytical inverse
320
+ of the related tendon force-length curve ``TendonForceLengthDeGroote2016``.
321
+
322
+ While it is possible to change the constant values, these were carefully
323
+ selected in the original publication to give the characteristic curve
324
+ specific and required properties. For example, the function produces no
325
+ force when the tendon is in an unstrained state. It also produces a force
326
+ of 1 normalized unit when the tendon is under a 5% strain.
327
+
328
+ Examples
329
+ ========
330
+
331
+ The preferred way to instantiate :class:`TendonForceLengthInverseDeGroote2016` is
332
+ using the :meth:`~.with_defaults` constructor because this will automatically
333
+ populate the constants within the characteristic curve equation with the
334
+ floating point values from the original publication. This constructor takes
335
+ a single argument corresponding to normalized tendon force-length, which is
336
+ equal to the tendon force. We'll create a :class:`~.Symbol` called ``fl_T`` to
337
+ represent this.
338
+
339
+ >>> from sympy import Symbol
340
+ >>> from sympy.physics.biomechanics import TendonForceLengthInverseDeGroote2016
341
+ >>> fl_T = Symbol('fl_T')
342
+ >>> l_T_tilde = TendonForceLengthInverseDeGroote2016.with_defaults(fl_T)
343
+ >>> l_T_tilde
344
+ TendonForceLengthInverseDeGroote2016(fl_T, 0.2, 0.995, 0.25,
345
+ 33.93669377311689)
346
+
347
+ It's also possible to populate the four constants with your own values too.
348
+
349
+ >>> from sympy import symbols
350
+ >>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
351
+ >>> l_T_tilde = TendonForceLengthInverseDeGroote2016(fl_T, c0, c1, c2, c3)
352
+ >>> l_T_tilde
353
+ TendonForceLengthInverseDeGroote2016(fl_T, c0, c1, c2, c3)
354
+
355
+ To inspect the actual symbolic expression that this function represents,
356
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
357
+ argument ``evaluate=False`` as this will keep the expression in its
358
+ canonical form and won't simplify any constants.
359
+
360
+ >>> l_T_tilde.doit(evaluate=False)
361
+ c1 + log((c2 + fl_T)/c0)/c3
362
+
363
+ The function can also be differentiated. We'll differentiate with respect
364
+ to l_T using the ``diff`` method on an instance with the single positional
365
+ argument ``l_T``.
366
+
367
+ >>> l_T_tilde.diff(fl_T)
368
+ 1/(c3*(c2 + fl_T))
369
+
370
+ References
371
+ ==========
372
+
373
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
374
+ of direct collocation optimal control problem formulations for
375
+ solving the muscle redundancy problem, Annals of biomedical
376
+ engineering, 44(10), (2016) pp. 2922-2936
377
+
378
+ """
379
+
380
+ @classmethod
381
+ def with_defaults(cls, fl_T):
382
+ r"""Recommended constructor that will use the published constants.
383
+
384
+ Explanation
385
+ ===========
386
+
387
+ Returns a new instance of the inverse tendon force-length function
388
+ using the four constant values specified in the original publication.
389
+
390
+ These have the values:
391
+
392
+ $c_0 = 0.2$
393
+ $c_1 = 0.995$
394
+ $c_2 = 0.25$
395
+ $c_3 = 33.93669377311689$
396
+
397
+ Parameters
398
+ ==========
399
+
400
+ fl_T : Any (sympifiable)
401
+ Normalized tendon force as a function of tendon length.
402
+
403
+ """
404
+ c0 = Float('0.2')
405
+ c1 = Float('0.995')
406
+ c2 = Float('0.25')
407
+ c3 = Float('33.93669377311689')
408
+ return cls(fl_T, c0, c1, c2, c3)
409
+
410
+ @classmethod
411
+ def eval(cls, fl_T, c0, c1, c2, c3):
412
+ """Evaluation of basic inputs.
413
+
414
+ Parameters
415
+ ==========
416
+
417
+ fl_T : Any (sympifiable)
418
+ Normalized tendon force as a function of tendon length.
419
+ c0 : Any (sympifiable)
420
+ The first constant in the characteristic equation. The published
421
+ value is ``0.2``.
422
+ c1 : Any (sympifiable)
423
+ The second constant in the characteristic equation. The published
424
+ value is ``0.995``.
425
+ c2 : Any (sympifiable)
426
+ The third constant in the characteristic equation. The published
427
+ value is ``0.25``.
428
+ c3 : Any (sympifiable)
429
+ The fourth constant in the characteristic equation. The published
430
+ value is ``33.93669377311689``.
431
+
432
+ """
433
+ pass
434
+
435
+ def _eval_evalf(self, prec):
436
+ """Evaluate the expression numerically using ``evalf``."""
437
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
438
+
439
+ def doit(self, deep=True, evaluate=True, **hints):
440
+ """Evaluate the expression defining the function.
441
+
442
+ Parameters
443
+ ==========
444
+
445
+ deep : bool
446
+ Whether ``doit`` should be recursively called. Default is ``True``.
447
+ evaluate : bool.
448
+ Whether the SymPy expression should be evaluated as it is
449
+ constructed. If ``False``, then no constant folding will be
450
+ conducted which will leave the expression in a more numerically-
451
+ stable for values of ``l_T_tilde`` that correspond to a sensible
452
+ operating range for a musculotendon. Default is ``True``.
453
+ **kwargs : dict[str, Any]
454
+ Additional keyword argument pairs to be recursively passed to
455
+ ``doit``.
456
+
457
+ """
458
+ fl_T, *constants = self.args
459
+ if deep:
460
+ hints['evaluate'] = evaluate
461
+ fl_T = fl_T.doit(deep=deep, **hints)
462
+ c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
463
+ else:
464
+ c0, c1, c2, c3 = constants
465
+
466
+ if evaluate:
467
+ return log((fl_T + c2)/c0)/c3 + c1
468
+
469
+ return log(UnevaluatedExpr((fl_T + c2)/c0))/c3 + c1
470
+
471
+ def fdiff(self, argindex=1):
472
+ """Derivative of the function with respect to a single argument.
473
+
474
+ Parameters
475
+ ==========
476
+
477
+ argindex : int
478
+ The index of the function's arguments with respect to which the
479
+ derivative should be taken. Argument indexes start at ``1``.
480
+ Default is ``1``.
481
+
482
+ """
483
+ fl_T, c0, c1, c2, c3 = self.args
484
+ if argindex == 1:
485
+ return 1/(c3*(fl_T + c2))
486
+ elif argindex == 2:
487
+ return -1/(c0*c3)
488
+ elif argindex == 3:
489
+ return Integer(1)
490
+ elif argindex == 4:
491
+ return 1/(c3*(fl_T + c2))
492
+ elif argindex == 5:
493
+ return -log(UnevaluatedExpr((fl_T + c2)/c0))/c3**2
494
+
495
+ raise ArgumentIndexError(self, argindex)
496
+
497
+ def inverse(self, argindex=1):
498
+ """Inverse function.
499
+
500
+ Parameters
501
+ ==========
502
+
503
+ argindex : int
504
+ Value to start indexing the arguments at. Default is ``1``.
505
+
506
+ """
507
+ return TendonForceLengthDeGroote2016
508
+
509
+ def _latex(self, printer):
510
+ """Print a LaTeX representation of the function defining the curve.
511
+
512
+ Parameters
513
+ ==========
514
+
515
+ printer : Printer
516
+ The printer to be used to print the LaTeX string representation.
517
+
518
+ """
519
+ fl_T = self.args[0]
520
+ _fl_T = printer._print(fl_T)
521
+ return r'\left( \operatorname{fl}^T \right)^{-1} \left( %s \right)' % _fl_T
522
+
523
+
524
+ class FiberForceLengthPassiveDeGroote2016(CharacteristicCurveFunction):
525
+ r"""Passive muscle fiber force-length curve based on De Groote et al., 2016
526
+ [1]_.
527
+
528
+ Explanation
529
+ ===========
530
+
531
+ The function is defined by the equation:
532
+
533
+ $fl^M_{pas} = \frac{\frac{\exp{c_1 \left(\tilde{l^M} - 1\right)}}{c_0} - 1}{\exp{c_1} - 1}$
534
+
535
+ with constant values of $c_0 = 0.6$ and $c_1 = 4.0$.
536
+
537
+ While it is possible to change the constant values, these were carefully
538
+ selected in the original publication to give the characteristic curve
539
+ specific and required properties. For example, the function produces a
540
+ passive fiber force very close to 0 for all normalized fiber lengths
541
+ between 0 and 1.
542
+
543
+ Examples
544
+ ========
545
+
546
+ The preferred way to instantiate :class:`FiberForceLengthPassiveDeGroote2016` is
547
+ using the :meth:`~.with_defaults` constructor because this will automatically
548
+ populate the constants within the characteristic curve equation with the
549
+ floating point values from the original publication. This constructor takes
550
+ a single argument corresponding to normalized muscle fiber length. We'll
551
+ create a :class:`~.Symbol` called ``l_M_tilde`` to represent this.
552
+
553
+ >>> from sympy import Symbol
554
+ >>> from sympy.physics.biomechanics import FiberForceLengthPassiveDeGroote2016
555
+ >>> l_M_tilde = Symbol('l_M_tilde')
556
+ >>> fl_M = FiberForceLengthPassiveDeGroote2016.with_defaults(l_M_tilde)
557
+ >>> fl_M
558
+ FiberForceLengthPassiveDeGroote2016(l_M_tilde, 0.6, 4.0)
559
+
560
+ It's also possible to populate the two constants with your own values too.
561
+
562
+ >>> from sympy import symbols
563
+ >>> c0, c1 = symbols('c0 c1')
564
+ >>> fl_M = FiberForceLengthPassiveDeGroote2016(l_M_tilde, c0, c1)
565
+ >>> fl_M
566
+ FiberForceLengthPassiveDeGroote2016(l_M_tilde, c0, c1)
567
+
568
+ You don't just have to use symbols as the arguments, it's also possible to
569
+ use expressions. Let's create a new pair of symbols, ``l_M`` and
570
+ ``l_M_opt``, representing muscle fiber length and optimal muscle fiber
571
+ length respectively. We can then represent ``l_M_tilde`` as an expression,
572
+ the ratio of these.
573
+
574
+ >>> l_M, l_M_opt = symbols('l_M l_M_opt')
575
+ >>> l_M_tilde = l_M/l_M_opt
576
+ >>> fl_M = FiberForceLengthPassiveDeGroote2016.with_defaults(l_M_tilde)
577
+ >>> fl_M
578
+ FiberForceLengthPassiveDeGroote2016(l_M/l_M_opt, 0.6, 4.0)
579
+
580
+ To inspect the actual symbolic expression that this function represents,
581
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
582
+ argument ``evaluate=False`` as this will keep the expression in its
583
+ canonical form and won't simplify any constants.
584
+
585
+ >>> fl_M.doit(evaluate=False)
586
+ 0.0186573603637741*(-1 + exp(6.66666666666667*(l_M/l_M_opt - 1)))
587
+
588
+ The function can also be differentiated. We'll differentiate with respect
589
+ to l_M using the ``diff`` method on an instance with the single positional
590
+ argument ``l_M``.
591
+
592
+ >>> fl_M.diff(l_M)
593
+ 0.12438240242516*exp(6.66666666666667*(l_M/l_M_opt - 1))/l_M_opt
594
+
595
+ References
596
+ ==========
597
+
598
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
599
+ of direct collocation optimal control problem formulations for
600
+ solving the muscle redundancy problem, Annals of biomedical
601
+ engineering, 44(10), (2016) pp. 2922-2936
602
+
603
+ """
604
+
605
+ @classmethod
606
+ def with_defaults(cls, l_M_tilde):
607
+ r"""Recommended constructor that will use the published constants.
608
+
609
+ Explanation
610
+ ===========
611
+
612
+ Returns a new instance of the muscle fiber passive force-length
613
+ function using the four constant values specified in the original
614
+ publication.
615
+
616
+ These have the values:
617
+
618
+ $c_0 = 0.6$
619
+ $c_1 = 4.0$
620
+
621
+ Parameters
622
+ ==========
623
+
624
+ l_M_tilde : Any (sympifiable)
625
+ Normalized muscle fiber length.
626
+
627
+ """
628
+ c0 = Float('0.6')
629
+ c1 = Float('4.0')
630
+ return cls(l_M_tilde, c0, c1)
631
+
632
+ @classmethod
633
+ def eval(cls, l_M_tilde, c0, c1):
634
+ """Evaluation of basic inputs.
635
+
636
+ Parameters
637
+ ==========
638
+
639
+ l_M_tilde : Any (sympifiable)
640
+ Normalized muscle fiber length.
641
+ c0 : Any (sympifiable)
642
+ The first constant in the characteristic equation. The published
643
+ value is ``0.6``.
644
+ c1 : Any (sympifiable)
645
+ The second constant in the characteristic equation. The published
646
+ value is ``4.0``.
647
+
648
+ """
649
+ pass
650
+
651
+ def _eval_evalf(self, prec):
652
+ """Evaluate the expression numerically using ``evalf``."""
653
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
654
+
655
+ def doit(self, deep=True, evaluate=True, **hints):
656
+ """Evaluate the expression defining the function.
657
+
658
+ Parameters
659
+ ==========
660
+
661
+ deep : bool
662
+ Whether ``doit`` should be recursively called. Default is ``True``.
663
+ evaluate : bool.
664
+ Whether the SymPy expression should be evaluated as it is
665
+ constructed. If ``False``, then no constant folding will be
666
+ conducted which will leave the expression in a more numerically-
667
+ stable for values of ``l_T_tilde`` that correspond to a sensible
668
+ operating range for a musculotendon. Default is ``True``.
669
+ **kwargs : dict[str, Any]
670
+ Additional keyword argument pairs to be recursively passed to
671
+ ``doit``.
672
+
673
+ """
674
+ l_M_tilde, *constants = self.args
675
+ if deep:
676
+ hints['evaluate'] = evaluate
677
+ l_M_tilde = l_M_tilde.doit(deep=deep, **hints)
678
+ c0, c1 = [c.doit(deep=deep, **hints) for c in constants]
679
+ else:
680
+ c0, c1 = constants
681
+
682
+ if evaluate:
683
+ return (exp((c1*(l_M_tilde - 1))/c0) - 1)/(exp(c1) - 1)
684
+
685
+ return (exp((c1*UnevaluatedExpr(l_M_tilde - 1))/c0) - 1)/(exp(c1) - 1)
686
+
687
+ def fdiff(self, argindex=1):
688
+ """Derivative of the function with respect to a single argument.
689
+
690
+ Parameters
691
+ ==========
692
+
693
+ argindex : int
694
+ The index of the function's arguments with respect to which the
695
+ derivative should be taken. Argument indexes start at ``1``.
696
+ Default is ``1``.
697
+
698
+ """
699
+ l_M_tilde, c0, c1 = self.args
700
+ if argindex == 1:
701
+ return c1*exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0)/(c0*(exp(c1) - 1))
702
+ elif argindex == 2:
703
+ return (
704
+ -c1*exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0)
705
+ *UnevaluatedExpr(l_M_tilde - 1)/(c0**2*(exp(c1) - 1))
706
+ )
707
+ elif argindex == 3:
708
+ return (
709
+ -exp(c1)*(-1 + exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0))/(exp(c1) - 1)**2
710
+ + exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0)*(l_M_tilde - 1)/(c0*(exp(c1) - 1))
711
+ )
712
+
713
+ raise ArgumentIndexError(self, argindex)
714
+
715
+ def inverse(self, argindex=1):
716
+ """Inverse function.
717
+
718
+ Parameters
719
+ ==========
720
+
721
+ argindex : int
722
+ Value to start indexing the arguments at. Default is ``1``.
723
+
724
+ """
725
+ return FiberForceLengthPassiveInverseDeGroote2016
726
+
727
+ def _latex(self, printer):
728
+ """Print a LaTeX representation of the function defining the curve.
729
+
730
+ Parameters
731
+ ==========
732
+
733
+ printer : Printer
734
+ The printer to be used to print the LaTeX string representation.
735
+
736
+ """
737
+ l_M_tilde = self.args[0]
738
+ _l_M_tilde = printer._print(l_M_tilde)
739
+ return r'\operatorname{fl}^M_{pas} \left( %s \right)' % _l_M_tilde
740
+
741
+
742
+ class FiberForceLengthPassiveInverseDeGroote2016(CharacteristicCurveFunction):
743
+ r"""Inverse passive muscle fiber force-length curve based on De Groote et
744
+ al., 2016 [1]_.
745
+
746
+ Explanation
747
+ ===========
748
+
749
+ Gives the normalized muscle fiber length that produces a specific normalized
750
+ passive muscle fiber force.
751
+
752
+ The function is defined by the equation:
753
+
754
+ ${fl^M_{pas}}^{-1} = \frac{c_0 \log{\left(\exp{c_1} - 1\right)fl^M_pas + 1}}{c_1} + 1$
755
+
756
+ with constant values of $c_0 = 0.6$ and $c_1 = 4.0$. This function is the
757
+ exact analytical inverse of the related tendon force-length curve
758
+ ``FiberForceLengthPassiveDeGroote2016``.
759
+
760
+ While it is possible to change the constant values, these were carefully
761
+ selected in the original publication to give the characteristic curve
762
+ specific and required properties. For example, the function produces a
763
+ passive fiber force very close to 0 for all normalized fiber lengths
764
+ between 0 and 1.
765
+
766
+ Examples
767
+ ========
768
+
769
+ The preferred way to instantiate
770
+ :class:`FiberForceLengthPassiveInverseDeGroote2016` is using the
771
+ :meth:`~.with_defaults` constructor because this will automatically populate the
772
+ constants within the characteristic curve equation with the floating point
773
+ values from the original publication. This constructor takes a single
774
+ argument corresponding to the normalized passive muscle fiber length-force
775
+ component of the muscle fiber force. We'll create a :class:`~.Symbol` called
776
+ ``fl_M_pas`` to represent this.
777
+
778
+ >>> from sympy import Symbol
779
+ >>> from sympy.physics.biomechanics import FiberForceLengthPassiveInverseDeGroote2016
780
+ >>> fl_M_pas = Symbol('fl_M_pas')
781
+ >>> l_M_tilde = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(fl_M_pas)
782
+ >>> l_M_tilde
783
+ FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, 0.6, 4.0)
784
+
785
+ It's also possible to populate the two constants with your own values too.
786
+
787
+ >>> from sympy import symbols
788
+ >>> c0, c1 = symbols('c0 c1')
789
+ >>> l_M_tilde = FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, c0, c1)
790
+ >>> l_M_tilde
791
+ FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, c0, c1)
792
+
793
+ To inspect the actual symbolic expression that this function represents,
794
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
795
+ argument ``evaluate=False`` as this will keep the expression in its
796
+ canonical form and won't simplify any constants.
797
+
798
+ >>> l_M_tilde.doit(evaluate=False)
799
+ c0*log(1 + fl_M_pas*(exp(c1) - 1))/c1 + 1
800
+
801
+ The function can also be differentiated. We'll differentiate with respect
802
+ to fl_M_pas using the ``diff`` method on an instance with the single positional
803
+ argument ``fl_M_pas``.
804
+
805
+ >>> l_M_tilde.diff(fl_M_pas)
806
+ c0*(exp(c1) - 1)/(c1*(fl_M_pas*(exp(c1) - 1) + 1))
807
+
808
+ References
809
+ ==========
810
+
811
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
812
+ of direct collocation optimal control problem formulations for
813
+ solving the muscle redundancy problem, Annals of biomedical
814
+ engineering, 44(10), (2016) pp. 2922-2936
815
+
816
+ """
817
+
818
+ @classmethod
819
+ def with_defaults(cls, fl_M_pas):
820
+ r"""Recommended constructor that will use the published constants.
821
+
822
+ Explanation
823
+ ===========
824
+
825
+ Returns a new instance of the inverse muscle fiber passive force-length
826
+ function using the four constant values specified in the original
827
+ publication.
828
+
829
+ These have the values:
830
+
831
+ $c_0 = 0.6$
832
+ $c_1 = 4.0$
833
+
834
+ Parameters
835
+ ==========
836
+
837
+ fl_M_pas : Any (sympifiable)
838
+ Normalized passive muscle fiber force as a function of muscle fiber
839
+ length.
840
+
841
+ """
842
+ c0 = Float('0.6')
843
+ c1 = Float('4.0')
844
+ return cls(fl_M_pas, c0, c1)
845
+
846
+ @classmethod
847
+ def eval(cls, fl_M_pas, c0, c1):
848
+ """Evaluation of basic inputs.
849
+
850
+ Parameters
851
+ ==========
852
+
853
+ fl_M_pas : Any (sympifiable)
854
+ Normalized passive muscle fiber force.
855
+ c0 : Any (sympifiable)
856
+ The first constant in the characteristic equation. The published
857
+ value is ``0.6``.
858
+ c1 : Any (sympifiable)
859
+ The second constant in the characteristic equation. The published
860
+ value is ``4.0``.
861
+
862
+ """
863
+ pass
864
+
865
+ def _eval_evalf(self, prec):
866
+ """Evaluate the expression numerically using ``evalf``."""
867
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
868
+
869
+ def doit(self, deep=True, evaluate=True, **hints):
870
+ """Evaluate the expression defining the function.
871
+
872
+ Parameters
873
+ ==========
874
+
875
+ deep : bool
876
+ Whether ``doit`` should be recursively called. Default is ``True``.
877
+ evaluate : bool.
878
+ Whether the SymPy expression should be evaluated as it is
879
+ constructed. If ``False``, then no constant folding will be
880
+ conducted which will leave the expression in a more numerically-
881
+ stable for values of ``l_T_tilde`` that correspond to a sensible
882
+ operating range for a musculotendon. Default is ``True``.
883
+ **kwargs : dict[str, Any]
884
+ Additional keyword argument pairs to be recursively passed to
885
+ ``doit``.
886
+
887
+ """
888
+ fl_M_pas, *constants = self.args
889
+ if deep:
890
+ hints['evaluate'] = evaluate
891
+ fl_M_pas = fl_M_pas.doit(deep=deep, **hints)
892
+ c0, c1 = [c.doit(deep=deep, **hints) for c in constants]
893
+ else:
894
+ c0, c1 = constants
895
+
896
+ if evaluate:
897
+ return c0*log(fl_M_pas*(exp(c1) - 1) + 1)/c1 + 1
898
+
899
+ return c0*log(UnevaluatedExpr(fl_M_pas*(exp(c1) - 1)) + 1)/c1 + 1
900
+
901
+ def fdiff(self, argindex=1):
902
+ """Derivative of the function with respect to a single argument.
903
+
904
+ Parameters
905
+ ==========
906
+
907
+ argindex : int
908
+ The index of the function's arguments with respect to which the
909
+ derivative should be taken. Argument indexes start at ``1``.
910
+ Default is ``1``.
911
+
912
+ """
913
+ fl_M_pas, c0, c1 = self.args
914
+ if argindex == 1:
915
+ return c0*(exp(c1) - 1)/(c1*(fl_M_pas*(exp(c1) - 1) + 1))
916
+ elif argindex == 2:
917
+ return log(fl_M_pas*(exp(c1) - 1) + 1)/c1
918
+ elif argindex == 3:
919
+ return (
920
+ c0*fl_M_pas*exp(c1)/(c1*(fl_M_pas*(exp(c1) - 1) + 1))
921
+ - c0*log(fl_M_pas*(exp(c1) - 1) + 1)/c1**2
922
+ )
923
+
924
+ raise ArgumentIndexError(self, argindex)
925
+
926
+ def inverse(self, argindex=1):
927
+ """Inverse function.
928
+
929
+ Parameters
930
+ ==========
931
+
932
+ argindex : int
933
+ Value to start indexing the arguments at. Default is ``1``.
934
+
935
+ """
936
+ return FiberForceLengthPassiveDeGroote2016
937
+
938
+ def _latex(self, printer):
939
+ """Print a LaTeX representation of the function defining the curve.
940
+
941
+ Parameters
942
+ ==========
943
+
944
+ printer : Printer
945
+ The printer to be used to print the LaTeX string representation.
946
+
947
+ """
948
+ fl_M_pas = self.args[0]
949
+ _fl_M_pas = printer._print(fl_M_pas)
950
+ return r'\left( \operatorname{fl}^M_{pas} \right)^{-1} \left( %s \right)' % _fl_M_pas
951
+
952
+
953
+ class FiberForceLengthActiveDeGroote2016(CharacteristicCurveFunction):
954
+ r"""Active muscle fiber force-length curve based on De Groote et al., 2016
955
+ [1]_.
956
+
957
+ Explanation
958
+ ===========
959
+
960
+ The function is defined by the equation:
961
+
962
+ $fl_{\text{act}}^M = c_0 \exp\left(-\frac{1}{2}\left(\frac{\tilde{l}^M - c_1}{c_2 + c_3 \tilde{l}^M}\right)^2\right)
963
+ + c_4 \exp\left(-\frac{1}{2}\left(\frac{\tilde{l}^M - c_5}{c_6 + c_7 \tilde{l}^M}\right)^2\right)
964
+ + c_8 \exp\left(-\frac{1}{2}\left(\frac{\tilde{l}^M - c_9}{c_{10} + c_{11} \tilde{l}^M}\right)^2\right)$
965
+
966
+ with constant values of $c0 = 0.814$, $c1 = 1.06$, $c2 = 0.162$,
967
+ $c3 = 0.0633$, $c4 = 0.433$, $c5 = 0.717$, $c6 = -0.0299$, $c7 = 0.2$,
968
+ $c8 = 0.1$, $c9 = 1.0$, $c10 = 0.354$, and $c11 = 0.0$.
969
+
970
+ While it is possible to change the constant values, these were carefully
971
+ selected in the original publication to give the characteristic curve
972
+ specific and required properties. For example, the function produces a
973
+ active fiber force of 1 at a normalized fiber length of 1, and an active
974
+ fiber force of 0 at normalized fiber lengths of 0 and 2.
975
+
976
+ Examples
977
+ ========
978
+
979
+ The preferred way to instantiate :class:`FiberForceLengthActiveDeGroote2016` is
980
+ using the :meth:`~.with_defaults` constructor because this will automatically
981
+ populate the constants within the characteristic curve equation with the
982
+ floating point values from the original publication. This constructor takes
983
+ a single argument corresponding to normalized muscle fiber length. We'll
984
+ create a :class:`~.Symbol` called ``l_M_tilde`` to represent this.
985
+
986
+ >>> from sympy import Symbol
987
+ >>> from sympy.physics.biomechanics import FiberForceLengthActiveDeGroote2016
988
+ >>> l_M_tilde = Symbol('l_M_tilde')
989
+ >>> fl_M = FiberForceLengthActiveDeGroote2016.with_defaults(l_M_tilde)
990
+ >>> fl_M
991
+ FiberForceLengthActiveDeGroote2016(l_M_tilde, 0.814, 1.06, 0.162, 0.0633,
992
+ 0.433, 0.717, -0.0299, 0.2, 0.1, 1.0, 0.354, 0.0)
993
+
994
+ It's also possible to populate the two constants with your own values too.
995
+
996
+ >>> from sympy import symbols
997
+ >>> c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11 = symbols('c0:12')
998
+ >>> fl_M = FiberForceLengthActiveDeGroote2016(l_M_tilde, c0, c1, c2, c3,
999
+ ... c4, c5, c6, c7, c8, c9, c10, c11)
1000
+ >>> fl_M
1001
+ FiberForceLengthActiveDeGroote2016(l_M_tilde, c0, c1, c2, c3, c4, c5, c6,
1002
+ c7, c8, c9, c10, c11)
1003
+
1004
+ You don't just have to use symbols as the arguments, it's also possible to
1005
+ use expressions. Let's create a new pair of symbols, ``l_M`` and
1006
+ ``l_M_opt``, representing muscle fiber length and optimal muscle fiber
1007
+ length respectively. We can then represent ``l_M_tilde`` as an expression,
1008
+ the ratio of these.
1009
+
1010
+ >>> l_M, l_M_opt = symbols('l_M l_M_opt')
1011
+ >>> l_M_tilde = l_M/l_M_opt
1012
+ >>> fl_M = FiberForceLengthActiveDeGroote2016.with_defaults(l_M_tilde)
1013
+ >>> fl_M
1014
+ FiberForceLengthActiveDeGroote2016(l_M/l_M_opt, 0.814, 1.06, 0.162, 0.0633,
1015
+ 0.433, 0.717, -0.0299, 0.2, 0.1, 1.0, 0.354, 0.0)
1016
+
1017
+ To inspect the actual symbolic expression that this function represents,
1018
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
1019
+ argument ``evaluate=False`` as this will keep the expression in its
1020
+ canonical form and won't simplify any constants.
1021
+
1022
+ >>> fl_M.doit(evaluate=False)
1023
+ 0.814*exp(-19.0519737844841*(l_M/l_M_opt
1024
+ - 1.06)**2/(0.390740740740741*l_M/l_M_opt + 1)**2)
1025
+ + 0.433*exp(-12.5*(l_M/l_M_opt - 0.717)**2/(l_M/l_M_opt - 0.1495)**2)
1026
+ + 0.1*exp(-3.98991349867535*(l_M/l_M_opt - 1.0)**2)
1027
+
1028
+ The function can also be differentiated. We'll differentiate with respect
1029
+ to l_M using the ``diff`` method on an instance with the single positional
1030
+ argument ``l_M``.
1031
+
1032
+ >>> fl_M.diff(l_M)
1033
+ ((-0.79798269973507*l_M/l_M_opt
1034
+ + 0.79798269973507)*exp(-3.98991349867535*(l_M/l_M_opt - 1.0)**2)
1035
+ + (10.825*(-l_M/l_M_opt + 0.717)/(l_M/l_M_opt - 0.1495)**2
1036
+ + 10.825*(l_M/l_M_opt - 0.717)**2/(l_M/l_M_opt
1037
+ - 0.1495)**3)*exp(-12.5*(l_M/l_M_opt - 0.717)**2/(l_M/l_M_opt - 0.1495)**2)
1038
+ + (31.0166133211401*(-l_M/l_M_opt + 1.06)/(0.390740740740741*l_M/l_M_opt
1039
+ + 1)**2 + 13.6174190361677*(0.943396226415094*l_M/l_M_opt
1040
+ - 1)**2/(0.390740740740741*l_M/l_M_opt
1041
+ + 1)**3)*exp(-21.4067977442463*(0.943396226415094*l_M/l_M_opt
1042
+ - 1)**2/(0.390740740740741*l_M/l_M_opt + 1)**2))/l_M_opt
1043
+
1044
+ References
1045
+ ==========
1046
+
1047
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
1048
+ of direct collocation optimal control problem formulations for
1049
+ solving the muscle redundancy problem, Annals of biomedical
1050
+ engineering, 44(10), (2016) pp. 2922-2936
1051
+
1052
+ """
1053
+
1054
+ @classmethod
1055
+ def with_defaults(cls, l_M_tilde):
1056
+ r"""Recommended constructor that will use the published constants.
1057
+
1058
+ Explanation
1059
+ ===========
1060
+
1061
+ Returns a new instance of the inverse muscle fiber act force-length
1062
+ function using the four constant values specified in the original
1063
+ publication.
1064
+
1065
+ These have the values:
1066
+
1067
+ $c0 = 0.814$
1068
+ $c1 = 1.06$
1069
+ $c2 = 0.162$
1070
+ $c3 = 0.0633$
1071
+ $c4 = 0.433$
1072
+ $c5 = 0.717$
1073
+ $c6 = -0.0299$
1074
+ $c7 = 0.2$
1075
+ $c8 = 0.1$
1076
+ $c9 = 1.0$
1077
+ $c10 = 0.354$
1078
+ $c11 = 0.0$
1079
+
1080
+ Parameters
1081
+ ==========
1082
+
1083
+ fl_M_act : Any (sympifiable)
1084
+ Normalized passive muscle fiber force as a function of muscle fiber
1085
+ length.
1086
+
1087
+ """
1088
+ c0 = Float('0.814')
1089
+ c1 = Float('1.06')
1090
+ c2 = Float('0.162')
1091
+ c3 = Float('0.0633')
1092
+ c4 = Float('0.433')
1093
+ c5 = Float('0.717')
1094
+ c6 = Float('-0.0299')
1095
+ c7 = Float('0.2')
1096
+ c8 = Float('0.1')
1097
+ c9 = Float('1.0')
1098
+ c10 = Float('0.354')
1099
+ c11 = Float('0.0')
1100
+ return cls(l_M_tilde, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11)
1101
+
1102
+ @classmethod
1103
+ def eval(cls, l_M_tilde, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11):
1104
+ """Evaluation of basic inputs.
1105
+
1106
+ Parameters
1107
+ ==========
1108
+
1109
+ l_M_tilde : Any (sympifiable)
1110
+ Normalized muscle fiber length.
1111
+ c0 : Any (sympifiable)
1112
+ The first constant in the characteristic equation. The published
1113
+ value is ``0.814``.
1114
+ c1 : Any (sympifiable)
1115
+ The second constant in the characteristic equation. The published
1116
+ value is ``1.06``.
1117
+ c2 : Any (sympifiable)
1118
+ The third constant in the characteristic equation. The published
1119
+ value is ``0.162``.
1120
+ c3 : Any (sympifiable)
1121
+ The fourth constant in the characteristic equation. The published
1122
+ value is ``0.0633``.
1123
+ c4 : Any (sympifiable)
1124
+ The fifth constant in the characteristic equation. The published
1125
+ value is ``0.433``.
1126
+ c5 : Any (sympifiable)
1127
+ The sixth constant in the characteristic equation. The published
1128
+ value is ``0.717``.
1129
+ c6 : Any (sympifiable)
1130
+ The seventh constant in the characteristic equation. The published
1131
+ value is ``-0.0299``.
1132
+ c7 : Any (sympifiable)
1133
+ The eighth constant in the characteristic equation. The published
1134
+ value is ``0.2``.
1135
+ c8 : Any (sympifiable)
1136
+ The ninth constant in the characteristic equation. The published
1137
+ value is ``0.1``.
1138
+ c9 : Any (sympifiable)
1139
+ The tenth constant in the characteristic equation. The published
1140
+ value is ``1.0``.
1141
+ c10 : Any (sympifiable)
1142
+ The eleventh constant in the characteristic equation. The published
1143
+ value is ``0.354``.
1144
+ c11 : Any (sympifiable)
1145
+ The tweflth constant in the characteristic equation. The published
1146
+ value is ``0.0``.
1147
+
1148
+ """
1149
+ pass
1150
+
1151
+ def _eval_evalf(self, prec):
1152
+ """Evaluate the expression numerically using ``evalf``."""
1153
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
1154
+
1155
+ def doit(self, deep=True, evaluate=True, **hints):
1156
+ """Evaluate the expression defining the function.
1157
+
1158
+ Parameters
1159
+ ==========
1160
+
1161
+ deep : bool
1162
+ Whether ``doit`` should be recursively called. Default is ``True``.
1163
+ evaluate : bool.
1164
+ Whether the SymPy expression should be evaluated as it is
1165
+ constructed. If ``False``, then no constant folding will be
1166
+ conducted which will leave the expression in a more numerically-
1167
+ stable for values of ``l_M_tilde`` that correspond to a sensible
1168
+ operating range for a musculotendon. Default is ``True``.
1169
+ **kwargs : dict[str, Any]
1170
+ Additional keyword argument pairs to be recursively passed to
1171
+ ``doit``.
1172
+
1173
+ """
1174
+ l_M_tilde, *constants = self.args
1175
+ if deep:
1176
+ hints['evaluate'] = evaluate
1177
+ l_M_tilde = l_M_tilde.doit(deep=deep, **hints)
1178
+ constants = [c.doit(deep=deep, **hints) for c in constants]
1179
+ c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11 = constants
1180
+
1181
+ if evaluate:
1182
+ return (
1183
+ c0*exp(-(((l_M_tilde - c1)/(c2 + c3*l_M_tilde))**2)/2)
1184
+ + c4*exp(-(((l_M_tilde - c5)/(c6 + c7*l_M_tilde))**2)/2)
1185
+ + c8*exp(-(((l_M_tilde - c9)/(c10 + c11*l_M_tilde))**2)/2)
1186
+ )
1187
+
1188
+ return (
1189
+ c0*exp(-((UnevaluatedExpr(l_M_tilde - c1)/(c2 + c3*l_M_tilde))**2)/2)
1190
+ + c4*exp(-((UnevaluatedExpr(l_M_tilde - c5)/(c6 + c7*l_M_tilde))**2)/2)
1191
+ + c8*exp(-((UnevaluatedExpr(l_M_tilde - c9)/(c10 + c11*l_M_tilde))**2)/2)
1192
+ )
1193
+
1194
+ def fdiff(self, argindex=1):
1195
+ """Derivative of the function with respect to a single argument.
1196
+
1197
+ Parameters
1198
+ ==========
1199
+
1200
+ argindex : int
1201
+ The index of the function's arguments with respect to which the
1202
+ derivative should be taken. Argument indexes start at ``1``.
1203
+ Default is ``1``.
1204
+
1205
+ """
1206
+ l_M_tilde, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11 = self.args
1207
+ if argindex == 1:
1208
+ return (
1209
+ c0*(
1210
+ c3*(l_M_tilde - c1)**2/(c2 + c3*l_M_tilde)**3
1211
+ + (c1 - l_M_tilde)/((c2 + c3*l_M_tilde)**2)
1212
+ )*exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
1213
+ + c4*(
1214
+ c7*(l_M_tilde - c5)**2/(c6 + c7*l_M_tilde)**3
1215
+ + (c5 - l_M_tilde)/((c6 + c7*l_M_tilde)**2)
1216
+ )*exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
1217
+ + c8*(
1218
+ c11*(l_M_tilde - c9)**2/(c10 + c11*l_M_tilde)**3
1219
+ + (c9 - l_M_tilde)/((c10 + c11*l_M_tilde)**2)
1220
+ )*exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
1221
+ )
1222
+ elif argindex == 2:
1223
+ return exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
1224
+ elif argindex == 3:
1225
+ return (
1226
+ c0*(l_M_tilde - c1)/(c2 + c3*l_M_tilde)**2
1227
+ *exp(-(l_M_tilde - c1)**2 /(2*(c2 + c3*l_M_tilde)**2))
1228
+ )
1229
+ elif argindex == 4:
1230
+ return (
1231
+ c0*(l_M_tilde - c1)**2/(c2 + c3*l_M_tilde)**3
1232
+ *exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
1233
+ )
1234
+ elif argindex == 5:
1235
+ return (
1236
+ c0*l_M_tilde*(l_M_tilde - c1)**2/(c2 + c3*l_M_tilde)**3
1237
+ *exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
1238
+ )
1239
+ elif argindex == 6:
1240
+ return exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
1241
+ elif argindex == 7:
1242
+ return (
1243
+ c4*(l_M_tilde - c5)/(c6 + c7*l_M_tilde)**2
1244
+ *exp(-(l_M_tilde - c5)**2 /(2*(c6 + c7*l_M_tilde)**2))
1245
+ )
1246
+ elif argindex == 8:
1247
+ return (
1248
+ c4*(l_M_tilde - c5)**2/(c6 + c7*l_M_tilde)**3
1249
+ *exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
1250
+ )
1251
+ elif argindex == 9:
1252
+ return (
1253
+ c4*l_M_tilde*(l_M_tilde - c5)**2/(c6 + c7*l_M_tilde)**3
1254
+ *exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
1255
+ )
1256
+ elif argindex == 10:
1257
+ return exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
1258
+ elif argindex == 11:
1259
+ return (
1260
+ c8*(l_M_tilde - c9)/(c10 + c11*l_M_tilde)**2
1261
+ *exp(-(l_M_tilde - c9)**2 /(2*(c10 + c11*l_M_tilde)**2))
1262
+ )
1263
+ elif argindex == 12:
1264
+ return (
1265
+ c8*(l_M_tilde - c9)**2/(c10 + c11*l_M_tilde)**3
1266
+ *exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
1267
+ )
1268
+ elif argindex == 13:
1269
+ return (
1270
+ c8*l_M_tilde*(l_M_tilde - c9)**2/(c10 + c11*l_M_tilde)**3
1271
+ *exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
1272
+ )
1273
+
1274
+ raise ArgumentIndexError(self, argindex)
1275
+
1276
+ def _latex(self, printer):
1277
+ """Print a LaTeX representation of the function defining the curve.
1278
+
1279
+ Parameters
1280
+ ==========
1281
+
1282
+ printer : Printer
1283
+ The printer to be used to print the LaTeX string representation.
1284
+
1285
+ """
1286
+ l_M_tilde = self.args[0]
1287
+ _l_M_tilde = printer._print(l_M_tilde)
1288
+ return r'\operatorname{fl}^M_{act} \left( %s \right)' % _l_M_tilde
1289
+
1290
+
1291
+ class FiberForceVelocityDeGroote2016(CharacteristicCurveFunction):
1292
+ r"""Muscle fiber force-velocity curve based on De Groote et al., 2016 [1]_.
1293
+
1294
+ Explanation
1295
+ ===========
1296
+
1297
+ Gives the normalized muscle fiber force produced as a function of
1298
+ normalized tendon velocity.
1299
+
1300
+ The function is defined by the equation:
1301
+
1302
+ $fv^M = c_0 \log{\left(c_1 \tilde{v}_m + c_2\right) + \sqrt{\left(c_1 \tilde{v}_m + c_2\right)^2 + 1}} + c_3$
1303
+
1304
+ with constant values of $c_0 = -0.318$, $c_1 = -8.149$, $c_2 = -0.374$, and
1305
+ $c_3 = 0.886$.
1306
+
1307
+ While it is possible to change the constant values, these were carefully
1308
+ selected in the original publication to give the characteristic curve
1309
+ specific and required properties. For example, the function produces a
1310
+ normalized muscle fiber force of 1 when the muscle fibers are contracting
1311
+ isometrically (they have an extension rate of 0).
1312
+
1313
+ Examples
1314
+ ========
1315
+
1316
+ The preferred way to instantiate :class:`FiberForceVelocityDeGroote2016` is using
1317
+ the :meth:`~.with_defaults` constructor because this will automatically populate
1318
+ the constants within the characteristic curve equation with the floating
1319
+ point values from the original publication. This constructor takes a single
1320
+ argument corresponding to normalized muscle fiber extension velocity. We'll
1321
+ create a :class:`~.Symbol` called ``v_M_tilde`` to represent this.
1322
+
1323
+ >>> from sympy import Symbol
1324
+ >>> from sympy.physics.biomechanics import FiberForceVelocityDeGroote2016
1325
+ >>> v_M_tilde = Symbol('v_M_tilde')
1326
+ >>> fv_M = FiberForceVelocityDeGroote2016.with_defaults(v_M_tilde)
1327
+ >>> fv_M
1328
+ FiberForceVelocityDeGroote2016(v_M_tilde, -0.318, -8.149, -0.374, 0.886)
1329
+
1330
+ It's also possible to populate the four constants with your own values too.
1331
+
1332
+ >>> from sympy import symbols
1333
+ >>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
1334
+ >>> fv_M = FiberForceVelocityDeGroote2016(v_M_tilde, c0, c1, c2, c3)
1335
+ >>> fv_M
1336
+ FiberForceVelocityDeGroote2016(v_M_tilde, c0, c1, c2, c3)
1337
+
1338
+ You don't just have to use symbols as the arguments, it's also possible to
1339
+ use expressions. Let's create a new pair of symbols, ``v_M`` and
1340
+ ``v_M_max``, representing muscle fiber extension velocity and maximum
1341
+ muscle fiber extension velocity respectively. We can then represent
1342
+ ``v_M_tilde`` as an expression, the ratio of these.
1343
+
1344
+ >>> v_M, v_M_max = symbols('v_M v_M_max')
1345
+ >>> v_M_tilde = v_M/v_M_max
1346
+ >>> fv_M = FiberForceVelocityDeGroote2016.with_defaults(v_M_tilde)
1347
+ >>> fv_M
1348
+ FiberForceVelocityDeGroote2016(v_M/v_M_max, -0.318, -8.149, -0.374, 0.886)
1349
+
1350
+ To inspect the actual symbolic expression that this function represents,
1351
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
1352
+ argument ``evaluate=False`` as this will keep the expression in its
1353
+ canonical form and won't simplify any constants.
1354
+
1355
+ >>> fv_M.doit(evaluate=False)
1356
+ 0.886 - 0.318*log(-8.149*v_M/v_M_max - 0.374 + sqrt(1 + (-8.149*v_M/v_M_max
1357
+ - 0.374)**2))
1358
+
1359
+ The function can also be differentiated. We'll differentiate with respect
1360
+ to v_M using the ``diff`` method on an instance with the single positional
1361
+ argument ``v_M``.
1362
+
1363
+ >>> fv_M.diff(v_M)
1364
+ 2.591382*(1 + (-8.149*v_M/v_M_max - 0.374)**2)**(-1/2)/v_M_max
1365
+
1366
+ References
1367
+ ==========
1368
+
1369
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
1370
+ of direct collocation optimal control problem formulations for
1371
+ solving the muscle redundancy problem, Annals of biomedical
1372
+ engineering, 44(10), (2016) pp. 2922-2936
1373
+
1374
+ """
1375
+
1376
+ @classmethod
1377
+ def with_defaults(cls, v_M_tilde):
1378
+ r"""Recommended constructor that will use the published constants.
1379
+
1380
+ Explanation
1381
+ ===========
1382
+
1383
+ Returns a new instance of the muscle fiber force-velocity function
1384
+ using the four constant values specified in the original publication.
1385
+
1386
+ These have the values:
1387
+
1388
+ $c_0 = -0.318$
1389
+ $c_1 = -8.149$
1390
+ $c_2 = -0.374$
1391
+ $c_3 = 0.886$
1392
+
1393
+ Parameters
1394
+ ==========
1395
+
1396
+ v_M_tilde : Any (sympifiable)
1397
+ Normalized muscle fiber extension velocity.
1398
+
1399
+ """
1400
+ c0 = Float('-0.318')
1401
+ c1 = Float('-8.149')
1402
+ c2 = Float('-0.374')
1403
+ c3 = Float('0.886')
1404
+ return cls(v_M_tilde, c0, c1, c2, c3)
1405
+
1406
+ @classmethod
1407
+ def eval(cls, v_M_tilde, c0, c1, c2, c3):
1408
+ """Evaluation of basic inputs.
1409
+
1410
+ Parameters
1411
+ ==========
1412
+
1413
+ v_M_tilde : Any (sympifiable)
1414
+ Normalized muscle fiber extension velocity.
1415
+ c0 : Any (sympifiable)
1416
+ The first constant in the characteristic equation. The published
1417
+ value is ``-0.318``.
1418
+ c1 : Any (sympifiable)
1419
+ The second constant in the characteristic equation. The published
1420
+ value is ``-8.149``.
1421
+ c2 : Any (sympifiable)
1422
+ The third constant in the characteristic equation. The published
1423
+ value is ``-0.374``.
1424
+ c3 : Any (sympifiable)
1425
+ The fourth constant in the characteristic equation. The published
1426
+ value is ``0.886``.
1427
+
1428
+ """
1429
+ pass
1430
+
1431
+ def _eval_evalf(self, prec):
1432
+ """Evaluate the expression numerically using ``evalf``."""
1433
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
1434
+
1435
+ def doit(self, deep=True, evaluate=True, **hints):
1436
+ """Evaluate the expression defining the function.
1437
+
1438
+ Parameters
1439
+ ==========
1440
+
1441
+ deep : bool
1442
+ Whether ``doit`` should be recursively called. Default is ``True``.
1443
+ evaluate : bool.
1444
+ Whether the SymPy expression should be evaluated as it is
1445
+ constructed. If ``False``, then no constant folding will be
1446
+ conducted which will leave the expression in a more numerically-
1447
+ stable for values of ``v_M_tilde`` that correspond to a sensible
1448
+ operating range for a musculotendon. Default is ``True``.
1449
+ **kwargs : dict[str, Any]
1450
+ Additional keyword argument pairs to be recursively passed to
1451
+ ``doit``.
1452
+
1453
+ """
1454
+ v_M_tilde, *constants = self.args
1455
+ if deep:
1456
+ hints['evaluate'] = evaluate
1457
+ v_M_tilde = v_M_tilde.doit(deep=deep, **hints)
1458
+ c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
1459
+ else:
1460
+ c0, c1, c2, c3 = constants
1461
+
1462
+ if evaluate:
1463
+ return c0*log(c1*v_M_tilde + c2 + sqrt((c1*v_M_tilde + c2)**2 + 1)) + c3
1464
+
1465
+ return c0*log(c1*v_M_tilde + c2 + sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)) + c3
1466
+
1467
+ def fdiff(self, argindex=1):
1468
+ """Derivative of the function with respect to a single argument.
1469
+
1470
+ Parameters
1471
+ ==========
1472
+
1473
+ argindex : int
1474
+ The index of the function's arguments with respect to which the
1475
+ derivative should be taken. Argument indexes start at ``1``.
1476
+ Default is ``1``.
1477
+
1478
+ """
1479
+ v_M_tilde, c0, c1, c2, c3 = self.args
1480
+ if argindex == 1:
1481
+ return c0*c1/sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
1482
+ elif argindex == 2:
1483
+ return log(
1484
+ c1*v_M_tilde + c2
1485
+ + sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
1486
+ )
1487
+ elif argindex == 3:
1488
+ return c0*v_M_tilde/sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
1489
+ elif argindex == 4:
1490
+ return c0/sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
1491
+ elif argindex == 5:
1492
+ return Integer(1)
1493
+
1494
+ raise ArgumentIndexError(self, argindex)
1495
+
1496
+ def inverse(self, argindex=1):
1497
+ """Inverse function.
1498
+
1499
+ Parameters
1500
+ ==========
1501
+
1502
+ argindex : int
1503
+ Value to start indexing the arguments at. Default is ``1``.
1504
+
1505
+ """
1506
+ return FiberForceVelocityInverseDeGroote2016
1507
+
1508
+ def _latex(self, printer):
1509
+ """Print a LaTeX representation of the function defining the curve.
1510
+
1511
+ Parameters
1512
+ ==========
1513
+
1514
+ printer : Printer
1515
+ The printer to be used to print the LaTeX string representation.
1516
+
1517
+ """
1518
+ v_M_tilde = self.args[0]
1519
+ _v_M_tilde = printer._print(v_M_tilde)
1520
+ return r'\operatorname{fv}^M \left( %s \right)' % _v_M_tilde
1521
+
1522
+
1523
+ class FiberForceVelocityInverseDeGroote2016(CharacteristicCurveFunction):
1524
+ r"""Inverse muscle fiber force-velocity curve based on De Groote et al.,
1525
+ 2016 [1]_.
1526
+
1527
+ Explanation
1528
+ ===========
1529
+
1530
+ Gives the normalized muscle fiber velocity that produces a specific
1531
+ normalized muscle fiber force.
1532
+
1533
+ The function is defined by the equation:
1534
+
1535
+ ${fv^M}^{-1} = \frac{\sinh{\frac{fv^M - c_3}{c_0}} - c_2}{c_1}$
1536
+
1537
+ with constant values of $c_0 = -0.318$, $c_1 = -8.149$, $c_2 = -0.374$, and
1538
+ $c_3 = 0.886$. This function is the exact analytical inverse of the related
1539
+ muscle fiber force-velocity curve ``FiberForceVelocityDeGroote2016``.
1540
+
1541
+ While it is possible to change the constant values, these were carefully
1542
+ selected in the original publication to give the characteristic curve
1543
+ specific and required properties. For example, the function produces a
1544
+ normalized muscle fiber force of 1 when the muscle fibers are contracting
1545
+ isometrically (they have an extension rate of 0).
1546
+
1547
+ Examples
1548
+ ========
1549
+
1550
+ The preferred way to instantiate :class:`FiberForceVelocityInverseDeGroote2016`
1551
+ is using the :meth:`~.with_defaults` constructor because this will automatically
1552
+ populate the constants within the characteristic curve equation with the
1553
+ floating point values from the original publication. This constructor takes
1554
+ a single argument corresponding to normalized muscle fiber force-velocity
1555
+ component of the muscle fiber force. We'll create a :class:`~.Symbol` called
1556
+ ``fv_M`` to represent this.
1557
+
1558
+ >>> from sympy import Symbol
1559
+ >>> from sympy.physics.biomechanics import FiberForceVelocityInverseDeGroote2016
1560
+ >>> fv_M = Symbol('fv_M')
1561
+ >>> v_M_tilde = FiberForceVelocityInverseDeGroote2016.with_defaults(fv_M)
1562
+ >>> v_M_tilde
1563
+ FiberForceVelocityInverseDeGroote2016(fv_M, -0.318, -8.149, -0.374, 0.886)
1564
+
1565
+ It's also possible to populate the four constants with your own values too.
1566
+
1567
+ >>> from sympy import symbols
1568
+ >>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
1569
+ >>> v_M_tilde = FiberForceVelocityInverseDeGroote2016(fv_M, c0, c1, c2, c3)
1570
+ >>> v_M_tilde
1571
+ FiberForceVelocityInverseDeGroote2016(fv_M, c0, c1, c2, c3)
1572
+
1573
+ To inspect the actual symbolic expression that this function represents,
1574
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
1575
+ argument ``evaluate=False`` as this will keep the expression in its
1576
+ canonical form and won't simplify any constants.
1577
+
1578
+ >>> v_M_tilde.doit(evaluate=False)
1579
+ (-c2 + sinh((-c3 + fv_M)/c0))/c1
1580
+
1581
+ The function can also be differentiated. We'll differentiate with respect
1582
+ to fv_M using the ``diff`` method on an instance with the single positional
1583
+ argument ``fv_M``.
1584
+
1585
+ >>> v_M_tilde.diff(fv_M)
1586
+ cosh((-c3 + fv_M)/c0)/(c0*c1)
1587
+
1588
+ References
1589
+ ==========
1590
+
1591
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
1592
+ of direct collocation optimal control problem formulations for
1593
+ solving the muscle redundancy problem, Annals of biomedical
1594
+ engineering, 44(10), (2016) pp. 2922-2936
1595
+
1596
+ """
1597
+
1598
+ @classmethod
1599
+ def with_defaults(cls, fv_M):
1600
+ r"""Recommended constructor that will use the published constants.
1601
+
1602
+ Explanation
1603
+ ===========
1604
+
1605
+ Returns a new instance of the inverse muscle fiber force-velocity
1606
+ function using the four constant values specified in the original
1607
+ publication.
1608
+
1609
+ These have the values:
1610
+
1611
+ $c_0 = -0.318$
1612
+ $c_1 = -8.149$
1613
+ $c_2 = -0.374$
1614
+ $c_3 = 0.886$
1615
+
1616
+ Parameters
1617
+ ==========
1618
+
1619
+ fv_M : Any (sympifiable)
1620
+ Normalized muscle fiber extension velocity.
1621
+
1622
+ """
1623
+ c0 = Float('-0.318')
1624
+ c1 = Float('-8.149')
1625
+ c2 = Float('-0.374')
1626
+ c3 = Float('0.886')
1627
+ return cls(fv_M, c0, c1, c2, c3)
1628
+
1629
+ @classmethod
1630
+ def eval(cls, fv_M, c0, c1, c2, c3):
1631
+ """Evaluation of basic inputs.
1632
+
1633
+ Parameters
1634
+ ==========
1635
+
1636
+ fv_M : Any (sympifiable)
1637
+ Normalized muscle fiber force as a function of muscle fiber
1638
+ extension velocity.
1639
+ c0 : Any (sympifiable)
1640
+ The first constant in the characteristic equation. The published
1641
+ value is ``-0.318``.
1642
+ c1 : Any (sympifiable)
1643
+ The second constant in the characteristic equation. The published
1644
+ value is ``-8.149``.
1645
+ c2 : Any (sympifiable)
1646
+ The third constant in the characteristic equation. The published
1647
+ value is ``-0.374``.
1648
+ c3 : Any (sympifiable)
1649
+ The fourth constant in the characteristic equation. The published
1650
+ value is ``0.886``.
1651
+
1652
+ """
1653
+ pass
1654
+
1655
+ def _eval_evalf(self, prec):
1656
+ """Evaluate the expression numerically using ``evalf``."""
1657
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
1658
+
1659
+ def doit(self, deep=True, evaluate=True, **hints):
1660
+ """Evaluate the expression defining the function.
1661
+
1662
+ Parameters
1663
+ ==========
1664
+
1665
+ deep : bool
1666
+ Whether ``doit`` should be recursively called. Default is ``True``.
1667
+ evaluate : bool.
1668
+ Whether the SymPy expression should be evaluated as it is
1669
+ constructed. If ``False``, then no constant folding will be
1670
+ conducted which will leave the expression in a more numerically-
1671
+ stable for values of ``fv_M`` that correspond to a sensible
1672
+ operating range for a musculotendon. Default is ``True``.
1673
+ **kwargs : dict[str, Any]
1674
+ Additional keyword argument pairs to be recursively passed to
1675
+ ``doit``.
1676
+
1677
+ """
1678
+ fv_M, *constants = self.args
1679
+ if deep:
1680
+ hints['evaluate'] = evaluate
1681
+ fv_M = fv_M.doit(deep=deep, **hints)
1682
+ c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
1683
+ else:
1684
+ c0, c1, c2, c3 = constants
1685
+
1686
+ if evaluate:
1687
+ return (sinh((fv_M - c3)/c0) - c2)/c1
1688
+
1689
+ return (sinh(UnevaluatedExpr(fv_M - c3)/c0) - c2)/c1
1690
+
1691
+ def fdiff(self, argindex=1):
1692
+ """Derivative of the function with respect to a single argument.
1693
+
1694
+ Parameters
1695
+ ==========
1696
+
1697
+ argindex : int
1698
+ The index of the function's arguments with respect to which the
1699
+ derivative should be taken. Argument indexes start at ``1``.
1700
+ Default is ``1``.
1701
+
1702
+ """
1703
+ fv_M, c0, c1, c2, c3 = self.args
1704
+ if argindex == 1:
1705
+ return cosh((fv_M - c3)/c0)/(c0*c1)
1706
+ elif argindex == 2:
1707
+ return (c3 - fv_M)*cosh((fv_M - c3)/c0)/(c0**2*c1)
1708
+ elif argindex == 3:
1709
+ return (c2 - sinh((fv_M - c3)/c0))/c1**2
1710
+ elif argindex == 4:
1711
+ return -1/c1
1712
+ elif argindex == 5:
1713
+ return -cosh((fv_M - c3)/c0)/(c0*c1)
1714
+
1715
+ raise ArgumentIndexError(self, argindex)
1716
+
1717
+ def inverse(self, argindex=1):
1718
+ """Inverse function.
1719
+
1720
+ Parameters
1721
+ ==========
1722
+
1723
+ argindex : int
1724
+ Value to start indexing the arguments at. Default is ``1``.
1725
+
1726
+ """
1727
+ return FiberForceVelocityDeGroote2016
1728
+
1729
+ def _latex(self, printer):
1730
+ """Print a LaTeX representation of the function defining the curve.
1731
+
1732
+ Parameters
1733
+ ==========
1734
+
1735
+ printer : Printer
1736
+ The printer to be used to print the LaTeX string representation.
1737
+
1738
+ """
1739
+ fv_M = self.args[0]
1740
+ _fv_M = printer._print(fv_M)
1741
+ return r'\left( \operatorname{fv}^M \right)^{-1} \left( %s \right)' % _fv_M
1742
+
1743
+
1744
+ @dataclass(frozen=True)
1745
+ class CharacteristicCurveCollection:
1746
+ """Simple data container to group together related characteristic curves."""
1747
+ tendon_force_length: CharacteristicCurveFunction
1748
+ tendon_force_length_inverse: CharacteristicCurveFunction
1749
+ fiber_force_length_passive: CharacteristicCurveFunction
1750
+ fiber_force_length_passive_inverse: CharacteristicCurveFunction
1751
+ fiber_force_length_active: CharacteristicCurveFunction
1752
+ fiber_force_velocity: CharacteristicCurveFunction
1753
+ fiber_force_velocity_inverse: CharacteristicCurveFunction
1754
+
1755
+ def __iter__(self):
1756
+ """Iterator support for ``CharacteristicCurveCollection``."""
1757
+ yield self.tendon_force_length
1758
+ yield self.tendon_force_length_inverse
1759
+ yield self.fiber_force_length_passive
1760
+ yield self.fiber_force_length_passive_inverse
1761
+ yield self.fiber_force_length_active
1762
+ yield self.fiber_force_velocity
1763
+ yield self.fiber_force_velocity_inverse
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/musculotendon.py ADDED
@@ -0,0 +1,1424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementations of musculotendon models.
2
+
3
+ Musculotendon models are a critical component of biomechanical models, one that
4
+ differentiates them from pure multibody systems. Musculotendon models produce a
5
+ force dependent on their level of activation, their length, and their
6
+ extension velocity. Length- and extension velocity-dependent force production
7
+ are governed by force-length and force-velocity characteristics.
8
+ These are normalized functions that are dependent on the musculotendon's state
9
+ and are specific to a given musculotendon model.
10
+
11
+ """
12
+
13
+ from abc import abstractmethod
14
+ from enum import IntEnum, unique
15
+
16
+ from sympy.core.numbers import Float, Integer
17
+ from sympy.core.symbol import Symbol, symbols
18
+ from sympy.functions.elementary.miscellaneous import sqrt
19
+ from sympy.functions.elementary.trigonometric import cos, sin
20
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix, diag, eye, zeros
21
+ from sympy.physics.biomechanics.activation import ActivationBase
22
+ from sympy.physics.biomechanics.curve import (
23
+ CharacteristicCurveCollection,
24
+ FiberForceLengthActiveDeGroote2016,
25
+ FiberForceLengthPassiveDeGroote2016,
26
+ FiberForceLengthPassiveInverseDeGroote2016,
27
+ FiberForceVelocityDeGroote2016,
28
+ FiberForceVelocityInverseDeGroote2016,
29
+ TendonForceLengthDeGroote2016,
30
+ TendonForceLengthInverseDeGroote2016,
31
+ )
32
+ from sympy.physics.biomechanics._mixin import _NamedMixin
33
+ from sympy.physics.mechanics.actuator import ForceActuator
34
+ from sympy.physics.vector.functions import dynamicsymbols
35
+
36
+
37
+ __all__ = [
38
+ 'MusculotendonBase',
39
+ 'MusculotendonDeGroote2016',
40
+ 'MusculotendonFormulation',
41
+ ]
42
+
43
+
44
+ @unique
45
+ class MusculotendonFormulation(IntEnum):
46
+ """Enumeration of types of musculotendon dynamics formulations.
47
+
48
+ Explanation
49
+ ===========
50
+
51
+ An (integer) enumeration is used as it allows for clearer selection of the
52
+ different formulations of musculotendon dynamics.
53
+
54
+ Members
55
+ =======
56
+
57
+ RIGID_TENDON : 0
58
+ A rigid tendon model.
59
+ FIBER_LENGTH_EXPLICIT : 1
60
+ An explicit elastic tendon model with the muscle fiber length (l_M) as
61
+ the state variable.
62
+ TENDON_FORCE_EXPLICIT : 2
63
+ An explicit elastic tendon model with the tendon force (F_T) as the
64
+ state variable.
65
+ FIBER_LENGTH_IMPLICIT : 3
66
+ An implicit elastic tendon model with the muscle fiber length (l_M) as
67
+ the state variable and the muscle fiber velocity as an additional input
68
+ variable.
69
+ TENDON_FORCE_IMPLICIT : 4
70
+ An implicit elastic tendon model with the tendon force (F_T) as the
71
+ state variable as the muscle fiber velocity as an additional input
72
+ variable.
73
+
74
+ """
75
+
76
+ RIGID_TENDON = 0
77
+ FIBER_LENGTH_EXPLICIT = 1
78
+ TENDON_FORCE_EXPLICIT = 2
79
+ FIBER_LENGTH_IMPLICIT = 3
80
+ TENDON_FORCE_IMPLICIT = 4
81
+
82
+ def __str__(self):
83
+ """Returns a string representation of the enumeration value.
84
+
85
+ Notes
86
+ =====
87
+
88
+ This hard coding is required due to an incompatibility between the
89
+ ``IntEnum`` implementations in Python 3.10 and Python 3.11
90
+ (https://github.com/python/cpython/issues/84247). From Python 3.11
91
+ onwards, the ``__str__`` method uses ``int.__str__``, whereas prior it
92
+ used ``Enum.__str__``. Once Python 3.11 becomes the minimum version
93
+ supported by SymPy, this method override can be removed.
94
+
95
+ """
96
+ return str(self.value)
97
+
98
+
99
+ _DEFAULT_MUSCULOTENDON_FORMULATION = MusculotendonFormulation.RIGID_TENDON
100
+
101
+
102
+ class MusculotendonBase(ForceActuator, _NamedMixin):
103
+ r"""Abstract base class for all musculotendon classes to inherit from.
104
+
105
+ Explanation
106
+ ===========
107
+
108
+ A musculotendon generates a contractile force based on its activation,
109
+ length, and shortening velocity. This abstract base class is to be inherited
110
+ by all musculotendon subclasses that implement different characteristic
111
+ musculotendon curves. Characteristic musculotendon curves are required for
112
+ the tendon force-length, passive fiber force-length, active fiber force-
113
+ length, and fiber force-velocity relationships.
114
+
115
+ Parameters
116
+ ==========
117
+
118
+ name : str
119
+ The name identifier associated with the musculotendon. This name is used
120
+ as a suffix when automatically generated symbols are instantiated. It
121
+ must be a string of nonzero length.
122
+ pathway : PathwayBase
123
+ The pathway that the actuator follows. This must be an instance of a
124
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
125
+ activation_dynamics : ActivationBase
126
+ The activation dynamics that will be modeled within the musculotendon.
127
+ This must be an instance of a concrete subclass of ``ActivationBase``,
128
+ e.g. ``FirstOrderActivationDeGroote2016``.
129
+ musculotendon_dynamics : MusculotendonFormulation | int
130
+ The formulation of musculotendon dynamics that should be used
131
+ internally, i.e. rigid or elastic tendon model, the choice of
132
+ musculotendon state etc. This must be a member of the integer
133
+ enumeration ``MusculotendonFormulation`` or an integer that can be cast
134
+ to a member. To use a rigid tendon formulation, set this to
135
+ ``MusculotendonFormulation.RIGID_TENDON`` (or the integer value ``0``,
136
+ which will be cast to the enumeration member). There are four possible
137
+ formulations for an elastic tendon model. To use an explicit formulation
138
+ with the fiber length as the state, set this to
139
+ ``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer value
140
+ ``1``). To use an explicit formulation with the tendon force as the
141
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_EXPLICIT``
142
+ (or the integer value ``2``). To use an implicit formulation with the
143
+ fiber length as the state, set this to
144
+ ``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer value
145
+ ``3``). To use an implicit formulation with the tendon force as the
146
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_IMPLICIT``
147
+ (or the integer value ``4``). The default is
148
+ ``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a rigid
149
+ tendon formulation.
150
+ tendon_slack_length : Expr | None
151
+ The length of the tendon when the musculotendon is in its unloaded
152
+ state. In a rigid tendon model the tendon length is the tendon slack
153
+ length. In all musculotendon models, tendon slack length is used to
154
+ normalize tendon length to give
155
+ :math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
156
+ peak_isometric_force : Expr | None
157
+ The maximum force that the muscle fiber can produce when it is
158
+ undergoing an isometric contraction (no lengthening velocity). In all
159
+ musculotendon models, peak isometric force is used to normalized tendon
160
+ and muscle fiber force to give
161
+ :math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
162
+ optimal_fiber_length : Expr | None
163
+ The muscle fiber length at which the muscle fibers produce no passive
164
+ force and their maximum active force. In all musculotendon models,
165
+ optimal fiber length is used to normalize muscle fiber length to give
166
+ :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
167
+ maximal_fiber_velocity : Expr | None
168
+ The fiber velocity at which, during muscle fiber shortening, the muscle
169
+ fibers are unable to produce any active force. In all musculotendon
170
+ models, maximal fiber velocity is used to normalize muscle fiber
171
+ extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
172
+ optimal_pennation_angle : Expr | None
173
+ The pennation angle when muscle fiber length equals the optimal fiber
174
+ length.
175
+ fiber_damping_coefficient : Expr | None
176
+ The coefficient of damping to be used in the damping element in the
177
+ muscle fiber model.
178
+ with_defaults : bool
179
+ Whether ``with_defaults`` alternate constructors should be used when
180
+ automatically constructing child classes. Default is ``False``.
181
+
182
+ """
183
+
184
+ def __init__(
185
+ self,
186
+ name,
187
+ pathway,
188
+ activation_dynamics,
189
+ *,
190
+ musculotendon_dynamics=_DEFAULT_MUSCULOTENDON_FORMULATION,
191
+ tendon_slack_length=None,
192
+ peak_isometric_force=None,
193
+ optimal_fiber_length=None,
194
+ maximal_fiber_velocity=None,
195
+ optimal_pennation_angle=None,
196
+ fiber_damping_coefficient=None,
197
+ with_defaults=False,
198
+ ):
199
+ self.name = name
200
+
201
+ # Supply a placeholder force to the super initializer, this will be
202
+ # replaced later
203
+ super().__init__(Symbol('F'), pathway)
204
+
205
+ # Activation dynamics
206
+ if not isinstance(activation_dynamics, ActivationBase):
207
+ msg = (
208
+ f'Can\'t set attribute `activation_dynamics` to '
209
+ f'{activation_dynamics} as it must be of type '
210
+ f'`ActivationBase`, not {type(activation_dynamics)}.'
211
+ )
212
+ raise TypeError(msg)
213
+ self._activation_dynamics = activation_dynamics
214
+ self._child_objects = (self._activation_dynamics, )
215
+
216
+ # Constants
217
+ if tendon_slack_length is not None:
218
+ self._l_T_slack = tendon_slack_length
219
+ else:
220
+ self._l_T_slack = Symbol(f'l_T_slack_{self.name}')
221
+ if peak_isometric_force is not None:
222
+ self._F_M_max = peak_isometric_force
223
+ else:
224
+ self._F_M_max = Symbol(f'F_M_max_{self.name}')
225
+ if optimal_fiber_length is not None:
226
+ self._l_M_opt = optimal_fiber_length
227
+ else:
228
+ self._l_M_opt = Symbol(f'l_M_opt_{self.name}')
229
+ if maximal_fiber_velocity is not None:
230
+ self._v_M_max = maximal_fiber_velocity
231
+ else:
232
+ self._v_M_max = Symbol(f'v_M_max_{self.name}')
233
+ if optimal_pennation_angle is not None:
234
+ self._alpha_opt = optimal_pennation_angle
235
+ else:
236
+ self._alpha_opt = Symbol(f'alpha_opt_{self.name}')
237
+ if fiber_damping_coefficient is not None:
238
+ self._beta = fiber_damping_coefficient
239
+ else:
240
+ self._beta = Symbol(f'beta_{self.name}')
241
+
242
+ # Musculotendon dynamics
243
+ self._with_defaults = with_defaults
244
+ if musculotendon_dynamics == MusculotendonFormulation.RIGID_TENDON:
245
+ self._rigid_tendon_musculotendon_dynamics()
246
+ elif musculotendon_dynamics == MusculotendonFormulation.FIBER_LENGTH_EXPLICIT:
247
+ self._fiber_length_explicit_musculotendon_dynamics()
248
+ elif musculotendon_dynamics == MusculotendonFormulation.TENDON_FORCE_EXPLICIT:
249
+ self._tendon_force_explicit_musculotendon_dynamics()
250
+ elif musculotendon_dynamics == MusculotendonFormulation.FIBER_LENGTH_IMPLICIT:
251
+ self._fiber_length_implicit_musculotendon_dynamics()
252
+ elif musculotendon_dynamics == MusculotendonFormulation.TENDON_FORCE_IMPLICIT:
253
+ self._tendon_force_implicit_musculotendon_dynamics()
254
+ else:
255
+ msg = (
256
+ f'Musculotendon dynamics {repr(musculotendon_dynamics)} '
257
+ f'passed to `musculotendon_dynamics` was of type '
258
+ f'{type(musculotendon_dynamics)}, must be '
259
+ f'{MusculotendonFormulation}.'
260
+ )
261
+ raise TypeError(msg)
262
+ self._musculotendon_dynamics = musculotendon_dynamics
263
+
264
+ # Must override the placeholder value in `self._force` now that the
265
+ # actual force has been calculated by
266
+ # `self._<MUSCULOTENDON FORMULATION>_musculotendon_dynamics`.
267
+ # Note that `self._force` assumes forces are expansile, musculotendon
268
+ # forces are contractile hence the minus sign preceeding `self._F_T`
269
+ # (the tendon force).
270
+ self._force = -self._F_T
271
+
272
+ @classmethod
273
+ def with_defaults(
274
+ cls,
275
+ name,
276
+ pathway,
277
+ activation_dynamics,
278
+ *,
279
+ musculotendon_dynamics=_DEFAULT_MUSCULOTENDON_FORMULATION,
280
+ tendon_slack_length=None,
281
+ peak_isometric_force=None,
282
+ optimal_fiber_length=None,
283
+ maximal_fiber_velocity=Float('10.0'),
284
+ optimal_pennation_angle=Float('0.0'),
285
+ fiber_damping_coefficient=Float('0.1'),
286
+ ):
287
+ r"""Recommended constructor that will use the published constants.
288
+
289
+ Explanation
290
+ ===========
291
+
292
+ Returns a new instance of the musculotendon class using recommended
293
+ values for ``v_M_max``, ``alpha_opt``, and ``beta``. The values are:
294
+
295
+ :math:`v^M_{max} = 10`
296
+ :math:`\alpha_{opt} = 0`
297
+ :math:`\beta = \frac{1}{10}`
298
+
299
+ The musculotendon curves are also instantiated using the constants from
300
+ the original publication.
301
+
302
+ Parameters
303
+ ==========
304
+
305
+ name : str
306
+ The name identifier associated with the musculotendon. This name is
307
+ used as a suffix when automatically generated symbols are
308
+ instantiated. It must be a string of nonzero length.
309
+ pathway : PathwayBase
310
+ The pathway that the actuator follows. This must be an instance of a
311
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
312
+ activation_dynamics : ActivationBase
313
+ The activation dynamics that will be modeled within the
314
+ musculotendon. This must be an instance of a concrete subclass of
315
+ ``ActivationBase``, e.g. ``FirstOrderActivationDeGroote2016``.
316
+ musculotendon_dynamics : MusculotendonFormulation | int
317
+ The formulation of musculotendon dynamics that should be used
318
+ internally, i.e. rigid or elastic tendon model, the choice of
319
+ musculotendon state etc. This must be a member of the integer
320
+ enumeration ``MusculotendonFormulation`` or an integer that can be
321
+ cast to a member. To use a rigid tendon formulation, set this to
322
+ ``MusculotendonFormulation.RIGID_TENDON`` (or the integer value
323
+ ``0``, which will be cast to the enumeration member). There are four
324
+ possible formulations for an elastic tendon model. To use an
325
+ explicit formulation with the fiber length as the state, set this to
326
+ ``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer
327
+ value ``1``). To use an explicit formulation with the tendon force
328
+ as the state, set this to
329
+ ``MusculotendonFormulation.TENDON_FORCE_EXPLICIT`` (or the integer
330
+ value ``2``). To use an implicit formulation with the fiber length
331
+ as the state, set this to
332
+ ``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer
333
+ value ``3``). To use an implicit formulation with the tendon force
334
+ as the state, set this to
335
+ ``MusculotendonFormulation.TENDON_FORCE_IMPLICIT`` (or the integer
336
+ value ``4``). The default is
337
+ ``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a
338
+ rigid tendon formulation.
339
+ tendon_slack_length : Expr | None
340
+ The length of the tendon when the musculotendon is in its unloaded
341
+ state. In a rigid tendon model the tendon length is the tendon slack
342
+ length. In all musculotendon models, tendon slack length is used to
343
+ normalize tendon length to give
344
+ :math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
345
+ peak_isometric_force : Expr | None
346
+ The maximum force that the muscle fiber can produce when it is
347
+ undergoing an isometric contraction (no lengthening velocity). In
348
+ all musculotendon models, peak isometric force is used to normalized
349
+ tendon and muscle fiber force to give
350
+ :math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
351
+ optimal_fiber_length : Expr | None
352
+ The muscle fiber length at which the muscle fibers produce no
353
+ passive force and their maximum active force. In all musculotendon
354
+ models, optimal fiber length is used to normalize muscle fiber
355
+ length to give :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
356
+ maximal_fiber_velocity : Expr | None
357
+ The fiber velocity at which, during muscle fiber shortening, the
358
+ muscle fibers are unable to produce any active force. In all
359
+ musculotendon models, maximal fiber velocity is used to normalize
360
+ muscle fiber extension velocity to give
361
+ :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
362
+ optimal_pennation_angle : Expr | None
363
+ The pennation angle when muscle fiber length equals the optimal
364
+ fiber length.
365
+ fiber_damping_coefficient : Expr | None
366
+ The coefficient of damping to be used in the damping element in the
367
+ muscle fiber model.
368
+
369
+ """
370
+ return cls(
371
+ name,
372
+ pathway,
373
+ activation_dynamics=activation_dynamics,
374
+ musculotendon_dynamics=musculotendon_dynamics,
375
+ tendon_slack_length=tendon_slack_length,
376
+ peak_isometric_force=peak_isometric_force,
377
+ optimal_fiber_length=optimal_fiber_length,
378
+ maximal_fiber_velocity=maximal_fiber_velocity,
379
+ optimal_pennation_angle=optimal_pennation_angle,
380
+ fiber_damping_coefficient=fiber_damping_coefficient,
381
+ with_defaults=True,
382
+ )
383
+
384
+ @abstractmethod
385
+ def curves(cls):
386
+ """Return a ``CharacteristicCurveCollection`` of the curves related to
387
+ the specific model."""
388
+ pass
389
+
390
+ @property
391
+ def tendon_slack_length(self):
392
+ r"""Symbol or value corresponding to the tendon slack length constant.
393
+
394
+ Explanation
395
+ ===========
396
+
397
+ The length of the tendon when the musculotendon is in its unloaded
398
+ state. In a rigid tendon model the tendon length is the tendon slack
399
+ length. In all musculotendon models, tendon slack length is used to
400
+ normalize tendon length to give
401
+ :math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
402
+
403
+ The alias ``l_T_slack`` can also be used to access the same attribute.
404
+
405
+ """
406
+ return self._l_T_slack
407
+
408
+ @property
409
+ def l_T_slack(self):
410
+ r"""Symbol or value corresponding to the tendon slack length constant.
411
+
412
+ Explanation
413
+ ===========
414
+
415
+ The length of the tendon when the musculotendon is in its unloaded
416
+ state. In a rigid tendon model the tendon length is the tendon slack
417
+ length. In all musculotendon models, tendon slack length is used to
418
+ normalize tendon length to give
419
+ :math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
420
+
421
+ The alias ``tendon_slack_length`` can also be used to access the same
422
+ attribute.
423
+
424
+ """
425
+ return self._l_T_slack
426
+
427
+ @property
428
+ def peak_isometric_force(self):
429
+ r"""Symbol or value corresponding to the peak isometric force constant.
430
+
431
+ Explanation
432
+ ===========
433
+
434
+ The maximum force that the muscle fiber can produce when it is
435
+ undergoing an isometric contraction (no lengthening velocity). In all
436
+ musculotendon models, peak isometric force is used to normalized tendon
437
+ and muscle fiber force to give
438
+ :math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
439
+
440
+ The alias ``F_M_max`` can also be used to access the same attribute.
441
+
442
+ """
443
+ return self._F_M_max
444
+
445
+ @property
446
+ def F_M_max(self):
447
+ r"""Symbol or value corresponding to the peak isometric force constant.
448
+
449
+ Explanation
450
+ ===========
451
+
452
+ The maximum force that the muscle fiber can produce when it is
453
+ undergoing an isometric contraction (no lengthening velocity). In all
454
+ musculotendon models, peak isometric force is used to normalized tendon
455
+ and muscle fiber force to give
456
+ :math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
457
+
458
+ The alias ``peak_isometric_force`` can also be used to access the same
459
+ attribute.
460
+
461
+ """
462
+ return self._F_M_max
463
+
464
+ @property
465
+ def optimal_fiber_length(self):
466
+ r"""Symbol or value corresponding to the optimal fiber length constant.
467
+
468
+ Explanation
469
+ ===========
470
+
471
+ The muscle fiber length at which the muscle fibers produce no passive
472
+ force and their maximum active force. In all musculotendon models,
473
+ optimal fiber length is used to normalize muscle fiber length to give
474
+ :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
475
+
476
+ The alias ``l_M_opt`` can also be used to access the same attribute.
477
+
478
+ """
479
+ return self._l_M_opt
480
+
481
+ @property
482
+ def l_M_opt(self):
483
+ r"""Symbol or value corresponding to the optimal fiber length constant.
484
+
485
+ Explanation
486
+ ===========
487
+
488
+ The muscle fiber length at which the muscle fibers produce no passive
489
+ force and their maximum active force. In all musculotendon models,
490
+ optimal fiber length is used to normalize muscle fiber length to give
491
+ :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
492
+
493
+ The alias ``optimal_fiber_length`` can also be used to access the same
494
+ attribute.
495
+
496
+ """
497
+ return self._l_M_opt
498
+
499
+ @property
500
+ def maximal_fiber_velocity(self):
501
+ r"""Symbol or value corresponding to the maximal fiber velocity constant.
502
+
503
+ Explanation
504
+ ===========
505
+
506
+ The fiber velocity at which, during muscle fiber shortening, the muscle
507
+ fibers are unable to produce any active force. In all musculotendon
508
+ models, maximal fiber velocity is used to normalize muscle fiber
509
+ extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
510
+
511
+ The alias ``v_M_max`` can also be used to access the same attribute.
512
+
513
+ """
514
+ return self._v_M_max
515
+
516
+ @property
517
+ def v_M_max(self):
518
+ r"""Symbol or value corresponding to the maximal fiber velocity constant.
519
+
520
+ Explanation
521
+ ===========
522
+
523
+ The fiber velocity at which, during muscle fiber shortening, the muscle
524
+ fibers are unable to produce any active force. In all musculotendon
525
+ models, maximal fiber velocity is used to normalize muscle fiber
526
+ extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
527
+
528
+ The alias ``maximal_fiber_velocity`` can also be used to access the same
529
+ attribute.
530
+
531
+ """
532
+ return self._v_M_max
533
+
534
+ @property
535
+ def optimal_pennation_angle(self):
536
+ """Symbol or value corresponding to the optimal pennation angle
537
+ constant.
538
+
539
+ Explanation
540
+ ===========
541
+
542
+ The pennation angle when muscle fiber length equals the optimal fiber
543
+ length.
544
+
545
+ The alias ``alpha_opt`` can also be used to access the same attribute.
546
+
547
+ """
548
+ return self._alpha_opt
549
+
550
+ @property
551
+ def alpha_opt(self):
552
+ """Symbol or value corresponding to the optimal pennation angle
553
+ constant.
554
+
555
+ Explanation
556
+ ===========
557
+
558
+ The pennation angle when muscle fiber length equals the optimal fiber
559
+ length.
560
+
561
+ The alias ``optimal_pennation_angle`` can also be used to access the
562
+ same attribute.
563
+
564
+ """
565
+ return self._alpha_opt
566
+
567
+ @property
568
+ def fiber_damping_coefficient(self):
569
+ """Symbol or value corresponding to the fiber damping coefficient
570
+ constant.
571
+
572
+ Explanation
573
+ ===========
574
+
575
+ The coefficient of damping to be used in the damping element in the
576
+ muscle fiber model.
577
+
578
+ The alias ``beta`` can also be used to access the same attribute.
579
+
580
+ """
581
+ return self._beta
582
+
583
+ @property
584
+ def beta(self):
585
+ """Symbol or value corresponding to the fiber damping coefficient
586
+ constant.
587
+
588
+ Explanation
589
+ ===========
590
+
591
+ The coefficient of damping to be used in the damping element in the
592
+ muscle fiber model.
593
+
594
+ The alias ``fiber_damping_coefficient`` can also be used to access the
595
+ same attribute.
596
+
597
+ """
598
+ return self._beta
599
+
600
+ @property
601
+ def activation_dynamics(self):
602
+ """Activation dynamics model governing this musculotendon's activation.
603
+
604
+ Explanation
605
+ ===========
606
+
607
+ Returns the instance of a subclass of ``ActivationBase`` that governs
608
+ the relationship between excitation and activation that is used to
609
+ represent the activation dynamics of this musculotendon.
610
+
611
+ """
612
+ return self._activation_dynamics
613
+
614
+ @property
615
+ def excitation(self):
616
+ """Dynamic symbol representing excitation.
617
+
618
+ Explanation
619
+ ===========
620
+
621
+ The alias ``e`` can also be used to access the same attribute.
622
+
623
+ """
624
+ return self._activation_dynamics._e
625
+
626
+ @property
627
+ def e(self):
628
+ """Dynamic symbol representing excitation.
629
+
630
+ Explanation
631
+ ===========
632
+
633
+ The alias ``excitation`` can also be used to access the same attribute.
634
+
635
+ """
636
+ return self._activation_dynamics._e
637
+
638
+ @property
639
+ def activation(self):
640
+ """Dynamic symbol representing activation.
641
+
642
+ Explanation
643
+ ===========
644
+
645
+ The alias ``a`` can also be used to access the same attribute.
646
+
647
+ """
648
+ return self._activation_dynamics._a
649
+
650
+ @property
651
+ def a(self):
652
+ """Dynamic symbol representing activation.
653
+
654
+ Explanation
655
+ ===========
656
+
657
+ The alias ``activation`` can also be used to access the same attribute.
658
+
659
+ """
660
+ return self._activation_dynamics._a
661
+
662
+ @property
663
+ def musculotendon_dynamics(self):
664
+ """The choice of rigid or type of elastic tendon musculotendon dynamics.
665
+
666
+ Explanation
667
+ ===========
668
+
669
+ The formulation of musculotendon dynamics that should be used
670
+ internally, i.e. rigid or elastic tendon model, the choice of
671
+ musculotendon state etc. This must be a member of the integer
672
+ enumeration ``MusculotendonFormulation`` or an integer that can be cast
673
+ to a member. To use a rigid tendon formulation, set this to
674
+ ``MusculotendonFormulation.RIGID_TENDON`` (or the integer value ``0``,
675
+ which will be cast to the enumeration member). There are four possible
676
+ formulations for an elastic tendon model. To use an explicit formulation
677
+ with the fiber length as the state, set this to
678
+ ``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer value
679
+ ``1``). To use an explicit formulation with the tendon force as the
680
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_EXPLICIT``
681
+ (or the integer value ``2``). To use an implicit formulation with the
682
+ fiber length as the state, set this to
683
+ ``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer value
684
+ ``3``). To use an implicit formulation with the tendon force as the
685
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_IMPLICIT``
686
+ (or the integer value ``4``). The default is
687
+ ``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a rigid
688
+ tendon formulation.
689
+
690
+ """
691
+ return self._musculotendon_dynamics
692
+
693
+ def _rigid_tendon_musculotendon_dynamics(self):
694
+ """Rigid tendon musculotendon."""
695
+ self._l_MT = self.pathway.length
696
+ self._v_MT = self.pathway.extension_velocity
697
+ self._l_T = self._l_T_slack
698
+ self._l_T_tilde = Integer(1)
699
+ self._l_M = sqrt((self._l_MT - self._l_T)**2 + (self._l_M_opt*sin(self._alpha_opt))**2)
700
+ self._l_M_tilde = self._l_M/self._l_M_opt
701
+ self._v_M = self._v_MT*(self._l_MT - self._l_T_slack)/self._l_M
702
+ self._v_M_tilde = self._v_M/self._v_M_max
703
+ if self._with_defaults:
704
+ self._fl_T = self.curves.tendon_force_length.with_defaults(self._l_T_tilde)
705
+ self._fl_M_pas = self.curves.fiber_force_length_passive.with_defaults(self._l_M_tilde)
706
+ self._fl_M_act = self.curves.fiber_force_length_active.with_defaults(self._l_M_tilde)
707
+ self._fv_M = self.curves.fiber_force_velocity.with_defaults(self._v_M_tilde)
708
+ else:
709
+ fl_T_constants = symbols(f'c_0:4_fl_T_{self.name}')
710
+ self._fl_T = self.curves.tendon_force_length(self._l_T_tilde, *fl_T_constants)
711
+ fl_M_pas_constants = symbols(f'c_0:2_fl_M_pas_{self.name}')
712
+ self._fl_M_pas = self.curves.fiber_force_length_passive(self._l_M_tilde, *fl_M_pas_constants)
713
+ fl_M_act_constants = symbols(f'c_0:12_fl_M_act_{self.name}')
714
+ self._fl_M_act = self.curves.fiber_force_length_active(self._l_M_tilde, *fl_M_act_constants)
715
+ fv_M_constants = symbols(f'c_0:4_fv_M_{self.name}')
716
+ self._fv_M = self.curves.fiber_force_velocity(self._v_M_tilde, *fv_M_constants)
717
+ self._F_M_tilde = self.a*self._fl_M_act*self._fv_M + self._fl_M_pas + self._beta*self._v_M_tilde
718
+ self._F_T_tilde = self._F_M_tilde
719
+ self._F_M = self._F_M_tilde*self._F_M_max
720
+ self._cos_alpha = cos(self._alpha_opt)
721
+ self._F_T = self._F_M*self._cos_alpha
722
+
723
+ # Containers
724
+ self._state_vars = zeros(0, 1)
725
+ self._input_vars = zeros(0, 1)
726
+ self._state_eqns = zeros(0, 1)
727
+ self._curve_constants = Matrix(
728
+ fl_T_constants
729
+ + fl_M_pas_constants
730
+ + fl_M_act_constants
731
+ + fv_M_constants
732
+ ) if not self._with_defaults else zeros(0, 1)
733
+
734
+ def _fiber_length_explicit_musculotendon_dynamics(self):
735
+ """Elastic tendon musculotendon using `l_M_tilde` as a state."""
736
+ self._l_M_tilde = dynamicsymbols(f'l_M_tilde_{self.name}')
737
+ self._l_MT = self.pathway.length
738
+ self._v_MT = self.pathway.extension_velocity
739
+ self._l_M = self._l_M_tilde*self._l_M_opt
740
+ self._l_T = self._l_MT - sqrt(self._l_M**2 - (self._l_M_opt*sin(self._alpha_opt))**2)
741
+ self._l_T_tilde = self._l_T/self._l_T_slack
742
+ self._cos_alpha = (self._l_MT - self._l_T)/self._l_M
743
+ if self._with_defaults:
744
+ self._fl_T = self.curves.tendon_force_length.with_defaults(self._l_T_tilde)
745
+ self._fl_M_pas = self.curves.fiber_force_length_passive.with_defaults(self._l_M_tilde)
746
+ self._fl_M_act = self.curves.fiber_force_length_active.with_defaults(self._l_M_tilde)
747
+ else:
748
+ fl_T_constants = symbols(f'c_0:4_fl_T_{self.name}')
749
+ self._fl_T = self.curves.tendon_force_length(self._l_T_tilde, *fl_T_constants)
750
+ fl_M_pas_constants = symbols(f'c_0:2_fl_M_pas_{self.name}')
751
+ self._fl_M_pas = self.curves.fiber_force_length_passive(self._l_M_tilde, *fl_M_pas_constants)
752
+ fl_M_act_constants = symbols(f'c_0:12_fl_M_act_{self.name}')
753
+ self._fl_M_act = self.curves.fiber_force_length_active(self._l_M_tilde, *fl_M_act_constants)
754
+ self._F_T_tilde = self._fl_T
755
+ self._F_T = self._F_T_tilde*self._F_M_max
756
+ self._F_M = self._F_T/self._cos_alpha
757
+ self._F_M_tilde = self._F_M/self._F_M_max
758
+ self._fv_M = (self._F_M_tilde - self._fl_M_pas)/(self.a*self._fl_M_act)
759
+ if self._with_defaults:
760
+ self._v_M_tilde = self.curves.fiber_force_velocity_inverse.with_defaults(self._fv_M)
761
+ else:
762
+ fv_M_constants = symbols(f'c_0:4_fv_M_{self.name}')
763
+ self._v_M_tilde = self.curves.fiber_force_velocity_inverse(self._fv_M, *fv_M_constants)
764
+ self._dl_M_tilde_dt = (self._v_M_max/self._l_M_opt)*self._v_M_tilde
765
+
766
+ self._state_vars = Matrix([self._l_M_tilde])
767
+ self._input_vars = zeros(0, 1)
768
+ self._state_eqns = Matrix([self._dl_M_tilde_dt])
769
+ self._curve_constants = Matrix(
770
+ fl_T_constants
771
+ + fl_M_pas_constants
772
+ + fl_M_act_constants
773
+ + fv_M_constants
774
+ ) if not self._with_defaults else zeros(0, 1)
775
+
776
+ def _tendon_force_explicit_musculotendon_dynamics(self):
777
+ """Elastic tendon musculotendon using `F_T_tilde` as a state."""
778
+ self._F_T_tilde = dynamicsymbols(f'F_T_tilde_{self.name}')
779
+ self._l_MT = self.pathway.length
780
+ self._v_MT = self.pathway.extension_velocity
781
+ self._fl_T = self._F_T_tilde
782
+ if self._with_defaults:
783
+ self._fl_T_inv = self.curves.tendon_force_length_inverse.with_defaults(self._fl_T)
784
+ else:
785
+ fl_T_constants = symbols(f'c_0:4_fl_T_{self.name}')
786
+ self._fl_T_inv = self.curves.tendon_force_length_inverse(self._fl_T, *fl_T_constants)
787
+ self._l_T_tilde = self._fl_T_inv
788
+ self._l_T = self._l_T_tilde*self._l_T_slack
789
+ self._l_M = sqrt((self._l_MT - self._l_T)**2 + (self._l_M_opt*sin(self._alpha_opt))**2)
790
+ self._l_M_tilde = self._l_M/self._l_M_opt
791
+ if self._with_defaults:
792
+ self._fl_M_pas = self.curves.fiber_force_length_passive.with_defaults(self._l_M_tilde)
793
+ self._fl_M_act = self.curves.fiber_force_length_active.with_defaults(self._l_M_tilde)
794
+ else:
795
+ fl_M_pas_constants = symbols(f'c_0:2_fl_M_pas_{self.name}')
796
+ self._fl_M_pas = self.curves.fiber_force_length_passive(self._l_M_tilde, *fl_M_pas_constants)
797
+ fl_M_act_constants = symbols(f'c_0:12_fl_M_act_{self.name}')
798
+ self._fl_M_act = self.curves.fiber_force_length_active(self._l_M_tilde, *fl_M_act_constants)
799
+ self._cos_alpha = (self._l_MT - self._l_T)/self._l_M
800
+ self._F_T = self._F_T_tilde*self._F_M_max
801
+ self._F_M = self._F_T/self._cos_alpha
802
+ self._F_M_tilde = self._F_M/self._F_M_max
803
+ self._fv_M = (self._F_M_tilde - self._fl_M_pas)/(self.a*self._fl_M_act)
804
+ if self._with_defaults:
805
+ self._fv_M_inv = self.curves.fiber_force_velocity_inverse.with_defaults(self._fv_M)
806
+ else:
807
+ fv_M_constants = symbols(f'c_0:4_fv_M_{self.name}')
808
+ self._fv_M_inv = self.curves.fiber_force_velocity_inverse(self._fv_M, *fv_M_constants)
809
+ self._v_M_tilde = self._fv_M_inv
810
+ self._v_M = self._v_M_tilde*self._v_M_max
811
+ self._v_T = self._v_MT - (self._v_M/self._cos_alpha)
812
+ self._v_T_tilde = self._v_T/self._l_T_slack
813
+ if self._with_defaults:
814
+ self._fl_T = self.curves.tendon_force_length.with_defaults(self._l_T_tilde)
815
+ else:
816
+ self._fl_T = self.curves.tendon_force_length(self._l_T_tilde, *fl_T_constants)
817
+ self._dF_T_tilde_dt = self._fl_T.diff(dynamicsymbols._t).subs({self._l_T_tilde.diff(dynamicsymbols._t): self._v_T_tilde})
818
+
819
+ self._state_vars = Matrix([self._F_T_tilde])
820
+ self._input_vars = zeros(0, 1)
821
+ self._state_eqns = Matrix([self._dF_T_tilde_dt])
822
+ self._curve_constants = Matrix(
823
+ fl_T_constants
824
+ + fl_M_pas_constants
825
+ + fl_M_act_constants
826
+ + fv_M_constants
827
+ ) if not self._with_defaults else zeros(0, 1)
828
+
829
+ def _fiber_length_implicit_musculotendon_dynamics(self):
830
+ raise NotImplementedError
831
+
832
+ def _tendon_force_implicit_musculotendon_dynamics(self):
833
+ raise NotImplementedError
834
+
835
+ @property
836
+ def state_vars(self):
837
+ """Ordered column matrix of functions of time that represent the state
838
+ variables.
839
+
840
+ Explanation
841
+ ===========
842
+
843
+ The alias ``x`` can also be used to access the same attribute.
844
+
845
+ """
846
+ state_vars = [self._state_vars]
847
+ for child in self._child_objects:
848
+ state_vars.append(child.state_vars)
849
+ return Matrix.vstack(*state_vars)
850
+
851
+ @property
852
+ def x(self):
853
+ """Ordered column matrix of functions of time that represent the state
854
+ variables.
855
+
856
+ Explanation
857
+ ===========
858
+
859
+ The alias ``state_vars`` can also be used to access the same attribute.
860
+
861
+ """
862
+ state_vars = [self._state_vars]
863
+ for child in self._child_objects:
864
+ state_vars.append(child.state_vars)
865
+ return Matrix.vstack(*state_vars)
866
+
867
+ @property
868
+ def input_vars(self):
869
+ """Ordered column matrix of functions of time that represent the input
870
+ variables.
871
+
872
+ Explanation
873
+ ===========
874
+
875
+ The alias ``r`` can also be used to access the same attribute.
876
+
877
+ """
878
+ input_vars = [self._input_vars]
879
+ for child in self._child_objects:
880
+ input_vars.append(child.input_vars)
881
+ return Matrix.vstack(*input_vars)
882
+
883
+ @property
884
+ def r(self):
885
+ """Ordered column matrix of functions of time that represent the input
886
+ variables.
887
+
888
+ Explanation
889
+ ===========
890
+
891
+ The alias ``input_vars`` can also be used to access the same attribute.
892
+
893
+ """
894
+ input_vars = [self._input_vars]
895
+ for child in self._child_objects:
896
+ input_vars.append(child.input_vars)
897
+ return Matrix.vstack(*input_vars)
898
+
899
+ @property
900
+ def constants(self):
901
+ """Ordered column matrix of non-time varying symbols present in ``M``
902
+ and ``F``.
903
+
904
+ Explanation
905
+ ===========
906
+
907
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
908
+ has been used instead of ``Symbol`` for a constant then that attribute
909
+ will not be included in the matrix returned by this property. This is
910
+ because the primary use of this property attribute is to provide an
911
+ ordered sequence of the still-free symbols that require numeric values
912
+ during code generation.
913
+
914
+ The alias ``p`` can also be used to access the same attribute.
915
+
916
+ """
917
+ musculotendon_constants = [
918
+ self._l_T_slack,
919
+ self._F_M_max,
920
+ self._l_M_opt,
921
+ self._v_M_max,
922
+ self._alpha_opt,
923
+ self._beta,
924
+ ]
925
+ musculotendon_constants = [
926
+ c for c in musculotendon_constants if not c.is_number
927
+ ]
928
+ constants = [
929
+ Matrix(musculotendon_constants)
930
+ if musculotendon_constants
931
+ else zeros(0, 1)
932
+ ]
933
+ for child in self._child_objects:
934
+ constants.append(child.constants)
935
+ constants.append(self._curve_constants)
936
+ return Matrix.vstack(*constants)
937
+
938
+ @property
939
+ def p(self):
940
+ """Ordered column matrix of non-time varying symbols present in ``M``
941
+ and ``F``.
942
+
943
+ Explanation
944
+ ===========
945
+
946
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
947
+ has been used instead of ``Symbol`` for a constant then that attribute
948
+ will not be included in the matrix returned by this property. This is
949
+ because the primary use of this property attribute is to provide an
950
+ ordered sequence of the still-free symbols that require numeric values
951
+ during code generation.
952
+
953
+ The alias ``constants`` can also be used to access the same attribute.
954
+
955
+ """
956
+ musculotendon_constants = [
957
+ self._l_T_slack,
958
+ self._F_M_max,
959
+ self._l_M_opt,
960
+ self._v_M_max,
961
+ self._alpha_opt,
962
+ self._beta,
963
+ ]
964
+ musculotendon_constants = [
965
+ c for c in musculotendon_constants if not c.is_number
966
+ ]
967
+ constants = [
968
+ Matrix(musculotendon_constants)
969
+ if musculotendon_constants
970
+ else zeros(0, 1)
971
+ ]
972
+ for child in self._child_objects:
973
+ constants.append(child.constants)
974
+ constants.append(self._curve_constants)
975
+ return Matrix.vstack(*constants)
976
+
977
+ @property
978
+ def M(self):
979
+ """Ordered square matrix of coefficients on the LHS of ``M x' = F``.
980
+
981
+ Explanation
982
+ ===========
983
+
984
+ The square matrix that forms part of the LHS of the linear system of
985
+ ordinary differential equations governing the activation dynamics:
986
+
987
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
988
+
989
+ As zeroth-order activation dynamics have no state variables, this
990
+ linear system has dimension 0 and therefore ``M`` is an empty square
991
+ ``Matrix`` with shape (0, 0).
992
+
993
+ """
994
+ M = [eye(len(self._state_vars))]
995
+ for child in self._child_objects:
996
+ M.append(child.M)
997
+ return diag(*M)
998
+
999
+ @property
1000
+ def F(self):
1001
+ """Ordered column matrix of equations on the RHS of ``M x' = F``.
1002
+
1003
+ Explanation
1004
+ ===========
1005
+
1006
+ The column matrix that forms the RHS of the linear system of ordinary
1007
+ differential equations governing the activation dynamics:
1008
+
1009
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
1010
+
1011
+ As zeroth-order activation dynamics have no state variables, this
1012
+ linear system has dimension 0 and therefore ``F`` is an empty column
1013
+ ``Matrix`` with shape (0, 1).
1014
+
1015
+ """
1016
+ F = [self._state_eqns]
1017
+ for child in self._child_objects:
1018
+ F.append(child.F)
1019
+ return Matrix.vstack(*F)
1020
+
1021
+ def rhs(self):
1022
+ """Ordered column matrix of equations for the solution of ``M x' = F``.
1023
+
1024
+ Explanation
1025
+ ===========
1026
+
1027
+ The solution to the linear system of ordinary differential equations
1028
+ governing the activation dynamics:
1029
+
1030
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
1031
+
1032
+ As zeroth-order activation dynamics have no state variables, this
1033
+ linear has dimension 0 and therefore this method returns an empty
1034
+ column ``Matrix`` with shape (0, 1).
1035
+
1036
+ """
1037
+ is_explicit = (
1038
+ MusculotendonFormulation.FIBER_LENGTH_EXPLICIT,
1039
+ MusculotendonFormulation.TENDON_FORCE_EXPLICIT,
1040
+ )
1041
+ if self.musculotendon_dynamics is MusculotendonFormulation.RIGID_TENDON:
1042
+ child_rhs = [child.rhs() for child in self._child_objects]
1043
+ return Matrix.vstack(*child_rhs)
1044
+ elif self.musculotendon_dynamics in is_explicit:
1045
+ rhs = self._state_eqns
1046
+ child_rhs = [child.rhs() for child in self._child_objects]
1047
+ return Matrix.vstack(rhs, *child_rhs)
1048
+ return self.M.solve(self.F)
1049
+
1050
+ def __repr__(self):
1051
+ """Returns a string representation to reinstantiate the model."""
1052
+ return (
1053
+ f'{self.__class__.__name__}({self.name!r}, '
1054
+ f'pathway={self.pathway!r}, '
1055
+ f'activation_dynamics={self.activation_dynamics!r}, '
1056
+ f'musculotendon_dynamics={self.musculotendon_dynamics}, '
1057
+ f'tendon_slack_length={self._l_T_slack!r}, '
1058
+ f'peak_isometric_force={self._F_M_max!r}, '
1059
+ f'optimal_fiber_length={self._l_M_opt!r}, '
1060
+ f'maximal_fiber_velocity={self._v_M_max!r}, '
1061
+ f'optimal_pennation_angle={self._alpha_opt!r}, '
1062
+ f'fiber_damping_coefficient={self._beta!r})'
1063
+ )
1064
+
1065
+ def __str__(self):
1066
+ """Returns a string representation of the expression for musculotendon
1067
+ force."""
1068
+ return str(self.force)
1069
+
1070
+
1071
+ class MusculotendonDeGroote2016(MusculotendonBase):
1072
+ r"""Musculotendon model using the curves of De Groote et al., 2016 [1]_.
1073
+
1074
+ Examples
1075
+ ========
1076
+
1077
+ This class models the musculotendon actuator parametrized by the
1078
+ characteristic curves described in De Groote et al., 2016 [1]_. Like all
1079
+ musculotendon models in SymPy's biomechanics module, it requires a pathway
1080
+ to define its line of action. We'll begin by creating a simple
1081
+ ``LinearPathway`` between two points that our musculotendon will follow.
1082
+ We'll create a point ``O`` to represent the musculotendon's origin and
1083
+ another ``I`` to represent its insertion.
1084
+
1085
+ >>> from sympy import symbols
1086
+ >>> from sympy.physics.mechanics import (LinearPathway, Point,
1087
+ ... ReferenceFrame, dynamicsymbols)
1088
+
1089
+ >>> N = ReferenceFrame('N')
1090
+ >>> O, I = O, P = symbols('O, I', cls=Point)
1091
+ >>> q, u = dynamicsymbols('q, u', real=True)
1092
+ >>> I.set_pos(O, q*N.x)
1093
+ >>> O.set_vel(N, 0)
1094
+ >>> I.set_vel(N, u*N.x)
1095
+ >>> pathway = LinearPathway(O, I)
1096
+ >>> pathway.attachments
1097
+ (O, I)
1098
+ >>> pathway.length
1099
+ Abs(q(t))
1100
+ >>> pathway.extension_velocity
1101
+ sign(q(t))*Derivative(q(t), t)
1102
+
1103
+ A musculotendon also takes an instance of an activation dynamics model as
1104
+ this will be used to provide symbols for the activation in the formulation
1105
+ of the musculotendon dynamics. We'll use an instance of
1106
+ ``FirstOrderActivationDeGroote2016`` to represent first-order activation
1107
+ dynamics. Note that a single name argument needs to be provided as SymPy
1108
+ will use this as a suffix.
1109
+
1110
+ >>> from sympy.physics.biomechanics import FirstOrderActivationDeGroote2016
1111
+
1112
+ >>> activation = FirstOrderActivationDeGroote2016('muscle')
1113
+ >>> activation.x
1114
+ Matrix([[a_muscle(t)]])
1115
+ >>> activation.r
1116
+ Matrix([[e_muscle(t)]])
1117
+ >>> activation.p
1118
+ Matrix([
1119
+ [tau_a_muscle],
1120
+ [tau_d_muscle],
1121
+ [ b_muscle]])
1122
+ >>> activation.rhs()
1123
+ Matrix([[((1/2 - tanh(b_muscle*(-a_muscle(t) + e_muscle(t)))/2)*(3*...]])
1124
+
1125
+ The musculotendon class requires symbols or values to be passed to represent
1126
+ the constants in the musculotendon dynamics. We'll use SymPy's ``symbols``
1127
+ function to create symbols for the maximum isometric force ``F_M_max``,
1128
+ optimal fiber length ``l_M_opt``, tendon slack length ``l_T_slack``, maximum
1129
+ fiber velocity ``v_M_max``, optimal pennation angle ``alpha_opt, and fiber
1130
+ damping coefficient ``beta``.
1131
+
1132
+ >>> F_M_max = symbols('F_M_max', real=True)
1133
+ >>> l_M_opt = symbols('l_M_opt', real=True)
1134
+ >>> l_T_slack = symbols('l_T_slack', real=True)
1135
+ >>> v_M_max = symbols('v_M_max', real=True)
1136
+ >>> alpha_opt = symbols('alpha_opt', real=True)
1137
+ >>> beta = symbols('beta', real=True)
1138
+
1139
+ We can then import the class ``MusculotendonDeGroote2016`` from the
1140
+ biomechanics module and create an instance by passing in the various objects
1141
+ we have previously instantiated. By default, a musculotendon model with
1142
+ rigid tendon musculotendon dynamics will be created.
1143
+
1144
+ >>> from sympy.physics.biomechanics import MusculotendonDeGroote2016
1145
+
1146
+ >>> rigid_tendon_muscle = MusculotendonDeGroote2016(
1147
+ ... 'muscle',
1148
+ ... pathway,
1149
+ ... activation,
1150
+ ... tendon_slack_length=l_T_slack,
1151
+ ... peak_isometric_force=F_M_max,
1152
+ ... optimal_fiber_length=l_M_opt,
1153
+ ... maximal_fiber_velocity=v_M_max,
1154
+ ... optimal_pennation_angle=alpha_opt,
1155
+ ... fiber_damping_coefficient=beta,
1156
+ ... )
1157
+
1158
+ We can inspect the various properties of the musculotendon, including
1159
+ getting the symbolic expression describing the force it produces using its
1160
+ ``force`` attribute.
1161
+
1162
+ >>> rigid_tendon_muscle.force
1163
+ -F_M_max*(beta*(-l_T_slack + Abs(q(t)))*sign(q(t))*Derivative(q(t), t)...
1164
+
1165
+ When we created the musculotendon object, we passed in an instance of an
1166
+ activation dynamics object that governs the activation within the
1167
+ musculotendon. SymPy makes a design choice here that the activation dynamics
1168
+ instance will be treated as a child object of the musculotendon dynamics.
1169
+ Therefore, if we want to inspect the state and input variables associated
1170
+ with the musculotendon model, we will also be returned the state and input
1171
+ variables associated with the child object, or the activation dynamics in
1172
+ this case. As the musculotendon model that we created here uses rigid tendon
1173
+ dynamics, no additional states or inputs relating to the musculotendon are
1174
+ introduces. Consequently, the model has a single state associated with it,
1175
+ the activation, and a single input associated with it, the excitation. The
1176
+ states and inputs can be inspected using the ``x`` and ``r`` attributes
1177
+ respectively. Note that both ``x`` and ``r`` have the alias attributes of
1178
+ ``state_vars`` and ``input_vars``.
1179
+
1180
+ >>> rigid_tendon_muscle.x
1181
+ Matrix([[a_muscle(t)]])
1182
+ >>> rigid_tendon_muscle.r
1183
+ Matrix([[e_muscle(t)]])
1184
+
1185
+ To see which constants are symbolic in the musculotendon model, we can use
1186
+ the ``p`` or ``constants`` attribute. This returns a ``Matrix`` populated
1187
+ by the constants that are represented by a ``Symbol`` rather than a numeric
1188
+ value.
1189
+
1190
+ >>> rigid_tendon_muscle.p
1191
+ Matrix([
1192
+ [ l_T_slack],
1193
+ [ F_M_max],
1194
+ [ l_M_opt],
1195
+ [ v_M_max],
1196
+ [ alpha_opt],
1197
+ [ beta],
1198
+ [ tau_a_muscle],
1199
+ [ tau_d_muscle],
1200
+ [ b_muscle],
1201
+ [ c_0_fl_T_muscle],
1202
+ [ c_1_fl_T_muscle],
1203
+ [ c_2_fl_T_muscle],
1204
+ [ c_3_fl_T_muscle],
1205
+ [ c_0_fl_M_pas_muscle],
1206
+ [ c_1_fl_M_pas_muscle],
1207
+ [ c_0_fl_M_act_muscle],
1208
+ [ c_1_fl_M_act_muscle],
1209
+ [ c_2_fl_M_act_muscle],
1210
+ [ c_3_fl_M_act_muscle],
1211
+ [ c_4_fl_M_act_muscle],
1212
+ [ c_5_fl_M_act_muscle],
1213
+ [ c_6_fl_M_act_muscle],
1214
+ [ c_7_fl_M_act_muscle],
1215
+ [ c_8_fl_M_act_muscle],
1216
+ [ c_9_fl_M_act_muscle],
1217
+ [c_10_fl_M_act_muscle],
1218
+ [c_11_fl_M_act_muscle],
1219
+ [ c_0_fv_M_muscle],
1220
+ [ c_1_fv_M_muscle],
1221
+ [ c_2_fv_M_muscle],
1222
+ [ c_3_fv_M_muscle]])
1223
+
1224
+ Finally, we can call the ``rhs`` method to return a ``Matrix`` that
1225
+ contains as its elements the righthand side of the ordinary differential
1226
+ equations corresponding to each of the musculotendon's states. Like the
1227
+ method with the same name on the ``Method`` classes in SymPy's mechanics
1228
+ module, this returns a column vector where the number of rows corresponds to
1229
+ the number of states. For our example here, we have a single state, the
1230
+ dynamic symbol ``a_muscle(t)``, so the returned value is a 1-by-1
1231
+ ``Matrix``.
1232
+
1233
+ >>> rigid_tendon_muscle.rhs()
1234
+ Matrix([[((1/2 - tanh(b_muscle*(-a_muscle(t) + e_muscle(t)))/2)*(3*...]])
1235
+
1236
+ The musculotendon class supports elastic tendon musculotendon models in
1237
+ addition to rigid tendon ones. You can choose to either use the fiber length
1238
+ or tendon force as an additional state. You can also specify whether an
1239
+ explicit or implicit formulation should be used. To select a formulation,
1240
+ pass a member of the ``MusculotendonFormulation`` enumeration to the
1241
+ ``musculotendon_dynamics`` parameter when calling the constructor. This
1242
+ enumeration is an ``IntEnum``, so you can also pass an integer, however it
1243
+ is recommended to use the enumeration as it is clearer which formulation you
1244
+ are actually selecting. Below, we'll use the ``FIBER_LENGTH_EXPLICIT``
1245
+ member to create a musculotendon with an elastic tendon that will use the
1246
+ (normalized) muscle fiber length as an additional state and will produce
1247
+ the governing ordinary differential equation in explicit form.
1248
+
1249
+ >>> from sympy.physics.biomechanics import MusculotendonFormulation
1250
+
1251
+ >>> elastic_tendon_muscle = MusculotendonDeGroote2016(
1252
+ ... 'muscle',
1253
+ ... pathway,
1254
+ ... activation,
1255
+ ... musculotendon_dynamics=MusculotendonFormulation.FIBER_LENGTH_EXPLICIT,
1256
+ ... tendon_slack_length=l_T_slack,
1257
+ ... peak_isometric_force=F_M_max,
1258
+ ... optimal_fiber_length=l_M_opt,
1259
+ ... maximal_fiber_velocity=v_M_max,
1260
+ ... optimal_pennation_angle=alpha_opt,
1261
+ ... fiber_damping_coefficient=beta,
1262
+ ... )
1263
+
1264
+ >>> elastic_tendon_muscle.force
1265
+ -F_M_max*TendonForceLengthDeGroote2016((-sqrt(l_M_opt**2*...
1266
+ >>> elastic_tendon_muscle.x
1267
+ Matrix([
1268
+ [l_M_tilde_muscle(t)],
1269
+ [ a_muscle(t)]])
1270
+ >>> elastic_tendon_muscle.r
1271
+ Matrix([[e_muscle(t)]])
1272
+ >>> elastic_tendon_muscle.p
1273
+ Matrix([
1274
+ [ l_T_slack],
1275
+ [ F_M_max],
1276
+ [ l_M_opt],
1277
+ [ v_M_max],
1278
+ [ alpha_opt],
1279
+ [ beta],
1280
+ [ tau_a_muscle],
1281
+ [ tau_d_muscle],
1282
+ [ b_muscle],
1283
+ [ c_0_fl_T_muscle],
1284
+ [ c_1_fl_T_muscle],
1285
+ [ c_2_fl_T_muscle],
1286
+ [ c_3_fl_T_muscle],
1287
+ [ c_0_fl_M_pas_muscle],
1288
+ [ c_1_fl_M_pas_muscle],
1289
+ [ c_0_fl_M_act_muscle],
1290
+ [ c_1_fl_M_act_muscle],
1291
+ [ c_2_fl_M_act_muscle],
1292
+ [ c_3_fl_M_act_muscle],
1293
+ [ c_4_fl_M_act_muscle],
1294
+ [ c_5_fl_M_act_muscle],
1295
+ [ c_6_fl_M_act_muscle],
1296
+ [ c_7_fl_M_act_muscle],
1297
+ [ c_8_fl_M_act_muscle],
1298
+ [ c_9_fl_M_act_muscle],
1299
+ [c_10_fl_M_act_muscle],
1300
+ [c_11_fl_M_act_muscle],
1301
+ [ c_0_fv_M_muscle],
1302
+ [ c_1_fv_M_muscle],
1303
+ [ c_2_fv_M_muscle],
1304
+ [ c_3_fv_M_muscle]])
1305
+ >>> elastic_tendon_muscle.rhs()
1306
+ Matrix([
1307
+ [v_M_max*FiberForceVelocityInverseDeGroote2016((l_M_opt*...],
1308
+ [ ((1/2 - tanh(b_muscle*(-a_muscle(t) + e_muscle(t)))/2)*(3*...]])
1309
+
1310
+ It is strongly recommended to use the alternate ``with_defaults``
1311
+ constructor when creating an instance because this will ensure that the
1312
+ published constants are used in the musculotendon characteristic curves.
1313
+
1314
+ >>> elastic_tendon_muscle = MusculotendonDeGroote2016.with_defaults(
1315
+ ... 'muscle',
1316
+ ... pathway,
1317
+ ... activation,
1318
+ ... musculotendon_dynamics=MusculotendonFormulation.FIBER_LENGTH_EXPLICIT,
1319
+ ... tendon_slack_length=l_T_slack,
1320
+ ... peak_isometric_force=F_M_max,
1321
+ ... optimal_fiber_length=l_M_opt,
1322
+ ... )
1323
+
1324
+ >>> elastic_tendon_muscle.x
1325
+ Matrix([
1326
+ [l_M_tilde_muscle(t)],
1327
+ [ a_muscle(t)]])
1328
+ >>> elastic_tendon_muscle.r
1329
+ Matrix([[e_muscle(t)]])
1330
+ >>> elastic_tendon_muscle.p
1331
+ Matrix([
1332
+ [ l_T_slack],
1333
+ [ F_M_max],
1334
+ [ l_M_opt],
1335
+ [tau_a_muscle],
1336
+ [tau_d_muscle],
1337
+ [ b_muscle]])
1338
+
1339
+ Parameters
1340
+ ==========
1341
+
1342
+ name : str
1343
+ The name identifier associated with the musculotendon. This name is used
1344
+ as a suffix when automatically generated symbols are instantiated. It
1345
+ must be a string of nonzero length.
1346
+ pathway : PathwayBase
1347
+ The pathway that the actuator follows. This must be an instance of a
1348
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
1349
+ activation_dynamics : ActivationBase
1350
+ The activation dynamics that will be modeled within the musculotendon.
1351
+ This must be an instance of a concrete subclass of ``ActivationBase``,
1352
+ e.g. ``FirstOrderActivationDeGroote2016``.
1353
+ musculotendon_dynamics : MusculotendonFormulation | int
1354
+ The formulation of musculotendon dynamics that should be used
1355
+ internally, i.e. rigid or elastic tendon model, the choice of
1356
+ musculotendon state etc. This must be a member of the integer
1357
+ enumeration ``MusculotendonFormulation`` or an integer that can be cast
1358
+ to a member. To use a rigid tendon formulation, set this to
1359
+ ``MusculotendonFormulation.RIGID_TENDON`` (or the integer value ``0``,
1360
+ which will be cast to the enumeration member). There are four possible
1361
+ formulations for an elastic tendon model. To use an explicit formulation
1362
+ with the fiber length as the state, set this to
1363
+ ``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer value
1364
+ ``1``). To use an explicit formulation with the tendon force as the
1365
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_EXPLICIT``
1366
+ (or the integer value ``2``). To use an implicit formulation with the
1367
+ fiber length as the state, set this to
1368
+ ``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer value
1369
+ ``3``). To use an implicit formulation with the tendon force as the
1370
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_IMPLICIT``
1371
+ (or the integer value ``4``). The default is
1372
+ ``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a rigid
1373
+ tendon formulation.
1374
+ tendon_slack_length : Expr | None
1375
+ The length of the tendon when the musculotendon is in its unloaded
1376
+ state. In a rigid tendon model the tendon length is the tendon slack
1377
+ length. In all musculotendon models, tendon slack length is used to
1378
+ normalize tendon length to give
1379
+ :math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
1380
+ peak_isometric_force : Expr | None
1381
+ The maximum force that the muscle fiber can produce when it is
1382
+ undergoing an isometric contraction (no lengthening velocity). In all
1383
+ musculotendon models, peak isometric force is used to normalized tendon
1384
+ and muscle fiber force to give
1385
+ :math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
1386
+ optimal_fiber_length : Expr | None
1387
+ The muscle fiber length at which the muscle fibers produce no passive
1388
+ force and their maximum active force. In all musculotendon models,
1389
+ optimal fiber length is used to normalize muscle fiber length to give
1390
+ :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
1391
+ maximal_fiber_velocity : Expr | None
1392
+ The fiber velocity at which, during muscle fiber shortening, the muscle
1393
+ fibers are unable to produce any active force. In all musculotendon
1394
+ models, maximal fiber velocity is used to normalize muscle fiber
1395
+ extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
1396
+ optimal_pennation_angle : Expr | None
1397
+ The pennation angle when muscle fiber length equals the optimal fiber
1398
+ length.
1399
+ fiber_damping_coefficient : Expr | None
1400
+ The coefficient of damping to be used in the damping element in the
1401
+ muscle fiber model.
1402
+ with_defaults : bool
1403
+ Whether ``with_defaults`` alternate constructors should be used when
1404
+ automatically constructing child classes. Default is ``False``.
1405
+
1406
+ References
1407
+ ==========
1408
+
1409
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
1410
+ of direct collocation optimal control problem formulations for
1411
+ solving the muscle redundancy problem, Annals of biomedical
1412
+ engineering, 44(10), (2016) pp. 2922-2936
1413
+
1414
+ """
1415
+
1416
+ curves = CharacteristicCurveCollection(
1417
+ tendon_force_length=TendonForceLengthDeGroote2016,
1418
+ tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
1419
+ fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
1420
+ fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
1421
+ fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
1422
+ fiber_force_velocity=FiberForceVelocityDeGroote2016,
1423
+ fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
1424
+ )
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__init__.py ADDED
File without changes
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (194 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_activation.cpython-310.pyc ADDED
Binary file (12 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_curve.cpython-310.pyc ADDED
Binary file (53.9 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_mixin.cpython-310.pyc ADDED
Binary file (2.73 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_musculotendon.cpython-310.pyc ADDED
Binary file (21.7 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_activation.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``sympy.physics.biomechanics.activation.py`` module."""
2
+
3
+ import pytest
4
+
5
+ from sympy import Symbol
6
+ from sympy.core.numbers import Float, Integer, Rational
7
+ from sympy.functions.elementary.hyperbolic import tanh
8
+ from sympy.matrices import Matrix
9
+ from sympy.matrices.dense import zeros
10
+ from sympy.physics.mechanics import dynamicsymbols
11
+ from sympy.physics.biomechanics import (
12
+ ActivationBase,
13
+ FirstOrderActivationDeGroote2016,
14
+ ZerothOrderActivation,
15
+ )
16
+ from sympy.physics.biomechanics._mixin import _NamedMixin
17
+ from sympy.simplify.simplify import simplify
18
+
19
+
20
+ class TestZerothOrderActivation:
21
+
22
+ @staticmethod
23
+ def test_class():
24
+ assert issubclass(ZerothOrderActivation, ActivationBase)
25
+ assert issubclass(ZerothOrderActivation, _NamedMixin)
26
+ assert ZerothOrderActivation.__name__ == 'ZerothOrderActivation'
27
+
28
+ @pytest.fixture(autouse=True)
29
+ def _zeroth_order_activation_fixture(self):
30
+ self.name = 'name'
31
+ self.e = dynamicsymbols('e_name')
32
+ self.instance = ZerothOrderActivation(self.name)
33
+
34
+ def test_instance(self):
35
+ instance = ZerothOrderActivation(self.name)
36
+ assert isinstance(instance, ZerothOrderActivation)
37
+
38
+ def test_with_defaults(self):
39
+ instance = ZerothOrderActivation.with_defaults(self.name)
40
+ assert isinstance(instance, ZerothOrderActivation)
41
+ assert instance == ZerothOrderActivation(self.name)
42
+
43
+ def test_name(self):
44
+ assert hasattr(self.instance, 'name')
45
+ assert self.instance.name == self.name
46
+
47
+ def test_order(self):
48
+ assert hasattr(self.instance, 'order')
49
+ assert self.instance.order == 0
50
+
51
+ def test_excitation_attribute(self):
52
+ assert hasattr(self.instance, 'e')
53
+ assert hasattr(self.instance, 'excitation')
54
+ e_expected = dynamicsymbols('e_name')
55
+ assert self.instance.e == e_expected
56
+ assert self.instance.excitation == e_expected
57
+ assert self.instance.e is self.instance.excitation
58
+
59
+ def test_activation_attribute(self):
60
+ assert hasattr(self.instance, 'a')
61
+ assert hasattr(self.instance, 'activation')
62
+ a_expected = dynamicsymbols('e_name')
63
+ assert self.instance.a == a_expected
64
+ assert self.instance.activation == a_expected
65
+ assert self.instance.a is self.instance.activation is self.instance.e
66
+
67
+ def test_state_vars_attribute(self):
68
+ assert hasattr(self.instance, 'x')
69
+ assert hasattr(self.instance, 'state_vars')
70
+ assert self.instance.x == self.instance.state_vars
71
+ x_expected = zeros(0, 1)
72
+ assert self.instance.x == x_expected
73
+ assert self.instance.state_vars == x_expected
74
+ assert isinstance(self.instance.x, Matrix)
75
+ assert isinstance(self.instance.state_vars, Matrix)
76
+ assert self.instance.x.shape == (0, 1)
77
+ assert self.instance.state_vars.shape == (0, 1)
78
+
79
+ def test_input_vars_attribute(self):
80
+ assert hasattr(self.instance, 'r')
81
+ assert hasattr(self.instance, 'input_vars')
82
+ assert self.instance.r == self.instance.input_vars
83
+ r_expected = Matrix([self.e])
84
+ assert self.instance.r == r_expected
85
+ assert self.instance.input_vars == r_expected
86
+ assert isinstance(self.instance.r, Matrix)
87
+ assert isinstance(self.instance.input_vars, Matrix)
88
+ assert self.instance.r.shape == (1, 1)
89
+ assert self.instance.input_vars.shape == (1, 1)
90
+
91
+ def test_constants_attribute(self):
92
+ assert hasattr(self.instance, 'p')
93
+ assert hasattr(self.instance, 'constants')
94
+ assert self.instance.p == self.instance.constants
95
+ p_expected = zeros(0, 1)
96
+ assert self.instance.p == p_expected
97
+ assert self.instance.constants == p_expected
98
+ assert isinstance(self.instance.p, Matrix)
99
+ assert isinstance(self.instance.constants, Matrix)
100
+ assert self.instance.p.shape == (0, 1)
101
+ assert self.instance.constants.shape == (0, 1)
102
+
103
+ def test_M_attribute(self):
104
+ assert hasattr(self.instance, 'M')
105
+ M_expected = Matrix([])
106
+ assert self.instance.M == M_expected
107
+ assert isinstance(self.instance.M, Matrix)
108
+ assert self.instance.M.shape == (0, 0)
109
+
110
+ def test_F(self):
111
+ assert hasattr(self.instance, 'F')
112
+ F_expected = zeros(0, 1)
113
+ assert self.instance.F == F_expected
114
+ assert isinstance(self.instance.F, Matrix)
115
+ assert self.instance.F.shape == (0, 1)
116
+
117
+ def test_rhs(self):
118
+ assert hasattr(self.instance, 'rhs')
119
+ rhs_expected = zeros(0, 1)
120
+ rhs = self.instance.rhs()
121
+ assert rhs == rhs_expected
122
+ assert isinstance(rhs, Matrix)
123
+ assert rhs.shape == (0, 1)
124
+
125
+ def test_repr(self):
126
+ expected = 'ZerothOrderActivation(\'name\')'
127
+ assert repr(self.instance) == expected
128
+
129
+
130
+ class TestFirstOrderActivationDeGroote2016:
131
+
132
+ @staticmethod
133
+ def test_class():
134
+ assert issubclass(FirstOrderActivationDeGroote2016, ActivationBase)
135
+ assert issubclass(FirstOrderActivationDeGroote2016, _NamedMixin)
136
+ assert FirstOrderActivationDeGroote2016.__name__ == 'FirstOrderActivationDeGroote2016'
137
+
138
+ @pytest.fixture(autouse=True)
139
+ def _first_order_activation_de_groote_2016_fixture(self):
140
+ self.name = 'name'
141
+ self.e = dynamicsymbols('e_name')
142
+ self.a = dynamicsymbols('a_name')
143
+ self.tau_a = Symbol('tau_a')
144
+ self.tau_d = Symbol('tau_d')
145
+ self.b = Symbol('b')
146
+ self.instance = FirstOrderActivationDeGroote2016(
147
+ self.name,
148
+ self.tau_a,
149
+ self.tau_d,
150
+ self.b,
151
+ )
152
+
153
+ def test_instance(self):
154
+ instance = FirstOrderActivationDeGroote2016(self.name)
155
+ assert isinstance(instance, FirstOrderActivationDeGroote2016)
156
+
157
+ def test_with_defaults(self):
158
+ instance = FirstOrderActivationDeGroote2016.with_defaults(self.name)
159
+ assert isinstance(instance, FirstOrderActivationDeGroote2016)
160
+ assert instance.tau_a == Float('0.015')
161
+ assert instance.activation_time_constant == Float('0.015')
162
+ assert instance.tau_d == Float('0.060')
163
+ assert instance.deactivation_time_constant == Float('0.060')
164
+ assert instance.b == Float('10.0')
165
+ assert instance.smoothing_rate == Float('10.0')
166
+
167
+ def test_name(self):
168
+ assert hasattr(self.instance, 'name')
169
+ assert self.instance.name == self.name
170
+
171
+ def test_order(self):
172
+ assert hasattr(self.instance, 'order')
173
+ assert self.instance.order == 1
174
+
175
+ def test_excitation(self):
176
+ assert hasattr(self.instance, 'e')
177
+ assert hasattr(self.instance, 'excitation')
178
+ e_expected = dynamicsymbols('e_name')
179
+ assert self.instance.e == e_expected
180
+ assert self.instance.excitation == e_expected
181
+ assert self.instance.e is self.instance.excitation
182
+
183
+ def test_excitation_is_immutable(self):
184
+ with pytest.raises(AttributeError):
185
+ self.instance.e = None
186
+ with pytest.raises(AttributeError):
187
+ self.instance.excitation = None
188
+
189
+ def test_activation(self):
190
+ assert hasattr(self.instance, 'a')
191
+ assert hasattr(self.instance, 'activation')
192
+ a_expected = dynamicsymbols('a_name')
193
+ assert self.instance.a == a_expected
194
+ assert self.instance.activation == a_expected
195
+
196
+ def test_activation_is_immutable(self):
197
+ with pytest.raises(AttributeError):
198
+ self.instance.a = None
199
+ with pytest.raises(AttributeError):
200
+ self.instance.activation = None
201
+
202
+ @pytest.mark.parametrize(
203
+ 'tau_a, expected',
204
+ [
205
+ (None, Symbol('tau_a_name')),
206
+ (Symbol('tau_a'), Symbol('tau_a')),
207
+ (Float('0.015'), Float('0.015')),
208
+ ]
209
+ )
210
+ def test_activation_time_constant(self, tau_a, expected):
211
+ instance = FirstOrderActivationDeGroote2016(
212
+ 'name', activation_time_constant=tau_a,
213
+ )
214
+ assert instance.tau_a == expected
215
+ assert instance.activation_time_constant == expected
216
+ assert instance.tau_a is instance.activation_time_constant
217
+
218
+ def test_activation_time_constant_is_immutable(self):
219
+ with pytest.raises(AttributeError):
220
+ self.instance.tau_a = None
221
+ with pytest.raises(AttributeError):
222
+ self.instance.activation_time_constant = None
223
+
224
+ @pytest.mark.parametrize(
225
+ 'tau_d, expected',
226
+ [
227
+ (None, Symbol('tau_d_name')),
228
+ (Symbol('tau_d'), Symbol('tau_d')),
229
+ (Float('0.060'), Float('0.060')),
230
+ ]
231
+ )
232
+ def test_deactivation_time_constant(self, tau_d, expected):
233
+ instance = FirstOrderActivationDeGroote2016(
234
+ 'name', deactivation_time_constant=tau_d,
235
+ )
236
+ assert instance.tau_d == expected
237
+ assert instance.deactivation_time_constant == expected
238
+ assert instance.tau_d is instance.deactivation_time_constant
239
+
240
+ def test_deactivation_time_constant_is_immutable(self):
241
+ with pytest.raises(AttributeError):
242
+ self.instance.tau_d = None
243
+ with pytest.raises(AttributeError):
244
+ self.instance.deactivation_time_constant = None
245
+
246
+ @pytest.mark.parametrize(
247
+ 'b, expected',
248
+ [
249
+ (None, Symbol('b_name')),
250
+ (Symbol('b'), Symbol('b')),
251
+ (Integer('10'), Integer('10')),
252
+ ]
253
+ )
254
+ def test_smoothing_rate(self, b, expected):
255
+ instance = FirstOrderActivationDeGroote2016(
256
+ 'name', smoothing_rate=b,
257
+ )
258
+ assert instance.b == expected
259
+ assert instance.smoothing_rate == expected
260
+ assert instance.b is instance.smoothing_rate
261
+
262
+ def test_smoothing_rate_is_immutable(self):
263
+ with pytest.raises(AttributeError):
264
+ self.instance.b = None
265
+ with pytest.raises(AttributeError):
266
+ self.instance.smoothing_rate = None
267
+
268
+ def test_state_vars(self):
269
+ assert hasattr(self.instance, 'x')
270
+ assert hasattr(self.instance, 'state_vars')
271
+ assert self.instance.x == self.instance.state_vars
272
+ x_expected = Matrix([self.a])
273
+ assert self.instance.x == x_expected
274
+ assert self.instance.state_vars == x_expected
275
+ assert isinstance(self.instance.x, Matrix)
276
+ assert isinstance(self.instance.state_vars, Matrix)
277
+ assert self.instance.x.shape == (1, 1)
278
+ assert self.instance.state_vars.shape == (1, 1)
279
+
280
+ def test_input_vars(self):
281
+ assert hasattr(self.instance, 'r')
282
+ assert hasattr(self.instance, 'input_vars')
283
+ assert self.instance.r == self.instance.input_vars
284
+ r_expected = Matrix([self.e])
285
+ assert self.instance.r == r_expected
286
+ assert self.instance.input_vars == r_expected
287
+ assert isinstance(self.instance.r, Matrix)
288
+ assert isinstance(self.instance.input_vars, Matrix)
289
+ assert self.instance.r.shape == (1, 1)
290
+ assert self.instance.input_vars.shape == (1, 1)
291
+
292
+ def test_constants(self):
293
+ assert hasattr(self.instance, 'p')
294
+ assert hasattr(self.instance, 'constants')
295
+ assert self.instance.p == self.instance.constants
296
+ p_expected = Matrix([self.tau_a, self.tau_d, self.b])
297
+ assert self.instance.p == p_expected
298
+ assert self.instance.constants == p_expected
299
+ assert isinstance(self.instance.p, Matrix)
300
+ assert isinstance(self.instance.constants, Matrix)
301
+ assert self.instance.p.shape == (3, 1)
302
+ assert self.instance.constants.shape == (3, 1)
303
+
304
+ def test_M(self):
305
+ assert hasattr(self.instance, 'M')
306
+ M_expected = Matrix([1])
307
+ assert self.instance.M == M_expected
308
+ assert isinstance(self.instance.M, Matrix)
309
+ assert self.instance.M.shape == (1, 1)
310
+
311
+ def test_F(self):
312
+ assert hasattr(self.instance, 'F')
313
+ da_expr = (
314
+ ((1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
315
+ *(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
316
+ + ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
317
+ *(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a))))
318
+ *(self.e - self.a)
319
+ )
320
+ F_expected = Matrix([da_expr])
321
+ assert self.instance.F == F_expected
322
+ assert isinstance(self.instance.F, Matrix)
323
+ assert self.instance.F.shape == (1, 1)
324
+
325
+ def test_rhs(self):
326
+ assert hasattr(self.instance, 'rhs')
327
+ da_expr = (
328
+ ((1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
329
+ *(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
330
+ + ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
331
+ *(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a))))
332
+ *(self.e - self.a)
333
+ )
334
+ rhs_expected = Matrix([da_expr])
335
+ rhs = self.instance.rhs()
336
+ assert rhs == rhs_expected
337
+ assert isinstance(rhs, Matrix)
338
+ assert rhs.shape == (1, 1)
339
+ assert simplify(self.instance.M.solve(self.instance.F) - rhs) == zeros(1)
340
+
341
+ def test_repr(self):
342
+ expected = (
343
+ 'FirstOrderActivationDeGroote2016(\'name\', '
344
+ 'activation_time_constant=tau_a, '
345
+ 'deactivation_time_constant=tau_d, '
346
+ 'smoothing_rate=b)'
347
+ )
348
+ assert repr(self.instance) == expected
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_curve.py ADDED
@@ -0,0 +1,1784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``sympy.physics.biomechanics.characteristic.py`` module."""
2
+
3
+ import pytest
4
+
5
+ from sympy.core.expr import UnevaluatedExpr
6
+ from sympy.core.function import Function
7
+ from sympy.core.numbers import Float, Integer
8
+ from sympy.core.symbol import Symbol, symbols
9
+ from sympy.external.importtools import import_module
10
+ from sympy.functions.elementary.exponential import exp, log
11
+ from sympy.functions.elementary.hyperbolic import cosh, sinh
12
+ from sympy.functions.elementary.miscellaneous import sqrt
13
+ from sympy.physics.biomechanics.curve import (
14
+ CharacteristicCurveCollection,
15
+ CharacteristicCurveFunction,
16
+ FiberForceLengthActiveDeGroote2016,
17
+ FiberForceLengthPassiveDeGroote2016,
18
+ FiberForceLengthPassiveInverseDeGroote2016,
19
+ FiberForceVelocityDeGroote2016,
20
+ FiberForceVelocityInverseDeGroote2016,
21
+ TendonForceLengthDeGroote2016,
22
+ TendonForceLengthInverseDeGroote2016,
23
+ )
24
+ from sympy.printing.c import C89CodePrinter, C99CodePrinter, C11CodePrinter
25
+ from sympy.printing.cxx import (
26
+ CXX98CodePrinter,
27
+ CXX11CodePrinter,
28
+ CXX17CodePrinter,
29
+ )
30
+ from sympy.printing.fortran import FCodePrinter
31
+ from sympy.printing.lambdarepr import LambdaPrinter
32
+ from sympy.printing.latex import LatexPrinter
33
+ from sympy.printing.octave import OctaveCodePrinter
34
+ from sympy.printing.numpy import (
35
+ CuPyPrinter,
36
+ JaxPrinter,
37
+ NumPyPrinter,
38
+ SciPyPrinter,
39
+ )
40
+ from sympy.printing.pycode import MpmathPrinter, PythonCodePrinter
41
+ from sympy.utilities.lambdify import lambdify
42
+
43
+ jax = import_module('jax')
44
+ numpy = import_module('numpy')
45
+
46
+ if jax:
47
+ jax.config.update('jax_enable_x64', True)
48
+
49
+
50
+ class TestCharacteristicCurveFunction:
51
+
52
+ @staticmethod
53
+ @pytest.mark.parametrize(
54
+ 'code_printer, expected',
55
+ [
56
+ (C89CodePrinter, '(a + b)*(c + d)*(e + f)'),
57
+ (C99CodePrinter, '(a + b)*(c + d)*(e + f)'),
58
+ (C11CodePrinter, '(a + b)*(c + d)*(e + f)'),
59
+ (CXX98CodePrinter, '(a + b)*(c + d)*(e + f)'),
60
+ (CXX11CodePrinter, '(a + b)*(c + d)*(e + f)'),
61
+ (CXX17CodePrinter, '(a + b)*(c + d)*(e + f)'),
62
+ (FCodePrinter, ' (a + b)*(c + d)*(e + f)'),
63
+ (OctaveCodePrinter, '(a + b).*(c + d).*(e + f)'),
64
+ (PythonCodePrinter, '(a + b)*(c + d)*(e + f)'),
65
+ (NumPyPrinter, '(a + b)*(c + d)*(e + f)'),
66
+ (SciPyPrinter, '(a + b)*(c + d)*(e + f)'),
67
+ (CuPyPrinter, '(a + b)*(c + d)*(e + f)'),
68
+ (JaxPrinter, '(a + b)*(c + d)*(e + f)'),
69
+ (MpmathPrinter, '(a + b)*(c + d)*(e + f)'),
70
+ (LambdaPrinter, '(a + b)*(c + d)*(e + f)'),
71
+ ]
72
+ )
73
+ def test_print_code_parenthesize(code_printer, expected):
74
+
75
+ class ExampleFunction(CharacteristicCurveFunction):
76
+
77
+ @classmethod
78
+ def eval(cls, a, b):
79
+ pass
80
+
81
+ def doit(self, **kwargs):
82
+ a, b = self.args
83
+ return a + b
84
+
85
+ a, b, c, d, e, f = symbols('a, b, c, d, e, f')
86
+ f1 = ExampleFunction(a, b)
87
+ f2 = ExampleFunction(c, d)
88
+ f3 = ExampleFunction(e, f)
89
+ assert code_printer().doprint(f1*f2*f3) == expected
90
+
91
+
92
+ class TestTendonForceLengthDeGroote2016:
93
+
94
+ @pytest.fixture(autouse=True)
95
+ def _tendon_force_length_arguments_fixture(self):
96
+ self.l_T_tilde = Symbol('l_T_tilde')
97
+ self.c0 = Symbol('c_0')
98
+ self.c1 = Symbol('c_1')
99
+ self.c2 = Symbol('c_2')
100
+ self.c3 = Symbol('c_3')
101
+ self.constants = (self.c0, self.c1, self.c2, self.c3)
102
+
103
+ @staticmethod
104
+ def test_class():
105
+ assert issubclass(TendonForceLengthDeGroote2016, Function)
106
+ assert issubclass(TendonForceLengthDeGroote2016, CharacteristicCurveFunction)
107
+ assert TendonForceLengthDeGroote2016.__name__ == 'TendonForceLengthDeGroote2016'
108
+
109
+ def test_instance(self):
110
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
111
+ assert isinstance(fl_T, TendonForceLengthDeGroote2016)
112
+ assert str(fl_T) == 'TendonForceLengthDeGroote2016(l_T_tilde, c_0, c_1, c_2, c_3)'
113
+
114
+ def test_doit(self):
115
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants).doit()
116
+ assert fl_T == self.c0*exp(self.c3*(self.l_T_tilde - self.c1)) - self.c2
117
+
118
+ def test_doit_evaluate_false(self):
119
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants).doit(evaluate=False)
120
+ assert fl_T == self.c0*exp(self.c3*UnevaluatedExpr(self.l_T_tilde - self.c1)) - self.c2
121
+
122
+ def test_with_defaults(self):
123
+ constants = (
124
+ Float('0.2'),
125
+ Float('0.995'),
126
+ Float('0.25'),
127
+ Float('33.93669377311689'),
128
+ )
129
+ fl_T_manual = TendonForceLengthDeGroote2016(self.l_T_tilde, *constants)
130
+ fl_T_constants = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
131
+ assert fl_T_manual == fl_T_constants
132
+
133
+ def test_differentiate_wrt_l_T_tilde(self):
134
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
135
+ expected = self.c0*self.c3*exp(self.c3*UnevaluatedExpr(-self.c1 + self.l_T_tilde))
136
+ assert fl_T.diff(self.l_T_tilde) == expected
137
+
138
+ def test_differentiate_wrt_c0(self):
139
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
140
+ expected = exp(self.c3*UnevaluatedExpr(-self.c1 + self.l_T_tilde))
141
+ assert fl_T.diff(self.c0) == expected
142
+
143
+ def test_differentiate_wrt_c1(self):
144
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
145
+ expected = -self.c0*self.c3*exp(self.c3*UnevaluatedExpr(self.l_T_tilde - self.c1))
146
+ assert fl_T.diff(self.c1) == expected
147
+
148
+ def test_differentiate_wrt_c2(self):
149
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
150
+ expected = Integer(-1)
151
+ assert fl_T.diff(self.c2) == expected
152
+
153
+ def test_differentiate_wrt_c3(self):
154
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
155
+ expected = self.c0*(self.l_T_tilde - self.c1)*exp(self.c3*UnevaluatedExpr(self.l_T_tilde - self.c1))
156
+ assert fl_T.diff(self.c3) == expected
157
+
158
+ def test_inverse(self):
159
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
160
+ assert fl_T.inverse() is TendonForceLengthInverseDeGroote2016
161
+
162
+ def test_function_print_latex(self):
163
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
164
+ expected = r'\operatorname{fl}^T \left( l_{T tilde} \right)'
165
+ assert LatexPrinter().doprint(fl_T) == expected
166
+
167
+ def test_expression_print_latex(self):
168
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
169
+ expected = r'c_{0} e^{c_{3} \left(- c_{1} + l_{T tilde}\right)} - c_{2}'
170
+ assert LatexPrinter().doprint(fl_T.doit()) == expected
171
+
172
+ @pytest.mark.parametrize(
173
+ 'code_printer, expected',
174
+ [
175
+ (
176
+ C89CodePrinter,
177
+ '(-0.25 + 0.20000000000000001*exp(33.93669377311689*(l_T_tilde - 0.995)))',
178
+ ),
179
+ (
180
+ C99CodePrinter,
181
+ '(-0.25 + 0.20000000000000001*exp(33.93669377311689*(l_T_tilde - 0.995)))',
182
+ ),
183
+ (
184
+ C11CodePrinter,
185
+ '(-0.25 + 0.20000000000000001*exp(33.93669377311689*(l_T_tilde - 0.995)))',
186
+ ),
187
+ (
188
+ CXX98CodePrinter,
189
+ '(-0.25 + 0.20000000000000001*exp(33.93669377311689*(l_T_tilde - 0.995)))',
190
+ ),
191
+ (
192
+ CXX11CodePrinter,
193
+ '(-0.25 + 0.20000000000000001*std::exp(33.93669377311689*(l_T_tilde - 0.995)))',
194
+ ),
195
+ (
196
+ CXX17CodePrinter,
197
+ '(-0.25 + 0.20000000000000001*std::exp(33.93669377311689*(l_T_tilde - 0.995)))',
198
+ ),
199
+ (
200
+ FCodePrinter,
201
+ ' (-0.25d0 + 0.2d0*exp(33.93669377311689d0*(l_T_tilde - 0.995d0)))',
202
+ ),
203
+ (
204
+ OctaveCodePrinter,
205
+ '(-0.25 + 0.2*exp(33.93669377311689*(l_T_tilde - 0.995)))',
206
+ ),
207
+ (
208
+ PythonCodePrinter,
209
+ '(-0.25 + 0.2*math.exp(33.93669377311689*(l_T_tilde - 0.995)))',
210
+ ),
211
+ (
212
+ NumPyPrinter,
213
+ '(-0.25 + 0.2*numpy.exp(33.93669377311689*(l_T_tilde - 0.995)))',
214
+ ),
215
+ (
216
+ SciPyPrinter,
217
+ '(-0.25 + 0.2*numpy.exp(33.93669377311689*(l_T_tilde - 0.995)))',
218
+ ),
219
+ (
220
+ CuPyPrinter,
221
+ '(-0.25 + 0.2*cupy.exp(33.93669377311689*(l_T_tilde - 0.995)))',
222
+ ),
223
+ (
224
+ JaxPrinter,
225
+ '(-0.25 + 0.2*jax.numpy.exp(33.93669377311689*(l_T_tilde - 0.995)))',
226
+ ),
227
+ (
228
+ MpmathPrinter,
229
+ '(mpmath.mpf((1, 1, -2, 1)) + mpmath.mpf((0, 3602879701896397, -54, 52))'
230
+ '*mpmath.exp(mpmath.mpf((0, 9552330089424741, -48, 54))*(l_T_tilde + '
231
+ 'mpmath.mpf((1, 8962163258467287, -53, 53)))))',
232
+ ),
233
+ (
234
+ LambdaPrinter,
235
+ '(-0.25 + 0.2*math.exp(33.93669377311689*(l_T_tilde - 0.995)))',
236
+ ),
237
+ ]
238
+ )
239
+ def test_print_code(self, code_printer, expected):
240
+ fl_T = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
241
+ assert code_printer().doprint(fl_T) == expected
242
+
243
+ def test_derivative_print_code(self):
244
+ fl_T = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
245
+ dfl_T_dl_T_tilde = fl_T.diff(self.l_T_tilde)
246
+ expected = '6.787338754623378*math.exp(33.93669377311689*(l_T_tilde - 0.995))'
247
+ assert PythonCodePrinter().doprint(dfl_T_dl_T_tilde) == expected
248
+
249
+ def test_lambdify(self):
250
+ fl_T = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
251
+ fl_T_callable = lambdify(self.l_T_tilde, fl_T)
252
+ assert fl_T_callable(1.0) == pytest.approx(-0.013014055039221595)
253
+
254
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
255
+ def test_lambdify_numpy(self):
256
+ fl_T = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
257
+ fl_T_callable = lambdify(self.l_T_tilde, fl_T, 'numpy')
258
+ l_T_tilde = numpy.array([0.95, 1.0, 1.01, 1.05])
259
+ expected = numpy.array([
260
+ -0.2065693181344816,
261
+ -0.0130140550392216,
262
+ 0.0827421191989246,
263
+ 1.04314889144172,
264
+ ])
265
+ numpy.testing.assert_allclose(fl_T_callable(l_T_tilde), expected)
266
+
267
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
268
+ def test_lambdify_jax(self):
269
+ fl_T = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
270
+ fl_T_callable = jax.jit(lambdify(self.l_T_tilde, fl_T, 'jax'))
271
+ l_T_tilde = jax.numpy.array([0.95, 1.0, 1.01, 1.05])
272
+ expected = jax.numpy.array([
273
+ -0.2065693181344816,
274
+ -0.0130140550392216,
275
+ 0.0827421191989246,
276
+ 1.04314889144172,
277
+ ])
278
+ numpy.testing.assert_allclose(fl_T_callable(l_T_tilde), expected)
279
+
280
+
281
+ class TestTendonForceLengthInverseDeGroote2016:
282
+
283
+ @pytest.fixture(autouse=True)
284
+ def _tendon_force_length_inverse_arguments_fixture(self):
285
+ self.fl_T = Symbol('fl_T')
286
+ self.c0 = Symbol('c_0')
287
+ self.c1 = Symbol('c_1')
288
+ self.c2 = Symbol('c_2')
289
+ self.c3 = Symbol('c_3')
290
+ self.constants = (self.c0, self.c1, self.c2, self.c3)
291
+
292
+ @staticmethod
293
+ def test_class():
294
+ assert issubclass(TendonForceLengthInverseDeGroote2016, Function)
295
+ assert issubclass(TendonForceLengthInverseDeGroote2016, CharacteristicCurveFunction)
296
+ assert TendonForceLengthInverseDeGroote2016.__name__ == 'TendonForceLengthInverseDeGroote2016'
297
+
298
+ def test_instance(self):
299
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
300
+ assert isinstance(fl_T_inv, TendonForceLengthInverseDeGroote2016)
301
+ assert str(fl_T_inv) == 'TendonForceLengthInverseDeGroote2016(fl_T, c_0, c_1, c_2, c_3)'
302
+
303
+ def test_doit(self):
304
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants).doit()
305
+ assert fl_T_inv == log((self.fl_T + self.c2)/self.c0)/self.c3 + self.c1
306
+
307
+ def test_doit_evaluate_false(self):
308
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants).doit(evaluate=False)
309
+ assert fl_T_inv == log(UnevaluatedExpr((self.fl_T + self.c2)/self.c0))/self.c3 + self.c1
310
+
311
+ def test_with_defaults(self):
312
+ constants = (
313
+ Float('0.2'),
314
+ Float('0.995'),
315
+ Float('0.25'),
316
+ Float('33.93669377311689'),
317
+ )
318
+ fl_T_inv_manual = TendonForceLengthInverseDeGroote2016(self.fl_T, *constants)
319
+ fl_T_inv_constants = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
320
+ assert fl_T_inv_manual == fl_T_inv_constants
321
+
322
+ def test_differentiate_wrt_fl_T(self):
323
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
324
+ expected = 1/(self.c3*(self.fl_T + self.c2))
325
+ assert fl_T_inv.diff(self.fl_T) == expected
326
+
327
+ def test_differentiate_wrt_c0(self):
328
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
329
+ expected = -1/(self.c0*self.c3)
330
+ assert fl_T_inv.diff(self.c0) == expected
331
+
332
+ def test_differentiate_wrt_c1(self):
333
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
334
+ expected = Integer(1)
335
+ assert fl_T_inv.diff(self.c1) == expected
336
+
337
+ def test_differentiate_wrt_c2(self):
338
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
339
+ expected = 1/(self.c3*(self.fl_T + self.c2))
340
+ assert fl_T_inv.diff(self.c2) == expected
341
+
342
+ def test_differentiate_wrt_c3(self):
343
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
344
+ expected = -log(UnevaluatedExpr((self.fl_T + self.c2)/self.c0))/self.c3**2
345
+ assert fl_T_inv.diff(self.c3) == expected
346
+
347
+ def test_inverse(self):
348
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
349
+ assert fl_T_inv.inverse() is TendonForceLengthDeGroote2016
350
+
351
+ def test_function_print_latex(self):
352
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
353
+ expected = r'\left( \operatorname{fl}^T \right)^{-1} \left( fl_{T} \right)'
354
+ assert LatexPrinter().doprint(fl_T_inv) == expected
355
+
356
+ def test_expression_print_latex(self):
357
+ fl_T = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
358
+ expected = r'c_{1} + \frac{\log{\left(\frac{c_{2} + fl_{T}}{c_{0}} \right)}}{c_{3}}'
359
+ assert LatexPrinter().doprint(fl_T.doit()) == expected
360
+
361
+ @pytest.mark.parametrize(
362
+ 'code_printer, expected',
363
+ [
364
+ (
365
+ C89CodePrinter,
366
+ '(0.995 + 0.029466630034306838*log(5.0*fl_T + 1.25))',
367
+ ),
368
+ (
369
+ C99CodePrinter,
370
+ '(0.995 + 0.029466630034306838*log(5.0*fl_T + 1.25))',
371
+ ),
372
+ (
373
+ C11CodePrinter,
374
+ '(0.995 + 0.029466630034306838*log(5.0*fl_T + 1.25))',
375
+ ),
376
+ (
377
+ CXX98CodePrinter,
378
+ '(0.995 + 0.029466630034306838*log(5.0*fl_T + 1.25))',
379
+ ),
380
+ (
381
+ CXX11CodePrinter,
382
+ '(0.995 + 0.029466630034306838*std::log(5.0*fl_T + 1.25))',
383
+ ),
384
+ (
385
+ CXX17CodePrinter,
386
+ '(0.995 + 0.029466630034306838*std::log(5.0*fl_T + 1.25))',
387
+ ),
388
+ (
389
+ FCodePrinter,
390
+ ' (0.995d0 + 0.02946663003430684d0*log(5.0d0*fl_T + 1.25d0))',
391
+ ),
392
+ (
393
+ OctaveCodePrinter,
394
+ '(0.995 + 0.02946663003430684*log(5.0*fl_T + 1.25))',
395
+ ),
396
+ (
397
+ PythonCodePrinter,
398
+ '(0.995 + 0.02946663003430684*math.log(5.0*fl_T + 1.25))',
399
+ ),
400
+ (
401
+ NumPyPrinter,
402
+ '(0.995 + 0.02946663003430684*numpy.log(5.0*fl_T + 1.25))',
403
+ ),
404
+ (
405
+ SciPyPrinter,
406
+ '(0.995 + 0.02946663003430684*numpy.log(5.0*fl_T + 1.25))',
407
+ ),
408
+ (
409
+ CuPyPrinter,
410
+ '(0.995 + 0.02946663003430684*cupy.log(5.0*fl_T + 1.25))',
411
+ ),
412
+ (
413
+ JaxPrinter,
414
+ '(0.995 + 0.02946663003430684*jax.numpy.log(5.0*fl_T + 1.25))',
415
+ ),
416
+ (
417
+ MpmathPrinter,
418
+ '(mpmath.mpf((0, 8962163258467287, -53, 53))'
419
+ ' + mpmath.mpf((0, 33972711434846347, -60, 55))'
420
+ '*mpmath.log(mpmath.mpf((0, 5, 0, 3))*fl_T + mpmath.mpf((0, 5, -2, 3))))',
421
+ ),
422
+ (
423
+ LambdaPrinter,
424
+ '(0.995 + 0.02946663003430684*math.log(5.0*fl_T + 1.25))',
425
+ ),
426
+ ]
427
+ )
428
+ def test_print_code(self, code_printer, expected):
429
+ fl_T_inv = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
430
+ assert code_printer().doprint(fl_T_inv) == expected
431
+
432
+ def test_derivative_print_code(self):
433
+ fl_T_inv = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
434
+ dfl_T_inv_dfl_T = fl_T_inv.diff(self.fl_T)
435
+ expected = '1/(33.93669377311689*fl_T + 8.484173443279222)'
436
+ assert PythonCodePrinter().doprint(dfl_T_inv_dfl_T) == expected
437
+
438
+ def test_lambdify(self):
439
+ fl_T_inv = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
440
+ fl_T_inv_callable = lambdify(self.fl_T, fl_T_inv)
441
+ assert fl_T_inv_callable(0.0) == pytest.approx(1.0015752885)
442
+
443
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
444
+ def test_lambdify_numpy(self):
445
+ fl_T_inv = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
446
+ fl_T_inv_callable = lambdify(self.fl_T, fl_T_inv, 'numpy')
447
+ fl_T = numpy.array([-0.2, -0.01, 0.0, 1.01, 1.02, 1.05])
448
+ expected = numpy.array([
449
+ 0.9541505769,
450
+ 1.0003724019,
451
+ 1.0015752885,
452
+ 1.0492347951,
453
+ 1.0494677341,
454
+ 1.0501557022,
455
+ ])
456
+ numpy.testing.assert_allclose(fl_T_inv_callable(fl_T), expected)
457
+
458
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
459
+ def test_lambdify_jax(self):
460
+ fl_T_inv = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
461
+ fl_T_inv_callable = jax.jit(lambdify(self.fl_T, fl_T_inv, 'jax'))
462
+ fl_T = jax.numpy.array([-0.2, -0.01, 0.0, 1.01, 1.02, 1.05])
463
+ expected = jax.numpy.array([
464
+ 0.9541505769,
465
+ 1.0003724019,
466
+ 1.0015752885,
467
+ 1.0492347951,
468
+ 1.0494677341,
469
+ 1.0501557022,
470
+ ])
471
+ numpy.testing.assert_allclose(fl_T_inv_callable(fl_T), expected)
472
+
473
+
474
+ class TestFiberForceLengthPassiveDeGroote2016:
475
+
476
+ @pytest.fixture(autouse=True)
477
+ def _fiber_force_length_passive_arguments_fixture(self):
478
+ self.l_M_tilde = Symbol('l_M_tilde')
479
+ self.c0 = Symbol('c_0')
480
+ self.c1 = Symbol('c_1')
481
+ self.constants = (self.c0, self.c1)
482
+
483
+ @staticmethod
484
+ def test_class():
485
+ assert issubclass(FiberForceLengthPassiveDeGroote2016, Function)
486
+ assert issubclass(FiberForceLengthPassiveDeGroote2016, CharacteristicCurveFunction)
487
+ assert FiberForceLengthPassiveDeGroote2016.__name__ == 'FiberForceLengthPassiveDeGroote2016'
488
+
489
+ def test_instance(self):
490
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
491
+ assert isinstance(fl_M_pas, FiberForceLengthPassiveDeGroote2016)
492
+ assert str(fl_M_pas) == 'FiberForceLengthPassiveDeGroote2016(l_M_tilde, c_0, c_1)'
493
+
494
+ def test_doit(self):
495
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants).doit()
496
+ assert fl_M_pas == (exp((self.c1*(self.l_M_tilde - 1))/self.c0) - 1)/(exp(self.c1) - 1)
497
+
498
+ def test_doit_evaluate_false(self):
499
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants).doit(evaluate=False)
500
+ assert fl_M_pas == (exp((self.c1*UnevaluatedExpr(self.l_M_tilde - 1))/self.c0) - 1)/(exp(self.c1) - 1)
501
+
502
+ def test_with_defaults(self):
503
+ constants = (
504
+ Float('0.6'),
505
+ Float('4.0'),
506
+ )
507
+ fl_M_pas_manual = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *constants)
508
+ fl_M_pas_constants = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
509
+ assert fl_M_pas_manual == fl_M_pas_constants
510
+
511
+ def test_differentiate_wrt_l_M_tilde(self):
512
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
513
+ expected = self.c1*exp(self.c1*UnevaluatedExpr(self.l_M_tilde - 1)/self.c0)/(self.c0*(exp(self.c1) - 1))
514
+ assert fl_M_pas.diff(self.l_M_tilde) == expected
515
+
516
+ def test_differentiate_wrt_c0(self):
517
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
518
+ expected = (
519
+ -self.c1*exp(self.c1*UnevaluatedExpr(self.l_M_tilde - 1)/self.c0)
520
+ *UnevaluatedExpr(self.l_M_tilde - 1)/(self.c0**2*(exp(self.c1) - 1))
521
+ )
522
+ assert fl_M_pas.diff(self.c0) == expected
523
+
524
+ def test_differentiate_wrt_c1(self):
525
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
526
+ expected = (
527
+ -exp(self.c1)*(-1 + exp(self.c1*UnevaluatedExpr(self.l_M_tilde - 1)/self.c0))/(exp(self.c1) - 1)**2
528
+ + exp(self.c1*UnevaluatedExpr(self.l_M_tilde - 1)/self.c0)*(self.l_M_tilde - 1)/(self.c0*(exp(self.c1) - 1))
529
+ )
530
+ assert fl_M_pas.diff(self.c1) == expected
531
+
532
+ def test_inverse(self):
533
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
534
+ assert fl_M_pas.inverse() is FiberForceLengthPassiveInverseDeGroote2016
535
+
536
+ def test_function_print_latex(self):
537
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
538
+ expected = r'\operatorname{fl}^M_{pas} \left( l_{M tilde} \right)'
539
+ assert LatexPrinter().doprint(fl_M_pas) == expected
540
+
541
+ def test_expression_print_latex(self):
542
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
543
+ expected = r'\frac{e^{\frac{c_{1} \left(l_{M tilde} - 1\right)}{c_{0}}} - 1}{e^{c_{1}} - 1}'
544
+ assert LatexPrinter().doprint(fl_M_pas.doit()) == expected
545
+
546
+ @pytest.mark.parametrize(
547
+ 'code_printer, expected',
548
+ [
549
+ (
550
+ C89CodePrinter,
551
+ '(0.01865736036377405*(-1 + exp(6.666666666666667*(l_M_tilde - 1))))',
552
+ ),
553
+ (
554
+ C99CodePrinter,
555
+ '(0.01865736036377405*(-1 + exp(6.666666666666667*(l_M_tilde - 1))))',
556
+ ),
557
+ (
558
+ C11CodePrinter,
559
+ '(0.01865736036377405*(-1 + exp(6.666666666666667*(l_M_tilde - 1))))',
560
+ ),
561
+ (
562
+ CXX98CodePrinter,
563
+ '(0.01865736036377405*(-1 + exp(6.666666666666667*(l_M_tilde - 1))))',
564
+ ),
565
+ (
566
+ CXX11CodePrinter,
567
+ '(0.01865736036377405*(-1 + std::exp(6.666666666666667*(l_M_tilde - 1))))',
568
+ ),
569
+ (
570
+ CXX17CodePrinter,
571
+ '(0.01865736036377405*(-1 + std::exp(6.666666666666667*(l_M_tilde - 1))))',
572
+ ),
573
+ (
574
+ FCodePrinter,
575
+ ' (0.0186573603637741d0*(-1 + exp(6.666666666666667d0*(l_M_tilde - 1\n'
576
+ ' @ ))))',
577
+ ),
578
+ (
579
+ OctaveCodePrinter,
580
+ '(0.0186573603637741*(-1 + exp(6.66666666666667*(l_M_tilde - 1))))',
581
+ ),
582
+ (
583
+ PythonCodePrinter,
584
+ '(0.0186573603637741*(-1 + math.exp(6.66666666666667*(l_M_tilde - 1))))',
585
+ ),
586
+ (
587
+ NumPyPrinter,
588
+ '(0.0186573603637741*(-1 + numpy.exp(6.66666666666667*(l_M_tilde - 1))))',
589
+ ),
590
+ (
591
+ SciPyPrinter,
592
+ '(0.0186573603637741*(-1 + numpy.exp(6.66666666666667*(l_M_tilde - 1))))',
593
+ ),
594
+ (
595
+ CuPyPrinter,
596
+ '(0.0186573603637741*(-1 + cupy.exp(6.66666666666667*(l_M_tilde - 1))))',
597
+ ),
598
+ (
599
+ JaxPrinter,
600
+ '(0.0186573603637741*(-1 + jax.numpy.exp(6.66666666666667*(l_M_tilde - 1))))',
601
+ ),
602
+ (
603
+ MpmathPrinter,
604
+ '(mpmath.mpf((0, 672202249456079, -55, 50))*(-1 + mpmath.exp('
605
+ 'mpmath.mpf((0, 7505999378950827, -50, 53))*(l_M_tilde - 1))))',
606
+ ),
607
+ (
608
+ LambdaPrinter,
609
+ '(0.0186573603637741*(-1 + math.exp(6.66666666666667*(l_M_tilde - 1))))',
610
+ ),
611
+ ]
612
+ )
613
+ def test_print_code(self, code_printer, expected):
614
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
615
+ assert code_printer().doprint(fl_M_pas) == expected
616
+
617
+ def test_derivative_print_code(self):
618
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
619
+ fl_M_pas_dl_M_tilde = fl_M_pas.diff(self.l_M_tilde)
620
+ expected = '0.12438240242516*math.exp(6.66666666666667*(l_M_tilde - 1))'
621
+ assert PythonCodePrinter().doprint(fl_M_pas_dl_M_tilde) == expected
622
+
623
+ def test_lambdify(self):
624
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
625
+ fl_M_pas_callable = lambdify(self.l_M_tilde, fl_M_pas)
626
+ assert fl_M_pas_callable(1.0) == pytest.approx(0.0)
627
+
628
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
629
+ def test_lambdify_numpy(self):
630
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
631
+ fl_M_pas_callable = lambdify(self.l_M_tilde, fl_M_pas, 'numpy')
632
+ l_M_tilde = numpy.array([0.5, 0.8, 0.9, 1.0, 1.1, 1.2, 1.5])
633
+ expected = numpy.array([
634
+ -0.0179917778,
635
+ -0.0137393336,
636
+ -0.0090783522,
637
+ 0.0,
638
+ 0.0176822155,
639
+ 0.0521224686,
640
+ 0.5043387669,
641
+ ])
642
+ numpy.testing.assert_allclose(fl_M_pas_callable(l_M_tilde), expected)
643
+
644
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
645
+ def test_lambdify_jax(self):
646
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
647
+ fl_M_pas_callable = jax.jit(lambdify(self.l_M_tilde, fl_M_pas, 'jax'))
648
+ l_M_tilde = jax.numpy.array([0.5, 0.8, 0.9, 1.0, 1.1, 1.2, 1.5])
649
+ expected = jax.numpy.array([
650
+ -0.0179917778,
651
+ -0.0137393336,
652
+ -0.0090783522,
653
+ 0.0,
654
+ 0.0176822155,
655
+ 0.0521224686,
656
+ 0.5043387669,
657
+ ])
658
+ numpy.testing.assert_allclose(fl_M_pas_callable(l_M_tilde), expected)
659
+
660
+
661
+ class TestFiberForceLengthPassiveInverseDeGroote2016:
662
+
663
+ @pytest.fixture(autouse=True)
664
+ def _fiber_force_length_passive_arguments_fixture(self):
665
+ self.fl_M_pas = Symbol('fl_M_pas')
666
+ self.c0 = Symbol('c_0')
667
+ self.c1 = Symbol('c_1')
668
+ self.constants = (self.c0, self.c1)
669
+
670
+ @staticmethod
671
+ def test_class():
672
+ assert issubclass(FiberForceLengthPassiveInverseDeGroote2016, Function)
673
+ assert issubclass(FiberForceLengthPassiveInverseDeGroote2016, CharacteristicCurveFunction)
674
+ assert FiberForceLengthPassiveInverseDeGroote2016.__name__ == 'FiberForceLengthPassiveInverseDeGroote2016'
675
+
676
+ def test_instance(self):
677
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
678
+ assert isinstance(fl_M_pas_inv, FiberForceLengthPassiveInverseDeGroote2016)
679
+ assert str(fl_M_pas_inv) == 'FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, c_0, c_1)'
680
+
681
+ def test_doit(self):
682
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants).doit()
683
+ assert fl_M_pas_inv == self.c0*log(self.fl_M_pas*(exp(self.c1) - 1) + 1)/self.c1 + 1
684
+
685
+ def test_doit_evaluate_false(self):
686
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants).doit(evaluate=False)
687
+ assert fl_M_pas_inv == self.c0*log(UnevaluatedExpr(self.fl_M_pas*(exp(self.c1) - 1)) + 1)/self.c1 + 1
688
+
689
+ def test_with_defaults(self):
690
+ constants = (
691
+ Float('0.6'),
692
+ Float('4.0'),
693
+ )
694
+ fl_M_pas_inv_manual = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *constants)
695
+ fl_M_pas_inv_constants = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
696
+ assert fl_M_pas_inv_manual == fl_M_pas_inv_constants
697
+
698
+ def test_differentiate_wrt_fl_T(self):
699
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
700
+ expected = self.c0*(exp(self.c1) - 1)/(self.c1*(self.fl_M_pas*(exp(self.c1) - 1) + 1))
701
+ assert fl_M_pas_inv.diff(self.fl_M_pas) == expected
702
+
703
+ def test_differentiate_wrt_c0(self):
704
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
705
+ expected = log(self.fl_M_pas*(exp(self.c1) - 1) + 1)/self.c1
706
+ assert fl_M_pas_inv.diff(self.c0) == expected
707
+
708
+ def test_differentiate_wrt_c1(self):
709
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
710
+ expected = (
711
+ self.c0*self.fl_M_pas*exp(self.c1)/(self.c1*(self.fl_M_pas*(exp(self.c1) - 1) + 1))
712
+ - self.c0*log(self.fl_M_pas*(exp(self.c1) - 1) + 1)/self.c1**2
713
+ )
714
+ assert fl_M_pas_inv.diff(self.c1) == expected
715
+
716
+ def test_inverse(self):
717
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
718
+ assert fl_M_pas_inv.inverse() is FiberForceLengthPassiveDeGroote2016
719
+
720
+ def test_function_print_latex(self):
721
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
722
+ expected = r'\left( \operatorname{fl}^M_{pas} \right)^{-1} \left( fl_{M pas} \right)'
723
+ assert LatexPrinter().doprint(fl_M_pas_inv) == expected
724
+
725
+ def test_expression_print_latex(self):
726
+ fl_T = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
727
+ expected = r'\frac{c_{0} \log{\left(fl_{M pas} \left(e^{c_{1}} - 1\right) + 1 \right)}}{c_{1}} + 1'
728
+ assert LatexPrinter().doprint(fl_T.doit()) == expected
729
+
730
+ @pytest.mark.parametrize(
731
+ 'code_printer, expected',
732
+ [
733
+ (
734
+ C89CodePrinter,
735
+ '(1 + 0.14999999999999999*log(1 + 53.598150033144236*fl_M_pas))',
736
+ ),
737
+ (
738
+ C99CodePrinter,
739
+ '(1 + 0.14999999999999999*log(1 + 53.598150033144236*fl_M_pas))',
740
+ ),
741
+ (
742
+ C11CodePrinter,
743
+ '(1 + 0.14999999999999999*log(1 + 53.598150033144236*fl_M_pas))',
744
+ ),
745
+ (
746
+ CXX98CodePrinter,
747
+ '(1 + 0.14999999999999999*log(1 + 53.598150033144236*fl_M_pas))',
748
+ ),
749
+ (
750
+ CXX11CodePrinter,
751
+ '(1 + 0.14999999999999999*std::log(1 + 53.598150033144236*fl_M_pas))',
752
+ ),
753
+ (
754
+ CXX17CodePrinter,
755
+ '(1 + 0.14999999999999999*std::log(1 + 53.598150033144236*fl_M_pas))',
756
+ ),
757
+ (
758
+ FCodePrinter,
759
+ ' (1 + 0.15d0*log(1.0d0 + 53.5981500331442d0*fl_M_pas))',
760
+ ),
761
+ (
762
+ OctaveCodePrinter,
763
+ '(1 + 0.15*log(1 + 53.5981500331442*fl_M_pas))',
764
+ ),
765
+ (
766
+ PythonCodePrinter,
767
+ '(1 + 0.15*math.log(1 + 53.5981500331442*fl_M_pas))',
768
+ ),
769
+ (
770
+ NumPyPrinter,
771
+ '(1 + 0.15*numpy.log(1 + 53.5981500331442*fl_M_pas))',
772
+ ),
773
+ (
774
+ SciPyPrinter,
775
+ '(1 + 0.15*numpy.log(1 + 53.5981500331442*fl_M_pas))',
776
+ ),
777
+ (
778
+ CuPyPrinter,
779
+ '(1 + 0.15*cupy.log(1 + 53.5981500331442*fl_M_pas))',
780
+ ),
781
+ (
782
+ JaxPrinter,
783
+ '(1 + 0.15*jax.numpy.log(1 + 53.5981500331442*fl_M_pas))',
784
+ ),
785
+ (
786
+ MpmathPrinter,
787
+ '(1 + mpmath.mpf((0, 5404319552844595, -55, 53))*mpmath.log(1 '
788
+ '+ mpmath.mpf((0, 942908627019595, -44, 50))*fl_M_pas))',
789
+ ),
790
+ (
791
+ LambdaPrinter,
792
+ '(1 + 0.15*math.log(1 + 53.5981500331442*fl_M_pas))',
793
+ ),
794
+ ]
795
+ )
796
+ def test_print_code(self, code_printer, expected):
797
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
798
+ assert code_printer().doprint(fl_M_pas_inv) == expected
799
+
800
+ def test_derivative_print_code(self):
801
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
802
+ dfl_M_pas_inv_dfl_T = fl_M_pas_inv.diff(self.fl_M_pas)
803
+ expected = '32.1588900198865/(214.392600132577*fl_M_pas + 4.0)'
804
+ assert PythonCodePrinter().doprint(dfl_M_pas_inv_dfl_T) == expected
805
+
806
+ def test_lambdify(self):
807
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
808
+ fl_M_pas_inv_callable = lambdify(self.fl_M_pas, fl_M_pas_inv)
809
+ assert fl_M_pas_inv_callable(0.0) == pytest.approx(1.0)
810
+
811
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
812
+ def test_lambdify_numpy(self):
813
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
814
+ fl_M_pas_inv_callable = lambdify(self.fl_M_pas, fl_M_pas_inv, 'numpy')
815
+ fl_M_pas = numpy.array([-0.01, 0.0, 0.01, 0.02, 0.05, 0.1])
816
+ expected = numpy.array([
817
+ 0.8848253714,
818
+ 1.0,
819
+ 1.0643754386,
820
+ 1.1092744701,
821
+ 1.1954331425,
822
+ 1.2774998934,
823
+ ])
824
+ numpy.testing.assert_allclose(fl_M_pas_inv_callable(fl_M_pas), expected)
825
+
826
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
827
+ def test_lambdify_jax(self):
828
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
829
+ fl_M_pas_inv_callable = jax.jit(lambdify(self.fl_M_pas, fl_M_pas_inv, 'jax'))
830
+ fl_M_pas = jax.numpy.array([-0.01, 0.0, 0.01, 0.02, 0.05, 0.1])
831
+ expected = jax.numpy.array([
832
+ 0.8848253714,
833
+ 1.0,
834
+ 1.0643754386,
835
+ 1.1092744701,
836
+ 1.1954331425,
837
+ 1.2774998934,
838
+ ])
839
+ numpy.testing.assert_allclose(fl_M_pas_inv_callable(fl_M_pas), expected)
840
+
841
+
842
+ class TestFiberForceLengthActiveDeGroote2016:
843
+
844
+ @pytest.fixture(autouse=True)
845
+ def _fiber_force_length_active_arguments_fixture(self):
846
+ self.l_M_tilde = Symbol('l_M_tilde')
847
+ self.c0 = Symbol('c_0')
848
+ self.c1 = Symbol('c_1')
849
+ self.c2 = Symbol('c_2')
850
+ self.c3 = Symbol('c_3')
851
+ self.c4 = Symbol('c_4')
852
+ self.c5 = Symbol('c_5')
853
+ self.c6 = Symbol('c_6')
854
+ self.c7 = Symbol('c_7')
855
+ self.c8 = Symbol('c_8')
856
+ self.c9 = Symbol('c_9')
857
+ self.c10 = Symbol('c_10')
858
+ self.c11 = Symbol('c_11')
859
+ self.constants = (
860
+ self.c0, self.c1, self.c2, self.c3, self.c4, self.c5,
861
+ self.c6, self.c7, self.c8, self.c9, self.c10, self.c11,
862
+ )
863
+
864
+ @staticmethod
865
+ def test_class():
866
+ assert issubclass(FiberForceLengthActiveDeGroote2016, Function)
867
+ assert issubclass(FiberForceLengthActiveDeGroote2016, CharacteristicCurveFunction)
868
+ assert FiberForceLengthActiveDeGroote2016.__name__ == 'FiberForceLengthActiveDeGroote2016'
869
+
870
+ def test_instance(self):
871
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
872
+ assert isinstance(fl_M_act, FiberForceLengthActiveDeGroote2016)
873
+ assert str(fl_M_act) == (
874
+ 'FiberForceLengthActiveDeGroote2016(l_M_tilde, c_0, c_1, c_2, c_3, '
875
+ 'c_4, c_5, c_6, c_7, c_8, c_9, c_10, c_11)'
876
+ )
877
+
878
+ def test_doit(self):
879
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants).doit()
880
+ assert fl_M_act == (
881
+ self.c0*exp(-(((self.l_M_tilde - self.c1)/(self.c2 + self.c3*self.l_M_tilde))**2)/2)
882
+ + self.c4*exp(-(((self.l_M_tilde - self.c5)/(self.c6 + self.c7*self.l_M_tilde))**2)/2)
883
+ + self.c8*exp(-(((self.l_M_tilde - self.c9)/(self.c10 + self.c11*self.l_M_tilde))**2)/2)
884
+ )
885
+
886
+ def test_doit_evaluate_false(self):
887
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants).doit(evaluate=False)
888
+ assert fl_M_act == (
889
+ self.c0*exp(-((UnevaluatedExpr(self.l_M_tilde - self.c1)/(self.c2 + self.c3*self.l_M_tilde))**2)/2)
890
+ + self.c4*exp(-((UnevaluatedExpr(self.l_M_tilde - self.c5)/(self.c6 + self.c7*self.l_M_tilde))**2)/2)
891
+ + self.c8*exp(-((UnevaluatedExpr(self.l_M_tilde - self.c9)/(self.c10 + self.c11*self.l_M_tilde))**2)/2)
892
+ )
893
+
894
+ def test_with_defaults(self):
895
+ constants = (
896
+ Float('0.814'),
897
+ Float('1.06'),
898
+ Float('0.162'),
899
+ Float('0.0633'),
900
+ Float('0.433'),
901
+ Float('0.717'),
902
+ Float('-0.0299'),
903
+ Float('0.2'),
904
+ Float('0.1'),
905
+ Float('1.0'),
906
+ Float('0.354'),
907
+ Float('0.0'),
908
+ )
909
+ fl_M_act_manual = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *constants)
910
+ fl_M_act_constants = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
911
+ assert fl_M_act_manual == fl_M_act_constants
912
+
913
+ def test_differentiate_wrt_l_M_tilde(self):
914
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
915
+ expected = (
916
+ self.c0*(
917
+ self.c3*(self.l_M_tilde - self.c1)**2/(self.c2 + self.c3*self.l_M_tilde)**3
918
+ + (self.c1 - self.l_M_tilde)/((self.c2 + self.c3*self.l_M_tilde)**2)
919
+ )*exp(-(self.l_M_tilde - self.c1)**2/(2*(self.c2 + self.c3*self.l_M_tilde)**2))
920
+ + self.c4*(
921
+ self.c7*(self.l_M_tilde - self.c5)**2/(self.c6 + self.c7*self.l_M_tilde)**3
922
+ + (self.c5 - self.l_M_tilde)/((self.c6 + self.c7*self.l_M_tilde)**2)
923
+ )*exp(-(self.l_M_tilde - self.c5)**2/(2*(self.c6 + self.c7*self.l_M_tilde)**2))
924
+ + self.c8*(
925
+ self.c11*(self.l_M_tilde - self.c9)**2/(self.c10 + self.c11*self.l_M_tilde)**3
926
+ + (self.c9 - self.l_M_tilde)/((self.c10 + self.c11*self.l_M_tilde)**2)
927
+ )*exp(-(self.l_M_tilde - self.c9)**2/(2*(self.c10 + self.c11*self.l_M_tilde)**2))
928
+ )
929
+ assert fl_M_act.diff(self.l_M_tilde) == expected
930
+
931
+ def test_differentiate_wrt_c0(self):
932
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
933
+ expected = exp(-(self.l_M_tilde - self.c1)**2/(2*(self.c2 + self.c3*self.l_M_tilde)**2))
934
+ assert fl_M_act.doit().diff(self.c0) == expected
935
+
936
+ def test_differentiate_wrt_c1(self):
937
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
938
+ expected = (
939
+ self.c0*(self.l_M_tilde - self.c1)/(self.c2 + self.c3*self.l_M_tilde)**2
940
+ *exp(-(self.l_M_tilde - self.c1)**2/(2*(self.c2 + self.c3*self.l_M_tilde)**2))
941
+ )
942
+ assert fl_M_act.diff(self.c1) == expected
943
+
944
+ def test_differentiate_wrt_c2(self):
945
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
946
+ expected = (
947
+ self.c0*(self.l_M_tilde - self.c1)**2/(self.c2 + self.c3*self.l_M_tilde)**3
948
+ *exp(-(self.l_M_tilde - self.c1)**2/(2*(self.c2 + self.c3*self.l_M_tilde)**2))
949
+ )
950
+ assert fl_M_act.diff(self.c2) == expected
951
+
952
+ def test_differentiate_wrt_c3(self):
953
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
954
+ expected = (
955
+ self.c0*self.l_M_tilde*(self.l_M_tilde - self.c1)**2/(self.c2 + self.c3*self.l_M_tilde)**3
956
+ *exp(-(self.l_M_tilde - self.c1)**2/(2*(self.c2 + self.c3*self.l_M_tilde)**2))
957
+ )
958
+ assert fl_M_act.diff(self.c3) == expected
959
+
960
+ def test_differentiate_wrt_c4(self):
961
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
962
+ expected = exp(-(self.l_M_tilde - self.c5)**2/(2*(self.c6 + self.c7*self.l_M_tilde)**2))
963
+ assert fl_M_act.diff(self.c4) == expected
964
+
965
+ def test_differentiate_wrt_c5(self):
966
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
967
+ expected = (
968
+ self.c4*(self.l_M_tilde - self.c5)/(self.c6 + self.c7*self.l_M_tilde)**2
969
+ *exp(-(self.l_M_tilde - self.c5)**2/(2*(self.c6 + self.c7*self.l_M_tilde)**2))
970
+ )
971
+ assert fl_M_act.diff(self.c5) == expected
972
+
973
+ def test_differentiate_wrt_c6(self):
974
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
975
+ expected = (
976
+ self.c4*(self.l_M_tilde - self.c5)**2/(self.c6 + self.c7*self.l_M_tilde)**3
977
+ *exp(-(self.l_M_tilde - self.c5)**2/(2*(self.c6 + self.c7*self.l_M_tilde)**2))
978
+ )
979
+ assert fl_M_act.diff(self.c6) == expected
980
+
981
+ def test_differentiate_wrt_c7(self):
982
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
983
+ expected = (
984
+ self.c4*self.l_M_tilde*(self.l_M_tilde - self.c5)**2/(self.c6 + self.c7*self.l_M_tilde)**3
985
+ *exp(-(self.l_M_tilde - self.c5)**2/(2*(self.c6 + self.c7*self.l_M_tilde)**2))
986
+ )
987
+ assert fl_M_act.diff(self.c7) == expected
988
+
989
+ def test_differentiate_wrt_c8(self):
990
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
991
+ expected = exp(-(self.l_M_tilde - self.c9)**2/(2*(self.c10 + self.c11*self.l_M_tilde)**2))
992
+ assert fl_M_act.diff(self.c8) == expected
993
+
994
+ def test_differentiate_wrt_c9(self):
995
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
996
+ expected = (
997
+ self.c8*(self.l_M_tilde - self.c9)/(self.c10 + self.c11*self.l_M_tilde)**2
998
+ *exp(-(self.l_M_tilde - self.c9)**2/(2*(self.c10 + self.c11*self.l_M_tilde)**2))
999
+ )
1000
+ assert fl_M_act.diff(self.c9) == expected
1001
+
1002
+ def test_differentiate_wrt_c10(self):
1003
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
1004
+ expected = (
1005
+ self.c8*(self.l_M_tilde - self.c9)**2/(self.c10 + self.c11*self.l_M_tilde)**3
1006
+ *exp(-(self.l_M_tilde - self.c9)**2/(2*(self.c10 + self.c11*self.l_M_tilde)**2))
1007
+ )
1008
+ assert fl_M_act.diff(self.c10) == expected
1009
+
1010
+ def test_differentiate_wrt_c11(self):
1011
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
1012
+ expected = (
1013
+ self.c8*self.l_M_tilde*(self.l_M_tilde - self.c9)**2/(self.c10 + self.c11*self.l_M_tilde)**3
1014
+ *exp(-(self.l_M_tilde - self.c9)**2/(2*(self.c10 + self.c11*self.l_M_tilde)**2))
1015
+ )
1016
+ assert fl_M_act.diff(self.c11) == expected
1017
+
1018
+ def test_function_print_latex(self):
1019
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
1020
+ expected = r'\operatorname{fl}^M_{act} \left( l_{M tilde} \right)'
1021
+ assert LatexPrinter().doprint(fl_M_act) == expected
1022
+
1023
+ def test_expression_print_latex(self):
1024
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
1025
+ expected = (
1026
+ r'c_{0} e^{- \frac{\left(- c_{1} + l_{M tilde}\right)^{2}}{2 \left(c_{2} + c_{3} l_{M tilde}\right)^{2}}} '
1027
+ r'+ c_{4} e^{- \frac{\left(- c_{5} + l_{M tilde}\right)^{2}}{2 \left(c_{6} + c_{7} l_{M tilde}\right)^{2}}} '
1028
+ r'+ c_{8} e^{- \frac{\left(- c_{9} + l_{M tilde}\right)^{2}}{2 \left(c_{10} + c_{11} l_{M tilde}\right)^{2}}}'
1029
+ )
1030
+ assert LatexPrinter().doprint(fl_M_act.doit()) == expected
1031
+
1032
+ @pytest.mark.parametrize(
1033
+ 'code_printer, expected',
1034
+ [
1035
+ (
1036
+ C89CodePrinter,
1037
+ (
1038
+ '(0.81399999999999995*exp(-19.051973784484073'
1039
+ '*pow(l_M_tilde - 1.0600000000000001, 2)'
1040
+ '/pow(0.39074074074074072*l_M_tilde + 1, 2)) '
1041
+ '+ 0.433*exp(-12.499999999999998'
1042
+ '*pow(l_M_tilde - 0.71699999999999997, 2)'
1043
+ '/pow(l_M_tilde - 0.14949999999999999, 2)) '
1044
+ '+ 0.10000000000000001*exp(-3.9899134986753491'
1045
+ '*pow(l_M_tilde - 1.0, 2)))'
1046
+ ),
1047
+ ),
1048
+ (
1049
+ C99CodePrinter,
1050
+ (
1051
+ '(0.81399999999999995*exp(-19.051973784484073'
1052
+ '*pow(l_M_tilde - 1.0600000000000001, 2)'
1053
+ '/pow(0.39074074074074072*l_M_tilde + 1, 2)) '
1054
+ '+ 0.433*exp(-12.499999999999998'
1055
+ '*pow(l_M_tilde - 0.71699999999999997, 2)'
1056
+ '/pow(l_M_tilde - 0.14949999999999999, 2)) '
1057
+ '+ 0.10000000000000001*exp(-3.9899134986753491'
1058
+ '*pow(l_M_tilde - 1.0, 2)))'
1059
+ ),
1060
+ ),
1061
+ (
1062
+ C11CodePrinter,
1063
+ (
1064
+ '(0.81399999999999995*exp(-19.051973784484073'
1065
+ '*pow(l_M_tilde - 1.0600000000000001, 2)'
1066
+ '/pow(0.39074074074074072*l_M_tilde + 1, 2)) '
1067
+ '+ 0.433*exp(-12.499999999999998'
1068
+ '*pow(l_M_tilde - 0.71699999999999997, 2)'
1069
+ '/pow(l_M_tilde - 0.14949999999999999, 2)) '
1070
+ '+ 0.10000000000000001*exp(-3.9899134986753491'
1071
+ '*pow(l_M_tilde - 1.0, 2)))'
1072
+ ),
1073
+ ),
1074
+ (
1075
+ CXX98CodePrinter,
1076
+ (
1077
+ '(0.81399999999999995*exp(-19.051973784484073'
1078
+ '*std::pow(l_M_tilde - 1.0600000000000001, 2)'
1079
+ '/std::pow(0.39074074074074072*l_M_tilde + 1, 2)) '
1080
+ '+ 0.433*exp(-12.499999999999998'
1081
+ '*std::pow(l_M_tilde - 0.71699999999999997, 2)'
1082
+ '/std::pow(l_M_tilde - 0.14949999999999999, 2)) '
1083
+ '+ 0.10000000000000001*exp(-3.9899134986753491'
1084
+ '*std::pow(l_M_tilde - 1.0, 2)))'
1085
+ ),
1086
+ ),
1087
+ (
1088
+ CXX11CodePrinter,
1089
+ (
1090
+ '(0.81399999999999995*std::exp(-19.051973784484073'
1091
+ '*std::pow(l_M_tilde - 1.0600000000000001, 2)'
1092
+ '/std::pow(0.39074074074074072*l_M_tilde + 1, 2)) '
1093
+ '+ 0.433*std::exp(-12.499999999999998'
1094
+ '*std::pow(l_M_tilde - 0.71699999999999997, 2)'
1095
+ '/std::pow(l_M_tilde - 0.14949999999999999, 2)) '
1096
+ '+ 0.10000000000000001*std::exp(-3.9899134986753491'
1097
+ '*std::pow(l_M_tilde - 1.0, 2)))'
1098
+ ),
1099
+ ),
1100
+ (
1101
+ CXX17CodePrinter,
1102
+ (
1103
+ '(0.81399999999999995*std::exp(-19.051973784484073'
1104
+ '*std::pow(l_M_tilde - 1.0600000000000001, 2)'
1105
+ '/std::pow(0.39074074074074072*l_M_tilde + 1, 2)) '
1106
+ '+ 0.433*std::exp(-12.499999999999998'
1107
+ '*std::pow(l_M_tilde - 0.71699999999999997, 2)'
1108
+ '/std::pow(l_M_tilde - 0.14949999999999999, 2)) '
1109
+ '+ 0.10000000000000001*std::exp(-3.9899134986753491'
1110
+ '*std::pow(l_M_tilde - 1.0, 2)))'
1111
+ ),
1112
+ ),
1113
+ (
1114
+ FCodePrinter,
1115
+ (
1116
+ ' (0.814d0*exp(-19.051973784484073d0*(l_M_tilde - 1.06d0)**2/(\n'
1117
+ ' @ 0.39074074074074072d0*l_M_tilde + 1.0d0)**2) + 0.433d0*exp(\n'
1118
+ ' @ -12.499999999999998d0*(l_M_tilde - 0.717d0)**2/(l_M_tilde -\n'
1119
+ ' @ 0.14949999999999999d0)**2) + 0.1d0*exp(-3.9899134986753491d0*(\n'
1120
+ ' @ l_M_tilde - 1.0d0)**2))'
1121
+ ),
1122
+ ),
1123
+ (
1124
+ OctaveCodePrinter,
1125
+ (
1126
+ '(0.814*exp(-19.0519737844841*(l_M_tilde - 1.06).^2'
1127
+ './(0.390740740740741*l_M_tilde + 1).^2) '
1128
+ '+ 0.433*exp(-12.5*(l_M_tilde - 0.717).^2'
1129
+ './(l_M_tilde - 0.1495).^2) '
1130
+ '+ 0.1*exp(-3.98991349867535*(l_M_tilde - 1.0).^2))'
1131
+ ),
1132
+ ),
1133
+ (
1134
+ PythonCodePrinter,
1135
+ (
1136
+ '(0.814*math.exp(-19.0519737844841*(l_M_tilde - 1.06)**2'
1137
+ '/(0.390740740740741*l_M_tilde + 1)**2) '
1138
+ '+ 0.433*math.exp(-12.5*(l_M_tilde - 0.717)**2'
1139
+ '/(l_M_tilde - 0.1495)**2) '
1140
+ '+ 0.1*math.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1141
+ ),
1142
+ ),
1143
+ (
1144
+ NumPyPrinter,
1145
+ (
1146
+ '(0.814*numpy.exp(-19.0519737844841*(l_M_tilde - 1.06)**2'
1147
+ '/(0.390740740740741*l_M_tilde + 1)**2) '
1148
+ '+ 0.433*numpy.exp(-12.5*(l_M_tilde - 0.717)**2'
1149
+ '/(l_M_tilde - 0.1495)**2) '
1150
+ '+ 0.1*numpy.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1151
+ ),
1152
+ ),
1153
+ (
1154
+ SciPyPrinter,
1155
+ (
1156
+ '(0.814*numpy.exp(-19.0519737844841*(l_M_tilde - 1.06)**2'
1157
+ '/(0.390740740740741*l_M_tilde + 1)**2) '
1158
+ '+ 0.433*numpy.exp(-12.5*(l_M_tilde - 0.717)**2'
1159
+ '/(l_M_tilde - 0.1495)**2) '
1160
+ '+ 0.1*numpy.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1161
+ ),
1162
+ ),
1163
+ (
1164
+ CuPyPrinter,
1165
+ (
1166
+ '(0.814*cupy.exp(-19.0519737844841*(l_M_tilde - 1.06)**2'
1167
+ '/(0.390740740740741*l_M_tilde + 1)**2) '
1168
+ '+ 0.433*cupy.exp(-12.5*(l_M_tilde - 0.717)**2'
1169
+ '/(l_M_tilde - 0.1495)**2) '
1170
+ '+ 0.1*cupy.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1171
+ ),
1172
+ ),
1173
+ (
1174
+ JaxPrinter,
1175
+ (
1176
+ '(0.814*jax.numpy.exp(-19.0519737844841*(l_M_tilde - 1.06)**2'
1177
+ '/(0.390740740740741*l_M_tilde + 1)**2) '
1178
+ '+ 0.433*jax.numpy.exp(-12.5*(l_M_tilde - 0.717)**2'
1179
+ '/(l_M_tilde - 0.1495)**2) '
1180
+ '+ 0.1*jax.numpy.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1181
+ ),
1182
+ ),
1183
+ (
1184
+ MpmathPrinter,
1185
+ (
1186
+ '(mpmath.mpf((0, 7331860193359167, -53, 53))'
1187
+ '*mpmath.exp(-mpmath.mpf((0, 5362653877279683, -48, 53))'
1188
+ '*(l_M_tilde + mpmath.mpf((1, 2386907802506363, -51, 52)))**2'
1189
+ '/(mpmath.mpf((0, 3519479708796943, -53, 52))*l_M_tilde + 1)**2) '
1190
+ '+ mpmath.mpf((0, 7800234554605699, -54, 53))'
1191
+ '*mpmath.exp(-mpmath.mpf((0, 7036874417766399, -49, 53))'
1192
+ '*(l_M_tilde + mpmath.mpf((1, 6458161865649291, -53, 53)))**2'
1193
+ '/(l_M_tilde + mpmath.mpf((1, 5386305154335113, -55, 53)))**2) '
1194
+ '+ mpmath.mpf((0, 3602879701896397, -55, 52))'
1195
+ '*mpmath.exp(-mpmath.mpf((0, 8984486472937407, -51, 53))'
1196
+ '*(l_M_tilde + mpmath.mpf((1, 1, 0, 1)))**2))'
1197
+ ),
1198
+ ),
1199
+ (
1200
+ LambdaPrinter,
1201
+ (
1202
+ '(0.814*math.exp(-19.0519737844841*(l_M_tilde - 1.06)**2'
1203
+ '/(0.390740740740741*l_M_tilde + 1)**2) '
1204
+ '+ 0.433*math.exp(-12.5*(l_M_tilde - 0.717)**2'
1205
+ '/(l_M_tilde - 0.1495)**2) '
1206
+ '+ 0.1*math.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1207
+ ),
1208
+ ),
1209
+ ]
1210
+ )
1211
+ def test_print_code(self, code_printer, expected):
1212
+ fl_M_act = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
1213
+ assert code_printer().doprint(fl_M_act) == expected
1214
+
1215
+ def test_derivative_print_code(self):
1216
+ fl_M_act = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
1217
+ fl_M_act_dl_M_tilde = fl_M_act.diff(self.l_M_tilde)
1218
+ expected = (
1219
+ '(0.79798269973507 - 0.79798269973507*l_M_tilde)'
1220
+ '*math.exp(-3.98991349867535*(l_M_tilde - 1.0)**2) '
1221
+ '+ (10.825*(0.717 - l_M_tilde)/(l_M_tilde - 0.1495)**2 '
1222
+ '+ 10.825*(l_M_tilde - 0.717)**2/(l_M_tilde - 0.1495)**3)'
1223
+ '*math.exp(-12.5*(l_M_tilde - 0.717)**2/(l_M_tilde - 0.1495)**2) '
1224
+ '+ (31.0166133211401*(1.06 - l_M_tilde)/(0.390740740740741*l_M_tilde + 1)**2 '
1225
+ '+ 13.6174190361677*(0.943396226415094*l_M_tilde - 1)**2'
1226
+ '/(0.390740740740741*l_M_tilde + 1)**3)'
1227
+ '*math.exp(-21.4067977442463*(0.943396226415094*l_M_tilde - 1)**2'
1228
+ '/(0.390740740740741*l_M_tilde + 1)**2)'
1229
+ )
1230
+ assert PythonCodePrinter().doprint(fl_M_act_dl_M_tilde) == expected
1231
+
1232
+ def test_lambdify(self):
1233
+ fl_M_act = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
1234
+ fl_M_act_callable = lambdify(self.l_M_tilde, fl_M_act)
1235
+ assert fl_M_act_callable(1.0) == pytest.approx(0.9941398866)
1236
+
1237
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
1238
+ def test_lambdify_numpy(self):
1239
+ fl_M_act = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
1240
+ fl_M_act_callable = lambdify(self.l_M_tilde, fl_M_act, 'numpy')
1241
+ l_M_tilde = numpy.array([0.0, 0.5, 1.0, 1.5, 2.0])
1242
+ expected = numpy.array([
1243
+ 0.0018501319,
1244
+ 0.0529122812,
1245
+ 0.9941398866,
1246
+ 0.2312431531,
1247
+ 0.0069595432,
1248
+ ])
1249
+ numpy.testing.assert_allclose(fl_M_act_callable(l_M_tilde), expected)
1250
+
1251
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
1252
+ def test_lambdify_jax(self):
1253
+ fl_M_act = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
1254
+ fl_M_act_callable = jax.jit(lambdify(self.l_M_tilde, fl_M_act, 'jax'))
1255
+ l_M_tilde = jax.numpy.array([0.0, 0.5, 1.0, 1.5, 2.0])
1256
+ expected = jax.numpy.array([
1257
+ 0.0018501319,
1258
+ 0.0529122812,
1259
+ 0.9941398866,
1260
+ 0.2312431531,
1261
+ 0.0069595432,
1262
+ ])
1263
+ numpy.testing.assert_allclose(fl_M_act_callable(l_M_tilde), expected)
1264
+
1265
+
1266
+ class TestFiberForceVelocityDeGroote2016:
1267
+
1268
+ @pytest.fixture(autouse=True)
1269
+ def _muscle_fiber_force_velocity_arguments_fixture(self):
1270
+ self.v_M_tilde = Symbol('v_M_tilde')
1271
+ self.c0 = Symbol('c_0')
1272
+ self.c1 = Symbol('c_1')
1273
+ self.c2 = Symbol('c_2')
1274
+ self.c3 = Symbol('c_3')
1275
+ self.constants = (self.c0, self.c1, self.c2, self.c3)
1276
+
1277
+ @staticmethod
1278
+ def test_class():
1279
+ assert issubclass(FiberForceVelocityDeGroote2016, Function)
1280
+ assert issubclass(FiberForceVelocityDeGroote2016, CharacteristicCurveFunction)
1281
+ assert FiberForceVelocityDeGroote2016.__name__ == 'FiberForceVelocityDeGroote2016'
1282
+
1283
+ def test_instance(self):
1284
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1285
+ assert isinstance(fv_M, FiberForceVelocityDeGroote2016)
1286
+ assert str(fv_M) == 'FiberForceVelocityDeGroote2016(v_M_tilde, c_0, c_1, c_2, c_3)'
1287
+
1288
+ def test_doit(self):
1289
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants).doit()
1290
+ expected = (
1291
+ self.c0 * log((self.c1 * self.v_M_tilde + self.c2)
1292
+ + sqrt((self.c1 * self.v_M_tilde + self.c2)**2 + 1)) + self.c3
1293
+ )
1294
+ assert fv_M == expected
1295
+
1296
+ def test_doit_evaluate_false(self):
1297
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants).doit(evaluate=False)
1298
+ expected = (
1299
+ self.c0 * log((self.c1 * self.v_M_tilde + self.c2)
1300
+ + sqrt(UnevaluatedExpr(self.c1 * self.v_M_tilde + self.c2)**2 + 1)) + self.c3
1301
+ )
1302
+ assert fv_M == expected
1303
+
1304
+ def test_with_defaults(self):
1305
+ constants = (
1306
+ Float('-0.318'),
1307
+ Float('-8.149'),
1308
+ Float('-0.374'),
1309
+ Float('0.886'),
1310
+ )
1311
+ fv_M_manual = FiberForceVelocityDeGroote2016(self.v_M_tilde, *constants)
1312
+ fv_M_constants = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1313
+ assert fv_M_manual == fv_M_constants
1314
+
1315
+ def test_differentiate_wrt_v_M_tilde(self):
1316
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1317
+ expected = (
1318
+ self.c0*self.c1
1319
+ /sqrt(UnevaluatedExpr(self.c1*self.v_M_tilde + self.c2)**2 + 1)
1320
+ )
1321
+ assert fv_M.diff(self.v_M_tilde) == expected
1322
+
1323
+ def test_differentiate_wrt_c0(self):
1324
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1325
+ expected = log(
1326
+ self.c1*self.v_M_tilde + self.c2
1327
+ + sqrt(UnevaluatedExpr(self.c1*self.v_M_tilde + self.c2)**2 + 1)
1328
+ )
1329
+ assert fv_M.diff(self.c0) == expected
1330
+
1331
+ def test_differentiate_wrt_c1(self):
1332
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1333
+ expected = (
1334
+ self.c0*self.v_M_tilde
1335
+ /sqrt(UnevaluatedExpr(self.c1*self.v_M_tilde + self.c2)**2 + 1)
1336
+ )
1337
+ assert fv_M.diff(self.c1) == expected
1338
+
1339
+ def test_differentiate_wrt_c2(self):
1340
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1341
+ expected = (
1342
+ self.c0
1343
+ /sqrt(UnevaluatedExpr(self.c1*self.v_M_tilde + self.c2)**2 + 1)
1344
+ )
1345
+ assert fv_M.diff(self.c2) == expected
1346
+
1347
+ def test_differentiate_wrt_c3(self):
1348
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1349
+ expected = Integer(1)
1350
+ assert fv_M.diff(self.c3) == expected
1351
+
1352
+ def test_inverse(self):
1353
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1354
+ assert fv_M.inverse() is FiberForceVelocityInverseDeGroote2016
1355
+
1356
+ def test_function_print_latex(self):
1357
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1358
+ expected = r'\operatorname{fv}^M \left( v_{M tilde} \right)'
1359
+ assert LatexPrinter().doprint(fv_M) == expected
1360
+
1361
+ def test_expression_print_latex(self):
1362
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1363
+ expected = (
1364
+ r'c_{0} \log{\left(c_{1} v_{M tilde} + c_{2} + \sqrt{\left(c_{1} '
1365
+ r'v_{M tilde} + c_{2}\right)^{2} + 1} \right)} + c_{3}'
1366
+ )
1367
+ assert LatexPrinter().doprint(fv_M.doit()) == expected
1368
+
1369
+ @pytest.mark.parametrize(
1370
+ 'code_printer, expected',
1371
+ [
1372
+ (
1373
+ C89CodePrinter,
1374
+ '(0.88600000000000001 - 0.318*log(-8.1489999999999991*v_M_tilde '
1375
+ '- 0.374 + sqrt(1 + pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1376
+ ),
1377
+ (
1378
+ C99CodePrinter,
1379
+ '(0.88600000000000001 - 0.318*log(-8.1489999999999991*v_M_tilde '
1380
+ '- 0.374 + sqrt(1 + pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1381
+ ),
1382
+ (
1383
+ C11CodePrinter,
1384
+ '(0.88600000000000001 - 0.318*log(-8.1489999999999991*v_M_tilde '
1385
+ '- 0.374 + sqrt(1 + pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1386
+ ),
1387
+ (
1388
+ CXX98CodePrinter,
1389
+ '(0.88600000000000001 - 0.318*log(-8.1489999999999991*v_M_tilde '
1390
+ '- 0.374 + std::sqrt(1 + std::pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1391
+ ),
1392
+ (
1393
+ CXX11CodePrinter,
1394
+ '(0.88600000000000001 - 0.318*std::log(-8.1489999999999991*v_M_tilde '
1395
+ '- 0.374 + std::sqrt(1 + std::pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1396
+ ),
1397
+ (
1398
+ CXX17CodePrinter,
1399
+ '(0.88600000000000001 - 0.318*std::log(-8.1489999999999991*v_M_tilde '
1400
+ '- 0.374 + std::sqrt(1 + std::pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1401
+ ),
1402
+ (
1403
+ FCodePrinter,
1404
+ ' (0.886d0 - 0.318d0*log(-8.1489999999999991d0*v_M_tilde - 0.374d0 +\n'
1405
+ ' @ sqrt(1.0d0 + (-8.149d0*v_M_tilde - 0.374d0)**2)))',
1406
+ ),
1407
+ (
1408
+ OctaveCodePrinter,
1409
+ '(0.886 - 0.318*log(-8.149*v_M_tilde - 0.374 '
1410
+ '+ sqrt(1 + (-8.149*v_M_tilde - 0.374).^2)))',
1411
+ ),
1412
+ (
1413
+ PythonCodePrinter,
1414
+ '(0.886 - 0.318*math.log(-8.149*v_M_tilde - 0.374 '
1415
+ '+ math.sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1416
+ ),
1417
+ (
1418
+ NumPyPrinter,
1419
+ '(0.886 - 0.318*numpy.log(-8.149*v_M_tilde - 0.374 '
1420
+ '+ numpy.sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1421
+ ),
1422
+ (
1423
+ SciPyPrinter,
1424
+ '(0.886 - 0.318*numpy.log(-8.149*v_M_tilde - 0.374 '
1425
+ '+ numpy.sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1426
+ ),
1427
+ (
1428
+ CuPyPrinter,
1429
+ '(0.886 - 0.318*cupy.log(-8.149*v_M_tilde - 0.374 '
1430
+ '+ cupy.sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1431
+ ),
1432
+ (
1433
+ JaxPrinter,
1434
+ '(0.886 - 0.318*jax.numpy.log(-8.149*v_M_tilde - 0.374 '
1435
+ '+ jax.numpy.sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1436
+ ),
1437
+ (
1438
+ MpmathPrinter,
1439
+ '(mpmath.mpf((0, 7980378539700519, -53, 53)) '
1440
+ '- mpmath.mpf((0, 5728578726015271, -54, 53))'
1441
+ '*mpmath.log(-mpmath.mpf((0, 4587479170430271, -49, 53))*v_M_tilde '
1442
+ '+ mpmath.mpf((1, 3368692521273131, -53, 52)) '
1443
+ '+ mpmath.sqrt(1 + (-mpmath.mpf((0, 4587479170430271, -49, 53))*v_M_tilde '
1444
+ '+ mpmath.mpf((1, 3368692521273131, -53, 52)))**2)))',
1445
+ ),
1446
+ (
1447
+ LambdaPrinter,
1448
+ '(0.886 - 0.318*math.log(-8.149*v_M_tilde - 0.374 '
1449
+ '+ sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1450
+ ),
1451
+ ]
1452
+ )
1453
+ def test_print_code(self, code_printer, expected):
1454
+ fv_M = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1455
+ assert code_printer().doprint(fv_M) == expected
1456
+
1457
+ def test_derivative_print_code(self):
1458
+ fv_M = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1459
+ dfv_M_dv_M_tilde = fv_M.diff(self.v_M_tilde)
1460
+ expected = '2.591382*(1 + (-8.149*v_M_tilde - 0.374)**2)**(-1/2)'
1461
+ assert PythonCodePrinter().doprint(dfv_M_dv_M_tilde) == expected
1462
+
1463
+ def test_lambdify(self):
1464
+ fv_M = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1465
+ fv_M_callable = lambdify(self.v_M_tilde, fv_M)
1466
+ assert fv_M_callable(0.0) == pytest.approx(1.002320622548512)
1467
+
1468
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
1469
+ def test_lambdify_numpy(self):
1470
+ fv_M = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1471
+ fv_M_callable = lambdify(self.v_M_tilde, fv_M, 'numpy')
1472
+ v_M_tilde = numpy.array([-1.0, -0.5, 0.0, 0.5])
1473
+ expected = numpy.array([
1474
+ 0.0120816781,
1475
+ 0.2438336294,
1476
+ 1.0023206225,
1477
+ 1.5850003903,
1478
+ ])
1479
+ numpy.testing.assert_allclose(fv_M_callable(v_M_tilde), expected)
1480
+
1481
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
1482
+ def test_lambdify_jax(self):
1483
+ fv_M = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1484
+ fv_M_callable = jax.jit(lambdify(self.v_M_tilde, fv_M, 'jax'))
1485
+ v_M_tilde = jax.numpy.array([-1.0, -0.5, 0.0, 0.5])
1486
+ expected = jax.numpy.array([
1487
+ 0.0120816781,
1488
+ 0.2438336294,
1489
+ 1.0023206225,
1490
+ 1.5850003903,
1491
+ ])
1492
+ numpy.testing.assert_allclose(fv_M_callable(v_M_tilde), expected)
1493
+
1494
+
1495
+ class TestFiberForceVelocityInverseDeGroote2016:
1496
+
1497
+ @pytest.fixture(autouse=True)
1498
+ def _tendon_force_length_inverse_arguments_fixture(self):
1499
+ self.fv_M = Symbol('fv_M')
1500
+ self.c0 = Symbol('c_0')
1501
+ self.c1 = Symbol('c_1')
1502
+ self.c2 = Symbol('c_2')
1503
+ self.c3 = Symbol('c_3')
1504
+ self.constants = (self.c0, self.c1, self.c2, self.c3)
1505
+
1506
+ @staticmethod
1507
+ def test_class():
1508
+ assert issubclass(FiberForceVelocityInverseDeGroote2016, Function)
1509
+ assert issubclass(FiberForceVelocityInverseDeGroote2016, CharacteristicCurveFunction)
1510
+ assert FiberForceVelocityInverseDeGroote2016.__name__ == 'FiberForceVelocityInverseDeGroote2016'
1511
+
1512
+ def test_instance(self):
1513
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1514
+ assert isinstance(fv_M_inv, FiberForceVelocityInverseDeGroote2016)
1515
+ assert str(fv_M_inv) == 'FiberForceVelocityInverseDeGroote2016(fv_M, c_0, c_1, c_2, c_3)'
1516
+
1517
+ def test_doit(self):
1518
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants).doit()
1519
+ assert fv_M_inv == (sinh((self.fv_M - self.c3)/self.c0) - self.c2)/self.c1
1520
+
1521
+ def test_doit_evaluate_false(self):
1522
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants).doit(evaluate=False)
1523
+ assert fv_M_inv == (sinh(UnevaluatedExpr(self.fv_M - self.c3)/self.c0) - self.c2)/self.c1
1524
+
1525
+ def test_with_defaults(self):
1526
+ constants = (
1527
+ Float('-0.318'),
1528
+ Float('-8.149'),
1529
+ Float('-0.374'),
1530
+ Float('0.886'),
1531
+ )
1532
+ fv_M_inv_manual = FiberForceVelocityInverseDeGroote2016(self.fv_M, *constants)
1533
+ fv_M_inv_constants = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1534
+ assert fv_M_inv_manual == fv_M_inv_constants
1535
+
1536
+ def test_differentiate_wrt_fv_M(self):
1537
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1538
+ expected = cosh((self.fv_M - self.c3)/self.c0)/(self.c0*self.c1)
1539
+ assert fv_M_inv.diff(self.fv_M) == expected
1540
+
1541
+ def test_differentiate_wrt_c0(self):
1542
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1543
+ expected = (self.c3 - self.fv_M)*cosh((self.fv_M - self.c3)/self.c0)/(self.c0**2*self.c1)
1544
+ assert fv_M_inv.diff(self.c0) == expected
1545
+
1546
+ def test_differentiate_wrt_c1(self):
1547
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1548
+ expected = (self.c2 - sinh((self.fv_M - self.c3)/self.c0))/self.c1**2
1549
+ assert fv_M_inv.diff(self.c1) == expected
1550
+
1551
+ def test_differentiate_wrt_c2(self):
1552
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1553
+ expected = -1/self.c1
1554
+ assert fv_M_inv.diff(self.c2) == expected
1555
+
1556
+ def test_differentiate_wrt_c3(self):
1557
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1558
+ expected = -cosh((self.fv_M - self.c3)/self.c0)/(self.c0*self.c1)
1559
+ assert fv_M_inv.diff(self.c3) == expected
1560
+
1561
+ def test_inverse(self):
1562
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1563
+ assert fv_M_inv.inverse() is FiberForceVelocityDeGroote2016
1564
+
1565
+ def test_function_print_latex(self):
1566
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1567
+ expected = r'\left( \operatorname{fv}^M \right)^{-1} \left( fv_{M} \right)'
1568
+ assert LatexPrinter().doprint(fv_M_inv) == expected
1569
+
1570
+ def test_expression_print_latex(self):
1571
+ fv_M = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1572
+ expected = r'\frac{- c_{2} + \sinh{\left(\frac{- c_{3} + fv_{M}}{c_{0}} \right)}}{c_{1}}'
1573
+ assert LatexPrinter().doprint(fv_M.doit()) == expected
1574
+
1575
+ @pytest.mark.parametrize(
1576
+ 'code_printer, expected',
1577
+ [
1578
+ (
1579
+ C89CodePrinter,
1580
+ '(-0.12271444348999878*(0.374 - sinh(3.1446540880503142*(fv_M '
1581
+ '- 0.88600000000000001))))',
1582
+ ),
1583
+ (
1584
+ C99CodePrinter,
1585
+ '(-0.12271444348999878*(0.374 - sinh(3.1446540880503142*(fv_M '
1586
+ '- 0.88600000000000001))))',
1587
+ ),
1588
+ (
1589
+ C11CodePrinter,
1590
+ '(-0.12271444348999878*(0.374 - sinh(3.1446540880503142*(fv_M '
1591
+ '- 0.88600000000000001))))',
1592
+ ),
1593
+ (
1594
+ CXX98CodePrinter,
1595
+ '(-0.12271444348999878*(0.374 - sinh(3.1446540880503142*(fv_M '
1596
+ '- 0.88600000000000001))))',
1597
+ ),
1598
+ (
1599
+ CXX11CodePrinter,
1600
+ '(-0.12271444348999878*(0.374 - std::sinh(3.1446540880503142'
1601
+ '*(fv_M - 0.88600000000000001))))',
1602
+ ),
1603
+ (
1604
+ CXX17CodePrinter,
1605
+ '(-0.12271444348999878*(0.374 - std::sinh(3.1446540880503142'
1606
+ '*(fv_M - 0.88600000000000001))))',
1607
+ ),
1608
+ (
1609
+ FCodePrinter,
1610
+ ' (-0.122714443489999d0*(0.374d0 - sinh(3.1446540880503142d0*(fv_M -\n'
1611
+ ' @ 0.886d0))))',
1612
+ ),
1613
+ (
1614
+ OctaveCodePrinter,
1615
+ '(-0.122714443489999*(0.374 - sinh(3.14465408805031*(fv_M '
1616
+ '- 0.886))))',
1617
+ ),
1618
+ (
1619
+ PythonCodePrinter,
1620
+ '(-0.122714443489999*(0.374 - math.sinh(3.14465408805031*(fv_M '
1621
+ '- 0.886))))',
1622
+ ),
1623
+ (
1624
+ NumPyPrinter,
1625
+ '(-0.122714443489999*(0.374 - numpy.sinh(3.14465408805031'
1626
+ '*(fv_M - 0.886))))',
1627
+ ),
1628
+ (
1629
+ SciPyPrinter,
1630
+ '(-0.122714443489999*(0.374 - numpy.sinh(3.14465408805031'
1631
+ '*(fv_M - 0.886))))',
1632
+ ),
1633
+ (
1634
+ CuPyPrinter,
1635
+ '(-0.122714443489999*(0.374 - cupy.sinh(3.14465408805031*(fv_M '
1636
+ '- 0.886))))',
1637
+ ),
1638
+ (
1639
+ JaxPrinter,
1640
+ '(-0.122714443489999*(0.374 - jax.numpy.sinh(3.14465408805031'
1641
+ '*(fv_M - 0.886))))',
1642
+ ),
1643
+ (
1644
+ MpmathPrinter,
1645
+ '(-mpmath.mpf((0, 8842507551592581, -56, 53))*(mpmath.mpf((0, '
1646
+ '3368692521273131, -53, 52)) - mpmath.sinh(mpmath.mpf((0, '
1647
+ '7081131489576251, -51, 53))*(fv_M + mpmath.mpf((1, '
1648
+ '7980378539700519, -53, 53))))))',
1649
+ ),
1650
+ (
1651
+ LambdaPrinter,
1652
+ '(-0.122714443489999*(0.374 - math.sinh(3.14465408805031*(fv_M '
1653
+ '- 0.886))))',
1654
+ ),
1655
+ ]
1656
+ )
1657
+ def test_print_code(self, code_printer, expected):
1658
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1659
+ assert code_printer().doprint(fv_M_inv) == expected
1660
+
1661
+ def test_derivative_print_code(self):
1662
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1663
+ dfv_M_inv_dfv_M = fv_M_inv.diff(self.fv_M)
1664
+ expected = (
1665
+ '0.385894476383644*math.cosh(3.14465408805031*fv_M '
1666
+ '- 2.78616352201258)'
1667
+ )
1668
+ assert PythonCodePrinter().doprint(dfv_M_inv_dfv_M) == expected
1669
+
1670
+ def test_lambdify(self):
1671
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1672
+ fv_M_inv_callable = lambdify(self.fv_M, fv_M_inv)
1673
+ assert fv_M_inv_callable(1.0) == pytest.approx(-0.0009548832444487479)
1674
+
1675
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
1676
+ def test_lambdify_numpy(self):
1677
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1678
+ fv_M_inv_callable = lambdify(self.fv_M, fv_M_inv, 'numpy')
1679
+ fv_M = numpy.array([0.8, 0.9, 1.0, 1.1, 1.2])
1680
+ expected = numpy.array([
1681
+ -0.0794881459,
1682
+ -0.0404909338,
1683
+ -0.0009548832,
1684
+ 0.043061991,
1685
+ 0.0959484397,
1686
+ ])
1687
+ numpy.testing.assert_allclose(fv_M_inv_callable(fv_M), expected)
1688
+
1689
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
1690
+ def test_lambdify_jax(self):
1691
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1692
+ fv_M_inv_callable = jax.jit(lambdify(self.fv_M, fv_M_inv, 'jax'))
1693
+ fv_M = jax.numpy.array([0.8, 0.9, 1.0, 1.1, 1.2])
1694
+ expected = jax.numpy.array([
1695
+ -0.0794881459,
1696
+ -0.0404909338,
1697
+ -0.0009548832,
1698
+ 0.043061991,
1699
+ 0.0959484397,
1700
+ ])
1701
+ numpy.testing.assert_allclose(fv_M_inv_callable(fv_M), expected)
1702
+
1703
+
1704
+ class TestCharacteristicCurveCollection:
1705
+
1706
+ @staticmethod
1707
+ def test_valid_constructor():
1708
+ curves = CharacteristicCurveCollection(
1709
+ tendon_force_length=TendonForceLengthDeGroote2016,
1710
+ tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
1711
+ fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
1712
+ fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
1713
+ fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
1714
+ fiber_force_velocity=FiberForceVelocityDeGroote2016,
1715
+ fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
1716
+ )
1717
+ assert curves.tendon_force_length is TendonForceLengthDeGroote2016
1718
+ assert curves.tendon_force_length_inverse is TendonForceLengthInverseDeGroote2016
1719
+ assert curves.fiber_force_length_passive is FiberForceLengthPassiveDeGroote2016
1720
+ assert curves.fiber_force_length_passive_inverse is FiberForceLengthPassiveInverseDeGroote2016
1721
+ assert curves.fiber_force_length_active is FiberForceLengthActiveDeGroote2016
1722
+ assert curves.fiber_force_velocity is FiberForceVelocityDeGroote2016
1723
+ assert curves.fiber_force_velocity_inverse is FiberForceVelocityInverseDeGroote2016
1724
+
1725
+ @staticmethod
1726
+ @pytest.mark.skip(reason='kw_only dataclasses only valid in Python >3.10')
1727
+ def test_invalid_constructor_keyword_only():
1728
+ with pytest.raises(TypeError):
1729
+ _ = CharacteristicCurveCollection(
1730
+ TendonForceLengthDeGroote2016,
1731
+ TendonForceLengthInverseDeGroote2016,
1732
+ FiberForceLengthPassiveDeGroote2016,
1733
+ FiberForceLengthPassiveInverseDeGroote2016,
1734
+ FiberForceLengthActiveDeGroote2016,
1735
+ FiberForceVelocityDeGroote2016,
1736
+ FiberForceVelocityInverseDeGroote2016,
1737
+ )
1738
+
1739
+ @staticmethod
1740
+ @pytest.mark.parametrize(
1741
+ 'kwargs',
1742
+ [
1743
+ {'tendon_force_length': TendonForceLengthDeGroote2016},
1744
+ {
1745
+ 'tendon_force_length': TendonForceLengthDeGroote2016,
1746
+ 'tendon_force_length_inverse': TendonForceLengthInverseDeGroote2016,
1747
+ 'fiber_force_length_passive': FiberForceLengthPassiveDeGroote2016,
1748
+ 'fiber_force_length_passive_inverse': FiberForceLengthPassiveInverseDeGroote2016,
1749
+ 'fiber_force_length_active': FiberForceLengthActiveDeGroote2016,
1750
+ 'fiber_force_velocity': FiberForceVelocityDeGroote2016,
1751
+ 'fiber_force_velocity_inverse': FiberForceVelocityInverseDeGroote2016,
1752
+ 'extra_kwarg': None,
1753
+ },
1754
+ ]
1755
+ )
1756
+ def test_invalid_constructor_wrong_number_args(kwargs):
1757
+ with pytest.raises(TypeError):
1758
+ _ = CharacteristicCurveCollection(**kwargs)
1759
+
1760
+ @staticmethod
1761
+ def test_instance_is_immutable():
1762
+ curves = CharacteristicCurveCollection(
1763
+ tendon_force_length=TendonForceLengthDeGroote2016,
1764
+ tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
1765
+ fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
1766
+ fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
1767
+ fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
1768
+ fiber_force_velocity=FiberForceVelocityDeGroote2016,
1769
+ fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
1770
+ )
1771
+ with pytest.raises(AttributeError):
1772
+ curves.tendon_force_length = None
1773
+ with pytest.raises(AttributeError):
1774
+ curves.tendon_force_length_inverse = None
1775
+ with pytest.raises(AttributeError):
1776
+ curves.fiber_force_length_passive = None
1777
+ with pytest.raises(AttributeError):
1778
+ curves.fiber_force_length_passive_inverse = None
1779
+ with pytest.raises(AttributeError):
1780
+ curves.fiber_force_length_active = None
1781
+ with pytest.raises(AttributeError):
1782
+ curves.fiber_force_velocity = None
1783
+ with pytest.raises(AttributeError):
1784
+ curves.fiber_force_velocity_inverse = None
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_mixin.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``sympy.physics.biomechanics._mixin.py`` module."""
2
+
3
+ import pytest
4
+
5
+ from sympy.physics.biomechanics._mixin import _NamedMixin
6
+
7
+
8
+ class TestNamedMixin:
9
+
10
+ @staticmethod
11
+ def test_subclass():
12
+
13
+ class Subclass(_NamedMixin):
14
+
15
+ def __init__(self, name):
16
+ self.name = name
17
+
18
+ instance = Subclass('name')
19
+ assert instance.name == 'name'
20
+
21
+ @pytest.fixture(autouse=True)
22
+ def _named_mixin_fixture(self):
23
+
24
+ class Subclass(_NamedMixin):
25
+
26
+ def __init__(self, name):
27
+ self.name = name
28
+
29
+ self.Subclass = Subclass
30
+
31
+ @pytest.mark.parametrize('name', ['a', 'name', 'long_name'])
32
+ def test_valid_name_argument(self, name):
33
+ instance = self.Subclass(name)
34
+ assert instance.name == name
35
+
36
+ @pytest.mark.parametrize('invalid_name', [0, 0.0, None, False])
37
+ def test_invalid_name_argument_not_str(self, invalid_name):
38
+ with pytest.raises(TypeError):
39
+ _ = self.Subclass(invalid_name)
40
+
41
+ def test_invalid_name_argument_zero_length_str(self):
42
+ with pytest.raises(ValueError):
43
+ _ = self.Subclass('')
44
+
45
+ def test_name_attribute_is_immutable(self):
46
+ instance = self.Subclass('name')
47
+ with pytest.raises(AttributeError):
48
+ instance.name = 'new_name'
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_musculotendon.py ADDED
@@ -0,0 +1,837 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``sympy.physics.biomechanics.musculotendon.py`` module."""
2
+
3
+ import abc
4
+
5
+ import pytest
6
+
7
+ from sympy.core.expr import UnevaluatedExpr
8
+ from sympy.core.numbers import Float, Integer, Rational
9
+ from sympy.core.symbol import Symbol
10
+ from sympy.functions.elementary.exponential import exp
11
+ from sympy.functions.elementary.hyperbolic import tanh
12
+ from sympy.functions.elementary.miscellaneous import sqrt
13
+ from sympy.functions.elementary.trigonometric import sin
14
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix, eye, zeros
15
+ from sympy.physics.biomechanics.activation import (
16
+ FirstOrderActivationDeGroote2016
17
+ )
18
+ from sympy.physics.biomechanics.curve import (
19
+ CharacteristicCurveCollection,
20
+ FiberForceLengthActiveDeGroote2016,
21
+ FiberForceLengthPassiveDeGroote2016,
22
+ FiberForceLengthPassiveInverseDeGroote2016,
23
+ FiberForceVelocityDeGroote2016,
24
+ FiberForceVelocityInverseDeGroote2016,
25
+ TendonForceLengthDeGroote2016,
26
+ TendonForceLengthInverseDeGroote2016,
27
+ )
28
+ from sympy.physics.biomechanics.musculotendon import (
29
+ MusculotendonBase,
30
+ MusculotendonDeGroote2016,
31
+ MusculotendonFormulation,
32
+ )
33
+ from sympy.physics.biomechanics._mixin import _NamedMixin
34
+ from sympy.physics.mechanics.actuator import ForceActuator
35
+ from sympy.physics.mechanics.pathway import LinearPathway
36
+ from sympy.physics.vector.frame import ReferenceFrame
37
+ from sympy.physics.vector.functions import dynamicsymbols
38
+ from sympy.physics.vector.point import Point
39
+ from sympy.simplify.simplify import simplify
40
+
41
+
42
+ class TestMusculotendonFormulation:
43
+ @staticmethod
44
+ def test_rigid_tendon_member():
45
+ assert MusculotendonFormulation(0) == 0
46
+ assert MusculotendonFormulation.RIGID_TENDON == 0
47
+
48
+ @staticmethod
49
+ def test_fiber_length_explicit_member():
50
+ assert MusculotendonFormulation(1) == 1
51
+ assert MusculotendonFormulation.FIBER_LENGTH_EXPLICIT == 1
52
+
53
+ @staticmethod
54
+ def test_tendon_force_explicit_member():
55
+ assert MusculotendonFormulation(2) == 2
56
+ assert MusculotendonFormulation.TENDON_FORCE_EXPLICIT == 2
57
+
58
+ @staticmethod
59
+ def test_fiber_length_implicit_member():
60
+ assert MusculotendonFormulation(3) == 3
61
+ assert MusculotendonFormulation.FIBER_LENGTH_IMPLICIT == 3
62
+
63
+ @staticmethod
64
+ def test_tendon_force_implicit_member():
65
+ assert MusculotendonFormulation(4) == 4
66
+ assert MusculotendonFormulation.TENDON_FORCE_IMPLICIT == 4
67
+
68
+
69
+ class TestMusculotendonBase:
70
+
71
+ @staticmethod
72
+ def test_is_abstract_base_class():
73
+ assert issubclass(MusculotendonBase, abc.ABC)
74
+
75
+ @staticmethod
76
+ def test_class():
77
+ assert issubclass(MusculotendonBase, ForceActuator)
78
+ assert issubclass(MusculotendonBase, _NamedMixin)
79
+ assert MusculotendonBase.__name__ == 'MusculotendonBase'
80
+
81
+ @staticmethod
82
+ def test_cannot_instantiate_directly():
83
+ with pytest.raises(TypeError):
84
+ _ = MusculotendonBase()
85
+
86
+
87
+ @pytest.mark.parametrize('musculotendon_concrete', [MusculotendonDeGroote2016])
88
+ class TestMusculotendonRigidTendon:
89
+
90
+ @pytest.fixture(autouse=True)
91
+ def _musculotendon_rigid_tendon_fixture(self, musculotendon_concrete):
92
+ self.name = 'name'
93
+ self.N = ReferenceFrame('N')
94
+ self.q = dynamicsymbols('q')
95
+ self.origin = Point('pO')
96
+ self.insertion = Point('pI')
97
+ self.insertion.set_pos(self.origin, self.q*self.N.x)
98
+ self.pathway = LinearPathway(self.origin, self.insertion)
99
+ self.activation = FirstOrderActivationDeGroote2016(self.name)
100
+ self.e = self.activation.excitation
101
+ self.a = self.activation.activation
102
+ self.tau_a = self.activation.activation_time_constant
103
+ self.tau_d = self.activation.deactivation_time_constant
104
+ self.b = self.activation.smoothing_rate
105
+ self.formulation = MusculotendonFormulation.RIGID_TENDON
106
+ self.l_T_slack = Symbol('l_T_slack')
107
+ self.F_M_max = Symbol('F_M_max')
108
+ self.l_M_opt = Symbol('l_M_opt')
109
+ self.v_M_max = Symbol('v_M_max')
110
+ self.alpha_opt = Symbol('alpha_opt')
111
+ self.beta = Symbol('beta')
112
+ self.instance = musculotendon_concrete(
113
+ self.name,
114
+ self.pathway,
115
+ self.activation,
116
+ musculotendon_dynamics=self.formulation,
117
+ tendon_slack_length=self.l_T_slack,
118
+ peak_isometric_force=self.F_M_max,
119
+ optimal_fiber_length=self.l_M_opt,
120
+ maximal_fiber_velocity=self.v_M_max,
121
+ optimal_pennation_angle=self.alpha_opt,
122
+ fiber_damping_coefficient=self.beta,
123
+ )
124
+ self.da_expr = (
125
+ (1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
126
+ *(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
127
+ + ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
128
+ *(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a)))
129
+ )*(self.e - self.a)
130
+
131
+ def test_state_vars(self):
132
+ assert hasattr(self.instance, 'x')
133
+ assert hasattr(self.instance, 'state_vars')
134
+ assert self.instance.x == self.instance.state_vars
135
+ x_expected = Matrix([self.a])
136
+ assert self.instance.x == x_expected
137
+ assert self.instance.state_vars == x_expected
138
+ assert isinstance(self.instance.x, Matrix)
139
+ assert isinstance(self.instance.state_vars, Matrix)
140
+ assert self.instance.x.shape == (1, 1)
141
+ assert self.instance.state_vars.shape == (1, 1)
142
+
143
+ def test_input_vars(self):
144
+ assert hasattr(self.instance, 'r')
145
+ assert hasattr(self.instance, 'input_vars')
146
+ assert self.instance.r == self.instance.input_vars
147
+ r_expected = Matrix([self.e])
148
+ assert self.instance.r == r_expected
149
+ assert self.instance.input_vars == r_expected
150
+ assert isinstance(self.instance.r, Matrix)
151
+ assert isinstance(self.instance.input_vars, Matrix)
152
+ assert self.instance.r.shape == (1, 1)
153
+ assert self.instance.input_vars.shape == (1, 1)
154
+
155
+ def test_constants(self):
156
+ assert hasattr(self.instance, 'p')
157
+ assert hasattr(self.instance, 'constants')
158
+ assert self.instance.p == self.instance.constants
159
+ p_expected = Matrix(
160
+ [
161
+ self.l_T_slack,
162
+ self.F_M_max,
163
+ self.l_M_opt,
164
+ self.v_M_max,
165
+ self.alpha_opt,
166
+ self.beta,
167
+ self.tau_a,
168
+ self.tau_d,
169
+ self.b,
170
+ Symbol('c_0_fl_T_name'),
171
+ Symbol('c_1_fl_T_name'),
172
+ Symbol('c_2_fl_T_name'),
173
+ Symbol('c_3_fl_T_name'),
174
+ Symbol('c_0_fl_M_pas_name'),
175
+ Symbol('c_1_fl_M_pas_name'),
176
+ Symbol('c_0_fl_M_act_name'),
177
+ Symbol('c_1_fl_M_act_name'),
178
+ Symbol('c_2_fl_M_act_name'),
179
+ Symbol('c_3_fl_M_act_name'),
180
+ Symbol('c_4_fl_M_act_name'),
181
+ Symbol('c_5_fl_M_act_name'),
182
+ Symbol('c_6_fl_M_act_name'),
183
+ Symbol('c_7_fl_M_act_name'),
184
+ Symbol('c_8_fl_M_act_name'),
185
+ Symbol('c_9_fl_M_act_name'),
186
+ Symbol('c_10_fl_M_act_name'),
187
+ Symbol('c_11_fl_M_act_name'),
188
+ Symbol('c_0_fv_M_name'),
189
+ Symbol('c_1_fv_M_name'),
190
+ Symbol('c_2_fv_M_name'),
191
+ Symbol('c_3_fv_M_name'),
192
+ ]
193
+ )
194
+ assert self.instance.p == p_expected
195
+ assert self.instance.constants == p_expected
196
+ assert isinstance(self.instance.p, Matrix)
197
+ assert isinstance(self.instance.constants, Matrix)
198
+ assert self.instance.p.shape == (31, 1)
199
+ assert self.instance.constants.shape == (31, 1)
200
+
201
+ def test_M(self):
202
+ assert hasattr(self.instance, 'M')
203
+ M_expected = Matrix([1])
204
+ assert self.instance.M == M_expected
205
+ assert isinstance(self.instance.M, Matrix)
206
+ assert self.instance.M.shape == (1, 1)
207
+
208
+ def test_F(self):
209
+ assert hasattr(self.instance, 'F')
210
+ F_expected = Matrix([self.da_expr])
211
+ assert self.instance.F == F_expected
212
+ assert isinstance(self.instance.F, Matrix)
213
+ assert self.instance.F.shape == (1, 1)
214
+
215
+ def test_rhs(self):
216
+ assert hasattr(self.instance, 'rhs')
217
+ rhs_expected = Matrix([self.da_expr])
218
+ rhs = self.instance.rhs()
219
+ assert isinstance(rhs, Matrix)
220
+ assert rhs.shape == (1, 1)
221
+ assert simplify(rhs - rhs_expected) == zeros(1)
222
+
223
+
224
+ @pytest.mark.parametrize(
225
+ 'musculotendon_concrete, curve',
226
+ [
227
+ (
228
+ MusculotendonDeGroote2016,
229
+ CharacteristicCurveCollection(
230
+ tendon_force_length=TendonForceLengthDeGroote2016,
231
+ tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
232
+ fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
233
+ fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
234
+ fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
235
+ fiber_force_velocity=FiberForceVelocityDeGroote2016,
236
+ fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
237
+ ),
238
+ )
239
+ ],
240
+ )
241
+ class TestFiberLengthExplicit:
242
+
243
+ @pytest.fixture(autouse=True)
244
+ def _musculotendon_fiber_length_explicit_fixture(
245
+ self,
246
+ musculotendon_concrete,
247
+ curve,
248
+ ):
249
+ self.name = 'name'
250
+ self.N = ReferenceFrame('N')
251
+ self.q = dynamicsymbols('q')
252
+ self.origin = Point('pO')
253
+ self.insertion = Point('pI')
254
+ self.insertion.set_pos(self.origin, self.q*self.N.x)
255
+ self.pathway = LinearPathway(self.origin, self.insertion)
256
+ self.activation = FirstOrderActivationDeGroote2016(self.name)
257
+ self.e = self.activation.excitation
258
+ self.a = self.activation.activation
259
+ self.tau_a = self.activation.activation_time_constant
260
+ self.tau_d = self.activation.deactivation_time_constant
261
+ self.b = self.activation.smoothing_rate
262
+ self.formulation = MusculotendonFormulation.FIBER_LENGTH_EXPLICIT
263
+ self.l_T_slack = Symbol('l_T_slack')
264
+ self.F_M_max = Symbol('F_M_max')
265
+ self.l_M_opt = Symbol('l_M_opt')
266
+ self.v_M_max = Symbol('v_M_max')
267
+ self.alpha_opt = Symbol('alpha_opt')
268
+ self.beta = Symbol('beta')
269
+ self.instance = musculotendon_concrete(
270
+ self.name,
271
+ self.pathway,
272
+ self.activation,
273
+ musculotendon_dynamics=self.formulation,
274
+ tendon_slack_length=self.l_T_slack,
275
+ peak_isometric_force=self.F_M_max,
276
+ optimal_fiber_length=self.l_M_opt,
277
+ maximal_fiber_velocity=self.v_M_max,
278
+ optimal_pennation_angle=self.alpha_opt,
279
+ fiber_damping_coefficient=self.beta,
280
+ with_defaults=True,
281
+ )
282
+ self.l_M_tilde = dynamicsymbols('l_M_tilde_name')
283
+ l_MT = self.pathway.length
284
+ l_M = self.l_M_tilde*self.l_M_opt
285
+ l_T = l_MT - sqrt(l_M**2 - (self.l_M_opt*sin(self.alpha_opt))**2)
286
+ fl_T = curve.tendon_force_length.with_defaults(l_T/self.l_T_slack)
287
+ fl_M_pas = curve.fiber_force_length_passive.with_defaults(self.l_M_tilde)
288
+ fl_M_act = curve.fiber_force_length_active.with_defaults(self.l_M_tilde)
289
+ v_M_tilde = curve.fiber_force_velocity_inverse.with_defaults(
290
+ ((((fl_T*self.F_M_max)/((l_MT - l_T)/l_M))/self.F_M_max) - fl_M_pas)
291
+ /(self.a*fl_M_act)
292
+ )
293
+ self.dl_M_tilde_expr = (self.v_M_max/self.l_M_opt)*v_M_tilde
294
+ self.da_expr = (
295
+ (1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
296
+ *(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
297
+ + ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
298
+ *(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a)))
299
+ )*(self.e - self.a)
300
+
301
+ def test_state_vars(self):
302
+ assert hasattr(self.instance, 'x')
303
+ assert hasattr(self.instance, 'state_vars')
304
+ assert self.instance.x == self.instance.state_vars
305
+ x_expected = Matrix([self.l_M_tilde, self.a])
306
+ assert self.instance.x == x_expected
307
+ assert self.instance.state_vars == x_expected
308
+ assert isinstance(self.instance.x, Matrix)
309
+ assert isinstance(self.instance.state_vars, Matrix)
310
+ assert self.instance.x.shape == (2, 1)
311
+ assert self.instance.state_vars.shape == (2, 1)
312
+
313
+ def test_input_vars(self):
314
+ assert hasattr(self.instance, 'r')
315
+ assert hasattr(self.instance, 'input_vars')
316
+ assert self.instance.r == self.instance.input_vars
317
+ r_expected = Matrix([self.e])
318
+ assert self.instance.r == r_expected
319
+ assert self.instance.input_vars == r_expected
320
+ assert isinstance(self.instance.r, Matrix)
321
+ assert isinstance(self.instance.input_vars, Matrix)
322
+ assert self.instance.r.shape == (1, 1)
323
+ assert self.instance.input_vars.shape == (1, 1)
324
+
325
+ def test_constants(self):
326
+ assert hasattr(self.instance, 'p')
327
+ assert hasattr(self.instance, 'constants')
328
+ assert self.instance.p == self.instance.constants
329
+ p_expected = Matrix(
330
+ [
331
+ self.l_T_slack,
332
+ self.F_M_max,
333
+ self.l_M_opt,
334
+ self.v_M_max,
335
+ self.alpha_opt,
336
+ self.beta,
337
+ self.tau_a,
338
+ self.tau_d,
339
+ self.b,
340
+ ]
341
+ )
342
+ assert self.instance.p == p_expected
343
+ assert self.instance.constants == p_expected
344
+ assert isinstance(self.instance.p, Matrix)
345
+ assert isinstance(self.instance.constants, Matrix)
346
+ assert self.instance.p.shape == (9, 1)
347
+ assert self.instance.constants.shape == (9, 1)
348
+
349
+ def test_M(self):
350
+ assert hasattr(self.instance, 'M')
351
+ M_expected = eye(2)
352
+ assert self.instance.M == M_expected
353
+ assert isinstance(self.instance.M, Matrix)
354
+ assert self.instance.M.shape == (2, 2)
355
+
356
+ def test_F(self):
357
+ assert hasattr(self.instance, 'F')
358
+ F_expected = Matrix([self.dl_M_tilde_expr, self.da_expr])
359
+ assert self.instance.F == F_expected
360
+ assert isinstance(self.instance.F, Matrix)
361
+ assert self.instance.F.shape == (2, 1)
362
+
363
+ def test_rhs(self):
364
+ assert hasattr(self.instance, 'rhs')
365
+ rhs_expected = Matrix([self.dl_M_tilde_expr, self.da_expr])
366
+ rhs = self.instance.rhs()
367
+ assert isinstance(rhs, Matrix)
368
+ assert rhs.shape == (2, 1)
369
+ assert simplify(rhs - rhs_expected) == zeros(2, 1)
370
+
371
+
372
+ @pytest.mark.parametrize(
373
+ 'musculotendon_concrete, curve',
374
+ [
375
+ (
376
+ MusculotendonDeGroote2016,
377
+ CharacteristicCurveCollection(
378
+ tendon_force_length=TendonForceLengthDeGroote2016,
379
+ tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
380
+ fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
381
+ fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
382
+ fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
383
+ fiber_force_velocity=FiberForceVelocityDeGroote2016,
384
+ fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
385
+ ),
386
+ )
387
+ ],
388
+ )
389
+ class TestTendonForceExplicit:
390
+
391
+ @pytest.fixture(autouse=True)
392
+ def _musculotendon_tendon_force_explicit_fixture(
393
+ self,
394
+ musculotendon_concrete,
395
+ curve,
396
+ ):
397
+ self.name = 'name'
398
+ self.N = ReferenceFrame('N')
399
+ self.q = dynamicsymbols('q')
400
+ self.origin = Point('pO')
401
+ self.insertion = Point('pI')
402
+ self.insertion.set_pos(self.origin, self.q*self.N.x)
403
+ self.pathway = LinearPathway(self.origin, self.insertion)
404
+ self.activation = FirstOrderActivationDeGroote2016(self.name)
405
+ self.e = self.activation.excitation
406
+ self.a = self.activation.activation
407
+ self.tau_a = self.activation.activation_time_constant
408
+ self.tau_d = self.activation.deactivation_time_constant
409
+ self.b = self.activation.smoothing_rate
410
+ self.formulation = MusculotendonFormulation.TENDON_FORCE_EXPLICIT
411
+ self.l_T_slack = Symbol('l_T_slack')
412
+ self.F_M_max = Symbol('F_M_max')
413
+ self.l_M_opt = Symbol('l_M_opt')
414
+ self.v_M_max = Symbol('v_M_max')
415
+ self.alpha_opt = Symbol('alpha_opt')
416
+ self.beta = Symbol('beta')
417
+ self.instance = musculotendon_concrete(
418
+ self.name,
419
+ self.pathway,
420
+ self.activation,
421
+ musculotendon_dynamics=self.formulation,
422
+ tendon_slack_length=self.l_T_slack,
423
+ peak_isometric_force=self.F_M_max,
424
+ optimal_fiber_length=self.l_M_opt,
425
+ maximal_fiber_velocity=self.v_M_max,
426
+ optimal_pennation_angle=self.alpha_opt,
427
+ fiber_damping_coefficient=self.beta,
428
+ with_defaults=True,
429
+ )
430
+ self.F_T_tilde = dynamicsymbols('F_T_tilde_name')
431
+ l_T_tilde = curve.tendon_force_length_inverse.with_defaults(self.F_T_tilde)
432
+ l_MT = self.pathway.length
433
+ v_MT = self.pathway.extension_velocity
434
+ l_T = l_T_tilde*self.l_T_slack
435
+ l_M = sqrt((l_MT - l_T)**2 + (self.l_M_opt*sin(self.alpha_opt))**2)
436
+ l_M_tilde = l_M/self.l_M_opt
437
+ cos_alpha = (l_MT - l_T)/l_M
438
+ F_T = self.F_T_tilde*self.F_M_max
439
+ F_M = F_T/cos_alpha
440
+ F_M_tilde = F_M/self.F_M_max
441
+ fl_M_pas = curve.fiber_force_length_passive.with_defaults(l_M_tilde)
442
+ fl_M_act = curve.fiber_force_length_active.with_defaults(l_M_tilde)
443
+ fv_M = (F_M_tilde - fl_M_pas)/(self.a*fl_M_act)
444
+ v_M_tilde = curve.fiber_force_velocity_inverse.with_defaults(fv_M)
445
+ v_M = v_M_tilde*self.v_M_max
446
+ v_T = v_MT - v_M/cos_alpha
447
+ v_T_tilde = v_T/self.l_T_slack
448
+ self.dF_T_tilde_expr = (
449
+ Float('0.2')*Float('33.93669377311689')*exp(
450
+ Float('33.93669377311689')*UnevaluatedExpr(l_T_tilde - Float('0.995'))
451
+ )*v_T_tilde
452
+ )
453
+ self.da_expr = (
454
+ (1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
455
+ *(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
456
+ + ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
457
+ *(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a)))
458
+ )*(self.e - self.a)
459
+
460
+ def test_state_vars(self):
461
+ assert hasattr(self.instance, 'x')
462
+ assert hasattr(self.instance, 'state_vars')
463
+ assert self.instance.x == self.instance.state_vars
464
+ x_expected = Matrix([self.F_T_tilde, self.a])
465
+ assert self.instance.x == x_expected
466
+ assert self.instance.state_vars == x_expected
467
+ assert isinstance(self.instance.x, Matrix)
468
+ assert isinstance(self.instance.state_vars, Matrix)
469
+ assert self.instance.x.shape == (2, 1)
470
+ assert self.instance.state_vars.shape == (2, 1)
471
+
472
+ def test_input_vars(self):
473
+ assert hasattr(self.instance, 'r')
474
+ assert hasattr(self.instance, 'input_vars')
475
+ assert self.instance.r == self.instance.input_vars
476
+ r_expected = Matrix([self.e])
477
+ assert self.instance.r == r_expected
478
+ assert self.instance.input_vars == r_expected
479
+ assert isinstance(self.instance.r, Matrix)
480
+ assert isinstance(self.instance.input_vars, Matrix)
481
+ assert self.instance.r.shape == (1, 1)
482
+ assert self.instance.input_vars.shape == (1, 1)
483
+
484
+ def test_constants(self):
485
+ assert hasattr(self.instance, 'p')
486
+ assert hasattr(self.instance, 'constants')
487
+ assert self.instance.p == self.instance.constants
488
+ p_expected = Matrix(
489
+ [
490
+ self.l_T_slack,
491
+ self.F_M_max,
492
+ self.l_M_opt,
493
+ self.v_M_max,
494
+ self.alpha_opt,
495
+ self.beta,
496
+ self.tau_a,
497
+ self.tau_d,
498
+ self.b,
499
+ ]
500
+ )
501
+ assert self.instance.p == p_expected
502
+ assert self.instance.constants == p_expected
503
+ assert isinstance(self.instance.p, Matrix)
504
+ assert isinstance(self.instance.constants, Matrix)
505
+ assert self.instance.p.shape == (9, 1)
506
+ assert self.instance.constants.shape == (9, 1)
507
+
508
+ def test_M(self):
509
+ assert hasattr(self.instance, 'M')
510
+ M_expected = eye(2)
511
+ assert self.instance.M == M_expected
512
+ assert isinstance(self.instance.M, Matrix)
513
+ assert self.instance.M.shape == (2, 2)
514
+
515
+ def test_F(self):
516
+ assert hasattr(self.instance, 'F')
517
+ F_expected = Matrix([self.dF_T_tilde_expr, self.da_expr])
518
+ assert self.instance.F == F_expected
519
+ assert isinstance(self.instance.F, Matrix)
520
+ assert self.instance.F.shape == (2, 1)
521
+
522
+ def test_rhs(self):
523
+ assert hasattr(self.instance, 'rhs')
524
+ rhs_expected = Matrix([self.dF_T_tilde_expr, self.da_expr])
525
+ rhs = self.instance.rhs()
526
+ assert isinstance(rhs, Matrix)
527
+ assert rhs.shape == (2, 1)
528
+ assert simplify(rhs - rhs_expected) == zeros(2, 1)
529
+
530
+
531
+ class TestMusculotendonDeGroote2016:
532
+
533
+ @staticmethod
534
+ def test_class():
535
+ assert issubclass(MusculotendonDeGroote2016, ForceActuator)
536
+ assert issubclass(MusculotendonDeGroote2016, _NamedMixin)
537
+ assert MusculotendonDeGroote2016.__name__ == 'MusculotendonDeGroote2016'
538
+
539
+ @staticmethod
540
+ def test_instance():
541
+ origin = Point('pO')
542
+ insertion = Point('pI')
543
+ insertion.set_pos(origin, dynamicsymbols('q')*ReferenceFrame('N').x)
544
+ pathway = LinearPathway(origin, insertion)
545
+ activation = FirstOrderActivationDeGroote2016('name')
546
+ l_T_slack = Symbol('l_T_slack')
547
+ F_M_max = Symbol('F_M_max')
548
+ l_M_opt = Symbol('l_M_opt')
549
+ v_M_max = Symbol('v_M_max')
550
+ alpha_opt = Symbol('alpha_opt')
551
+ beta = Symbol('beta')
552
+ instance = MusculotendonDeGroote2016(
553
+ 'name',
554
+ pathway,
555
+ activation,
556
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
557
+ tendon_slack_length=l_T_slack,
558
+ peak_isometric_force=F_M_max,
559
+ optimal_fiber_length=l_M_opt,
560
+ maximal_fiber_velocity=v_M_max,
561
+ optimal_pennation_angle=alpha_opt,
562
+ fiber_damping_coefficient=beta,
563
+ )
564
+ assert isinstance(instance, MusculotendonDeGroote2016)
565
+
566
+ @pytest.fixture(autouse=True)
567
+ def _musculotendon_fixture(self):
568
+ self.name = 'name'
569
+ self.N = ReferenceFrame('N')
570
+ self.q = dynamicsymbols('q')
571
+ self.origin = Point('pO')
572
+ self.insertion = Point('pI')
573
+ self.insertion.set_pos(self.origin, self.q*self.N.x)
574
+ self.pathway = LinearPathway(self.origin, self.insertion)
575
+ self.activation = FirstOrderActivationDeGroote2016(self.name)
576
+ self.l_T_slack = Symbol('l_T_slack')
577
+ self.F_M_max = Symbol('F_M_max')
578
+ self.l_M_opt = Symbol('l_M_opt')
579
+ self.v_M_max = Symbol('v_M_max')
580
+ self.alpha_opt = Symbol('alpha_opt')
581
+ self.beta = Symbol('beta')
582
+
583
+ def test_with_defaults(self):
584
+ origin = Point('pO')
585
+ insertion = Point('pI')
586
+ insertion.set_pos(origin, dynamicsymbols('q')*ReferenceFrame('N').x)
587
+ pathway = LinearPathway(origin, insertion)
588
+ activation = FirstOrderActivationDeGroote2016('name')
589
+ l_T_slack = Symbol('l_T_slack')
590
+ F_M_max = Symbol('F_M_max')
591
+ l_M_opt = Symbol('l_M_opt')
592
+ v_M_max = Float('10.0')
593
+ alpha_opt = Float('0.0')
594
+ beta = Float('0.1')
595
+ instance = MusculotendonDeGroote2016.with_defaults(
596
+ 'name',
597
+ pathway,
598
+ activation,
599
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
600
+ tendon_slack_length=l_T_slack,
601
+ peak_isometric_force=F_M_max,
602
+ optimal_fiber_length=l_M_opt,
603
+ )
604
+ assert instance.tendon_slack_length == l_T_slack
605
+ assert instance.peak_isometric_force == F_M_max
606
+ assert instance.optimal_fiber_length == l_M_opt
607
+ assert instance.maximal_fiber_velocity == v_M_max
608
+ assert instance.optimal_pennation_angle == alpha_opt
609
+ assert instance.fiber_damping_coefficient == beta
610
+
611
+ @pytest.mark.parametrize(
612
+ 'l_T_slack, expected',
613
+ [
614
+ (None, Symbol('l_T_slack_name')),
615
+ (Symbol('l_T_slack'), Symbol('l_T_slack')),
616
+ (Rational(1, 2), Rational(1, 2)),
617
+ (Float('0.5'), Float('0.5')),
618
+ ],
619
+ )
620
+ def test_tendon_slack_length(self, l_T_slack, expected):
621
+ instance = MusculotendonDeGroote2016(
622
+ self.name,
623
+ self.pathway,
624
+ self.activation,
625
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
626
+ tendon_slack_length=l_T_slack,
627
+ peak_isometric_force=self.F_M_max,
628
+ optimal_fiber_length=self.l_M_opt,
629
+ maximal_fiber_velocity=self.v_M_max,
630
+ optimal_pennation_angle=self.alpha_opt,
631
+ fiber_damping_coefficient=self.beta,
632
+ )
633
+ assert instance.l_T_slack == expected
634
+ assert instance.tendon_slack_length == expected
635
+
636
+ @pytest.mark.parametrize(
637
+ 'F_M_max, expected',
638
+ [
639
+ (None, Symbol('F_M_max_name')),
640
+ (Symbol('F_M_max'), Symbol('F_M_max')),
641
+ (Integer(1000), Integer(1000)),
642
+ (Float('1000.0'), Float('1000.0')),
643
+ ],
644
+ )
645
+ def test_peak_isometric_force(self, F_M_max, expected):
646
+ instance = MusculotendonDeGroote2016(
647
+ self.name,
648
+ self.pathway,
649
+ self.activation,
650
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
651
+ tendon_slack_length=self.l_T_slack,
652
+ peak_isometric_force=F_M_max,
653
+ optimal_fiber_length=self.l_M_opt,
654
+ maximal_fiber_velocity=self.v_M_max,
655
+ optimal_pennation_angle=self.alpha_opt,
656
+ fiber_damping_coefficient=self.beta,
657
+ )
658
+ assert instance.F_M_max == expected
659
+ assert instance.peak_isometric_force == expected
660
+
661
+ @pytest.mark.parametrize(
662
+ 'l_M_opt, expected',
663
+ [
664
+ (None, Symbol('l_M_opt_name')),
665
+ (Symbol('l_M_opt'), Symbol('l_M_opt')),
666
+ (Rational(1, 2), Rational(1, 2)),
667
+ (Float('0.5'), Float('0.5')),
668
+ ],
669
+ )
670
+ def test_optimal_fiber_length(self, l_M_opt, expected):
671
+ instance = MusculotendonDeGroote2016(
672
+ self.name,
673
+ self.pathway,
674
+ self.activation,
675
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
676
+ tendon_slack_length=self.l_T_slack,
677
+ peak_isometric_force=self.F_M_max,
678
+ optimal_fiber_length=l_M_opt,
679
+ maximal_fiber_velocity=self.v_M_max,
680
+ optimal_pennation_angle=self.alpha_opt,
681
+ fiber_damping_coefficient=self.beta,
682
+ )
683
+ assert instance.l_M_opt == expected
684
+ assert instance.optimal_fiber_length == expected
685
+
686
+ @pytest.mark.parametrize(
687
+ 'v_M_max, expected',
688
+ [
689
+ (None, Symbol('v_M_max_name')),
690
+ (Symbol('v_M_max'), Symbol('v_M_max')),
691
+ (Integer(10), Integer(10)),
692
+ (Float('10.0'), Float('10.0')),
693
+ ],
694
+ )
695
+ def test_maximal_fiber_velocity(self, v_M_max, expected):
696
+ instance = MusculotendonDeGroote2016(
697
+ self.name,
698
+ self.pathway,
699
+ self.activation,
700
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
701
+ tendon_slack_length=self.l_T_slack,
702
+ peak_isometric_force=self.F_M_max,
703
+ optimal_fiber_length=self.l_M_opt,
704
+ maximal_fiber_velocity=v_M_max,
705
+ optimal_pennation_angle=self.alpha_opt,
706
+ fiber_damping_coefficient=self.beta,
707
+ )
708
+ assert instance.v_M_max == expected
709
+ assert instance.maximal_fiber_velocity == expected
710
+
711
+ @pytest.mark.parametrize(
712
+ 'alpha_opt, expected',
713
+ [
714
+ (None, Symbol('alpha_opt_name')),
715
+ (Symbol('alpha_opt'), Symbol('alpha_opt')),
716
+ (Integer(0), Integer(0)),
717
+ (Float('0.1'), Float('0.1')),
718
+ ],
719
+ )
720
+ def test_optimal_pennation_angle(self, alpha_opt, expected):
721
+ instance = MusculotendonDeGroote2016(
722
+ self.name,
723
+ self.pathway,
724
+ self.activation,
725
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
726
+ tendon_slack_length=self.l_T_slack,
727
+ peak_isometric_force=self.F_M_max,
728
+ optimal_fiber_length=self.l_M_opt,
729
+ maximal_fiber_velocity=self.v_M_max,
730
+ optimal_pennation_angle=alpha_opt,
731
+ fiber_damping_coefficient=self.beta,
732
+ )
733
+ assert instance.alpha_opt == expected
734
+ assert instance.optimal_pennation_angle == expected
735
+
736
+ @pytest.mark.parametrize(
737
+ 'beta, expected',
738
+ [
739
+ (None, Symbol('beta_name')),
740
+ (Symbol('beta'), Symbol('beta')),
741
+ (Integer(0), Integer(0)),
742
+ (Rational(1, 10), Rational(1, 10)),
743
+ (Float('0.1'), Float('0.1')),
744
+ ],
745
+ )
746
+ def test_fiber_damping_coefficient(self, beta, expected):
747
+ instance = MusculotendonDeGroote2016(
748
+ self.name,
749
+ self.pathway,
750
+ self.activation,
751
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
752
+ tendon_slack_length=self.l_T_slack,
753
+ peak_isometric_force=self.F_M_max,
754
+ optimal_fiber_length=self.l_M_opt,
755
+ maximal_fiber_velocity=self.v_M_max,
756
+ optimal_pennation_angle=self.alpha_opt,
757
+ fiber_damping_coefficient=beta,
758
+ )
759
+ assert instance.beta == expected
760
+ assert instance.fiber_damping_coefficient == expected
761
+
762
+ def test_excitation(self):
763
+ instance = MusculotendonDeGroote2016(
764
+ self.name,
765
+ self.pathway,
766
+ self.activation,
767
+ )
768
+ assert hasattr(instance, 'e')
769
+ assert hasattr(instance, 'excitation')
770
+ e_expected = dynamicsymbols('e_name')
771
+ assert instance.e == e_expected
772
+ assert instance.excitation == e_expected
773
+ assert instance.e is instance.excitation
774
+
775
+ def test_excitation_is_immutable(self):
776
+ instance = MusculotendonDeGroote2016(
777
+ self.name,
778
+ self.pathway,
779
+ self.activation,
780
+ )
781
+ with pytest.raises(AttributeError):
782
+ instance.e = None
783
+ with pytest.raises(AttributeError):
784
+ instance.excitation = None
785
+
786
+ def test_activation(self):
787
+ instance = MusculotendonDeGroote2016(
788
+ self.name,
789
+ self.pathway,
790
+ self.activation,
791
+ )
792
+ assert hasattr(instance, 'a')
793
+ assert hasattr(instance, 'activation')
794
+ a_expected = dynamicsymbols('a_name')
795
+ assert instance.a == a_expected
796
+ assert instance.activation == a_expected
797
+
798
+ def test_activation_is_immutable(self):
799
+ instance = MusculotendonDeGroote2016(
800
+ self.name,
801
+ self.pathway,
802
+ self.activation,
803
+ )
804
+ with pytest.raises(AttributeError):
805
+ instance.a = None
806
+ with pytest.raises(AttributeError):
807
+ instance.activation = None
808
+
809
+ def test_repr(self):
810
+ instance = MusculotendonDeGroote2016(
811
+ self.name,
812
+ self.pathway,
813
+ self.activation,
814
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
815
+ tendon_slack_length=self.l_T_slack,
816
+ peak_isometric_force=self.F_M_max,
817
+ optimal_fiber_length=self.l_M_opt,
818
+ maximal_fiber_velocity=self.v_M_max,
819
+ optimal_pennation_angle=self.alpha_opt,
820
+ fiber_damping_coefficient=self.beta,
821
+ )
822
+ expected = (
823
+ 'MusculotendonDeGroote2016(\'name\', '
824
+ 'pathway=LinearPathway(pO, pI), '
825
+ 'activation_dynamics=FirstOrderActivationDeGroote2016(\'name\', '
826
+ 'activation_time_constant=tau_a_name, '
827
+ 'deactivation_time_constant=tau_d_name, '
828
+ 'smoothing_rate=b_name), '
829
+ 'musculotendon_dynamics=0, '
830
+ 'tendon_slack_length=l_T_slack, '
831
+ 'peak_isometric_force=F_M_max, '
832
+ 'optimal_fiber_length=l_M_opt, '
833
+ 'maximal_fiber_velocity=v_M_max, '
834
+ 'optimal_pennation_angle=alpha_opt, '
835
+ 'fiber_damping_coefficient=beta)'
836
+ )
837
+ assert repr(instance) == expected
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (334 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/cable.cpython-310.pyc ADDED
Binary file (16.6 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (201 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-310.pyc ADDED
Binary file (21.6 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/control/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .lti import (TransferFunction, Series, MIMOSeries, Parallel, MIMOParallel,
2
+ Feedback, MIMOFeedback, TransferFunctionMatrix, StateSpace, gbt, bilinear, forward_diff,
3
+ backward_diff, phase_margin, gain_margin)
4
+ from .control_plots import (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
5
+ step_response_plot, impulse_response_numerical_data, impulse_response_plot, ramp_response_numerical_data,
6
+ ramp_response_plot, bode_magnitude_numerical_data, bode_phase_numerical_data, bode_magnitude_plot,
7
+ bode_phase_plot, bode_plot)
8
+
9
+ __all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel',
10
+ 'MIMOParallel', 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix', 'StateSpace',
11
+ 'gbt', 'bilinear', 'forward_diff', 'backward_diff', 'phase_margin', 'gain_margin',
12
+ 'pole_zero_numerical_data', 'pole_zero_plot', 'step_response_numerical_data',
13
+ 'step_response_plot', 'impulse_response_numerical_data', 'impulse_response_plot',
14
+ 'ramp_response_numerical_data', 'ramp_response_plot',
15
+ 'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
16
+ 'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/control/control_plots.py ADDED
@@ -0,0 +1,978 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import I, pi
2
+ from sympy.functions.elementary.exponential import (exp, log)
3
+ from sympy.polys.partfrac import apart
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.external import import_module
6
+ from sympy.functions import arg, Abs
7
+ from sympy.integrals.laplace import _fast_inverse_laplace
8
+ from sympy.physics.control.lti import SISOLinearTimeInvariant
9
+ from sympy.plotting.series import LineOver1DRangeSeries
10
+ from sympy.polys.polytools import Poly
11
+ from sympy.printing.latex import latex
12
+
13
+ __all__ = ['pole_zero_numerical_data', 'pole_zero_plot',
14
+ 'step_response_numerical_data', 'step_response_plot',
15
+ 'impulse_response_numerical_data', 'impulse_response_plot',
16
+ 'ramp_response_numerical_data', 'ramp_response_plot',
17
+ 'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
18
+ 'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
19
+
20
+ matplotlib = import_module(
21
+ 'matplotlib', import_kwargs={'fromlist': ['pyplot']},
22
+ catch=(RuntimeError,))
23
+
24
+ numpy = import_module('numpy')
25
+
26
+ if matplotlib:
27
+ plt = matplotlib.pyplot
28
+
29
+ if numpy:
30
+ np = numpy # Matplotlib already has numpy as a compulsory dependency. No need to install it separately.
31
+
32
+
33
+ def _check_system(system):
34
+ """Function to check whether the dynamical system passed for plots is
35
+ compatible or not."""
36
+ if not isinstance(system, SISOLinearTimeInvariant):
37
+ raise NotImplementedError("Only SISO LTI systems are currently supported.")
38
+ sys = system.to_expr()
39
+ len_free_symbols = len(sys.free_symbols)
40
+ if len_free_symbols > 1:
41
+ raise ValueError("Extra degree of freedom found. Make sure"
42
+ " that there are no free symbols in the dynamical system other"
43
+ " than the variable of Laplace transform.")
44
+ if sys.has(exp):
45
+ # Should test that exp is not part of a constant, in which case
46
+ # no exception is required, compare exp(s) with s*exp(1)
47
+ raise NotImplementedError("Time delay terms are not supported.")
48
+
49
+
50
+ def pole_zero_numerical_data(system):
51
+ """
52
+ Returns the numerical data of poles and zeros of the system.
53
+ It is internally used by ``pole_zero_plot`` to get the data
54
+ for plotting poles and zeros. Users can use this data to further
55
+ analyse the dynamics of the system or plot using a different
56
+ backend/plotting-module.
57
+
58
+ Parameters
59
+ ==========
60
+
61
+ system : SISOLinearTimeInvariant
62
+ The system for which the pole-zero data is to be computed.
63
+
64
+ Returns
65
+ =======
66
+
67
+ tuple : (zeros, poles)
68
+ zeros = Zeros of the system. NumPy array of complex numbers.
69
+ poles = Poles of the system. NumPy array of complex numbers.
70
+
71
+ Raises
72
+ ======
73
+
74
+ NotImplementedError
75
+ When a SISO LTI system is not passed.
76
+
77
+ When time delay terms are present in the system.
78
+
79
+ ValueError
80
+ When more than one free symbol is present in the system.
81
+ The only variable in the transfer function should be
82
+ the variable of the Laplace transform.
83
+
84
+ Examples
85
+ ========
86
+
87
+ >>> from sympy.abc import s
88
+ >>> from sympy.physics.control.lti import TransferFunction
89
+ >>> from sympy.physics.control.control_plots import pole_zero_numerical_data
90
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
91
+ >>> pole_zero_numerical_data(tf1) # doctest: +SKIP
92
+ ([-0.+1.j 0.-1.j], [-2. +0.j -0.5+0.8660254j -0.5-0.8660254j -1. +0.j ])
93
+
94
+ See Also
95
+ ========
96
+
97
+ pole_zero_plot
98
+
99
+ """
100
+ _check_system(system)
101
+ system = system.doit() # Get the equivalent TransferFunction object.
102
+
103
+ num_poly = Poly(system.num, system.var).all_coeffs()
104
+ den_poly = Poly(system.den, system.var).all_coeffs()
105
+
106
+ num_poly = np.array(num_poly, dtype=np.complex128)
107
+ den_poly = np.array(den_poly, dtype=np.complex128)
108
+
109
+ zeros = np.roots(num_poly)
110
+ poles = np.roots(den_poly)
111
+
112
+ return zeros, poles
113
+
114
+
115
+ def pole_zero_plot(system, pole_color='blue', pole_markersize=10,
116
+ zero_color='orange', zero_markersize=7, grid=True, show_axes=True,
117
+ show=True, **kwargs):
118
+ r"""
119
+ Returns the Pole-Zero plot (also known as PZ Plot or PZ Map) of a system.
120
+
121
+ A Pole-Zero plot is a graphical representation of a system's poles and
122
+ zeros. It is plotted on a complex plane, with circular markers representing
123
+ the system's zeros and 'x' shaped markers representing the system's poles.
124
+
125
+ Parameters
126
+ ==========
127
+
128
+ system : SISOLinearTimeInvariant type systems
129
+ The system for which the pole-zero plot is to be computed.
130
+ pole_color : str, tuple, optional
131
+ The color of the pole points on the plot. Default color
132
+ is blue. The color can be provided as a matplotlib color string,
133
+ or a 3-tuple of floats each in the 0-1 range.
134
+ pole_markersize : Number, optional
135
+ The size of the markers used to mark the poles in the plot.
136
+ Default pole markersize is 10.
137
+ zero_color : str, tuple, optional
138
+ The color of the zero points on the plot. Default color
139
+ is orange. The color can be provided as a matplotlib color string,
140
+ or a 3-tuple of floats each in the 0-1 range.
141
+ zero_markersize : Number, optional
142
+ The size of the markers used to mark the zeros in the plot.
143
+ Default zero markersize is 7.
144
+ grid : boolean, optional
145
+ If ``True``, the plot will have a grid. Defaults to True.
146
+ show_axes : boolean, optional
147
+ If ``True``, the coordinate axes will be shown. Defaults to False.
148
+ show : boolean, optional
149
+ If ``True``, the plot will be displayed otherwise
150
+ the equivalent matplotlib ``plot`` object will be returned.
151
+ Defaults to True.
152
+
153
+ Examples
154
+ ========
155
+
156
+ .. plot::
157
+ :context: close-figs
158
+ :format: doctest
159
+ :include-source: True
160
+
161
+ >>> from sympy.abc import s
162
+ >>> from sympy.physics.control.lti import TransferFunction
163
+ >>> from sympy.physics.control.control_plots import pole_zero_plot
164
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
165
+ >>> pole_zero_plot(tf1) # doctest: +SKIP
166
+
167
+ See Also
168
+ ========
169
+
170
+ pole_zero_numerical_data
171
+
172
+ References
173
+ ==========
174
+
175
+ .. [1] https://en.wikipedia.org/wiki/Pole%E2%80%93zero_plot
176
+
177
+ """
178
+ zeros, poles = pole_zero_numerical_data(system)
179
+
180
+ zero_real = np.real(zeros)
181
+ zero_imag = np.imag(zeros)
182
+
183
+ pole_real = np.real(poles)
184
+ pole_imag = np.imag(poles)
185
+
186
+ plt.plot(pole_real, pole_imag, 'x', mfc='none',
187
+ markersize=pole_markersize, color=pole_color)
188
+ plt.plot(zero_real, zero_imag, 'o', markersize=zero_markersize,
189
+ color=zero_color)
190
+ plt.xlabel('Real Axis')
191
+ plt.ylabel('Imaginary Axis')
192
+ plt.title(f'Poles and Zeros of ${latex(system)}$', pad=20)
193
+
194
+ if grid:
195
+ plt.grid()
196
+ if show_axes:
197
+ plt.axhline(0, color='black')
198
+ plt.axvline(0, color='black')
199
+ if show:
200
+ plt.show()
201
+ return
202
+
203
+ return plt
204
+
205
+
206
+ def step_response_numerical_data(system, prec=8, lower_limit=0,
207
+ upper_limit=10, **kwargs):
208
+ """
209
+ Returns the numerical values of the points in the step response plot
210
+ of a SISO continuous-time system. By default, adaptive sampling
211
+ is used. If the user wants to instead get an uniformly
212
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
213
+ and ``n`` must be passed as additional kwargs.
214
+ Refer to the parameters of class :class:`sympy.plotting.series.LineOver1DRangeSeries`
215
+ for more details.
216
+
217
+ Parameters
218
+ ==========
219
+
220
+ system : SISOLinearTimeInvariant
221
+ The system for which the unit step response data is to be computed.
222
+ prec : int, optional
223
+ The decimal point precision for the point coordinate values.
224
+ Defaults to 8.
225
+ lower_limit : Number, optional
226
+ The lower limit of the plot range. Defaults to 0.
227
+ upper_limit : Number, optional
228
+ The upper limit of the plot range. Defaults to 10.
229
+ kwargs :
230
+ Additional keyword arguments are passed to the underlying
231
+ :class:`sympy.plotting.series.LineOver1DRangeSeries` class.
232
+
233
+ Returns
234
+ =======
235
+
236
+ tuple : (x, y)
237
+ x = Time-axis values of the points in the step response. NumPy array.
238
+ y = Amplitude-axis values of the points in the step response. NumPy array.
239
+
240
+ Raises
241
+ ======
242
+
243
+ NotImplementedError
244
+ When a SISO LTI system is not passed.
245
+
246
+ When time delay terms are present in the system.
247
+
248
+ ValueError
249
+ When more than one free symbol is present in the system.
250
+ The only variable in the transfer function should be
251
+ the variable of the Laplace transform.
252
+
253
+ When ``lower_limit`` parameter is less than 0.
254
+
255
+ Examples
256
+ ========
257
+
258
+ >>> from sympy.abc import s
259
+ >>> from sympy.physics.control.lti import TransferFunction
260
+ >>> from sympy.physics.control.control_plots import step_response_numerical_data
261
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
262
+ >>> step_response_numerical_data(tf1) # doctest: +SKIP
263
+ ([0.0, 0.025413462339411542, 0.0484508722725343, ... , 9.670250533855183, 9.844291913708725, 10.0],
264
+ [0.0, 0.023844582399907256, 0.042894276802320226, ..., 6.828770759094287e-12, 6.456457160755703e-12])
265
+
266
+ See Also
267
+ ========
268
+
269
+ step_response_plot
270
+
271
+ """
272
+ if lower_limit < 0:
273
+ raise ValueError("Lower limit of time must be greater "
274
+ "than or equal to zero.")
275
+ _check_system(system)
276
+ _x = Dummy("x")
277
+ expr = system.to_expr()/(system.var)
278
+ expr = apart(expr, system.var, full=True)
279
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
280
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
281
+ **kwargs).get_points()
282
+
283
+
284
+ def step_response_plot(system, color='b', prec=8, lower_limit=0,
285
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
286
+ r"""
287
+ Returns the unit step response of a continuous-time system. It is
288
+ the response of the system when the input signal is a step function.
289
+
290
+ Parameters
291
+ ==========
292
+
293
+ system : SISOLinearTimeInvariant type
294
+ The LTI SISO system for which the Step Response is to be computed.
295
+ color : str, tuple, optional
296
+ The color of the line. Default is Blue.
297
+ show : boolean, optional
298
+ If ``True``, the plot will be displayed otherwise
299
+ the equivalent matplotlib ``plot`` object will be returned.
300
+ Defaults to True.
301
+ lower_limit : Number, optional
302
+ The lower limit of the plot range. Defaults to 0.
303
+ upper_limit : Number, optional
304
+ The upper limit of the plot range. Defaults to 10.
305
+ prec : int, optional
306
+ The decimal point precision for the point coordinate values.
307
+ Defaults to 8.
308
+ show_axes : boolean, optional
309
+ If ``True``, the coordinate axes will be shown. Defaults to False.
310
+ grid : boolean, optional
311
+ If ``True``, the plot will have a grid. Defaults to True.
312
+
313
+ Examples
314
+ ========
315
+
316
+ .. plot::
317
+ :context: close-figs
318
+ :format: doctest
319
+ :include-source: True
320
+
321
+ >>> from sympy.abc import s
322
+ >>> from sympy.physics.control.lti import TransferFunction
323
+ >>> from sympy.physics.control.control_plots import step_response_plot
324
+ >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
325
+ >>> step_response_plot(tf1) # doctest: +SKIP
326
+
327
+ See Also
328
+ ========
329
+
330
+ impulse_response_plot, ramp_response_plot
331
+
332
+ References
333
+ ==========
334
+
335
+ .. [1] https://www.mathworks.com/help/control/ref/lti.step.html
336
+
337
+ """
338
+ x, y = step_response_numerical_data(system, prec=prec,
339
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
340
+ plt.plot(x, y, color=color)
341
+ plt.xlabel('Time (s)')
342
+ plt.ylabel('Amplitude')
343
+ plt.title(f'Unit Step Response of ${latex(system)}$', pad=20)
344
+
345
+ if grid:
346
+ plt.grid()
347
+ if show_axes:
348
+ plt.axhline(0, color='black')
349
+ plt.axvline(0, color='black')
350
+ if show:
351
+ plt.show()
352
+ return
353
+
354
+ return plt
355
+
356
+
357
+ def impulse_response_numerical_data(system, prec=8, lower_limit=0,
358
+ upper_limit=10, **kwargs):
359
+ """
360
+ Returns the numerical values of the points in the impulse response plot
361
+ of a SISO continuous-time system. By default, adaptive sampling
362
+ is used. If the user wants to instead get an uniformly
363
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
364
+ and ``n`` must be passed as additional kwargs.
365
+ Refer to the parameters of class :class:`sympy.plotting.series.LineOver1DRangeSeries`
366
+ for more details.
367
+
368
+ Parameters
369
+ ==========
370
+
371
+ system : SISOLinearTimeInvariant
372
+ The system for which the impulse response data is to be computed.
373
+ prec : int, optional
374
+ The decimal point precision for the point coordinate values.
375
+ Defaults to 8.
376
+ lower_limit : Number, optional
377
+ The lower limit of the plot range. Defaults to 0.
378
+ upper_limit : Number, optional
379
+ The upper limit of the plot range. Defaults to 10.
380
+ kwargs :
381
+ Additional keyword arguments are passed to the underlying
382
+ :class:`sympy.plotting.series.LineOver1DRangeSeries` class.
383
+
384
+ Returns
385
+ =======
386
+
387
+ tuple : (x, y)
388
+ x = Time-axis values of the points in the impulse response. NumPy array.
389
+ y = Amplitude-axis values of the points in the impulse response. NumPy array.
390
+
391
+ Raises
392
+ ======
393
+
394
+ NotImplementedError
395
+ When a SISO LTI system is not passed.
396
+
397
+ When time delay terms are present in the system.
398
+
399
+ ValueError
400
+ When more than one free symbol is present in the system.
401
+ The only variable in the transfer function should be
402
+ the variable of the Laplace transform.
403
+
404
+ When ``lower_limit`` parameter is less than 0.
405
+
406
+ Examples
407
+ ========
408
+
409
+ >>> from sympy.abc import s
410
+ >>> from sympy.physics.control.lti import TransferFunction
411
+ >>> from sympy.physics.control.control_plots import impulse_response_numerical_data
412
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
413
+ >>> impulse_response_numerical_data(tf1) # doctest: +SKIP
414
+ ([0.0, 0.06616480200395854,... , 9.854500743565858, 10.0],
415
+ [0.9999999799999999, 0.7042848373025861,...,7.170748906965121e-13, -5.1901263495547205e-12])
416
+
417
+ See Also
418
+ ========
419
+
420
+ impulse_response_plot
421
+
422
+ """
423
+ if lower_limit < 0:
424
+ raise ValueError("Lower limit of time must be greater "
425
+ "than or equal to zero.")
426
+ _check_system(system)
427
+ _x = Dummy("x")
428
+ expr = system.to_expr()
429
+ expr = apart(expr, system.var, full=True)
430
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
431
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
432
+ **kwargs).get_points()
433
+
434
+
435
+ def impulse_response_plot(system, color='b', prec=8, lower_limit=0,
436
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
437
+ r"""
438
+ Returns the unit impulse response (Input is the Dirac-Delta Function) of a
439
+ continuous-time system.
440
+
441
+ Parameters
442
+ ==========
443
+
444
+ system : SISOLinearTimeInvariant type
445
+ The LTI SISO system for which the Impulse Response is to be computed.
446
+ color : str, tuple, optional
447
+ The color of the line. Default is Blue.
448
+ show : boolean, optional
449
+ If ``True``, the plot will be displayed otherwise
450
+ the equivalent matplotlib ``plot`` object will be returned.
451
+ Defaults to True.
452
+ lower_limit : Number, optional
453
+ The lower limit of the plot range. Defaults to 0.
454
+ upper_limit : Number, optional
455
+ The upper limit of the plot range. Defaults to 10.
456
+ prec : int, optional
457
+ The decimal point precision for the point coordinate values.
458
+ Defaults to 8.
459
+ show_axes : boolean, optional
460
+ If ``True``, the coordinate axes will be shown. Defaults to False.
461
+ grid : boolean, optional
462
+ If ``True``, the plot will have a grid. Defaults to True.
463
+
464
+ Examples
465
+ ========
466
+
467
+ .. plot::
468
+ :context: close-figs
469
+ :format: doctest
470
+ :include-source: True
471
+
472
+ >>> from sympy.abc import s
473
+ >>> from sympy.physics.control.lti import TransferFunction
474
+ >>> from sympy.physics.control.control_plots import impulse_response_plot
475
+ >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
476
+ >>> impulse_response_plot(tf1) # doctest: +SKIP
477
+
478
+ See Also
479
+ ========
480
+
481
+ step_response_plot, ramp_response_plot
482
+
483
+ References
484
+ ==========
485
+
486
+ .. [1] https://www.mathworks.com/help/control/ref/dynamicsystem.impulse.html
487
+
488
+ """
489
+ x, y = impulse_response_numerical_data(system, prec=prec,
490
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
491
+ plt.plot(x, y, color=color)
492
+ plt.xlabel('Time (s)')
493
+ plt.ylabel('Amplitude')
494
+ plt.title(f'Impulse Response of ${latex(system)}$', pad=20)
495
+
496
+ if grid:
497
+ plt.grid()
498
+ if show_axes:
499
+ plt.axhline(0, color='black')
500
+ plt.axvline(0, color='black')
501
+ if show:
502
+ plt.show()
503
+ return
504
+
505
+ return plt
506
+
507
+
508
+ def ramp_response_numerical_data(system, slope=1, prec=8,
509
+ lower_limit=0, upper_limit=10, **kwargs):
510
+ """
511
+ Returns the numerical values of the points in the ramp response plot
512
+ of a SISO continuous-time system. By default, adaptive sampling
513
+ is used. If the user wants to instead get an uniformly
514
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
515
+ and ``n`` must be passed as additional kwargs.
516
+ Refer to the parameters of class :class:`sympy.plotting.series.LineOver1DRangeSeries`
517
+ for more details.
518
+
519
+ Parameters
520
+ ==========
521
+
522
+ system : SISOLinearTimeInvariant
523
+ The system for which the ramp response data is to be computed.
524
+ slope : Number, optional
525
+ The slope of the input ramp function. Defaults to 1.
526
+ prec : int, optional
527
+ The decimal point precision for the point coordinate values.
528
+ Defaults to 8.
529
+ lower_limit : Number, optional
530
+ The lower limit of the plot range. Defaults to 0.
531
+ upper_limit : Number, optional
532
+ The upper limit of the plot range. Defaults to 10.
533
+ kwargs :
534
+ Additional keyword arguments are passed to the underlying
535
+ :class:`sympy.plotting.series.LineOver1DRangeSeries` class.
536
+
537
+ Returns
538
+ =======
539
+
540
+ tuple : (x, y)
541
+ x = Time-axis values of the points in the ramp response plot. NumPy array.
542
+ y = Amplitude-axis values of the points in the ramp response plot. NumPy array.
543
+
544
+ Raises
545
+ ======
546
+
547
+ NotImplementedError
548
+ When a SISO LTI system is not passed.
549
+
550
+ When time delay terms are present in the system.
551
+
552
+ ValueError
553
+ When more than one free symbol is present in the system.
554
+ The only variable in the transfer function should be
555
+ the variable of the Laplace transform.
556
+
557
+ When ``lower_limit`` parameter is less than 0.
558
+
559
+ When ``slope`` is negative.
560
+
561
+ Examples
562
+ ========
563
+
564
+ >>> from sympy.abc import s
565
+ >>> from sympy.physics.control.lti import TransferFunction
566
+ >>> from sympy.physics.control.control_plots import ramp_response_numerical_data
567
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
568
+ >>> ramp_response_numerical_data(tf1) # doctest: +SKIP
569
+ (([0.0, 0.12166980856813935,..., 9.861246379582118, 10.0],
570
+ [1.4504508011325967e-09, 0.006046440489058766,..., 0.12499999999568202, 0.12499999999661349]))
571
+
572
+ See Also
573
+ ========
574
+
575
+ ramp_response_plot
576
+
577
+ """
578
+ if slope < 0:
579
+ raise ValueError("Slope must be greater than or equal"
580
+ " to zero.")
581
+ if lower_limit < 0:
582
+ raise ValueError("Lower limit of time must be greater "
583
+ "than or equal to zero.")
584
+ _check_system(system)
585
+ _x = Dummy("x")
586
+ expr = (slope*system.to_expr())/((system.var)**2)
587
+ expr = apart(expr, system.var, full=True)
588
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
589
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
590
+ **kwargs).get_points()
591
+
592
+
593
+ def ramp_response_plot(system, slope=1, color='b', prec=8, lower_limit=0,
594
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
595
+ r"""
596
+ Returns the ramp response of a continuous-time system.
597
+
598
+ Ramp function is defined as the straight line
599
+ passing through origin ($f(x) = mx$). The slope of
600
+ the ramp function can be varied by the user and
601
+ the default value is 1.
602
+
603
+ Parameters
604
+ ==========
605
+
606
+ system : SISOLinearTimeInvariant type
607
+ The LTI SISO system for which the Ramp Response is to be computed.
608
+ slope : Number, optional
609
+ The slope of the input ramp function. Defaults to 1.
610
+ color : str, tuple, optional
611
+ The color of the line. Default is Blue.
612
+ show : boolean, optional
613
+ If ``True``, the plot will be displayed otherwise
614
+ the equivalent matplotlib ``plot`` object will be returned.
615
+ Defaults to True.
616
+ lower_limit : Number, optional
617
+ The lower limit of the plot range. Defaults to 0.
618
+ upper_limit : Number, optional
619
+ The upper limit of the plot range. Defaults to 10.
620
+ prec : int, optional
621
+ The decimal point precision for the point coordinate values.
622
+ Defaults to 8.
623
+ show_axes : boolean, optional
624
+ If ``True``, the coordinate axes will be shown. Defaults to False.
625
+ grid : boolean, optional
626
+ If ``True``, the plot will have a grid. Defaults to True.
627
+
628
+ Examples
629
+ ========
630
+
631
+ .. plot::
632
+ :context: close-figs
633
+ :format: doctest
634
+ :include-source: True
635
+
636
+ >>> from sympy.abc import s
637
+ >>> from sympy.physics.control.lti import TransferFunction
638
+ >>> from sympy.physics.control.control_plots import ramp_response_plot
639
+ >>> tf1 = TransferFunction(s, (s+4)*(s+8), s)
640
+ >>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP
641
+
642
+ See Also
643
+ ========
644
+
645
+ step_response_plot, impulse_response_plot
646
+
647
+ References
648
+ ==========
649
+
650
+ .. [1] https://en.wikipedia.org/wiki/Ramp_function
651
+
652
+ """
653
+ x, y = ramp_response_numerical_data(system, slope=slope, prec=prec,
654
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
655
+ plt.plot(x, y, color=color)
656
+ plt.xlabel('Time (s)')
657
+ plt.ylabel('Amplitude')
658
+ plt.title(f'Ramp Response of ${latex(system)}$ [Slope = {slope}]', pad=20)
659
+
660
+ if grid:
661
+ plt.grid()
662
+ if show_axes:
663
+ plt.axhline(0, color='black')
664
+ plt.axvline(0, color='black')
665
+ if show:
666
+ plt.show()
667
+ return
668
+
669
+ return plt
670
+
671
+
672
+ def bode_magnitude_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', **kwargs):
673
+ """
674
+ Returns the numerical data of the Bode magnitude plot of the system.
675
+ It is internally used by ``bode_magnitude_plot`` to get the data
676
+ for plotting Bode magnitude plot. Users can use this data to further
677
+ analyse the dynamics of the system or plot using a different
678
+ backend/plotting-module.
679
+
680
+ Parameters
681
+ ==========
682
+
683
+ system : SISOLinearTimeInvariant
684
+ The system for which the data is to be computed.
685
+ initial_exp : Number, optional
686
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
687
+ final_exp : Number, optional
688
+ The final exponent of 10 of the semilog plot. Defaults to 5.
689
+ freq_unit : string, optional
690
+ User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
691
+
692
+ Returns
693
+ =======
694
+
695
+ tuple : (x, y)
696
+ x = x-axis values of the Bode magnitude plot.
697
+ y = y-axis values of the Bode magnitude plot.
698
+
699
+ Raises
700
+ ======
701
+
702
+ NotImplementedError
703
+ When a SISO LTI system is not passed.
704
+
705
+ When time delay terms are present in the system.
706
+
707
+ ValueError
708
+ When more than one free symbol is present in the system.
709
+ The only variable in the transfer function should be
710
+ the variable of the Laplace transform.
711
+
712
+ When incorrect frequency units are given as input.
713
+
714
+ Examples
715
+ ========
716
+
717
+ >>> from sympy.abc import s
718
+ >>> from sympy.physics.control.lti import TransferFunction
719
+ >>> from sympy.physics.control.control_plots import bode_magnitude_numerical_data
720
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
721
+ >>> bode_magnitude_numerical_data(tf1) # doctest: +SKIP
722
+ ([1e-05, 1.5148378120533502e-05,..., 68437.36188804005, 100000.0],
723
+ [-6.020599914256786, -6.0205999155219505,..., -193.4117304087953, -200.00000000260573])
724
+
725
+ See Also
726
+ ========
727
+
728
+ bode_magnitude_plot, bode_phase_numerical_data
729
+
730
+ """
731
+ _check_system(system)
732
+ expr = system.to_expr()
733
+ freq_units = ('rad/sec', 'Hz')
734
+ if freq_unit not in freq_units:
735
+ raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
736
+
737
+ _w = Dummy("w", real=True)
738
+ if freq_unit == 'Hz':
739
+ repl = I*_w*2*pi
740
+ else:
741
+ repl = I*_w
742
+ w_expr = expr.subs({system.var: repl})
743
+
744
+ mag = 20*log(Abs(w_expr), 10)
745
+
746
+ x, y = LineOver1DRangeSeries(mag,
747
+ (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
748
+
749
+ return x, y
750
+
751
+
752
+ def bode_magnitude_plot(system, initial_exp=-5, final_exp=5,
753
+ color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', **kwargs):
754
+ r"""
755
+ Returns the Bode magnitude plot of a continuous-time system.
756
+
757
+ See ``bode_plot`` for all the parameters.
758
+ """
759
+ x, y = bode_magnitude_numerical_data(system, initial_exp=initial_exp,
760
+ final_exp=final_exp, freq_unit=freq_unit)
761
+ plt.plot(x, y, color=color, **kwargs)
762
+ plt.xscale('log')
763
+
764
+
765
+ plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
766
+ plt.ylabel('Magnitude (dB)')
767
+ plt.title(f'Bode Plot (Magnitude) of ${latex(system)}$', pad=20)
768
+
769
+ if grid:
770
+ plt.grid(True)
771
+ if show_axes:
772
+ plt.axhline(0, color='black')
773
+ plt.axvline(0, color='black')
774
+ if show:
775
+ plt.show()
776
+ return
777
+
778
+ return plt
779
+
780
+
781
+ def bode_phase_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', phase_unit='rad', phase_unwrap = True, **kwargs):
782
+ """
783
+ Returns the numerical data of the Bode phase plot of the system.
784
+ It is internally used by ``bode_phase_plot`` to get the data
785
+ for plotting Bode phase plot. Users can use this data to further
786
+ analyse the dynamics of the system or plot using a different
787
+ backend/plotting-module.
788
+
789
+ Parameters
790
+ ==========
791
+
792
+ system : SISOLinearTimeInvariant
793
+ The system for which the Bode phase plot data is to be computed.
794
+ initial_exp : Number, optional
795
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
796
+ final_exp : Number, optional
797
+ The final exponent of 10 of the semilog plot. Defaults to 5.
798
+ freq_unit : string, optional
799
+ User can choose between ``'rad/sec'`` (radians/second) and '``'Hz'`` (Hertz) as frequency units.
800
+ phase_unit : string, optional
801
+ User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
802
+ phase_unwrap : bool, optional
803
+ Set to ``True`` by default.
804
+
805
+ Returns
806
+ =======
807
+
808
+ tuple : (x, y)
809
+ x = x-axis values of the Bode phase plot.
810
+ y = y-axis values of the Bode phase plot.
811
+
812
+ Raises
813
+ ======
814
+
815
+ NotImplementedError
816
+ When a SISO LTI system is not passed.
817
+
818
+ When time delay terms are present in the system.
819
+
820
+ ValueError
821
+ When more than one free symbol is present in the system.
822
+ The only variable in the transfer function should be
823
+ the variable of the Laplace transform.
824
+
825
+ When incorrect frequency or phase units are given as input.
826
+
827
+ Examples
828
+ ========
829
+
830
+ >>> from sympy.abc import s
831
+ >>> from sympy.physics.control.lti import TransferFunction
832
+ >>> from sympy.physics.control.control_plots import bode_phase_numerical_data
833
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
834
+ >>> bode_phase_numerical_data(tf1) # doctest: +SKIP
835
+ ([1e-05, 1.4472354033813751e-05, 2.035581932165858e-05,..., 47577.3248186011, 67884.09326036123, 100000.0],
836
+ [-2.5000000000291665e-05, -3.6180885085e-05, -5.08895483066e-05,...,-3.1415085799262523, -3.14155265358979])
837
+
838
+ See Also
839
+ ========
840
+
841
+ bode_magnitude_plot, bode_phase_numerical_data
842
+
843
+ """
844
+ _check_system(system)
845
+ expr = system.to_expr()
846
+ freq_units = ('rad/sec', 'Hz')
847
+ phase_units = ('rad', 'deg')
848
+ if freq_unit not in freq_units:
849
+ raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
850
+ if phase_unit not in phase_units:
851
+ raise ValueError('Only "rad" and "deg" are accepted phase units.')
852
+
853
+ _w = Dummy("w", real=True)
854
+ if freq_unit == 'Hz':
855
+ repl = I*_w*2*pi
856
+ else:
857
+ repl = I*_w
858
+ w_expr = expr.subs({system.var: repl})
859
+
860
+ if phase_unit == 'deg':
861
+ phase = arg(w_expr)*180/pi
862
+ else:
863
+ phase = arg(w_expr)
864
+
865
+ x, y = LineOver1DRangeSeries(phase,
866
+ (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
867
+
868
+ half = None
869
+ if phase_unwrap:
870
+ if(phase_unit == 'rad'):
871
+ half = pi
872
+ elif(phase_unit == 'deg'):
873
+ half = 180
874
+ if half:
875
+ unit = 2*half
876
+ for i in range(1, len(y)):
877
+ diff = y[i] - y[i - 1]
878
+ if diff > half: # Jump from -half to half
879
+ y[i] = (y[i] - unit)
880
+ elif diff < -half: # Jump from half to -half
881
+ y[i] = (y[i] + unit)
882
+
883
+ return x, y
884
+
885
+
886
+ def bode_phase_plot(system, initial_exp=-5, final_exp=5,
887
+ color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', phase_unit='rad', phase_unwrap=True, **kwargs):
888
+ r"""
889
+ Returns the Bode phase plot of a continuous-time system.
890
+
891
+ See ``bode_plot`` for all the parameters.
892
+ """
893
+ x, y = bode_phase_numerical_data(system, initial_exp=initial_exp,
894
+ final_exp=final_exp, freq_unit=freq_unit, phase_unit=phase_unit, phase_unwrap=phase_unwrap)
895
+ plt.plot(x, y, color=color, **kwargs)
896
+ plt.xscale('log')
897
+
898
+ plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
899
+ plt.ylabel('Phase (%s)' % phase_unit)
900
+ plt.title(f'Bode Plot (Phase) of ${latex(system)}$', pad=20)
901
+
902
+ if grid:
903
+ plt.grid(True)
904
+ if show_axes:
905
+ plt.axhline(0, color='black')
906
+ plt.axvline(0, color='black')
907
+ if show:
908
+ plt.show()
909
+ return
910
+
911
+ return plt
912
+
913
+
914
+ def bode_plot(system, initial_exp=-5, final_exp=5,
915
+ grid=True, show_axes=False, show=True, freq_unit='rad/sec', phase_unit='rad', phase_unwrap=True, **kwargs):
916
+ r"""
917
+ Returns the Bode phase and magnitude plots of a continuous-time system.
918
+
919
+ Parameters
920
+ ==========
921
+
922
+ system : SISOLinearTimeInvariant type
923
+ The LTI SISO system for which the Bode Plot is to be computed.
924
+ initial_exp : Number, optional
925
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
926
+ final_exp : Number, optional
927
+ The final exponent of 10 of the semilog plot. Defaults to 5.
928
+ show : boolean, optional
929
+ If ``True``, the plot will be displayed otherwise
930
+ the equivalent matplotlib ``plot`` object will be returned.
931
+ Defaults to True.
932
+ prec : int, optional
933
+ The decimal point precision for the point coordinate values.
934
+ Defaults to 8.
935
+ grid : boolean, optional
936
+ If ``True``, the plot will have a grid. Defaults to True.
937
+ show_axes : boolean, optional
938
+ If ``True``, the coordinate axes will be shown. Defaults to False.
939
+ freq_unit : string, optional
940
+ User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
941
+ phase_unit : string, optional
942
+ User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
943
+
944
+ Examples
945
+ ========
946
+
947
+ .. plot::
948
+ :context: close-figs
949
+ :format: doctest
950
+ :include-source: True
951
+
952
+ >>> from sympy.abc import s
953
+ >>> from sympy.physics.control.lti import TransferFunction
954
+ >>> from sympy.physics.control.control_plots import bode_plot
955
+ >>> tf1 = TransferFunction(1*s**2 + 0.1*s + 7.5, 1*s**4 + 0.12*s**3 + 9*s**2, s)
956
+ >>> bode_plot(tf1, initial_exp=0.2, final_exp=0.7) # doctest: +SKIP
957
+
958
+ See Also
959
+ ========
960
+
961
+ bode_magnitude_plot, bode_phase_plot
962
+
963
+ """
964
+ plt.subplot(211)
965
+ mag = bode_magnitude_plot(system, initial_exp=initial_exp, final_exp=final_exp,
966
+ show=False, grid=grid, show_axes=show_axes,
967
+ freq_unit=freq_unit, **kwargs)
968
+ mag.title(f'Bode Plot of ${latex(system)}$', pad=20)
969
+ mag.xlabel(None)
970
+ plt.subplot(212)
971
+ bode_phase_plot(system, initial_exp=initial_exp, final_exp=final_exp,
972
+ show=False, grid=grid, show_axes=show_axes, freq_unit=freq_unit, phase_unit=phase_unit, phase_unwrap=phase_unwrap, **kwargs).title(None)
973
+
974
+ if show:
975
+ plt.show()
976
+ return
977
+
978
+ return plt
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/control/lti.py ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/control/tests/__init__.py ADDED
File without changes
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/control/tests/test_control_plots.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import isclose
2
+ from sympy.core.numbers import I
3
+ from sympy.core.symbol import Dummy
4
+ from sympy.functions.elementary.complexes import (Abs, arg)
5
+ from sympy.functions.elementary.exponential import log
6
+ from sympy.abc import s, p, a
7
+ from sympy.external import import_module
8
+ from sympy.physics.control.control_plots import \
9
+ (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
10
+ step_response_plot, impulse_response_numerical_data,
11
+ impulse_response_plot, ramp_response_numerical_data,
12
+ ramp_response_plot, bode_magnitude_numerical_data,
13
+ bode_phase_numerical_data, bode_plot)
14
+ from sympy.physics.control.lti import (TransferFunction,
15
+ Series, Parallel, TransferFunctionMatrix)
16
+ from sympy.testing.pytest import raises, skip
17
+
18
+ matplotlib = import_module(
19
+ 'matplotlib', import_kwargs={'fromlist': ['pyplot']},
20
+ catch=(RuntimeError,))
21
+
22
+ numpy = import_module('numpy')
23
+
24
+ tf1 = TransferFunction(1, p**2 + 0.5*p + 2, p)
25
+ tf2 = TransferFunction(p, 6*p**2 + 3*p + 1, p)
26
+ tf3 = TransferFunction(p, p**3 - 1, p)
27
+ tf4 = TransferFunction(10, p**3, p)
28
+ tf5 = TransferFunction(5, s**2 + 2*s + 10, s)
29
+ tf6 = TransferFunction(1, 1, s)
30
+ tf7 = TransferFunction(4*s*3 + 9*s**2 + 0.1*s + 11, 8*s**6 + 9*s**4 + 11, s)
31
+ tf8 = TransferFunction(5, s**2 + (2+I)*s + 10, s)
32
+
33
+ ser1 = Series(tf4, TransferFunction(1, p - 5, p))
34
+ ser2 = Series(tf3, TransferFunction(p, p + 2, p))
35
+
36
+ par1 = Parallel(tf1, tf2)
37
+
38
+
39
+ def _to_tuple(a, b):
40
+ return tuple(a), tuple(b)
41
+
42
+ def _trim_tuple(a, b):
43
+ a, b = _to_tuple(a, b)
44
+ return tuple(a[0: 2] + a[len(a)//2 : len(a)//2 + 1] + a[-2:]), \
45
+ tuple(b[0: 2] + b[len(b)//2 : len(b)//2 + 1] + b[-2:])
46
+
47
+ def y_coordinate_equality(plot_data_func, evalf_func, system):
48
+ """Checks whether the y-coordinate value of the plotted
49
+ data point is equal to the value of the function at a
50
+ particular x."""
51
+ x, y = plot_data_func(system)
52
+ x, y = _trim_tuple(x, y)
53
+ y_exp = tuple(evalf_func(system, x_i) for x_i in x)
54
+ return all(Abs(y_exp_i - y_i) < 1e-8 for y_exp_i, y_i in zip(y_exp, y))
55
+
56
+
57
+ def test_errors():
58
+ if not matplotlib:
59
+ skip("Matplotlib not the default backend")
60
+
61
+ # Invalid `system` check
62
+ tfm = TransferFunctionMatrix([[tf6, tf5], [tf5, tf6]])
63
+ expr = 1/(s**2 - 1)
64
+ raises(NotImplementedError, lambda: pole_zero_plot(tfm))
65
+ raises(NotImplementedError, lambda: pole_zero_numerical_data(expr))
66
+ raises(NotImplementedError, lambda: impulse_response_plot(expr))
67
+ raises(NotImplementedError, lambda: impulse_response_numerical_data(tfm))
68
+ raises(NotImplementedError, lambda: step_response_plot(tfm))
69
+ raises(NotImplementedError, lambda: step_response_numerical_data(expr))
70
+ raises(NotImplementedError, lambda: ramp_response_plot(expr))
71
+ raises(NotImplementedError, lambda: ramp_response_numerical_data(tfm))
72
+ raises(NotImplementedError, lambda: bode_plot(tfm))
73
+
74
+ # More than 1 variables
75
+ tf_a = TransferFunction(a, s + 1, s)
76
+ raises(ValueError, lambda: pole_zero_plot(tf_a))
77
+ raises(ValueError, lambda: pole_zero_numerical_data(tf_a))
78
+ raises(ValueError, lambda: impulse_response_plot(tf_a))
79
+ raises(ValueError, lambda: impulse_response_numerical_data(tf_a))
80
+ raises(ValueError, lambda: step_response_plot(tf_a))
81
+ raises(ValueError, lambda: step_response_numerical_data(tf_a))
82
+ raises(ValueError, lambda: ramp_response_plot(tf_a))
83
+ raises(ValueError, lambda: ramp_response_numerical_data(tf_a))
84
+ raises(ValueError, lambda: bode_plot(tf_a))
85
+
86
+ # lower_limit > 0 for response plots
87
+ raises(ValueError, lambda: impulse_response_plot(tf1, lower_limit=-1))
88
+ raises(ValueError, lambda: step_response_plot(tf1, lower_limit=-0.1))
89
+ raises(ValueError, lambda: ramp_response_plot(tf1, lower_limit=-4/3))
90
+
91
+ # slope in ramp_response_plot() is negative
92
+ raises(ValueError, lambda: ramp_response_plot(tf1, slope=-0.1))
93
+
94
+ # incorrect frequency or phase unit
95
+ raises(ValueError, lambda: bode_plot(tf1,freq_unit = 'hz'))
96
+ raises(ValueError, lambda: bode_plot(tf1,phase_unit = 'degree'))
97
+
98
+
99
+ def test_pole_zero():
100
+ if not numpy:
101
+ skip("NumPy is required for this test")
102
+
103
+ def pz_tester(sys, expected_value):
104
+ z, p = pole_zero_numerical_data(sys)
105
+ z_check = numpy.allclose(z, expected_value[0])
106
+ p_check = numpy.allclose(p, expected_value[1])
107
+ return p_check and z_check
108
+
109
+ exp1 = [[], [-0.24999999999999994+1.3919410907075054j, -0.24999999999999994-1.3919410907075054j]]
110
+ exp2 = [[0.0], [-0.25+0.3227486121839514j, -0.25-0.3227486121839514j]]
111
+ exp3 = [[0.0], [-0.5000000000000004+0.8660254037844395j,
112
+ -0.5000000000000004-0.8660254037844395j, 0.9999999999999998+0j]]
113
+ exp4 = [[], [5.0, 0.0, 0.0, 0.0]]
114
+ exp5 = [[-5.645751311064592, -0.5000000000000008, -0.3542486889354093],
115
+ [-0.24999999999999986+1.3919410907075052j,
116
+ -0.24999999999999986-1.3919410907075052j, -0.2499999999999998+0.32274861218395134j,
117
+ -0.2499999999999998-0.32274861218395134j]]
118
+ exp6 = [[], [-1.1641600331447917-3.545808351896439j,
119
+ -0.8358399668552097+2.5458083518964383j]]
120
+
121
+ assert pz_tester(tf1, exp1)
122
+ assert pz_tester(tf2, exp2)
123
+ assert pz_tester(tf3, exp3)
124
+ assert pz_tester(ser1, exp4)
125
+ assert pz_tester(par1, exp5)
126
+ assert pz_tester(tf8, exp6)
127
+
128
+
129
+ def test_bode():
130
+ if not numpy:
131
+ skip("NumPy is required for this test")
132
+
133
+ def bode_phase_evalf(system, point):
134
+ expr = system.to_expr()
135
+ _w = Dummy("w", real=True)
136
+ w_expr = expr.subs({system.var: I*_w})
137
+ return arg(w_expr).subs({_w: point}).evalf()
138
+
139
+ def bode_mag_evalf(system, point):
140
+ expr = system.to_expr()
141
+ _w = Dummy("w", real=True)
142
+ w_expr = expr.subs({system.var: I*_w})
143
+ return 20*log(Abs(w_expr), 10).subs({_w: point}).evalf()
144
+
145
+ def test_bode_data(sys):
146
+ return y_coordinate_equality(bode_magnitude_numerical_data, bode_mag_evalf, sys) \
147
+ and y_coordinate_equality(bode_phase_numerical_data, bode_phase_evalf, sys)
148
+
149
+ assert test_bode_data(tf1)
150
+ assert test_bode_data(tf2)
151
+ assert test_bode_data(tf3)
152
+ assert test_bode_data(tf4)
153
+ assert test_bode_data(tf5)
154
+
155
+
156
+ def check_point_accuracy(a, b):
157
+ return all(isclose(*_, rel_tol=1e-1, abs_tol=1e-6
158
+ ) for _ in zip(a, b))
159
+
160
+
161
+ def test_impulse_response():
162
+ if not numpy:
163
+ skip("NumPy is required for this test")
164
+
165
+ def impulse_res_tester(sys, expected_value):
166
+ x, y = _to_tuple(*impulse_response_numerical_data(sys,
167
+ adaptive=False, n=10))
168
+ x_check = check_point_accuracy(x, expected_value[0])
169
+ y_check = check_point_accuracy(y, expected_value[1])
170
+ return x_check and y_check
171
+
172
+ exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
173
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
174
+ (0.0, 0.544019738507865, 0.01993849743234938, -0.31140243360893216, -0.022852779906491996, 0.1778306498155759,
175
+ 0.01962941084328499, -0.1013115194573652, -0.014975541213105696, 0.0575789724730714))
176
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
177
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.1666666675, 0.08389223412935855,
178
+ 0.02338051973475047, -0.014966807776379383, -0.034645954223054234, -0.040560075735512804,
179
+ -0.037658628907103885, -0.030149507719590022, -0.021162090730736834, -0.012721292737437523))
180
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
181
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (4.369893391586999e-09, 1.1750333000630964,
182
+ 3.2922404058312473, 9.432290008148343, 28.37098083007151, 86.18577464367974, 261.90356653762115,
183
+ 795.6538758627842, 2416.9920942096983, 7342.159505206647))
184
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
185
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 6.17283950617284, 24.69135802469136,
186
+ 55.555555555555564, 98.76543209876544, 154.320987654321, 222.22222222222226, 302.46913580246917,
187
+ 395.0617283950618, 500.0))
188
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
189
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, -0.10455606138085417,
190
+ 0.06757671513476461, -0.03234567568833768, 0.013582514927757873, -0.005273419510705473,
191
+ 0.0019364083003354075, -0.000680070134067832, 0.00022969845960406913, -7.476094359583917e-05))
192
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
193
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
194
+ (-6.016699583000218e-09, 0.35039802056107394, 3.3728423827689884, 12.119846079276684,
195
+ 25.86101014293389, 29.352480635282088, -30.49475907497664, -273.8717189554019, -863.2381702029659,
196
+ -1747.0262164682233))
197
+ exp7 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335,
198
+ 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779,
199
+ 8.88888888888889, 10.0), (0.0, 18.934638095560974, 5346.93244680907, 1384609.8718249386,
200
+ 358161126.65801865, 92645770015.70108, 23964739753087.42, 6198974342083139.0, 1.603492601616059e+18,
201
+ 4.147764422869658e+20))
202
+
203
+ assert impulse_res_tester(tf1, exp1)
204
+ assert impulse_res_tester(tf2, exp2)
205
+ assert impulse_res_tester(tf3, exp3)
206
+ assert impulse_res_tester(tf4, exp4)
207
+ assert impulse_res_tester(tf5, exp5)
208
+ assert impulse_res_tester(tf7, exp6)
209
+ assert impulse_res_tester(ser1, exp7)
210
+
211
+
212
+ def test_step_response():
213
+ if not numpy:
214
+ skip("NumPy is required for this test")
215
+
216
+ def step_res_tester(sys, expected_value):
217
+ x, y = _to_tuple(*step_response_numerical_data(sys,
218
+ adaptive=False, n=10))
219
+ x_check = check_point_accuracy(x, expected_value[0])
220
+ y_check = check_point_accuracy(y, expected_value[1])
221
+ return x_check and y_check
222
+
223
+ exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
224
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
225
+ (-1.9193285738516863e-08, 0.42283495488246126, 0.7840485977945262, 0.5546841805655717,
226
+ 0.33903033806932087, 0.4627251747410237, 0.5909907598988051, 0.5247213989553071,
227
+ 0.4486997874319281, 0.4839358435839171))
228
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
229
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
230
+ (0.0, 0.13728409095645816, 0.19474559355325086, 0.1974909129243011, 0.16841657696573073,
231
+ 0.12559777736159378, 0.08153828016664713, 0.04360471317348958, 0.015072994568868221,
232
+ -0.003636420058445484))
233
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
234
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
235
+ (0.0, 0.6314542141914303, 2.9356520038101035, 9.37731009663807, 28.452300356688376,
236
+ 86.25721933273988, 261.9236645044672, 795.6435410577224, 2416.9786984578764, 7342.154119725917))
237
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
238
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
239
+ (0.0, 2.286236899862826, 18.28989519890261, 61.72839629629631, 146.31916159122088, 285.7796124828532,
240
+ 493.8271703703705, 784.1792566529494, 1170.553292729767, 1666.6667))
241
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
242
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
243
+ (-3.999999997894577e-09, 0.6720357068882895, 0.4429938256137113, 0.5182010838004518,
244
+ 0.4944139147159695, 0.5016379853883338, 0.4995466896527733, 0.5001154784851325,
245
+ 0.49997448824584123, 0.5000039745919259))
246
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
247
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
248
+ (-1.5433688493882158e-09, 0.3428705539937336, 1.1253619102202777, 3.1849962651016517,
249
+ 9.47532757182671, 28.727231099148135, 87.29426924860557, 265.2138681048606, 805.6636260007757,
250
+ 2447.387582370878))
251
+
252
+ assert step_res_tester(tf1, exp1)
253
+ assert step_res_tester(tf2, exp2)
254
+ assert step_res_tester(tf3, exp3)
255
+ assert step_res_tester(tf4, exp4)
256
+ assert step_res_tester(tf5, exp5)
257
+ assert step_res_tester(ser2, exp6)
258
+
259
+
260
+ def test_ramp_response():
261
+ if not numpy:
262
+ skip("NumPy is required for this test")
263
+
264
+ def ramp_res_tester(sys, num_points, expected_value, slope=1):
265
+ x, y = _to_tuple(*ramp_response_numerical_data(sys,
266
+ slope=slope, adaptive=False, n=num_points))
267
+ x_check = check_point_accuracy(x, expected_value[0])
268
+ y_check = check_point_accuracy(y, expected_value[1])
269
+ return x_check and y_check
270
+
271
+ exp1 = ((0.0, 2.0, 4.0, 6.0, 8.0, 10.0), (0.0, 0.7324667795033895, 1.9909720978650398,
272
+ 2.7956587704217783, 3.9224897567931514, 4.85022655284895))
273
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
274
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
275
+ (2.4360213402019326e-08, 0.10175320182493253, 0.33057612497658406, 0.5967937263298935,
276
+ 0.8431511866718248, 1.0398805391471613, 1.1776043125035738, 1.2600994825747305, 1.2981042689274653,
277
+ 1.304684417610106))
278
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
279
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-3.9329040468771836e-08,
280
+ 0.34686634635794555, 2.9998828170537903, 12.33303690737476, 40.993913948137795, 127.84145222317912,
281
+ 391.41713691996, 1192.0006858708389, 3623.9808672503405, 11011.728034546572))
282
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
283
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.9051973784484078, 30.483158055174524,
284
+ 154.32098765432104, 487.7305288827924, 1190.7483615302544, 2469.1358024691367, 4574.3789056546275,
285
+ 7803.688462124678, 12500.0))
286
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
287
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 3.8844361856975635, 9.141792069209865,
288
+ 14.096349157657231, 19.09783068994694, 24.10179770390321, 29.09907319114121, 34.10040420185154,
289
+ 39.09983919254265, 44.10006013058409))
290
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
291
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.1111111111111112, 2.2222222222222223,
292
+ 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0))
293
+
294
+ assert ramp_res_tester(tf1, 6, exp1)
295
+ assert ramp_res_tester(tf2, 10, exp2, 1.2)
296
+ assert ramp_res_tester(tf3, 10, exp3, 1.5)
297
+ assert ramp_res_tester(tf4, 10, exp4, 3)
298
+ assert ramp_res_tester(tf5, 10, exp5, 9)
299
+ assert ramp_res_tester(tf6, 10, exp6)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/__init__.py ADDED
File without changes
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (179 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/gamma_matrices.cpython-310.pyc ADDED
Binary file (14 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/gamma_matrices.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module to handle gamma matrices expressed as tensor objects.
3
+
4
+ Examples
5
+ ========
6
+
7
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
8
+ >>> from sympy.tensor.tensor import tensor_indices
9
+ >>> i = tensor_indices('i', LorentzIndex)
10
+ >>> G(i)
11
+ GammaMatrix(i)
12
+
13
+ Note that there is already an instance of GammaMatrixHead in four dimensions:
14
+ GammaMatrix, which is simply declare as
15
+
16
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix
17
+ >>> from sympy.tensor.tensor import tensor_indices
18
+ >>> i = tensor_indices('i', LorentzIndex)
19
+ >>> GammaMatrix(i)
20
+ GammaMatrix(i)
21
+
22
+ To access the metric tensor
23
+
24
+ >>> LorentzIndex.metric
25
+ metric(LorentzIndex,LorentzIndex)
26
+
27
+ """
28
+ from sympy.core.mul import Mul
29
+ from sympy.core.singleton import S
30
+ from sympy.matrices.dense import eye
31
+ from sympy.matrices.expressions.trace import trace
32
+ from sympy.tensor.tensor import TensorIndexType, TensorIndex,\
33
+ TensMul, TensAdd, tensor_mul, Tensor, TensorHead, TensorSymmetry
34
+
35
+
36
+ # DiracSpinorIndex = TensorIndexType('DiracSpinorIndex', dim=4, dummy_name="S")
37
+
38
+
39
+ LorentzIndex = TensorIndexType('LorentzIndex', dim=4, dummy_name="L")
40
+
41
+
42
+ GammaMatrix = TensorHead("GammaMatrix", [LorentzIndex],
43
+ TensorSymmetry.no_symmetry(1), comm=None)
44
+
45
+
46
+ def extract_type_tens(expression, component):
47
+ """
48
+ Extract from a ``TensExpr`` all tensors with `component`.
49
+
50
+ Returns two tensor expressions:
51
+
52
+ * the first contains all ``Tensor`` of having `component`.
53
+ * the second contains all remaining.
54
+
55
+
56
+ """
57
+ if isinstance(expression, Tensor):
58
+ sp = [expression]
59
+ elif isinstance(expression, TensMul):
60
+ sp = expression.args
61
+ else:
62
+ raise ValueError('wrong type')
63
+
64
+ # Collect all gamma matrices of the same dimension
65
+ new_expr = S.One
66
+ residual_expr = S.One
67
+ for i in sp:
68
+ if isinstance(i, Tensor) and i.component == component:
69
+ new_expr *= i
70
+ else:
71
+ residual_expr *= i
72
+ return new_expr, residual_expr
73
+
74
+
75
+ def simplify_gamma_expression(expression):
76
+ extracted_expr, residual_expr = extract_type_tens(expression, GammaMatrix)
77
+ res_expr = _simplify_single_line(extracted_expr)
78
+ return res_expr * residual_expr
79
+
80
+
81
+ def simplify_gpgp(ex, sort=True):
82
+ """
83
+ simplify products ``G(i)*p(-i)*G(j)*p(-j) -> p(i)*p(-i)``
84
+
85
+ Examples
86
+ ========
87
+
88
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
89
+ LorentzIndex, simplify_gpgp
90
+ >>> from sympy.tensor.tensor import tensor_indices, tensor_heads
91
+ >>> p, q = tensor_heads('p, q', [LorentzIndex])
92
+ >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
93
+ >>> ps = p(i0)*G(-i0)
94
+ >>> qs = q(i0)*G(-i0)
95
+ >>> simplify_gpgp(ps*qs*qs)
96
+ GammaMatrix(-L_0)*p(L_0)*q(L_1)*q(-L_1)
97
+ """
98
+ def _simplify_gpgp(ex):
99
+ components = ex.components
100
+ a = []
101
+ comp_map = []
102
+ for i, comp in enumerate(components):
103
+ comp_map.extend([i]*comp.rank)
104
+ dum = [(i[0], i[1], comp_map[i[0]], comp_map[i[1]]) for i in ex.dum]
105
+ for i in range(len(components)):
106
+ if components[i] != GammaMatrix:
107
+ continue
108
+ for dx in dum:
109
+ if dx[2] == i:
110
+ p_pos1 = dx[3]
111
+ elif dx[3] == i:
112
+ p_pos1 = dx[2]
113
+ else:
114
+ continue
115
+ comp1 = components[p_pos1]
116
+ if comp1.comm == 0 and comp1.rank == 1:
117
+ a.append((i, p_pos1))
118
+ if not a:
119
+ return ex
120
+ elim = set()
121
+ tv = []
122
+ hit = True
123
+ coeff = S.One
124
+ ta = None
125
+ while hit:
126
+ hit = False
127
+ for i, ai in enumerate(a[:-1]):
128
+ if ai[0] in elim:
129
+ continue
130
+ if ai[0] != a[i + 1][0] - 1:
131
+ continue
132
+ if components[ai[1]] != components[a[i + 1][1]]:
133
+ continue
134
+ elim.add(ai[0])
135
+ elim.add(ai[1])
136
+ elim.add(a[i + 1][0])
137
+ elim.add(a[i + 1][1])
138
+ if not ta:
139
+ ta = ex.split()
140
+ mu = TensorIndex('mu', LorentzIndex)
141
+ hit = True
142
+ if i == 0:
143
+ coeff = ex.coeff
144
+ tx = components[ai[1]](mu)*components[ai[1]](-mu)
145
+ if len(a) == 2:
146
+ tx *= 4 # eye(4)
147
+ tv.append(tx)
148
+ break
149
+
150
+ if tv:
151
+ a = [x for j, x in enumerate(ta) if j not in elim]
152
+ a.extend(tv)
153
+ t = tensor_mul(*a)*coeff
154
+ # t = t.replace(lambda x: x.is_Matrix, lambda x: 1)
155
+ return t
156
+ else:
157
+ return ex
158
+
159
+ if sort:
160
+ ex = ex.sorted_components()
161
+ # this would be better off with pattern matching
162
+ while 1:
163
+ t = _simplify_gpgp(ex)
164
+ if t != ex:
165
+ ex = t
166
+ else:
167
+ return t
168
+
169
+
170
+ def gamma_trace(t):
171
+ """
172
+ trace of a single line of gamma matrices
173
+
174
+ Examples
175
+ ========
176
+
177
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
178
+ gamma_trace, LorentzIndex
179
+ >>> from sympy.tensor.tensor import tensor_indices, tensor_heads
180
+ >>> p, q = tensor_heads('p, q', [LorentzIndex])
181
+ >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
182
+ >>> ps = p(i0)*G(-i0)
183
+ >>> qs = q(i0)*G(-i0)
184
+ >>> gamma_trace(G(i0)*G(i1))
185
+ 4*metric(i0, i1)
186
+ >>> gamma_trace(ps*ps) - 4*p(i0)*p(-i0)
187
+ 0
188
+ >>> gamma_trace(ps*qs + ps*ps) - 4*p(i0)*p(-i0) - 4*p(i0)*q(-i0)
189
+ 0
190
+
191
+ """
192
+ if isinstance(t, TensAdd):
193
+ res = TensAdd(*[gamma_trace(x) for x in t.args])
194
+ return res
195
+ t = _simplify_single_line(t)
196
+ res = _trace_single_line(t)
197
+ return res
198
+
199
+
200
+ def _simplify_single_line(expression):
201
+ """
202
+ Simplify single-line product of gamma matrices.
203
+
204
+ Examples
205
+ ========
206
+
207
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
208
+ LorentzIndex, _simplify_single_line
209
+ >>> from sympy.tensor.tensor import tensor_indices, TensorHead
210
+ >>> p = TensorHead('p', [LorentzIndex])
211
+ >>> i0,i1 = tensor_indices('i0:2', LorentzIndex)
212
+ >>> _simplify_single_line(G(i0)*G(i1)*p(-i1)*G(-i0)) + 2*G(i0)*p(-i0)
213
+ 0
214
+
215
+ """
216
+ t1, t2 = extract_type_tens(expression, GammaMatrix)
217
+ if t1 != 1:
218
+ t1 = kahane_simplify(t1)
219
+ res = t1*t2
220
+ return res
221
+
222
+
223
+ def _trace_single_line(t):
224
+ """
225
+ Evaluate the trace of a single gamma matrix line inside a ``TensExpr``.
226
+
227
+ Notes
228
+ =====
229
+
230
+ If there are ``DiracSpinorIndex.auto_left`` and ``DiracSpinorIndex.auto_right``
231
+ indices trace over them; otherwise traces are not implied (explain)
232
+
233
+
234
+ Examples
235
+ ========
236
+
237
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
238
+ LorentzIndex, _trace_single_line
239
+ >>> from sympy.tensor.tensor import tensor_indices, TensorHead
240
+ >>> p = TensorHead('p', [LorentzIndex])
241
+ >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
242
+ >>> _trace_single_line(G(i0)*G(i1))
243
+ 4*metric(i0, i1)
244
+ >>> _trace_single_line(G(i0)*p(-i0)*G(i1)*p(-i1)) - 4*p(i0)*p(-i0)
245
+ 0
246
+
247
+ """
248
+ def _trace_single_line1(t):
249
+ t = t.sorted_components()
250
+ components = t.components
251
+ ncomps = len(components)
252
+ g = LorentzIndex.metric
253
+ # gamma matirices are in a[i:j]
254
+ hit = 0
255
+ for i in range(ncomps):
256
+ if components[i] == GammaMatrix:
257
+ hit = 1
258
+ break
259
+
260
+ for j in range(i + hit, ncomps):
261
+ if components[j] != GammaMatrix:
262
+ break
263
+ else:
264
+ j = ncomps
265
+ numG = j - i
266
+ if numG == 0:
267
+ tcoeff = t.coeff
268
+ return t.nocoeff if tcoeff else t
269
+ if numG % 2 == 1:
270
+ return TensMul.from_data(S.Zero, [], [], [])
271
+ elif numG > 4:
272
+ # find the open matrix indices and connect them:
273
+ a = t.split()
274
+ ind1 = a[i].get_indices()[0]
275
+ ind2 = a[i + 1].get_indices()[0]
276
+ aa = a[:i] + a[i + 2:]
277
+ t1 = tensor_mul(*aa)*g(ind1, ind2)
278
+ t1 = t1.contract_metric(g)
279
+ args = [t1]
280
+ sign = 1
281
+ for k in range(i + 2, j):
282
+ sign = -sign
283
+ ind2 = a[k].get_indices()[0]
284
+ aa = a[:i] + a[i + 1:k] + a[k + 1:]
285
+ t2 = sign*tensor_mul(*aa)*g(ind1, ind2)
286
+ t2 = t2.contract_metric(g)
287
+ t2 = simplify_gpgp(t2, False)
288
+ args.append(t2)
289
+ t3 = TensAdd(*args)
290
+ t3 = _trace_single_line(t3)
291
+ return t3
292
+ else:
293
+ a = t.split()
294
+ t1 = _gamma_trace1(*a[i:j])
295
+ a2 = a[:i] + a[j:]
296
+ t2 = tensor_mul(*a2)
297
+ t3 = t1*t2
298
+ if not t3:
299
+ return t3
300
+ t3 = t3.contract_metric(g)
301
+ return t3
302
+
303
+ t = t.expand()
304
+ if isinstance(t, TensAdd):
305
+ a = [_trace_single_line1(x)*x.coeff for x in t.args]
306
+ return TensAdd(*a)
307
+ elif isinstance(t, (Tensor, TensMul)):
308
+ r = t.coeff*_trace_single_line1(t)
309
+ return r
310
+ else:
311
+ return trace(t)
312
+
313
+
314
+ def _gamma_trace1(*a):
315
+ gctr = 4 # FIXME specific for d=4
316
+ g = LorentzIndex.metric
317
+ if not a:
318
+ return gctr
319
+ n = len(a)
320
+ if n%2 == 1:
321
+ #return TensMul.from_data(S.Zero, [], [], [])
322
+ return S.Zero
323
+ if n == 2:
324
+ ind0 = a[0].get_indices()[0]
325
+ ind1 = a[1].get_indices()[0]
326
+ return gctr*g(ind0, ind1)
327
+ if n == 4:
328
+ ind0 = a[0].get_indices()[0]
329
+ ind1 = a[1].get_indices()[0]
330
+ ind2 = a[2].get_indices()[0]
331
+ ind3 = a[3].get_indices()[0]
332
+
333
+ return gctr*(g(ind0, ind1)*g(ind2, ind3) - \
334
+ g(ind0, ind2)*g(ind1, ind3) + g(ind0, ind3)*g(ind1, ind2))
335
+
336
+
337
+ def kahane_simplify(expression):
338
+ r"""
339
+ This function cancels contracted elements in a product of four
340
+ dimensional gamma matrices, resulting in an expression equal to the given
341
+ one, without the contracted gamma matrices.
342
+
343
+ Parameters
344
+ ==========
345
+
346
+ `expression` the tensor expression containing the gamma matrices to simplify.
347
+
348
+ Notes
349
+ =====
350
+
351
+ If spinor indices are given, the matrices must be given in
352
+ the order given in the product.
353
+
354
+ Algorithm
355
+ =========
356
+
357
+ The idea behind the algorithm is to use some well-known identities,
358
+ i.e., for contractions enclosing an even number of `\gamma` matrices
359
+
360
+ `\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N}} \gamma_\mu = 2 (\gamma_{a_{2N}} \gamma_{a_1} \cdots \gamma_{a_{2N-1}} + \gamma_{a_{2N-1}} \cdots \gamma_{a_1} \gamma_{a_{2N}} )`
361
+
362
+ for an odd number of `\gamma` matrices
363
+
364
+ `\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N+1}} \gamma_\mu = -2 \gamma_{a_{2N+1}} \gamma_{a_{2N}} \cdots \gamma_{a_{1}}`
365
+
366
+ Instead of repeatedly applying these identities to cancel out all contracted indices,
367
+ it is possible to recognize the links that would result from such an operation,
368
+ the problem is thus reduced to a simple rearrangement of free gamma matrices.
369
+
370
+ Examples
371
+ ========
372
+
373
+ When using, always remember that the original expression coefficient
374
+ has to be handled separately
375
+
376
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
377
+ >>> from sympy.physics.hep.gamma_matrices import kahane_simplify
378
+ >>> from sympy.tensor.tensor import tensor_indices
379
+ >>> i0, i1, i2 = tensor_indices('i0:3', LorentzIndex)
380
+ >>> ta = G(i0)*G(-i0)
381
+ >>> kahane_simplify(ta)
382
+ Matrix([
383
+ [4, 0, 0, 0],
384
+ [0, 4, 0, 0],
385
+ [0, 0, 4, 0],
386
+ [0, 0, 0, 4]])
387
+ >>> tb = G(i0)*G(i1)*G(-i0)
388
+ >>> kahane_simplify(tb)
389
+ -2*GammaMatrix(i1)
390
+ >>> t = G(i0)*G(-i0)
391
+ >>> kahane_simplify(t)
392
+ Matrix([
393
+ [4, 0, 0, 0],
394
+ [0, 4, 0, 0],
395
+ [0, 0, 4, 0],
396
+ [0, 0, 0, 4]])
397
+ >>> t = G(i0)*G(-i0)
398
+ >>> kahane_simplify(t)
399
+ Matrix([
400
+ [4, 0, 0, 0],
401
+ [0, 4, 0, 0],
402
+ [0, 0, 4, 0],
403
+ [0, 0, 0, 4]])
404
+
405
+ If there are no contractions, the same expression is returned
406
+
407
+ >>> tc = G(i0)*G(i1)
408
+ >>> kahane_simplify(tc)
409
+ GammaMatrix(i0)*GammaMatrix(i1)
410
+
411
+ References
412
+ ==========
413
+
414
+ [1] Algorithm for Reducing Contracted Products of gamma Matrices,
415
+ Joseph Kahane, Journal of Mathematical Physics, Vol. 9, No. 10, October 1968.
416
+ """
417
+
418
+ if isinstance(expression, Mul):
419
+ return expression
420
+ if isinstance(expression, TensAdd):
421
+ return TensAdd(*[kahane_simplify(arg) for arg in expression.args])
422
+
423
+ if isinstance(expression, Tensor):
424
+ return expression
425
+
426
+ assert isinstance(expression, TensMul)
427
+
428
+ gammas = expression.args
429
+
430
+ for gamma in gammas:
431
+ assert gamma.component == GammaMatrix
432
+
433
+ free = expression.free
434
+ # spinor_free = [_ for _ in expression.free_in_args if _[1] != 0]
435
+
436
+ # if len(spinor_free) == 2:
437
+ # spinor_free.sort(key=lambda x: x[2])
438
+ # assert spinor_free[0][1] == 1 and spinor_free[-1][1] == 2
439
+ # assert spinor_free[0][2] == 0
440
+ # elif spinor_free:
441
+ # raise ValueError('spinor indices do not match')
442
+
443
+ dum = []
444
+ for dum_pair in expression.dum:
445
+ if expression.index_types[dum_pair[0]] == LorentzIndex:
446
+ dum.append((dum_pair[0], dum_pair[1]))
447
+
448
+ dum = sorted(dum)
449
+
450
+ if len(dum) == 0: # or GammaMatrixHead:
451
+ # no contractions in `expression`, just return it.
452
+ return expression
453
+
454
+ # find the `first_dum_pos`, i.e. the position of the first contracted
455
+ # gamma matrix, Kahane's algorithm as described in his paper requires the
456
+ # gamma matrix expression to start with a contracted gamma matrix, this is
457
+ # a workaround which ignores possible initial free indices, and re-adds
458
+ # them later.
459
+
460
+ first_dum_pos = min(map(min, dum))
461
+
462
+ # for p1, p2, a1, a2 in expression.dum_in_args:
463
+ # if p1 != 0 or p2 != 0:
464
+ # # only Lorentz indices, skip Dirac indices:
465
+ # continue
466
+ # first_dum_pos = min(p1, p2)
467
+ # break
468
+
469
+ total_number = len(free) + len(dum)*2
470
+ number_of_contractions = len(dum)
471
+
472
+ free_pos = [None]*total_number
473
+ for i in free:
474
+ free_pos[i[1]] = i[0]
475
+
476
+ # `index_is_free` is a list of booleans, to identify index position
477
+ # and whether that index is free or dummy.
478
+ index_is_free = [False]*total_number
479
+
480
+ for i, indx in enumerate(free):
481
+ index_is_free[indx[1]] = True
482
+
483
+ # `links` is a dictionary containing the graph described in Kahane's paper,
484
+ # to every key correspond one or two values, representing the linked indices.
485
+ # All values in `links` are integers, negative numbers are used in the case
486
+ # where it is necessary to insert gamma matrices between free indices, in
487
+ # order to make Kahane's algorithm work (see paper).
488
+ links = {i: [] for i in range(first_dum_pos, total_number)}
489
+
490
+ # `cum_sign` is a step variable to mark the sign of every index, see paper.
491
+ cum_sign = -1
492
+ # `cum_sign_list` keeps storage for all `cum_sign` (every index).
493
+ cum_sign_list = [None]*total_number
494
+ block_free_count = 0
495
+
496
+ # multiply `resulting_coeff` by the coefficient parameter, the rest
497
+ # of the algorithm ignores a scalar coefficient.
498
+ resulting_coeff = S.One
499
+
500
+ # initialize a list of lists of indices. The outer list will contain all
501
+ # additive tensor expressions, while the inner list will contain the
502
+ # free indices (rearranged according to the algorithm).
503
+ resulting_indices = [[]]
504
+
505
+ # start to count the `connected_components`, which together with the number
506
+ # of contractions, determines a -1 or +1 factor to be multiplied.
507
+ connected_components = 1
508
+
509
+ # First loop: here we fill `cum_sign_list`, and draw the links
510
+ # among consecutive indices (they are stored in `links`). Links among
511
+ # non-consecutive indices will be drawn later.
512
+ for i, is_free in enumerate(index_is_free):
513
+ # if `expression` starts with free indices, they are ignored here;
514
+ # they are later added as they are to the beginning of all
515
+ # `resulting_indices` list of lists of indices.
516
+ if i < first_dum_pos:
517
+ continue
518
+
519
+ if is_free:
520
+ block_free_count += 1
521
+ # if previous index was free as well, draw an arch in `links`.
522
+ if block_free_count > 1:
523
+ links[i - 1].append(i)
524
+ links[i].append(i - 1)
525
+ else:
526
+ # Change the sign of the index (`cum_sign`) if the number of free
527
+ # indices preceding it is even.
528
+ cum_sign *= 1 if (block_free_count % 2) else -1
529
+ if block_free_count == 0 and i != first_dum_pos:
530
+ # check if there are two consecutive dummy indices:
531
+ # in this case create virtual indices with negative position,
532
+ # these "virtual" indices represent the insertion of two
533
+ # gamma^0 matrices to separate consecutive dummy indices, as
534
+ # Kahane's algorithm requires dummy indices to be separated by
535
+ # free indices. The product of two gamma^0 matrices is unity,
536
+ # so the new expression being examined is the same as the
537
+ # original one.
538
+ if cum_sign == -1:
539
+ links[-1-i] = [-1-i+1]
540
+ links[-1-i+1] = [-1-i]
541
+ if (i - cum_sign) in links:
542
+ if i != first_dum_pos:
543
+ links[i].append(i - cum_sign)
544
+ if block_free_count != 0:
545
+ if i - cum_sign < len(index_is_free):
546
+ if index_is_free[i - cum_sign]:
547
+ links[i - cum_sign].append(i)
548
+ block_free_count = 0
549
+
550
+ cum_sign_list[i] = cum_sign
551
+
552
+ # The previous loop has only created links between consecutive free indices,
553
+ # it is necessary to properly create links among dummy (contracted) indices,
554
+ # according to the rules described in Kahane's paper. There is only one exception
555
+ # to Kahane's rules: the negative indices, which handle the case of some
556
+ # consecutive free indices (Kahane's paper just describes dummy indices
557
+ # separated by free indices, hinting that free indices can be added without
558
+ # altering the expression result).
559
+ for i in dum:
560
+ # get the positions of the two contracted indices:
561
+ pos1 = i[0]
562
+ pos2 = i[1]
563
+
564
+ # create Kahane's upper links, i.e. the upper arcs between dummy
565
+ # (i.e. contracted) indices:
566
+ links[pos1].append(pos2)
567
+ links[pos2].append(pos1)
568
+
569
+ # create Kahane's lower links, this corresponds to the arcs below
570
+ # the line described in the paper:
571
+
572
+ # first we move `pos1` and `pos2` according to the sign of the indices:
573
+ linkpos1 = pos1 + cum_sign_list[pos1]
574
+ linkpos2 = pos2 + cum_sign_list[pos2]
575
+
576
+ # otherwise, perform some checks before creating the lower arcs:
577
+
578
+ # make sure we are not exceeding the total number of indices:
579
+ if linkpos1 >= total_number:
580
+ continue
581
+ if linkpos2 >= total_number:
582
+ continue
583
+
584
+ # make sure we are not below the first dummy index in `expression`:
585
+ if linkpos1 < first_dum_pos:
586
+ continue
587
+ if linkpos2 < first_dum_pos:
588
+ continue
589
+
590
+ # check if the previous loop created "virtual" indices between dummy
591
+ # indices, in such a case relink `linkpos1` and `linkpos2`:
592
+ if (-1-linkpos1) in links:
593
+ linkpos1 = -1-linkpos1
594
+ if (-1-linkpos2) in links:
595
+ linkpos2 = -1-linkpos2
596
+
597
+ # move only if not next to free index:
598
+ if linkpos1 >= 0 and not index_is_free[linkpos1]:
599
+ linkpos1 = pos1
600
+
601
+ if linkpos2 >=0 and not index_is_free[linkpos2]:
602
+ linkpos2 = pos2
603
+
604
+ # create the lower arcs:
605
+ if linkpos2 not in links[linkpos1]:
606
+ links[linkpos1].append(linkpos2)
607
+ if linkpos1 not in links[linkpos2]:
608
+ links[linkpos2].append(linkpos1)
609
+
610
+ # This loop starts from the `first_dum_pos` index (first dummy index)
611
+ # walks through the graph deleting the visited indices from `links`,
612
+ # it adds a gamma matrix for every free index in encounters, while it
613
+ # completely ignores dummy indices and virtual indices.
614
+ pointer = first_dum_pos
615
+ previous_pointer = 0
616
+ while True:
617
+ if pointer in links:
618
+ next_ones = links.pop(pointer)
619
+ else:
620
+ break
621
+
622
+ if previous_pointer in next_ones:
623
+ next_ones.remove(previous_pointer)
624
+
625
+ previous_pointer = pointer
626
+
627
+ if next_ones:
628
+ pointer = next_ones[0]
629
+ else:
630
+ break
631
+
632
+ if pointer == previous_pointer:
633
+ break
634
+ if pointer >=0 and free_pos[pointer] is not None:
635
+ for ri in resulting_indices:
636
+ ri.append(free_pos[pointer])
637
+
638
+ # The following loop removes the remaining connected components in `links`.
639
+ # If there are free indices inside a connected component, it gives a
640
+ # contribution to the resulting expression given by the factor
641
+ # `gamma_a gamma_b ... gamma_z + gamma_z ... gamma_b gamma_a`, in Kahanes's
642
+ # paper represented as {gamma_a, gamma_b, ... , gamma_z},
643
+ # virtual indices are ignored. The variable `connected_components` is
644
+ # increased by one for every connected component this loop encounters.
645
+
646
+ # If the connected component has virtual and dummy indices only
647
+ # (no free indices), it contributes to `resulting_indices` by a factor of two.
648
+ # The multiplication by two is a result of the
649
+ # factor {gamma^0, gamma^0} = 2 I, as it appears in Kahane's paper.
650
+ # Note: curly brackets are meant as in the paper, as a generalized
651
+ # multi-element anticommutator!
652
+
653
+ while links:
654
+ connected_components += 1
655
+ pointer = min(links.keys())
656
+ previous_pointer = pointer
657
+ # the inner loop erases the visited indices from `links`, and it adds
658
+ # all free indices to `prepend_indices` list, virtual indices are
659
+ # ignored.
660
+ prepend_indices = []
661
+ while True:
662
+ if pointer in links:
663
+ next_ones = links.pop(pointer)
664
+ else:
665
+ break
666
+
667
+ if previous_pointer in next_ones:
668
+ if len(next_ones) > 1:
669
+ next_ones.remove(previous_pointer)
670
+
671
+ previous_pointer = pointer
672
+
673
+ if next_ones:
674
+ pointer = next_ones[0]
675
+
676
+ if pointer >= first_dum_pos and free_pos[pointer] is not None:
677
+ prepend_indices.insert(0, free_pos[pointer])
678
+ # if `prepend_indices` is void, it means there are no free indices
679
+ # in the loop (and it can be shown that there must be a virtual index),
680
+ # loops of virtual indices only contribute by a factor of two:
681
+ if len(prepend_indices) == 0:
682
+ resulting_coeff *= 2
683
+ # otherwise, add the free indices in `prepend_indices` to
684
+ # the `resulting_indices`:
685
+ else:
686
+ expr1 = prepend_indices
687
+ expr2 = list(reversed(prepend_indices))
688
+ resulting_indices = [expri + ri for ri in resulting_indices for expri in (expr1, expr2)]
689
+
690
+ # sign correction, as described in Kahane's paper:
691
+ resulting_coeff *= -1 if (number_of_contractions - connected_components + 1) % 2 else 1
692
+ # power of two factor, as described in Kahane's paper:
693
+ resulting_coeff *= 2**(number_of_contractions)
694
+
695
+ # If `first_dum_pos` is not zero, it means that there are trailing free gamma
696
+ # matrices in front of `expression`, so multiply by them:
697
+ resulting_indices = [ free_pos[0:first_dum_pos] + ri for ri in resulting_indices ]
698
+
699
+ resulting_expr = S.Zero
700
+ for i in resulting_indices:
701
+ temp_expr = S.One
702
+ for j in i:
703
+ temp_expr *= GammaMatrix(j)
704
+ resulting_expr += temp_expr
705
+
706
+ t = resulting_coeff * resulting_expr
707
+ t1 = None
708
+ if isinstance(t, TensAdd):
709
+ t1 = t.args[0]
710
+ elif isinstance(t, TensMul):
711
+ t1 = t
712
+ if t1:
713
+ pass
714
+ else:
715
+ t = eye(4)*t
716
+ return t
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/tests/__init__.py ADDED
File without changes
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/test_gamma_matrices.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hep/tests/test_gamma_matrices.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.matrices.dense import eye, Matrix
2
+ from sympy.tensor.tensor import tensor_indices, TensorHead, tensor_heads, \
3
+ TensExpr, canon_bp
4
+ from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex, \
5
+ kahane_simplify, gamma_trace, _simplify_single_line, simplify_gamma_expression
6
+ from sympy import Symbol
7
+
8
+
9
+ def _is_tensor_eq(arg1, arg2):
10
+ arg1 = canon_bp(arg1)
11
+ arg2 = canon_bp(arg2)
12
+ if isinstance(arg1, TensExpr):
13
+ return arg1.equals(arg2)
14
+ elif isinstance(arg2, TensExpr):
15
+ return arg2.equals(arg1)
16
+ return arg1 == arg2
17
+
18
+ def execute_gamma_simplify_tests_for_function(tfunc, D):
19
+ """
20
+ Perform tests to check if sfunc is able to simplify gamma matrix expressions.
21
+
22
+ Parameters
23
+ ==========
24
+
25
+ `sfunc` a function to simplify a `TIDS`, shall return the simplified `TIDS`.
26
+ `D` the number of dimension (in most cases `D=4`).
27
+
28
+ """
29
+
30
+ mu, nu, rho, sigma = tensor_indices("mu, nu, rho, sigma", LorentzIndex)
31
+ a1, a2, a3, a4, a5, a6 = tensor_indices("a1:7", LorentzIndex)
32
+ mu11, mu12, mu21, mu31, mu32, mu41, mu51, mu52 = tensor_indices("mu11, mu12, mu21, mu31, mu32, mu41, mu51, mu52", LorentzIndex)
33
+ mu61, mu71, mu72 = tensor_indices("mu61, mu71, mu72", LorentzIndex)
34
+ m0, m1, m2, m3, m4, m5, m6 = tensor_indices("m0:7", LorentzIndex)
35
+
36
+ def g(xx, yy):
37
+ return (G(xx)*G(yy) + G(yy)*G(xx))/2
38
+
39
+ # Some examples taken from Kahane's paper, 4 dim only:
40
+ if D == 4:
41
+ t = (G(a1)*G(mu11)*G(a2)*G(mu21)*G(-a1)*G(mu31)*G(-a2))
42
+ assert _is_tensor_eq(tfunc(t), -4*G(mu11)*G(mu31)*G(mu21) - 4*G(mu31)*G(mu11)*G(mu21))
43
+
44
+ t = (G(a1)*G(mu11)*G(mu12)*\
45
+ G(a2)*G(mu21)*\
46
+ G(a3)*G(mu31)*G(mu32)*\
47
+ G(a4)*G(mu41)*\
48
+ G(-a2)*G(mu51)*G(mu52)*\
49
+ G(-a1)*G(mu61)*\
50
+ G(-a3)*G(mu71)*G(mu72)*\
51
+ G(-a4))
52
+ assert _is_tensor_eq(tfunc(t), \
53
+ 16*G(mu31)*G(mu32)*G(mu72)*G(mu71)*G(mu11)*G(mu52)*G(mu51)*G(mu12)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu31)*G(mu32)*G(mu72)*G(mu71)*G(mu12)*G(mu51)*G(mu52)*G(mu11)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu71)*G(mu72)*G(mu32)*G(mu31)*G(mu11)*G(mu52)*G(mu51)*G(mu12)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu71)*G(mu72)*G(mu32)*G(mu31)*G(mu12)*G(mu51)*G(mu52)*G(mu11)*G(mu61)*G(mu21)*G(mu41))
54
+
55
+ # Fully Lorentz-contracted expressions, these return scalars:
56
+
57
+ def add_delta(ne):
58
+ return ne * eye(4) # DiracSpinorIndex.delta(DiracSpinorIndex.auto_left, -DiracSpinorIndex.auto_right)
59
+
60
+ t = (G(mu)*G(-mu))
61
+ ts = add_delta(D)
62
+ assert _is_tensor_eq(tfunc(t), ts)
63
+
64
+ t = (G(mu)*G(nu)*G(-mu)*G(-nu))
65
+ ts = add_delta(2*D - D**2) # -8
66
+ assert _is_tensor_eq(tfunc(t), ts)
67
+
68
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
69
+ ts = add_delta(D**2) # 16
70
+ assert _is_tensor_eq(tfunc(t), ts)
71
+
72
+ t = (G(mu)*G(nu)*G(-rho)*G(-nu)*G(-mu)*G(rho))
73
+ ts = add_delta(4*D - 4*D**2 + D**3) # 16
74
+ assert _is_tensor_eq(tfunc(t), ts)
75
+
76
+ t = (G(mu)*G(nu)*G(rho)*G(-rho)*G(-nu)*G(-mu))
77
+ ts = add_delta(D**3) # 64
78
+ assert _is_tensor_eq(tfunc(t), ts)
79
+
80
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(-a3)*G(-a1)*G(-a2)*G(-a4))
81
+ ts = add_delta(-8*D + 16*D**2 - 8*D**3 + D**4) # -32
82
+ assert _is_tensor_eq(tfunc(t), ts)
83
+
84
+ t = (G(-mu)*G(-nu)*G(-rho)*G(-sigma)*G(nu)*G(mu)*G(sigma)*G(rho))
85
+ ts = add_delta(-16*D + 24*D**2 - 8*D**3 + D**4) # 64
86
+ assert _is_tensor_eq(tfunc(t), ts)
87
+
88
+ t = (G(-mu)*G(nu)*G(-rho)*G(sigma)*G(rho)*G(-nu)*G(mu)*G(-sigma))
89
+ ts = add_delta(8*D - 12*D**2 + 6*D**3 - D**4) # -32
90
+ assert _is_tensor_eq(tfunc(t), ts)
91
+
92
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(-a3)*G(-a2)*G(-a1)*G(-a5)*G(-a4))
93
+ ts = add_delta(64*D - 112*D**2 + 60*D**3 - 12*D**4 + D**5) # 256
94
+ assert _is_tensor_eq(tfunc(t), ts)
95
+
96
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(-a3)*G(-a1)*G(-a2)*G(-a4)*G(-a5))
97
+ ts = add_delta(64*D - 120*D**2 + 72*D**3 - 16*D**4 + D**5) # -128
98
+ assert _is_tensor_eq(tfunc(t), ts)
99
+
100
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(a6)*G(-a3)*G(-a2)*G(-a1)*G(-a6)*G(-a5)*G(-a4))
101
+ ts = add_delta(416*D - 816*D**2 + 528*D**3 - 144*D**4 + 18*D**5 - D**6) # -128
102
+ assert _is_tensor_eq(tfunc(t), ts)
103
+
104
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(a6)*G(-a2)*G(-a3)*G(-a1)*G(-a6)*G(-a4)*G(-a5))
105
+ ts = add_delta(416*D - 848*D**2 + 584*D**3 - 172*D**4 + 22*D**5 - D**6) # -128
106
+ assert _is_tensor_eq(tfunc(t), ts)
107
+
108
+ # Expressions with free indices:
109
+
110
+ t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
111
+ assert _is_tensor_eq(tfunc(t), (-2*G(sigma)*G(rho)*G(nu) + (4-D)*G(nu)*G(rho)*G(sigma)))
112
+
113
+ t = (G(mu)*G(nu)*G(-mu))
114
+ assert _is_tensor_eq(tfunc(t), (2-D)*G(nu))
115
+
116
+ t = (G(mu)*G(nu)*G(rho)*G(-mu))
117
+ assert _is_tensor_eq(tfunc(t), 2*G(nu)*G(rho) + 2*G(rho)*G(nu) - (4-D)*G(nu)*G(rho))
118
+
119
+ t = 2*G(m2)*G(m0)*G(m1)*G(-m0)*G(-m1)
120
+ st = tfunc(t)
121
+ assert _is_tensor_eq(st, (D*(-2*D + 4))*G(m2))
122
+
123
+ t = G(m2)*G(m0)*G(m1)*G(-m0)*G(-m2)
124
+ st = tfunc(t)
125
+ assert _is_tensor_eq(st, ((-D + 2)**2)*G(m1))
126
+
127
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(-m1)
128
+ st = tfunc(t)
129
+ assert _is_tensor_eq(st, (D - 4)*G(m0)*G(m2)*G(m3) + 4*G(m0)*g(m2, m3))
130
+
131
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(-m1)*G(-m0)
132
+ st = tfunc(t)
133
+ assert _is_tensor_eq(st, ((D - 4)**2)*G(m2)*G(m3) + (8*D - 16)*g(m2, m3))
134
+
135
+ t = G(m2)*G(m0)*G(m1)*G(-m2)*G(-m0)
136
+ st = tfunc(t)
137
+ assert _is_tensor_eq(st, ((-D + 2)*(D - 4) + 4)*G(m1))
138
+
139
+ t = G(m3)*G(m1)*G(m0)*G(m2)*G(-m3)*G(-m0)*G(-m2)
140
+ st = tfunc(t)
141
+ assert _is_tensor_eq(st, (-4*D + (-D + 2)**2*(D - 4) + 8)*G(m1))
142
+
143
+ t = 2*G(m0)*G(m1)*G(m2)*G(m3)*G(-m0)
144
+ st = tfunc(t)
145
+ assert _is_tensor_eq(st, ((-2*D + 8)*G(m1)*G(m2)*G(m3) - 4*G(m3)*G(m2)*G(m1)))
146
+
147
+ t = G(m5)*G(m0)*G(m1)*G(m4)*G(m2)*G(-m4)*G(m3)*G(-m0)
148
+ st = tfunc(t)
149
+ assert _is_tensor_eq(st, (((-D + 2)*(-D + 4))*G(m5)*G(m1)*G(m2)*G(m3) + (2*D - 4)*G(m5)*G(m3)*G(m2)*G(m1)))
150
+
151
+ t = -G(m0)*G(m1)*G(m2)*G(m3)*G(-m0)*G(m4)
152
+ st = tfunc(t)
153
+ assert _is_tensor_eq(st, ((D - 4)*G(m1)*G(m2)*G(m3)*G(m4) + 2*G(m3)*G(m2)*G(m1)*G(m4)))
154
+
155
+ t = G(-m5)*G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)*G(m5)
156
+ st = tfunc(t)
157
+
158
+ result1 = ((-D + 4)**2 + 4)*G(m1)*G(m2)*G(m3)*G(m4) +\
159
+ (4*D - 16)*G(m3)*G(m2)*G(m1)*G(m4) + (4*D - 16)*G(m4)*G(m1)*G(m2)*G(m3)\
160
+ + 4*G(m2)*G(m1)*G(m4)*G(m3) + 4*G(m3)*G(m4)*G(m1)*G(m2) +\
161
+ 4*G(m4)*G(m3)*G(m2)*G(m1)
162
+
163
+ # Kahane's algorithm yields this result, which is equivalent to `result1`
164
+ # in four dimensions, but is not automatically recognized as equal:
165
+ result2 = 8*G(m1)*G(m2)*G(m3)*G(m4) + 8*G(m4)*G(m3)*G(m2)*G(m1)
166
+
167
+ if D == 4:
168
+ assert _is_tensor_eq(st, (result1)) or _is_tensor_eq(st, (result2))
169
+ else:
170
+ assert _is_tensor_eq(st, (result1))
171
+
172
+ # and a few very simple cases, with no contracted indices:
173
+
174
+ t = G(m0)
175
+ st = tfunc(t)
176
+ assert _is_tensor_eq(st, t)
177
+
178
+ t = -7*G(m0)
179
+ st = tfunc(t)
180
+ assert _is_tensor_eq(st, t)
181
+
182
+ t = 224*G(m0)*G(m1)*G(-m2)*G(m3)
183
+ st = tfunc(t)
184
+ assert _is_tensor_eq(st, t)
185
+
186
+
187
+ def test_kahane_algorithm():
188
+ # Wrap this function to convert to and from TIDS:
189
+
190
+ def tfunc(e):
191
+ return _simplify_single_line(e)
192
+
193
+ execute_gamma_simplify_tests_for_function(tfunc, D=4)
194
+
195
+
196
+ def test_kahane_simplify1():
197
+ i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15 = tensor_indices('i0:16', LorentzIndex)
198
+ mu, nu, rho, sigma = tensor_indices("mu, nu, rho, sigma", LorentzIndex)
199
+ D = 4
200
+ t = G(i0)*G(i1)
201
+ r = kahane_simplify(t)
202
+ assert r.equals(t)
203
+
204
+ t = G(i0)*G(i1)*G(-i0)
205
+ r = kahane_simplify(t)
206
+ assert r.equals(-2*G(i1))
207
+ t = G(i0)*G(i1)*G(-i0)
208
+ r = kahane_simplify(t)
209
+ assert r.equals(-2*G(i1))
210
+
211
+ t = G(i0)*G(i1)
212
+ r = kahane_simplify(t)
213
+ assert r.equals(t)
214
+ t = G(i0)*G(i1)
215
+ r = kahane_simplify(t)
216
+ assert r.equals(t)
217
+ t = G(i0)*G(-i0)
218
+ r = kahane_simplify(t)
219
+ assert r.equals(4*eye(4))
220
+ t = G(i0)*G(-i0)
221
+ r = kahane_simplify(t)
222
+ assert r.equals(4*eye(4))
223
+ t = G(i0)*G(-i0)
224
+ r = kahane_simplify(t)
225
+ assert r.equals(4*eye(4))
226
+ t = G(i0)*G(i1)*G(-i0)
227
+ r = kahane_simplify(t)
228
+ assert r.equals(-2*G(i1))
229
+ t = G(i0)*G(i1)*G(-i0)*G(-i1)
230
+ r = kahane_simplify(t)
231
+ assert r.equals((2*D - D**2)*eye(4))
232
+ t = G(i0)*G(i1)*G(-i0)*G(-i1)
233
+ r = kahane_simplify(t)
234
+ assert r.equals((2*D - D**2)*eye(4))
235
+ t = G(i0)*G(-i0)*G(i1)*G(-i1)
236
+ r = kahane_simplify(t)
237
+ assert r.equals(16*eye(4))
238
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
239
+ r = kahane_simplify(t)
240
+ assert r.equals(D**2*eye(4))
241
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
242
+ r = kahane_simplify(t)
243
+ assert r.equals(D**2*eye(4))
244
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
245
+ r = kahane_simplify(t)
246
+ assert r.equals(D**2*eye(4))
247
+ t = (G(mu)*G(nu)*G(-rho)*G(-nu)*G(-mu)*G(rho))
248
+ r = kahane_simplify(t)
249
+ assert r.equals((4*D - 4*D**2 + D**3)*eye(4))
250
+ t = (G(-mu)*G(-nu)*G(-rho)*G(-sigma)*G(nu)*G(mu)*G(sigma)*G(rho))
251
+ r = kahane_simplify(t)
252
+ assert r.equals((-16*D + 24*D**2 - 8*D**3 + D**4)*eye(4))
253
+ t = (G(-mu)*G(nu)*G(-rho)*G(sigma)*G(rho)*G(-nu)*G(mu)*G(-sigma))
254
+ r = kahane_simplify(t)
255
+ assert r.equals((8*D - 12*D**2 + 6*D**3 - D**4)*eye(4))
256
+
257
+ # Expressions with free indices:
258
+ t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
259
+ r = kahane_simplify(t)
260
+ assert r.equals(-2*G(sigma)*G(rho)*G(nu))
261
+ t = (G(mu)*G(-mu)*G(rho)*G(sigma))
262
+ r = kahane_simplify(t)
263
+ assert r.equals(4*G(rho)*G(sigma))
264
+ t = (G(rho)*G(sigma)*G(mu)*G(-mu))
265
+ r = kahane_simplify(t)
266
+ assert r.equals(4*G(rho)*G(sigma))
267
+
268
+ def test_gamma_matrix_class():
269
+ i, j, k = tensor_indices('i,j,k', LorentzIndex)
270
+
271
+ # define another type of TensorHead to see if exprs are correctly handled:
272
+ A = TensorHead('A', [LorentzIndex])
273
+
274
+ t = A(k)*G(i)*G(-i)
275
+ ts = simplify_gamma_expression(t)
276
+ assert _is_tensor_eq(ts, Matrix([
277
+ [4, 0, 0, 0],
278
+ [0, 4, 0, 0],
279
+ [0, 0, 4, 0],
280
+ [0, 0, 0, 4]])*A(k))
281
+
282
+ t = G(i)*A(k)*G(j)
283
+ ts = simplify_gamma_expression(t)
284
+ assert _is_tensor_eq(ts, A(k)*G(i)*G(j))
285
+
286
+ execute_gamma_simplify_tests_for_function(simplify_gamma_expression, D=4)
287
+
288
+
289
+ def test_gamma_matrix_trace():
290
+ g = LorentzIndex.metric
291
+
292
+ m0, m1, m2, m3, m4, m5, m6 = tensor_indices('m0:7', LorentzIndex)
293
+ n0, n1, n2, n3, n4, n5 = tensor_indices('n0:6', LorentzIndex)
294
+
295
+ # working in D=4 dimensions
296
+ D = 4
297
+
298
+ # traces of odd number of gamma matrices are zero:
299
+ t = G(m0)
300
+ t1 = gamma_trace(t)
301
+ assert t1.equals(0)
302
+
303
+ t = G(m0)*G(m1)*G(m2)
304
+ t1 = gamma_trace(t)
305
+ assert t1.equals(0)
306
+
307
+ t = G(m0)*G(m1)*G(-m0)
308
+ t1 = gamma_trace(t)
309
+ assert t1.equals(0)
310
+
311
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)
312
+ t1 = gamma_trace(t)
313
+ assert t1.equals(0)
314
+
315
+ # traces without internal contractions:
316
+ t = G(m0)*G(m1)
317
+ t1 = gamma_trace(t)
318
+ assert _is_tensor_eq(t1, 4*g(m0, m1))
319
+
320
+ t = G(m0)*G(m1)*G(m2)*G(m3)
321
+ t1 = gamma_trace(t)
322
+ t2 = -4*g(m0, m2)*g(m1, m3) + 4*g(m0, m1)*g(m2, m3) + 4*g(m0, m3)*g(m1, m2)
323
+ assert _is_tensor_eq(t1, t2)
324
+
325
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(m5)
326
+ t1 = gamma_trace(t)
327
+ t2 = t1*g(-m0, -m5)
328
+ t2 = t2.contract_metric(g)
329
+ assert _is_tensor_eq(t2, D*gamma_trace(G(m1)*G(m2)*G(m3)*G(m4)))
330
+
331
+ # traces of expressions with internal contractions:
332
+ t = G(m0)*G(-m0)
333
+ t1 = gamma_trace(t)
334
+ assert t1.equals(4*D)
335
+
336
+ t = G(m0)*G(m1)*G(-m0)*G(-m1)
337
+ t1 = gamma_trace(t)
338
+ assert t1.equals(8*D - 4*D**2)
339
+
340
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)
341
+ t1 = gamma_trace(t)
342
+ t2 = (-4*D)*g(m1, m3)*g(m2, m4) + (4*D)*g(m1, m2)*g(m3, m4) + \
343
+ (4*D)*g(m1, m4)*g(m2, m3)
344
+ assert _is_tensor_eq(t1, t2)
345
+
346
+ t = G(-m5)*G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)*G(m5)
347
+ t1 = gamma_trace(t)
348
+ t2 = (32*D + 4*(-D + 4)**2 - 64)*(g(m1, m2)*g(m3, m4) - \
349
+ g(m1, m3)*g(m2, m4) + g(m1, m4)*g(m2, m3))
350
+ assert _is_tensor_eq(t1, t2)
351
+
352
+ t = G(m0)*G(m1)*G(-m0)*G(m3)
353
+ t1 = gamma_trace(t)
354
+ assert t1.equals((-4*D + 8)*g(m1, m3))
355
+
356
+ # p, q = S1('p,q')
357
+ # ps = p(m0)*G(-m0)
358
+ # qs = q(m0)*G(-m0)
359
+ # t = ps*qs*ps*qs
360
+ # t1 = gamma_trace(t)
361
+ # assert t1 == 8*p(m0)*q(-m0)*p(m1)*q(-m1) - 4*p(m0)*p(-m0)*q(m1)*q(-m1)
362
+
363
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(m5)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)*G(-m5)
364
+ t1 = gamma_trace(t)
365
+ assert t1.equals(-4*D**6 + 120*D**5 - 1040*D**4 + 3360*D**3 - 4480*D**2 + 2048*D)
366
+
367
+ t = G(m0)*G(m1)*G(n1)*G(m2)*G(n2)*G(m3)*G(m4)*G(-n2)*G(-n1)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)
368
+ t1 = gamma_trace(t)
369
+ tresu = -7168*D + 16768*D**2 - 14400*D**3 + 5920*D**4 - 1232*D**5 + 120*D**6 - 4*D**7
370
+ assert t1.equals(tresu)
371
+
372
+ # checked with Mathematica
373
+ # In[1]:= <<Tracer.m
374
+ # In[2]:= Spur[l];
375
+ # In[3]:= GammaTrace[l, {m0},{m1},{n1},{m2},{n2},{m3},{m4},{n3},{n4},{m0},{m1},{m2},{m3},{m4}]
376
+ t = G(m0)*G(m1)*G(n1)*G(m2)*G(n2)*G(m3)*G(m4)*G(n3)*G(n4)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)
377
+ t1 = gamma_trace(t)
378
+ # t1 = t1.expand_coeff()
379
+ c1 = -4*D**5 + 120*D**4 - 1200*D**3 + 5280*D**2 - 10560*D + 7808
380
+ c2 = -4*D**5 + 88*D**4 - 560*D**3 + 1440*D**2 - 1600*D + 640
381
+ assert _is_tensor_eq(t1, c1*g(n1, n4)*g(n2, n3) + c2*g(n1, n2)*g(n3, n4) + \
382
+ (-c1)*g(n1, n3)*g(n2, n4))
383
+
384
+ p, q = tensor_heads('p,q', [LorentzIndex])
385
+ ps = p(m0)*G(-m0)
386
+ qs = q(m0)*G(-m0)
387
+ p2 = p(m0)*p(-m0)
388
+ q2 = q(m0)*q(-m0)
389
+ pq = p(m0)*q(-m0)
390
+ t = ps*qs*ps*qs
391
+ r = gamma_trace(t)
392
+ assert _is_tensor_eq(r, 8*pq*pq - 4*p2*q2)
393
+ t = ps*qs*ps*qs*ps*qs
394
+ r = gamma_trace(t)
395
+ assert _is_tensor_eq(r, -12*p2*pq*q2 + 16*pq*pq*pq)
396
+ t = ps*qs*ps*qs*ps*qs*ps*qs
397
+ r = gamma_trace(t)
398
+ assert _is_tensor_eq(r, -32*pq*pq*p2*q2 + 32*pq*pq*pq*pq + 4*p2*p2*q2*q2)
399
+
400
+ t = 4*p(m1)*p(m0)*p(-m0)*q(-m1)*q(m2)*q(-m2)
401
+ assert _is_tensor_eq(gamma_trace(t), t)
402
+ t = ps*ps*ps*ps*ps*ps*ps*ps
403
+ r = gamma_trace(t)
404
+ assert r.equals(4*p2*p2*p2*p2)
405
+
406
+
407
+ def test_bug_13636():
408
+ """Test issue 13636 regarding handling traces of sums of products
409
+ of GammaMatrix mixed with other factors."""
410
+ pi, ki, pf = tensor_heads("pi, ki, pf", [LorentzIndex])
411
+ i0, i1, i2, i3, i4 = tensor_indices("i0:5", LorentzIndex)
412
+ x = Symbol("x")
413
+ pis = pi(i2) * G(-i2)
414
+ kis = ki(i3) * G(-i3)
415
+ pfs = pf(i4) * G(-i4)
416
+
417
+ a = pfs * G(i0) * kis * G(i1) * pis * G(-i1) * kis * G(-i0)
418
+ b = pfs * G(i0) * kis * G(i1) * pis * x * G(-i0) * pi(-i1)
419
+ ta = gamma_trace(a)
420
+ tb = gamma_trace(b)
421
+ t_a_plus_b = gamma_trace(a + b)
422
+ assert ta == 4 * (
423
+ -4 * ki(i0) * ki(-i0) * pf(i1) * pi(-i1)
424
+ + 8 * ki(i0) * ki(i1) * pf(-i0) * pi(-i1)
425
+ )
426
+ assert tb == -8 * x * ki(i0) * pf(-i0) * pi(i1) * pi(-i1)
427
+ assert t_a_plus_b == ta + tb
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/optics/__init__.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = [
2
+ 'TWave',
3
+
4
+ 'RayTransferMatrix', 'FreeSpace', 'FlatRefraction', 'CurvedRefraction',
5
+ 'FlatMirror', 'CurvedMirror', 'ThinLens', 'GeometricRay', 'BeamParameter',
6
+ 'waist2rayleigh', 'rayleigh2waist', 'geometric_conj_ab',
7
+ 'geometric_conj_af', 'geometric_conj_bf', 'gaussian_conj',
8
+ 'conjugate_gauss_beams',
9
+
10
+ 'Medium',
11
+
12
+ 'refraction_angle', 'deviation', 'fresnel_coefficients', 'brewster_angle',
13
+ 'critical_angle', 'lens_makers_formula', 'mirror_formula', 'lens_formula',
14
+ 'hyperfocal_distance', 'transverse_magnification',
15
+
16
+ 'jones_vector', 'stokes_vector', 'jones_2_stokes', 'linear_polarizer',
17
+ 'phase_retarder', 'half_wave_retarder', 'quarter_wave_retarder',
18
+ 'transmissive_filter', 'reflective_filter', 'mueller_matrix',
19
+ 'polarizing_beam_splitter',
20
+ ]
21
+ from .waves import TWave
22
+
23
+ from .gaussopt import (RayTransferMatrix, FreeSpace, FlatRefraction,
24
+ CurvedRefraction, FlatMirror, CurvedMirror, ThinLens, GeometricRay,
25
+ BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab,
26
+ geometric_conj_af, geometric_conj_bf, gaussian_conj,
27
+ conjugate_gauss_beams)
28
+
29
+ from .medium import Medium
30
+
31
+ from .utils import (refraction_angle, deviation, fresnel_coefficients,
32
+ brewster_angle, critical_angle, lens_makers_formula, mirror_formula,
33
+ lens_formula, hyperfocal_distance, transverse_magnification)
34
+
35
+ from .polarization import (jones_vector, stokes_vector, jones_2_stokes,
36
+ linear_polarizer, phase_retarder, half_wave_retarder,
37
+ quarter_wave_retarder, transmissive_filter, reflective_filter,
38
+ mueller_matrix, polarizing_beam_splitter)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.51 kB). View file