Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- pllava/lib/python3.10/site-packages/sympy/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/__pycache__/abc.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/__pycache__/conftest.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/__pycache__/galgebra.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/__pycache__/release.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/__pycache__/this.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/algebras/__pycache__/quaternion.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/algebras/quaternion.py +1667 -0
- pllava/lib/python3.10/site-packages/sympy/algebras/tests/__init__.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/algebras/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/calculus.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/common.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/ntheory.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/order.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/sets.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/categories/__init__.py +33 -0
- pllava/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/categories/baseclasses.py +978 -0
- pllava/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py +2582 -0
- pllava/lib/python3.10/site-packages/sympy/categories/tests/__init__.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/categories/tests/test_baseclasses.py +209 -0
- pllava/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py +919 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/__init__.py +19 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/diffgeom.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/diffgeom.py +2270 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/rn.py +143 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__init__.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_class_structure.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_diffgeom.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_function_diffgeom_book.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_hyperbolic_space.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/test_class_structure.py +33 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/test_diffgeom.py +342 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/test_function_diffgeom_book.py +145 -0
- pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/test_hyperbolic_space.py +91 -0
- pllava/lib/python3.10/site-packages/sympy/polys/__pycache__/polytools.cpython-310.pyc +3 -0
- pllava/lib/python3.10/site-packages/sympy/polys/tests/__pycache__/test_polytools.cpython-310.pyc +3 -0
- pllava/lib/python3.10/site-packages/sympy/tensor/__init__.py +23 -0
- pllava/lib/python3.10/site-packages/sympy/tensor/array/__init__.py +271 -0
- pllava/lib/python3.10/site-packages/sympy/tensor/array/array_derivatives.py +129 -0
- pllava/lib/python3.10/site-packages/sympy/tensor/array/dense_ndim_array.py +206 -0
.gitattributes
CHANGED
|
@@ -297,3 +297,5 @@ pllava/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__pycach
|
|
| 297 |
pllava/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 298 |
pllava/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 299 |
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_spin.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 297 |
pllava/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 298 |
pllava/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 299 |
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_spin.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 300 |
+
pllava/lib/python3.10/site-packages/sympy/polys/__pycache__/polytools.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 301 |
+
pllava/lib/python3.10/site-packages/sympy/polys/tests/__pycache__/test_polytools.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
pllava/lib/python3.10/site-packages/sympy/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (28.3 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/__pycache__/abc.cpython-310.pyc
ADDED
|
Binary file (3.51 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/__pycache__/conftest.cpython-310.pyc
ADDED
|
Binary file (2.93 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/__pycache__/galgebra.cpython-310.pyc
ADDED
|
Binary file (269 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/__pycache__/release.cpython-310.pyc
ADDED
|
Binary file (178 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/__pycache__/this.cpython-310.pyc
ADDED
|
Binary file (717 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/algebras/__pycache__/quaternion.cpython-310.pyc
ADDED
|
Binary file (47.2 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/algebras/quaternion.py
ADDED
|
@@ -0,0 +1,1667 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import Rational
|
| 2 |
+
from sympy.core.singleton import S
|
| 3 |
+
from sympy.core.relational import is_eq
|
| 4 |
+
from sympy.functions.elementary.complexes import (conjugate, im, re, sign)
|
| 5 |
+
from sympy.functions.elementary.exponential import (exp, log as ln)
|
| 6 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 7 |
+
from sympy.functions.elementary.trigonometric import (acos, asin, atan2)
|
| 8 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 9 |
+
from sympy.simplify.trigsimp import trigsimp
|
| 10 |
+
from sympy.integrals.integrals import integrate
|
| 11 |
+
from sympy.matrices.dense import MutableDenseMatrix as Matrix
|
| 12 |
+
from sympy.core.sympify import sympify, _sympify
|
| 13 |
+
from sympy.core.expr import Expr
|
| 14 |
+
from sympy.core.logic import fuzzy_not, fuzzy_or
|
| 15 |
+
from sympy.utilities.misc import as_int
|
| 16 |
+
|
| 17 |
+
from mpmath.libmp.libmpf import prec_to_dps
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _check_norm(elements, norm):
|
| 21 |
+
"""validate if input norm is consistent"""
|
| 22 |
+
if norm is not None and norm.is_number:
|
| 23 |
+
if norm.is_positive is False:
|
| 24 |
+
raise ValueError("Input norm must be positive.")
|
| 25 |
+
|
| 26 |
+
numerical = all(i.is_number and i.is_real is True for i in elements)
|
| 27 |
+
if numerical and is_eq(norm**2, sum(i**2 for i in elements)) is False:
|
| 28 |
+
raise ValueError("Incompatible value for norm.")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _is_extrinsic(seq):
|
| 32 |
+
"""validate seq and return True if seq is lowercase and False if uppercase"""
|
| 33 |
+
if type(seq) != str:
|
| 34 |
+
raise ValueError('Expected seq to be a string.')
|
| 35 |
+
if len(seq) != 3:
|
| 36 |
+
raise ValueError("Expected 3 axes, got `{}`.".format(seq))
|
| 37 |
+
|
| 38 |
+
intrinsic = seq.isupper()
|
| 39 |
+
extrinsic = seq.islower()
|
| 40 |
+
if not (intrinsic or extrinsic):
|
| 41 |
+
raise ValueError("seq must either be fully uppercase (for extrinsic "
|
| 42 |
+
"rotations), or fully lowercase, for intrinsic "
|
| 43 |
+
"rotations).")
|
| 44 |
+
|
| 45 |
+
i, j, k = seq.lower()
|
| 46 |
+
if (i == j) or (j == k):
|
| 47 |
+
raise ValueError("Consecutive axes must be different")
|
| 48 |
+
|
| 49 |
+
bad = set(seq) - set('xyzXYZ')
|
| 50 |
+
if bad:
|
| 51 |
+
raise ValueError("Expected axes from `seq` to be from "
|
| 52 |
+
"['x', 'y', 'z'] or ['X', 'Y', 'Z'], "
|
| 53 |
+
"got {}".format(''.join(bad)))
|
| 54 |
+
|
| 55 |
+
return extrinsic
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Quaternion(Expr):
|
| 59 |
+
"""Provides basic quaternion operations.
|
| 60 |
+
Quaternion objects can be instantiated as ``Quaternion(a, b, c, d)``
|
| 61 |
+
as in $q = a + bi + cj + dk$.
|
| 62 |
+
|
| 63 |
+
Parameters
|
| 64 |
+
==========
|
| 65 |
+
|
| 66 |
+
norm : None or number
|
| 67 |
+
Pre-defined quaternion norm. If a value is given, Quaternion.norm
|
| 68 |
+
returns this pre-defined value instead of calculating the norm
|
| 69 |
+
|
| 70 |
+
Examples
|
| 71 |
+
========
|
| 72 |
+
|
| 73 |
+
>>> from sympy import Quaternion
|
| 74 |
+
>>> q = Quaternion(1, 2, 3, 4)
|
| 75 |
+
>>> q
|
| 76 |
+
1 + 2*i + 3*j + 4*k
|
| 77 |
+
|
| 78 |
+
Quaternions over complex fields can be defined as:
|
| 79 |
+
|
| 80 |
+
>>> from sympy import Quaternion
|
| 81 |
+
>>> from sympy import symbols, I
|
| 82 |
+
>>> x = symbols('x')
|
| 83 |
+
>>> q1 = Quaternion(x, x**3, x, x**2, real_field = False)
|
| 84 |
+
>>> q2 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
|
| 85 |
+
>>> q1
|
| 86 |
+
x + x**3*i + x*j + x**2*k
|
| 87 |
+
>>> q2
|
| 88 |
+
(3 + 4*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k
|
| 89 |
+
|
| 90 |
+
Defining symbolic unit quaternions:
|
| 91 |
+
|
| 92 |
+
>>> from sympy import Quaternion
|
| 93 |
+
>>> from sympy.abc import w, x, y, z
|
| 94 |
+
>>> q = Quaternion(w, x, y, z, norm=1)
|
| 95 |
+
>>> q
|
| 96 |
+
w + x*i + y*j + z*k
|
| 97 |
+
>>> q.norm()
|
| 98 |
+
1
|
| 99 |
+
|
| 100 |
+
References
|
| 101 |
+
==========
|
| 102 |
+
|
| 103 |
+
.. [1] https://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/
|
| 104 |
+
.. [2] https://en.wikipedia.org/wiki/Quaternion
|
| 105 |
+
|
| 106 |
+
"""
|
| 107 |
+
_op_priority = 11.0
|
| 108 |
+
|
| 109 |
+
is_commutative = False
|
| 110 |
+
|
| 111 |
+
def __new__(cls, a=0, b=0, c=0, d=0, real_field=True, norm=None):
|
| 112 |
+
a, b, c, d = map(sympify, (a, b, c, d))
|
| 113 |
+
|
| 114 |
+
if any(i.is_commutative is False for i in [a, b, c, d]):
|
| 115 |
+
raise ValueError("arguments have to be commutative")
|
| 116 |
+
obj = super().__new__(cls, a, b, c, d)
|
| 117 |
+
obj._real_field = real_field
|
| 118 |
+
obj.set_norm(norm)
|
| 119 |
+
return obj
|
| 120 |
+
|
| 121 |
+
def set_norm(self, norm):
|
| 122 |
+
"""Sets norm of an already instantiated quaternion.
|
| 123 |
+
|
| 124 |
+
Parameters
|
| 125 |
+
==========
|
| 126 |
+
|
| 127 |
+
norm : None or number
|
| 128 |
+
Pre-defined quaternion norm. If a value is given, Quaternion.norm
|
| 129 |
+
returns this pre-defined value instead of calculating the norm
|
| 130 |
+
|
| 131 |
+
Examples
|
| 132 |
+
========
|
| 133 |
+
|
| 134 |
+
>>> from sympy import Quaternion
|
| 135 |
+
>>> from sympy.abc import a, b, c, d
|
| 136 |
+
>>> q = Quaternion(a, b, c, d)
|
| 137 |
+
>>> q.norm()
|
| 138 |
+
sqrt(a**2 + b**2 + c**2 + d**2)
|
| 139 |
+
|
| 140 |
+
Setting the norm:
|
| 141 |
+
|
| 142 |
+
>>> q.set_norm(1)
|
| 143 |
+
>>> q.norm()
|
| 144 |
+
1
|
| 145 |
+
|
| 146 |
+
Removing set norm:
|
| 147 |
+
|
| 148 |
+
>>> q.set_norm(None)
|
| 149 |
+
>>> q.norm()
|
| 150 |
+
sqrt(a**2 + b**2 + c**2 + d**2)
|
| 151 |
+
|
| 152 |
+
"""
|
| 153 |
+
norm = sympify(norm)
|
| 154 |
+
_check_norm(self.args, norm)
|
| 155 |
+
self._norm = norm
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
def a(self):
|
| 159 |
+
return self.args[0]
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def b(self):
|
| 163 |
+
return self.args[1]
|
| 164 |
+
|
| 165 |
+
@property
|
| 166 |
+
def c(self):
|
| 167 |
+
return self.args[2]
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def d(self):
|
| 171 |
+
return self.args[3]
|
| 172 |
+
|
| 173 |
+
@property
|
| 174 |
+
def real_field(self):
|
| 175 |
+
return self._real_field
|
| 176 |
+
|
| 177 |
+
@property
|
| 178 |
+
def product_matrix_left(self):
|
| 179 |
+
r"""Returns 4 x 4 Matrix equivalent to a Hamilton product from the
|
| 180 |
+
left. This can be useful when treating quaternion elements as column
|
| 181 |
+
vectors. Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d
|
| 182 |
+
are real numbers, the product matrix from the left is:
|
| 183 |
+
|
| 184 |
+
.. math::
|
| 185 |
+
|
| 186 |
+
M = \begin{bmatrix} a &-b &-c &-d \\
|
| 187 |
+
b & a &-d & c \\
|
| 188 |
+
c & d & a &-b \\
|
| 189 |
+
d &-c & b & a \end{bmatrix}
|
| 190 |
+
|
| 191 |
+
Examples
|
| 192 |
+
========
|
| 193 |
+
|
| 194 |
+
>>> from sympy import Quaternion
|
| 195 |
+
>>> from sympy.abc import a, b, c, d
|
| 196 |
+
>>> q1 = Quaternion(1, 0, 0, 1)
|
| 197 |
+
>>> q2 = Quaternion(a, b, c, d)
|
| 198 |
+
>>> q1.product_matrix_left
|
| 199 |
+
Matrix([
|
| 200 |
+
[1, 0, 0, -1],
|
| 201 |
+
[0, 1, -1, 0],
|
| 202 |
+
[0, 1, 1, 0],
|
| 203 |
+
[1, 0, 0, 1]])
|
| 204 |
+
|
| 205 |
+
>>> q1.product_matrix_left * q2.to_Matrix()
|
| 206 |
+
Matrix([
|
| 207 |
+
[a - d],
|
| 208 |
+
[b - c],
|
| 209 |
+
[b + c],
|
| 210 |
+
[a + d]])
|
| 211 |
+
|
| 212 |
+
This is equivalent to:
|
| 213 |
+
|
| 214 |
+
>>> (q1 * q2).to_Matrix()
|
| 215 |
+
Matrix([
|
| 216 |
+
[a - d],
|
| 217 |
+
[b - c],
|
| 218 |
+
[b + c],
|
| 219 |
+
[a + d]])
|
| 220 |
+
"""
|
| 221 |
+
return Matrix([
|
| 222 |
+
[self.a, -self.b, -self.c, -self.d],
|
| 223 |
+
[self.b, self.a, -self.d, self.c],
|
| 224 |
+
[self.c, self.d, self.a, -self.b],
|
| 225 |
+
[self.d, -self.c, self.b, self.a]])
|
| 226 |
+
|
| 227 |
+
@property
|
| 228 |
+
def product_matrix_right(self):
|
| 229 |
+
r"""Returns 4 x 4 Matrix equivalent to a Hamilton product from the
|
| 230 |
+
right. This can be useful when treating quaternion elements as column
|
| 231 |
+
vectors. Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d
|
| 232 |
+
are real numbers, the product matrix from the left is:
|
| 233 |
+
|
| 234 |
+
.. math::
|
| 235 |
+
|
| 236 |
+
M = \begin{bmatrix} a &-b &-c &-d \\
|
| 237 |
+
b & a & d &-c \\
|
| 238 |
+
c &-d & a & b \\
|
| 239 |
+
d & c &-b & a \end{bmatrix}
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
Examples
|
| 243 |
+
========
|
| 244 |
+
|
| 245 |
+
>>> from sympy import Quaternion
|
| 246 |
+
>>> from sympy.abc import a, b, c, d
|
| 247 |
+
>>> q1 = Quaternion(a, b, c, d)
|
| 248 |
+
>>> q2 = Quaternion(1, 0, 0, 1)
|
| 249 |
+
>>> q2.product_matrix_right
|
| 250 |
+
Matrix([
|
| 251 |
+
[1, 0, 0, -1],
|
| 252 |
+
[0, 1, 1, 0],
|
| 253 |
+
[0, -1, 1, 0],
|
| 254 |
+
[1, 0, 0, 1]])
|
| 255 |
+
|
| 256 |
+
Note the switched arguments: the matrix represents the quaternion on
|
| 257 |
+
the right, but is still considered as a matrix multiplication from the
|
| 258 |
+
left.
|
| 259 |
+
|
| 260 |
+
>>> q2.product_matrix_right * q1.to_Matrix()
|
| 261 |
+
Matrix([
|
| 262 |
+
[ a - d],
|
| 263 |
+
[ b + c],
|
| 264 |
+
[-b + c],
|
| 265 |
+
[ a + d]])
|
| 266 |
+
|
| 267 |
+
This is equivalent to:
|
| 268 |
+
|
| 269 |
+
>>> (q1 * q2).to_Matrix()
|
| 270 |
+
Matrix([
|
| 271 |
+
[ a - d],
|
| 272 |
+
[ b + c],
|
| 273 |
+
[-b + c],
|
| 274 |
+
[ a + d]])
|
| 275 |
+
"""
|
| 276 |
+
return Matrix([
|
| 277 |
+
[self.a, -self.b, -self.c, -self.d],
|
| 278 |
+
[self.b, self.a, self.d, -self.c],
|
| 279 |
+
[self.c, -self.d, self.a, self.b],
|
| 280 |
+
[self.d, self.c, -self.b, self.a]])
|
| 281 |
+
|
| 282 |
+
def to_Matrix(self, vector_only=False):
|
| 283 |
+
"""Returns elements of quaternion as a column vector.
|
| 284 |
+
By default, a ``Matrix`` of length 4 is returned, with the real part as the
|
| 285 |
+
first element.
|
| 286 |
+
If ``vector_only`` is ``True``, returns only imaginary part as a Matrix of
|
| 287 |
+
length 3.
|
| 288 |
+
|
| 289 |
+
Parameters
|
| 290 |
+
==========
|
| 291 |
+
|
| 292 |
+
vector_only : bool
|
| 293 |
+
If True, only imaginary part is returned.
|
| 294 |
+
Default value: False
|
| 295 |
+
|
| 296 |
+
Returns
|
| 297 |
+
=======
|
| 298 |
+
|
| 299 |
+
Matrix
|
| 300 |
+
A column vector constructed by the elements of the quaternion.
|
| 301 |
+
|
| 302 |
+
Examples
|
| 303 |
+
========
|
| 304 |
+
|
| 305 |
+
>>> from sympy import Quaternion
|
| 306 |
+
>>> from sympy.abc import a, b, c, d
|
| 307 |
+
>>> q = Quaternion(a, b, c, d)
|
| 308 |
+
>>> q
|
| 309 |
+
a + b*i + c*j + d*k
|
| 310 |
+
|
| 311 |
+
>>> q.to_Matrix()
|
| 312 |
+
Matrix([
|
| 313 |
+
[a],
|
| 314 |
+
[b],
|
| 315 |
+
[c],
|
| 316 |
+
[d]])
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
>>> q.to_Matrix(vector_only=True)
|
| 320 |
+
Matrix([
|
| 321 |
+
[b],
|
| 322 |
+
[c],
|
| 323 |
+
[d]])
|
| 324 |
+
|
| 325 |
+
"""
|
| 326 |
+
if vector_only:
|
| 327 |
+
return Matrix(self.args[1:])
|
| 328 |
+
else:
|
| 329 |
+
return Matrix(self.args)
|
| 330 |
+
|
| 331 |
+
@classmethod
|
| 332 |
+
def from_Matrix(cls, elements):
|
| 333 |
+
"""Returns quaternion from elements of a column vector`.
|
| 334 |
+
If vector_only is True, returns only imaginary part as a Matrix of
|
| 335 |
+
length 3.
|
| 336 |
+
|
| 337 |
+
Parameters
|
| 338 |
+
==========
|
| 339 |
+
|
| 340 |
+
elements : Matrix, list or tuple of length 3 or 4. If length is 3,
|
| 341 |
+
assume real part is zero.
|
| 342 |
+
Default value: False
|
| 343 |
+
|
| 344 |
+
Returns
|
| 345 |
+
=======
|
| 346 |
+
|
| 347 |
+
Quaternion
|
| 348 |
+
A quaternion created from the input elements.
|
| 349 |
+
|
| 350 |
+
Examples
|
| 351 |
+
========
|
| 352 |
+
|
| 353 |
+
>>> from sympy import Quaternion
|
| 354 |
+
>>> from sympy.abc import a, b, c, d
|
| 355 |
+
>>> q = Quaternion.from_Matrix([a, b, c, d])
|
| 356 |
+
>>> q
|
| 357 |
+
a + b*i + c*j + d*k
|
| 358 |
+
|
| 359 |
+
>>> q = Quaternion.from_Matrix([b, c, d])
|
| 360 |
+
>>> q
|
| 361 |
+
0 + b*i + c*j + d*k
|
| 362 |
+
|
| 363 |
+
"""
|
| 364 |
+
length = len(elements)
|
| 365 |
+
if length != 3 and length != 4:
|
| 366 |
+
raise ValueError("Input elements must have length 3 or 4, got {} "
|
| 367 |
+
"elements".format(length))
|
| 368 |
+
|
| 369 |
+
if length == 3:
|
| 370 |
+
return Quaternion(0, *elements)
|
| 371 |
+
else:
|
| 372 |
+
return Quaternion(*elements)
|
| 373 |
+
|
| 374 |
+
@classmethod
|
| 375 |
+
def from_euler(cls, angles, seq):
|
| 376 |
+
"""Returns quaternion equivalent to rotation represented by the Euler
|
| 377 |
+
angles, in the sequence defined by ``seq``.
|
| 378 |
+
|
| 379 |
+
Parameters
|
| 380 |
+
==========
|
| 381 |
+
|
| 382 |
+
angles : list, tuple or Matrix of 3 numbers
|
| 383 |
+
The Euler angles (in radians).
|
| 384 |
+
seq : string of length 3
|
| 385 |
+
Represents the sequence of rotations.
|
| 386 |
+
For extrinsic rotations, seq must be all lowercase and its elements
|
| 387 |
+
must be from the set ``{'x', 'y', 'z'}``
|
| 388 |
+
For intrinsic rotations, seq must be all uppercase and its elements
|
| 389 |
+
must be from the set ``{'X', 'Y', 'Z'}``
|
| 390 |
+
|
| 391 |
+
Returns
|
| 392 |
+
=======
|
| 393 |
+
|
| 394 |
+
Quaternion
|
| 395 |
+
The normalized rotation quaternion calculated from the Euler angles
|
| 396 |
+
in the given sequence.
|
| 397 |
+
|
| 398 |
+
Examples
|
| 399 |
+
========
|
| 400 |
+
|
| 401 |
+
>>> from sympy import Quaternion
|
| 402 |
+
>>> from sympy import pi
|
| 403 |
+
>>> q = Quaternion.from_euler([pi/2, 0, 0], 'xyz')
|
| 404 |
+
>>> q
|
| 405 |
+
sqrt(2)/2 + sqrt(2)/2*i + 0*j + 0*k
|
| 406 |
+
|
| 407 |
+
>>> q = Quaternion.from_euler([0, pi/2, pi] , 'zyz')
|
| 408 |
+
>>> q
|
| 409 |
+
0 + (-sqrt(2)/2)*i + 0*j + sqrt(2)/2*k
|
| 410 |
+
|
| 411 |
+
>>> q = Quaternion.from_euler([0, pi/2, pi] , 'ZYZ')
|
| 412 |
+
>>> q
|
| 413 |
+
0 + sqrt(2)/2*i + 0*j + sqrt(2)/2*k
|
| 414 |
+
|
| 415 |
+
"""
|
| 416 |
+
|
| 417 |
+
if len(angles) != 3:
|
| 418 |
+
raise ValueError("3 angles must be given.")
|
| 419 |
+
|
| 420 |
+
extrinsic = _is_extrinsic(seq)
|
| 421 |
+
i, j, k = seq.lower()
|
| 422 |
+
|
| 423 |
+
# get elementary basis vectors
|
| 424 |
+
ei = [1 if n == i else 0 for n in 'xyz']
|
| 425 |
+
ej = [1 if n == j else 0 for n in 'xyz']
|
| 426 |
+
ek = [1 if n == k else 0 for n in 'xyz']
|
| 427 |
+
|
| 428 |
+
# calculate distinct quaternions
|
| 429 |
+
qi = cls.from_axis_angle(ei, angles[0])
|
| 430 |
+
qj = cls.from_axis_angle(ej, angles[1])
|
| 431 |
+
qk = cls.from_axis_angle(ek, angles[2])
|
| 432 |
+
|
| 433 |
+
if extrinsic:
|
| 434 |
+
return trigsimp(qk * qj * qi)
|
| 435 |
+
else:
|
| 436 |
+
return trigsimp(qi * qj * qk)
|
| 437 |
+
|
| 438 |
+
def to_euler(self, seq, angle_addition=True, avoid_square_root=False):
|
| 439 |
+
r"""Returns Euler angles representing same rotation as the quaternion,
|
| 440 |
+
in the sequence given by ``seq``. This implements the method described
|
| 441 |
+
in [1]_.
|
| 442 |
+
|
| 443 |
+
For degenerate cases (gymbal lock cases), the third angle is
|
| 444 |
+
set to zero.
|
| 445 |
+
|
| 446 |
+
Parameters
|
| 447 |
+
==========
|
| 448 |
+
|
| 449 |
+
seq : string of length 3
|
| 450 |
+
Represents the sequence of rotations.
|
| 451 |
+
For extrinsic rotations, seq must be all lowercase and its elements
|
| 452 |
+
must be from the set ``{'x', 'y', 'z'}``
|
| 453 |
+
For intrinsic rotations, seq must be all uppercase and its elements
|
| 454 |
+
must be from the set ``{'X', 'Y', 'Z'}``
|
| 455 |
+
|
| 456 |
+
angle_addition : bool
|
| 457 |
+
When True, first and third angles are given as an addition and
|
| 458 |
+
subtraction of two simpler ``atan2`` expressions. When False, the
|
| 459 |
+
first and third angles are each given by a single more complicated
|
| 460 |
+
``atan2`` expression. This equivalent expression is given by:
|
| 461 |
+
|
| 462 |
+
.. math::
|
| 463 |
+
|
| 464 |
+
\operatorname{atan_2} (b,a) \pm \operatorname{atan_2} (d,c) =
|
| 465 |
+
\operatorname{atan_2} (bc\pm ad, ac\mp bd)
|
| 466 |
+
|
| 467 |
+
Default value: True
|
| 468 |
+
|
| 469 |
+
avoid_square_root : bool
|
| 470 |
+
When True, the second angle is calculated with an expression based
|
| 471 |
+
on ``acos``, which is slightly more complicated but avoids a square
|
| 472 |
+
root. When False, second angle is calculated with ``atan2``, which
|
| 473 |
+
is simpler and can be better for numerical reasons (some
|
| 474 |
+
numerical implementations of ``acos`` have problems near zero).
|
| 475 |
+
Default value: False
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
Returns
|
| 479 |
+
=======
|
| 480 |
+
|
| 481 |
+
Tuple
|
| 482 |
+
The Euler angles calculated from the quaternion
|
| 483 |
+
|
| 484 |
+
Examples
|
| 485 |
+
========
|
| 486 |
+
|
| 487 |
+
>>> from sympy import Quaternion
|
| 488 |
+
>>> from sympy.abc import a, b, c, d
|
| 489 |
+
>>> euler = Quaternion(a, b, c, d).to_euler('zyz')
|
| 490 |
+
>>> euler
|
| 491 |
+
(-atan2(-b, c) + atan2(d, a),
|
| 492 |
+
2*atan2(sqrt(b**2 + c**2), sqrt(a**2 + d**2)),
|
| 493 |
+
atan2(-b, c) + atan2(d, a))
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
References
|
| 497 |
+
==========
|
| 498 |
+
|
| 499 |
+
.. [1] https://doi.org/10.1371/journal.pone.0276302
|
| 500 |
+
|
| 501 |
+
"""
|
| 502 |
+
if self.is_zero_quaternion():
|
| 503 |
+
raise ValueError('Cannot convert a quaternion with norm 0.')
|
| 504 |
+
|
| 505 |
+
angles = [0, 0, 0]
|
| 506 |
+
|
| 507 |
+
extrinsic = _is_extrinsic(seq)
|
| 508 |
+
i, j, k = seq.lower()
|
| 509 |
+
|
| 510 |
+
# get index corresponding to elementary basis vectors
|
| 511 |
+
i = 'xyz'.index(i) + 1
|
| 512 |
+
j = 'xyz'.index(j) + 1
|
| 513 |
+
k = 'xyz'.index(k) + 1
|
| 514 |
+
|
| 515 |
+
if not extrinsic:
|
| 516 |
+
i, k = k, i
|
| 517 |
+
|
| 518 |
+
# check if sequence is symmetric
|
| 519 |
+
symmetric = i == k
|
| 520 |
+
if symmetric:
|
| 521 |
+
k = 6 - i - j
|
| 522 |
+
|
| 523 |
+
# parity of the permutation
|
| 524 |
+
sign = (i - j) * (j - k) * (k - i) // 2
|
| 525 |
+
|
| 526 |
+
# permutate elements
|
| 527 |
+
elements = [self.a, self.b, self.c, self.d]
|
| 528 |
+
a = elements[0]
|
| 529 |
+
b = elements[i]
|
| 530 |
+
c = elements[j]
|
| 531 |
+
d = elements[k] * sign
|
| 532 |
+
|
| 533 |
+
if not symmetric:
|
| 534 |
+
a, b, c, d = a - c, b + d, c + a, d - b
|
| 535 |
+
|
| 536 |
+
if avoid_square_root:
|
| 537 |
+
if symmetric:
|
| 538 |
+
n2 = self.norm()**2
|
| 539 |
+
angles[1] = acos((a * a + b * b - c * c - d * d) / n2)
|
| 540 |
+
else:
|
| 541 |
+
n2 = 2 * self.norm()**2
|
| 542 |
+
angles[1] = asin((c * c + d * d - a * a - b * b) / n2)
|
| 543 |
+
else:
|
| 544 |
+
angles[1] = 2 * atan2(sqrt(c * c + d * d), sqrt(a * a + b * b))
|
| 545 |
+
if not symmetric:
|
| 546 |
+
angles[1] -= S.Pi / 2
|
| 547 |
+
|
| 548 |
+
# Check for singularities in numerical cases
|
| 549 |
+
case = 0
|
| 550 |
+
if is_eq(c, S.Zero) and is_eq(d, S.Zero):
|
| 551 |
+
case = 1
|
| 552 |
+
if is_eq(a, S.Zero) and is_eq(b, S.Zero):
|
| 553 |
+
case = 2
|
| 554 |
+
|
| 555 |
+
if case == 0:
|
| 556 |
+
if angle_addition:
|
| 557 |
+
angles[0] = atan2(b, a) + atan2(d, c)
|
| 558 |
+
angles[2] = atan2(b, a) - atan2(d, c)
|
| 559 |
+
else:
|
| 560 |
+
angles[0] = atan2(b*c + a*d, a*c - b*d)
|
| 561 |
+
angles[2] = atan2(b*c - a*d, a*c + b*d)
|
| 562 |
+
|
| 563 |
+
else: # any degenerate case
|
| 564 |
+
angles[2 * (not extrinsic)] = S.Zero
|
| 565 |
+
if case == 1:
|
| 566 |
+
angles[2 * extrinsic] = 2 * atan2(b, a)
|
| 567 |
+
else:
|
| 568 |
+
angles[2 * extrinsic] = 2 * atan2(d, c)
|
| 569 |
+
angles[2 * extrinsic] *= (-1 if extrinsic else 1)
|
| 570 |
+
|
| 571 |
+
# for Tait-Bryan angles
|
| 572 |
+
if not symmetric:
|
| 573 |
+
angles[0] *= sign
|
| 574 |
+
|
| 575 |
+
if extrinsic:
|
| 576 |
+
return tuple(angles[::-1])
|
| 577 |
+
else:
|
| 578 |
+
return tuple(angles)
|
| 579 |
+
|
| 580 |
+
@classmethod
|
| 581 |
+
def from_axis_angle(cls, vector, angle):
|
| 582 |
+
"""Returns a rotation quaternion given the axis and the angle of rotation.
|
| 583 |
+
|
| 584 |
+
Parameters
|
| 585 |
+
==========
|
| 586 |
+
|
| 587 |
+
vector : tuple of three numbers
|
| 588 |
+
The vector representation of the given axis.
|
| 589 |
+
angle : number
|
| 590 |
+
The angle by which axis is rotated (in radians).
|
| 591 |
+
|
| 592 |
+
Returns
|
| 593 |
+
=======
|
| 594 |
+
|
| 595 |
+
Quaternion
|
| 596 |
+
The normalized rotation quaternion calculated from the given axis and the angle of rotation.
|
| 597 |
+
|
| 598 |
+
Examples
|
| 599 |
+
========
|
| 600 |
+
|
| 601 |
+
>>> from sympy import Quaternion
|
| 602 |
+
>>> from sympy import pi, sqrt
|
| 603 |
+
>>> q = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), 2*pi/3)
|
| 604 |
+
>>> q
|
| 605 |
+
1/2 + 1/2*i + 1/2*j + 1/2*k
|
| 606 |
+
|
| 607 |
+
"""
|
| 608 |
+
(x, y, z) = vector
|
| 609 |
+
norm = sqrt(x**2 + y**2 + z**2)
|
| 610 |
+
(x, y, z) = (x / norm, y / norm, z / norm)
|
| 611 |
+
s = sin(angle * S.Half)
|
| 612 |
+
a = cos(angle * S.Half)
|
| 613 |
+
b = x * s
|
| 614 |
+
c = y * s
|
| 615 |
+
d = z * s
|
| 616 |
+
|
| 617 |
+
# note that this quaternion is already normalized by construction:
|
| 618 |
+
# c^2 + (s*x)^2 + (s*y)^2 + (s*z)^2 = c^2 + s^2*(x^2 + y^2 + z^2) = c^2 + s^2 * 1 = c^2 + s^2 = 1
|
| 619 |
+
# so, what we return is a normalized quaternion
|
| 620 |
+
|
| 621 |
+
return cls(a, b, c, d)
|
| 622 |
+
|
| 623 |
+
@classmethod
|
| 624 |
+
def from_rotation_matrix(cls, M):
|
| 625 |
+
"""Returns the equivalent quaternion of a matrix. The quaternion will be normalized
|
| 626 |
+
only if the matrix is special orthogonal (orthogonal and det(M) = 1).
|
| 627 |
+
|
| 628 |
+
Parameters
|
| 629 |
+
==========
|
| 630 |
+
|
| 631 |
+
M : Matrix
|
| 632 |
+
Input matrix to be converted to equivalent quaternion. M must be special
|
| 633 |
+
orthogonal (orthogonal and det(M) = 1) for the quaternion to be normalized.
|
| 634 |
+
|
| 635 |
+
Returns
|
| 636 |
+
=======
|
| 637 |
+
|
| 638 |
+
Quaternion
|
| 639 |
+
The quaternion equivalent to given matrix.
|
| 640 |
+
|
| 641 |
+
Examples
|
| 642 |
+
========
|
| 643 |
+
|
| 644 |
+
>>> from sympy import Quaternion
|
| 645 |
+
>>> from sympy import Matrix, symbols, cos, sin, trigsimp
|
| 646 |
+
>>> x = symbols('x')
|
| 647 |
+
>>> M = Matrix([[cos(x), -sin(x), 0], [sin(x), cos(x), 0], [0, 0, 1]])
|
| 648 |
+
>>> q = trigsimp(Quaternion.from_rotation_matrix(M))
|
| 649 |
+
>>> q
|
| 650 |
+
sqrt(2)*sqrt(cos(x) + 1)/2 + 0*i + 0*j + sqrt(2 - 2*cos(x))*sign(sin(x))/2*k
|
| 651 |
+
|
| 652 |
+
"""
|
| 653 |
+
|
| 654 |
+
absQ = M.det()**Rational(1, 3)
|
| 655 |
+
|
| 656 |
+
a = sqrt(absQ + M[0, 0] + M[1, 1] + M[2, 2]) / 2
|
| 657 |
+
b = sqrt(absQ + M[0, 0] - M[1, 1] - M[2, 2]) / 2
|
| 658 |
+
c = sqrt(absQ - M[0, 0] + M[1, 1] - M[2, 2]) / 2
|
| 659 |
+
d = sqrt(absQ - M[0, 0] - M[1, 1] + M[2, 2]) / 2
|
| 660 |
+
|
| 661 |
+
b = b * sign(M[2, 1] - M[1, 2])
|
| 662 |
+
c = c * sign(M[0, 2] - M[2, 0])
|
| 663 |
+
d = d * sign(M[1, 0] - M[0, 1])
|
| 664 |
+
|
| 665 |
+
return Quaternion(a, b, c, d)
|
| 666 |
+
|
| 667 |
+
def __add__(self, other):
|
| 668 |
+
return self.add(other)
|
| 669 |
+
|
| 670 |
+
def __radd__(self, other):
|
| 671 |
+
return self.add(other)
|
| 672 |
+
|
| 673 |
+
def __sub__(self, other):
|
| 674 |
+
return self.add(other*-1)
|
| 675 |
+
|
| 676 |
+
def __mul__(self, other):
|
| 677 |
+
return self._generic_mul(self, _sympify(other))
|
| 678 |
+
|
| 679 |
+
def __rmul__(self, other):
|
| 680 |
+
return self._generic_mul(_sympify(other), self)
|
| 681 |
+
|
| 682 |
+
def __pow__(self, p):
|
| 683 |
+
return self.pow(p)
|
| 684 |
+
|
| 685 |
+
def __neg__(self):
|
| 686 |
+
return Quaternion(-self.a, -self.b, -self.c, -self.d)
|
| 687 |
+
|
| 688 |
+
def __truediv__(self, other):
|
| 689 |
+
return self * sympify(other)**-1
|
| 690 |
+
|
| 691 |
+
def __rtruediv__(self, other):
|
| 692 |
+
return sympify(other) * self**-1
|
| 693 |
+
|
| 694 |
+
def _eval_Integral(self, *args):
|
| 695 |
+
return self.integrate(*args)
|
| 696 |
+
|
| 697 |
+
def diff(self, *symbols, **kwargs):
|
| 698 |
+
kwargs.setdefault('evaluate', True)
|
| 699 |
+
return self.func(*[a.diff(*symbols, **kwargs) for a in self.args])
|
| 700 |
+
|
| 701 |
+
def add(self, other):
|
| 702 |
+
"""Adds quaternions.
|
| 703 |
+
|
| 704 |
+
Parameters
|
| 705 |
+
==========
|
| 706 |
+
|
| 707 |
+
other : Quaternion
|
| 708 |
+
The quaternion to add to current (self) quaternion.
|
| 709 |
+
|
| 710 |
+
Returns
|
| 711 |
+
=======
|
| 712 |
+
|
| 713 |
+
Quaternion
|
| 714 |
+
The resultant quaternion after adding self to other
|
| 715 |
+
|
| 716 |
+
Examples
|
| 717 |
+
========
|
| 718 |
+
|
| 719 |
+
>>> from sympy import Quaternion
|
| 720 |
+
>>> from sympy import symbols
|
| 721 |
+
>>> q1 = Quaternion(1, 2, 3, 4)
|
| 722 |
+
>>> q2 = Quaternion(5, 6, 7, 8)
|
| 723 |
+
>>> q1.add(q2)
|
| 724 |
+
6 + 8*i + 10*j + 12*k
|
| 725 |
+
>>> q1 + 5
|
| 726 |
+
6 + 2*i + 3*j + 4*k
|
| 727 |
+
>>> x = symbols('x', real = True)
|
| 728 |
+
>>> q1.add(x)
|
| 729 |
+
(x + 1) + 2*i + 3*j + 4*k
|
| 730 |
+
|
| 731 |
+
Quaternions over complex fields :
|
| 732 |
+
|
| 733 |
+
>>> from sympy import Quaternion
|
| 734 |
+
>>> from sympy import I
|
| 735 |
+
>>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
|
| 736 |
+
>>> q3.add(2 + 3*I)
|
| 737 |
+
(5 + 7*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k
|
| 738 |
+
|
| 739 |
+
"""
|
| 740 |
+
q1 = self
|
| 741 |
+
q2 = sympify(other)
|
| 742 |
+
|
| 743 |
+
# If q2 is a number or a SymPy expression instead of a quaternion
|
| 744 |
+
if not isinstance(q2, Quaternion):
|
| 745 |
+
if q1.real_field and q2.is_complex:
|
| 746 |
+
return Quaternion(re(q2) + q1.a, im(q2) + q1.b, q1.c, q1.d)
|
| 747 |
+
elif q2.is_commutative:
|
| 748 |
+
return Quaternion(q1.a + q2, q1.b, q1.c, q1.d)
|
| 749 |
+
else:
|
| 750 |
+
raise ValueError("Only commutative expressions can be added with a Quaternion.")
|
| 751 |
+
|
| 752 |
+
return Quaternion(q1.a + q2.a, q1.b + q2.b, q1.c + q2.c, q1.d
|
| 753 |
+
+ q2.d)
|
| 754 |
+
|
| 755 |
+
def mul(self, other):
|
| 756 |
+
"""Multiplies quaternions.
|
| 757 |
+
|
| 758 |
+
Parameters
|
| 759 |
+
==========
|
| 760 |
+
|
| 761 |
+
other : Quaternion or symbol
|
| 762 |
+
The quaternion to multiply to current (self) quaternion.
|
| 763 |
+
|
| 764 |
+
Returns
|
| 765 |
+
=======
|
| 766 |
+
|
| 767 |
+
Quaternion
|
| 768 |
+
The resultant quaternion after multiplying self with other
|
| 769 |
+
|
| 770 |
+
Examples
|
| 771 |
+
========
|
| 772 |
+
|
| 773 |
+
>>> from sympy import Quaternion
|
| 774 |
+
>>> from sympy import symbols
|
| 775 |
+
>>> q1 = Quaternion(1, 2, 3, 4)
|
| 776 |
+
>>> q2 = Quaternion(5, 6, 7, 8)
|
| 777 |
+
>>> q1.mul(q2)
|
| 778 |
+
(-60) + 12*i + 30*j + 24*k
|
| 779 |
+
>>> q1.mul(2)
|
| 780 |
+
2 + 4*i + 6*j + 8*k
|
| 781 |
+
>>> x = symbols('x', real = True)
|
| 782 |
+
>>> q1.mul(x)
|
| 783 |
+
x + 2*x*i + 3*x*j + 4*x*k
|
| 784 |
+
|
| 785 |
+
Quaternions over complex fields :
|
| 786 |
+
|
| 787 |
+
>>> from sympy import Quaternion
|
| 788 |
+
>>> from sympy import I
|
| 789 |
+
>>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
|
| 790 |
+
>>> q3.mul(2 + 3*I)
|
| 791 |
+
(2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k
|
| 792 |
+
|
| 793 |
+
"""
|
| 794 |
+
return self._generic_mul(self, _sympify(other))
|
| 795 |
+
|
| 796 |
+
@staticmethod
|
| 797 |
+
def _generic_mul(q1, q2):
|
| 798 |
+
"""Generic multiplication.
|
| 799 |
+
|
| 800 |
+
Parameters
|
| 801 |
+
==========
|
| 802 |
+
|
| 803 |
+
q1 : Quaternion or symbol
|
| 804 |
+
q2 : Quaternion or symbol
|
| 805 |
+
|
| 806 |
+
It is important to note that if neither q1 nor q2 is a Quaternion,
|
| 807 |
+
this function simply returns q1 * q2.
|
| 808 |
+
|
| 809 |
+
Returns
|
| 810 |
+
=======
|
| 811 |
+
|
| 812 |
+
Quaternion
|
| 813 |
+
The resultant quaternion after multiplying q1 and q2
|
| 814 |
+
|
| 815 |
+
Examples
|
| 816 |
+
========
|
| 817 |
+
|
| 818 |
+
>>> from sympy import Quaternion
|
| 819 |
+
>>> from sympy import Symbol, S
|
| 820 |
+
>>> q1 = Quaternion(1, 2, 3, 4)
|
| 821 |
+
>>> q2 = Quaternion(5, 6, 7, 8)
|
| 822 |
+
>>> Quaternion._generic_mul(q1, q2)
|
| 823 |
+
(-60) + 12*i + 30*j + 24*k
|
| 824 |
+
>>> Quaternion._generic_mul(q1, S(2))
|
| 825 |
+
2 + 4*i + 6*j + 8*k
|
| 826 |
+
>>> x = Symbol('x', real = True)
|
| 827 |
+
>>> Quaternion._generic_mul(q1, x)
|
| 828 |
+
x + 2*x*i + 3*x*j + 4*x*k
|
| 829 |
+
|
| 830 |
+
Quaternions over complex fields :
|
| 831 |
+
|
| 832 |
+
>>> from sympy import I
|
| 833 |
+
>>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
|
| 834 |
+
>>> Quaternion._generic_mul(q3, 2 + 3*I)
|
| 835 |
+
(2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k
|
| 836 |
+
|
| 837 |
+
"""
|
| 838 |
+
# None is a Quaternion:
|
| 839 |
+
if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion):
|
| 840 |
+
return q1 * q2
|
| 841 |
+
|
| 842 |
+
# If q1 is a number or a SymPy expression instead of a quaternion
|
| 843 |
+
if not isinstance(q1, Quaternion):
|
| 844 |
+
if q2.real_field and q1.is_complex:
|
| 845 |
+
return Quaternion(re(q1), im(q1), 0, 0) * q2
|
| 846 |
+
elif q1.is_commutative:
|
| 847 |
+
return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d)
|
| 848 |
+
else:
|
| 849 |
+
raise ValueError("Only commutative expressions can be multiplied with a Quaternion.")
|
| 850 |
+
|
| 851 |
+
# If q2 is a number or a SymPy expression instead of a quaternion
|
| 852 |
+
if not isinstance(q2, Quaternion):
|
| 853 |
+
if q1.real_field and q2.is_complex:
|
| 854 |
+
return q1 * Quaternion(re(q2), im(q2), 0, 0)
|
| 855 |
+
elif q2.is_commutative:
|
| 856 |
+
return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d)
|
| 857 |
+
else:
|
| 858 |
+
raise ValueError("Only commutative expressions can be multiplied with a Quaternion.")
|
| 859 |
+
|
| 860 |
+
# If any of the quaternions has a fixed norm, pre-compute norm
|
| 861 |
+
if q1._norm is None and q2._norm is None:
|
| 862 |
+
norm = None
|
| 863 |
+
else:
|
| 864 |
+
norm = q1.norm() * q2.norm()
|
| 865 |
+
|
| 866 |
+
return Quaternion(-q1.b*q2.b - q1.c*q2.c - q1.d*q2.d + q1.a*q2.a,
|
| 867 |
+
q1.b*q2.a + q1.c*q2.d - q1.d*q2.c + q1.a*q2.b,
|
| 868 |
+
-q1.b*q2.d + q1.c*q2.a + q1.d*q2.b + q1.a*q2.c,
|
| 869 |
+
q1.b*q2.c - q1.c*q2.b + q1.d*q2.a + q1.a * q2.d,
|
| 870 |
+
norm=norm)
|
| 871 |
+
|
| 872 |
+
def _eval_conjugate(self):
|
| 873 |
+
"""Returns the conjugate of the quaternion."""
|
| 874 |
+
q = self
|
| 875 |
+
return Quaternion(q.a, -q.b, -q.c, -q.d, norm=q._norm)
|
| 876 |
+
|
| 877 |
+
def norm(self):
|
| 878 |
+
"""Returns the norm of the quaternion."""
|
| 879 |
+
if self._norm is None: # check if norm is pre-defined
|
| 880 |
+
q = self
|
| 881 |
+
# trigsimp is used to simplify sin(x)^2 + cos(x)^2 (these terms
|
| 882 |
+
# arise when from_axis_angle is used).
|
| 883 |
+
return sqrt(trigsimp(q.a**2 + q.b**2 + q.c**2 + q.d**2))
|
| 884 |
+
|
| 885 |
+
return self._norm
|
| 886 |
+
|
| 887 |
+
def normalize(self):
|
| 888 |
+
"""Returns the normalized form of the quaternion."""
|
| 889 |
+
q = self
|
| 890 |
+
return q * (1/q.norm())
|
| 891 |
+
|
| 892 |
+
def inverse(self):
|
| 893 |
+
"""Returns the inverse of the quaternion."""
|
| 894 |
+
q = self
|
| 895 |
+
if not q.norm():
|
| 896 |
+
raise ValueError("Cannot compute inverse for a quaternion with zero norm")
|
| 897 |
+
return conjugate(q) * (1/q.norm()**2)
|
| 898 |
+
|
| 899 |
+
def pow(self, p):
|
| 900 |
+
"""Finds the pth power of the quaternion.
|
| 901 |
+
|
| 902 |
+
Parameters
|
| 903 |
+
==========
|
| 904 |
+
|
| 905 |
+
p : int
|
| 906 |
+
Power to be applied on quaternion.
|
| 907 |
+
|
| 908 |
+
Returns
|
| 909 |
+
=======
|
| 910 |
+
|
| 911 |
+
Quaternion
|
| 912 |
+
Returns the p-th power of the current quaternion.
|
| 913 |
+
Returns the inverse if p = -1.
|
| 914 |
+
|
| 915 |
+
Examples
|
| 916 |
+
========
|
| 917 |
+
|
| 918 |
+
>>> from sympy import Quaternion
|
| 919 |
+
>>> q = Quaternion(1, 2, 3, 4)
|
| 920 |
+
>>> q.pow(4)
|
| 921 |
+
668 + (-224)*i + (-336)*j + (-448)*k
|
| 922 |
+
|
| 923 |
+
"""
|
| 924 |
+
try:
|
| 925 |
+
q, p = self, as_int(p)
|
| 926 |
+
except ValueError:
|
| 927 |
+
return NotImplemented
|
| 928 |
+
|
| 929 |
+
if p < 0:
|
| 930 |
+
q, p = q.inverse(), -p
|
| 931 |
+
|
| 932 |
+
if p == 1:
|
| 933 |
+
return q
|
| 934 |
+
|
| 935 |
+
res = Quaternion(1, 0, 0, 0)
|
| 936 |
+
while p > 0:
|
| 937 |
+
if p & 1:
|
| 938 |
+
res *= q
|
| 939 |
+
q *= q
|
| 940 |
+
p >>= 1
|
| 941 |
+
|
| 942 |
+
return res
|
| 943 |
+
|
| 944 |
+
def exp(self):
|
| 945 |
+
"""Returns the exponential of $q$, given by $e^q$.
|
| 946 |
+
|
| 947 |
+
Returns
|
| 948 |
+
=======
|
| 949 |
+
|
| 950 |
+
Quaternion
|
| 951 |
+
The exponential of the quaternion.
|
| 952 |
+
|
| 953 |
+
Examples
|
| 954 |
+
========
|
| 955 |
+
|
| 956 |
+
>>> from sympy import Quaternion
|
| 957 |
+
>>> q = Quaternion(1, 2, 3, 4)
|
| 958 |
+
>>> q.exp()
|
| 959 |
+
E*cos(sqrt(29))
|
| 960 |
+
+ 2*sqrt(29)*E*sin(sqrt(29))/29*i
|
| 961 |
+
+ 3*sqrt(29)*E*sin(sqrt(29))/29*j
|
| 962 |
+
+ 4*sqrt(29)*E*sin(sqrt(29))/29*k
|
| 963 |
+
|
| 964 |
+
"""
|
| 965 |
+
# exp(q) = e^a(cos||v|| + v/||v||*sin||v||)
|
| 966 |
+
q = self
|
| 967 |
+
vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2)
|
| 968 |
+
a = exp(q.a) * cos(vector_norm)
|
| 969 |
+
b = exp(q.a) * sin(vector_norm) * q.b / vector_norm
|
| 970 |
+
c = exp(q.a) * sin(vector_norm) * q.c / vector_norm
|
| 971 |
+
d = exp(q.a) * sin(vector_norm) * q.d / vector_norm
|
| 972 |
+
|
| 973 |
+
return Quaternion(a, b, c, d)
|
| 974 |
+
|
| 975 |
+
def log(self):
|
| 976 |
+
r"""Returns the logarithm of the quaternion, given by $\log q$.
|
| 977 |
+
|
| 978 |
+
Examples
|
| 979 |
+
========
|
| 980 |
+
|
| 981 |
+
>>> from sympy import Quaternion
|
| 982 |
+
>>> q = Quaternion(1, 2, 3, 4)
|
| 983 |
+
>>> q.log()
|
| 984 |
+
log(sqrt(30))
|
| 985 |
+
+ 2*sqrt(29)*acos(sqrt(30)/30)/29*i
|
| 986 |
+
+ 3*sqrt(29)*acos(sqrt(30)/30)/29*j
|
| 987 |
+
+ 4*sqrt(29)*acos(sqrt(30)/30)/29*k
|
| 988 |
+
|
| 989 |
+
"""
|
| 990 |
+
# log(q) = log||q|| + v/||v||*arccos(a/||q||)
|
| 991 |
+
q = self
|
| 992 |
+
vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2)
|
| 993 |
+
q_norm = q.norm()
|
| 994 |
+
a = ln(q_norm)
|
| 995 |
+
b = q.b * acos(q.a / q_norm) / vector_norm
|
| 996 |
+
c = q.c * acos(q.a / q_norm) / vector_norm
|
| 997 |
+
d = q.d * acos(q.a / q_norm) / vector_norm
|
| 998 |
+
|
| 999 |
+
return Quaternion(a, b, c, d)
|
| 1000 |
+
|
| 1001 |
+
def _eval_subs(self, *args):
|
| 1002 |
+
elements = [i.subs(*args) for i in self.args]
|
| 1003 |
+
norm = self._norm
|
| 1004 |
+
if norm is not None:
|
| 1005 |
+
norm = norm.subs(*args)
|
| 1006 |
+
_check_norm(elements, norm)
|
| 1007 |
+
return Quaternion(*elements, norm=norm)
|
| 1008 |
+
|
| 1009 |
+
def _eval_evalf(self, prec):
|
| 1010 |
+
"""Returns the floating point approximations (decimal numbers) of the quaternion.
|
| 1011 |
+
|
| 1012 |
+
Returns
|
| 1013 |
+
=======
|
| 1014 |
+
|
| 1015 |
+
Quaternion
|
| 1016 |
+
Floating point approximations of quaternion(self)
|
| 1017 |
+
|
| 1018 |
+
Examples
|
| 1019 |
+
========
|
| 1020 |
+
|
| 1021 |
+
>>> from sympy import Quaternion
|
| 1022 |
+
>>> from sympy import sqrt
|
| 1023 |
+
>>> q = Quaternion(1/sqrt(1), 1/sqrt(2), 1/sqrt(3), 1/sqrt(4))
|
| 1024 |
+
>>> q.evalf()
|
| 1025 |
+
1.00000000000000
|
| 1026 |
+
+ 0.707106781186547*i
|
| 1027 |
+
+ 0.577350269189626*j
|
| 1028 |
+
+ 0.500000000000000*k
|
| 1029 |
+
|
| 1030 |
+
"""
|
| 1031 |
+
nprec = prec_to_dps(prec)
|
| 1032 |
+
return Quaternion(*[arg.evalf(n=nprec) for arg in self.args])
|
| 1033 |
+
|
| 1034 |
+
def pow_cos_sin(self, p):
|
| 1035 |
+
"""Computes the pth power in the cos-sin form.
|
| 1036 |
+
|
| 1037 |
+
Parameters
|
| 1038 |
+
==========
|
| 1039 |
+
|
| 1040 |
+
p : int
|
| 1041 |
+
Power to be applied on quaternion.
|
| 1042 |
+
|
| 1043 |
+
Returns
|
| 1044 |
+
=======
|
| 1045 |
+
|
| 1046 |
+
Quaternion
|
| 1047 |
+
The p-th power in the cos-sin form.
|
| 1048 |
+
|
| 1049 |
+
Examples
|
| 1050 |
+
========
|
| 1051 |
+
|
| 1052 |
+
>>> from sympy import Quaternion
|
| 1053 |
+
>>> q = Quaternion(1, 2, 3, 4)
|
| 1054 |
+
>>> q.pow_cos_sin(4)
|
| 1055 |
+
900*cos(4*acos(sqrt(30)/30))
|
| 1056 |
+
+ 1800*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*i
|
| 1057 |
+
+ 2700*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*j
|
| 1058 |
+
+ 3600*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*k
|
| 1059 |
+
|
| 1060 |
+
"""
|
| 1061 |
+
# q = ||q||*(cos(a) + u*sin(a))
|
| 1062 |
+
# q^p = ||q||^p * (cos(p*a) + u*sin(p*a))
|
| 1063 |
+
|
| 1064 |
+
q = self
|
| 1065 |
+
(v, angle) = q.to_axis_angle()
|
| 1066 |
+
q2 = Quaternion.from_axis_angle(v, p * angle)
|
| 1067 |
+
return q2 * (q.norm()**p)
|
| 1068 |
+
|
| 1069 |
+
def integrate(self, *args):
|
| 1070 |
+
"""Computes integration of quaternion.
|
| 1071 |
+
|
| 1072 |
+
Returns
|
| 1073 |
+
=======
|
| 1074 |
+
|
| 1075 |
+
Quaternion
|
| 1076 |
+
Integration of the quaternion(self) with the given variable.
|
| 1077 |
+
|
| 1078 |
+
Examples
|
| 1079 |
+
========
|
| 1080 |
+
|
| 1081 |
+
Indefinite Integral of quaternion :
|
| 1082 |
+
|
| 1083 |
+
>>> from sympy import Quaternion
|
| 1084 |
+
>>> from sympy.abc import x
|
| 1085 |
+
>>> q = Quaternion(1, 2, 3, 4)
|
| 1086 |
+
>>> q.integrate(x)
|
| 1087 |
+
x + 2*x*i + 3*x*j + 4*x*k
|
| 1088 |
+
|
| 1089 |
+
Definite integral of quaternion :
|
| 1090 |
+
|
| 1091 |
+
>>> from sympy import Quaternion
|
| 1092 |
+
>>> from sympy.abc import x
|
| 1093 |
+
>>> q = Quaternion(1, 2, 3, 4)
|
| 1094 |
+
>>> q.integrate((x, 1, 5))
|
| 1095 |
+
4 + 8*i + 12*j + 16*k
|
| 1096 |
+
|
| 1097 |
+
"""
|
| 1098 |
+
# TODO: is this expression correct?
|
| 1099 |
+
return Quaternion(integrate(self.a, *args), integrate(self.b, *args),
|
| 1100 |
+
integrate(self.c, *args), integrate(self.d, *args))
|
| 1101 |
+
|
| 1102 |
+
@staticmethod
|
| 1103 |
+
def rotate_point(pin, r):
|
| 1104 |
+
"""Returns the coordinates of the point pin (a 3 tuple) after rotation.
|
| 1105 |
+
|
| 1106 |
+
Parameters
|
| 1107 |
+
==========
|
| 1108 |
+
|
| 1109 |
+
pin : tuple
|
| 1110 |
+
A 3-element tuple of coordinates of a point which needs to be
|
| 1111 |
+
rotated.
|
| 1112 |
+
r : Quaternion or tuple
|
| 1113 |
+
Axis and angle of rotation.
|
| 1114 |
+
|
| 1115 |
+
It's important to note that when r is a tuple, it must be of the form
|
| 1116 |
+
(axis, angle)
|
| 1117 |
+
|
| 1118 |
+
Returns
|
| 1119 |
+
=======
|
| 1120 |
+
|
| 1121 |
+
tuple
|
| 1122 |
+
The coordinates of the point after rotation.
|
| 1123 |
+
|
| 1124 |
+
Examples
|
| 1125 |
+
========
|
| 1126 |
+
|
| 1127 |
+
>>> from sympy import Quaternion
|
| 1128 |
+
>>> from sympy import symbols, trigsimp, cos, sin
|
| 1129 |
+
>>> x = symbols('x')
|
| 1130 |
+
>>> q = Quaternion(cos(x/2), 0, 0, sin(x/2))
|
| 1131 |
+
>>> trigsimp(Quaternion.rotate_point((1, 1, 1), q))
|
| 1132 |
+
(sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1)
|
| 1133 |
+
>>> (axis, angle) = q.to_axis_angle()
|
| 1134 |
+
>>> trigsimp(Quaternion.rotate_point((1, 1, 1), (axis, angle)))
|
| 1135 |
+
(sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1)
|
| 1136 |
+
|
| 1137 |
+
"""
|
| 1138 |
+
if isinstance(r, tuple):
|
| 1139 |
+
# if r is of the form (vector, angle)
|
| 1140 |
+
q = Quaternion.from_axis_angle(r[0], r[1])
|
| 1141 |
+
else:
|
| 1142 |
+
# if r is a quaternion
|
| 1143 |
+
q = r.normalize()
|
| 1144 |
+
pout = q * Quaternion(0, pin[0], pin[1], pin[2]) * conjugate(q)
|
| 1145 |
+
return (pout.b, pout.c, pout.d)
|
| 1146 |
+
|
| 1147 |
+
def to_axis_angle(self):
|
| 1148 |
+
"""Returns the axis and angle of rotation of a quaternion.
|
| 1149 |
+
|
| 1150 |
+
Returns
|
| 1151 |
+
=======
|
| 1152 |
+
|
| 1153 |
+
tuple
|
| 1154 |
+
Tuple of (axis, angle)
|
| 1155 |
+
|
| 1156 |
+
Examples
|
| 1157 |
+
========
|
| 1158 |
+
|
| 1159 |
+
>>> from sympy import Quaternion
|
| 1160 |
+
>>> q = Quaternion(1, 1, 1, 1)
|
| 1161 |
+
>>> (axis, angle) = q.to_axis_angle()
|
| 1162 |
+
>>> axis
|
| 1163 |
+
(sqrt(3)/3, sqrt(3)/3, sqrt(3)/3)
|
| 1164 |
+
>>> angle
|
| 1165 |
+
2*pi/3
|
| 1166 |
+
|
| 1167 |
+
"""
|
| 1168 |
+
q = self
|
| 1169 |
+
if q.a.is_negative:
|
| 1170 |
+
q = q * -1
|
| 1171 |
+
|
| 1172 |
+
q = q.normalize()
|
| 1173 |
+
angle = trigsimp(2 * acos(q.a))
|
| 1174 |
+
|
| 1175 |
+
# Since quaternion is normalised, q.a is less than 1.
|
| 1176 |
+
s = sqrt(1 - q.a*q.a)
|
| 1177 |
+
|
| 1178 |
+
x = trigsimp(q.b / s)
|
| 1179 |
+
y = trigsimp(q.c / s)
|
| 1180 |
+
z = trigsimp(q.d / s)
|
| 1181 |
+
|
| 1182 |
+
v = (x, y, z)
|
| 1183 |
+
t = (v, angle)
|
| 1184 |
+
|
| 1185 |
+
return t
|
| 1186 |
+
|
| 1187 |
+
def to_rotation_matrix(self, v=None, homogeneous=True):
|
| 1188 |
+
"""Returns the equivalent rotation transformation matrix of the quaternion
|
| 1189 |
+
which represents rotation about the origin if ``v`` is not passed.
|
| 1190 |
+
|
| 1191 |
+
Parameters
|
| 1192 |
+
==========
|
| 1193 |
+
|
| 1194 |
+
v : tuple or None
|
| 1195 |
+
Default value: None
|
| 1196 |
+
homogeneous : bool
|
| 1197 |
+
When True, gives an expression that may be more efficient for
|
| 1198 |
+
symbolic calculations but less so for direct evaluation. Both
|
| 1199 |
+
formulas are mathematically equivalent.
|
| 1200 |
+
Default value: True
|
| 1201 |
+
|
| 1202 |
+
Returns
|
| 1203 |
+
=======
|
| 1204 |
+
|
| 1205 |
+
tuple
|
| 1206 |
+
Returns the equivalent rotation transformation matrix of the quaternion
|
| 1207 |
+
which represents rotation about the origin if v is not passed.
|
| 1208 |
+
|
| 1209 |
+
Examples
|
| 1210 |
+
========
|
| 1211 |
+
|
| 1212 |
+
>>> from sympy import Quaternion
|
| 1213 |
+
>>> from sympy import symbols, trigsimp, cos, sin
|
| 1214 |
+
>>> x = symbols('x')
|
| 1215 |
+
>>> q = Quaternion(cos(x/2), 0, 0, sin(x/2))
|
| 1216 |
+
>>> trigsimp(q.to_rotation_matrix())
|
| 1217 |
+
Matrix([
|
| 1218 |
+
[cos(x), -sin(x), 0],
|
| 1219 |
+
[sin(x), cos(x), 0],
|
| 1220 |
+
[ 0, 0, 1]])
|
| 1221 |
+
|
| 1222 |
+
Generates a 4x4 transformation matrix (used for rotation about a point
|
| 1223 |
+
other than the origin) if the point(v) is passed as an argument.
|
| 1224 |
+
"""
|
| 1225 |
+
|
| 1226 |
+
q = self
|
| 1227 |
+
s = q.norm()**-2
|
| 1228 |
+
|
| 1229 |
+
# diagonal elements are different according to parameter normal
|
| 1230 |
+
if homogeneous:
|
| 1231 |
+
m00 = s*(q.a**2 + q.b**2 - q.c**2 - q.d**2)
|
| 1232 |
+
m11 = s*(q.a**2 - q.b**2 + q.c**2 - q.d**2)
|
| 1233 |
+
m22 = s*(q.a**2 - q.b**2 - q.c**2 + q.d**2)
|
| 1234 |
+
else:
|
| 1235 |
+
m00 = 1 - 2*s*(q.c**2 + q.d**2)
|
| 1236 |
+
m11 = 1 - 2*s*(q.b**2 + q.d**2)
|
| 1237 |
+
m22 = 1 - 2*s*(q.b**2 + q.c**2)
|
| 1238 |
+
|
| 1239 |
+
m01 = 2*s*(q.b*q.c - q.d*q.a)
|
| 1240 |
+
m02 = 2*s*(q.b*q.d + q.c*q.a)
|
| 1241 |
+
|
| 1242 |
+
m10 = 2*s*(q.b*q.c + q.d*q.a)
|
| 1243 |
+
m12 = 2*s*(q.c*q.d - q.b*q.a)
|
| 1244 |
+
|
| 1245 |
+
m20 = 2*s*(q.b*q.d - q.c*q.a)
|
| 1246 |
+
m21 = 2*s*(q.c*q.d + q.b*q.a)
|
| 1247 |
+
|
| 1248 |
+
if not v:
|
| 1249 |
+
return Matrix([[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]])
|
| 1250 |
+
|
| 1251 |
+
else:
|
| 1252 |
+
(x, y, z) = v
|
| 1253 |
+
|
| 1254 |
+
m03 = x - x*m00 - y*m01 - z*m02
|
| 1255 |
+
m13 = y - x*m10 - y*m11 - z*m12
|
| 1256 |
+
m23 = z - x*m20 - y*m21 - z*m22
|
| 1257 |
+
m30 = m31 = m32 = 0
|
| 1258 |
+
m33 = 1
|
| 1259 |
+
|
| 1260 |
+
return Matrix([[m00, m01, m02, m03], [m10, m11, m12, m13],
|
| 1261 |
+
[m20, m21, m22, m23], [m30, m31, m32, m33]])
|
| 1262 |
+
|
| 1263 |
+
def scalar_part(self):
|
| 1264 |
+
r"""Returns scalar part($\mathbf{S}(q)$) of the quaternion q.
|
| 1265 |
+
|
| 1266 |
+
Explanation
|
| 1267 |
+
===========
|
| 1268 |
+
|
| 1269 |
+
Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{S}(q) = a$.
|
| 1270 |
+
|
| 1271 |
+
Examples
|
| 1272 |
+
========
|
| 1273 |
+
|
| 1274 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1275 |
+
>>> q = Quaternion(4, 8, 13, 12)
|
| 1276 |
+
>>> q.scalar_part()
|
| 1277 |
+
4
|
| 1278 |
+
|
| 1279 |
+
"""
|
| 1280 |
+
|
| 1281 |
+
return self.a
|
| 1282 |
+
|
| 1283 |
+
def vector_part(self):
|
| 1284 |
+
r"""
|
| 1285 |
+
Returns $\mathbf{V}(q)$, the vector part of the quaternion $q$.
|
| 1286 |
+
|
| 1287 |
+
Explanation
|
| 1288 |
+
===========
|
| 1289 |
+
|
| 1290 |
+
Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{V}(q) = bi + cj + dk$.
|
| 1291 |
+
|
| 1292 |
+
Examples
|
| 1293 |
+
========
|
| 1294 |
+
|
| 1295 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1296 |
+
>>> q = Quaternion(1, 1, 1, 1)
|
| 1297 |
+
>>> q.vector_part()
|
| 1298 |
+
0 + 1*i + 1*j + 1*k
|
| 1299 |
+
|
| 1300 |
+
>>> q = Quaternion(4, 8, 13, 12)
|
| 1301 |
+
>>> q.vector_part()
|
| 1302 |
+
0 + 8*i + 13*j + 12*k
|
| 1303 |
+
|
| 1304 |
+
"""
|
| 1305 |
+
|
| 1306 |
+
return Quaternion(0, self.b, self.c, self.d)
|
| 1307 |
+
|
| 1308 |
+
def axis(self):
|
| 1309 |
+
r"""
|
| 1310 |
+
Returns $\mathbf{Ax}(q)$, the axis of the quaternion $q$.
|
| 1311 |
+
|
| 1312 |
+
Explanation
|
| 1313 |
+
===========
|
| 1314 |
+
|
| 1315 |
+
Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{Ax}(q)$ i.e., the versor of the vector part of that quaternion
|
| 1316 |
+
equal to $\mathbf{U}[\mathbf{V}(q)]$.
|
| 1317 |
+
The axis is always an imaginary unit with square equal to $-1 + 0i + 0j + 0k$.
|
| 1318 |
+
|
| 1319 |
+
Examples
|
| 1320 |
+
========
|
| 1321 |
+
|
| 1322 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1323 |
+
>>> q = Quaternion(1, 1, 1, 1)
|
| 1324 |
+
>>> q.axis()
|
| 1325 |
+
0 + sqrt(3)/3*i + sqrt(3)/3*j + sqrt(3)/3*k
|
| 1326 |
+
|
| 1327 |
+
See Also
|
| 1328 |
+
========
|
| 1329 |
+
|
| 1330 |
+
vector_part
|
| 1331 |
+
|
| 1332 |
+
"""
|
| 1333 |
+
axis = self.vector_part().normalize()
|
| 1334 |
+
|
| 1335 |
+
return Quaternion(0, axis.b, axis.c, axis.d)
|
| 1336 |
+
|
| 1337 |
+
def is_pure(self):
|
| 1338 |
+
"""
|
| 1339 |
+
Returns true if the quaternion is pure, false if the quaternion is not pure
|
| 1340 |
+
or returns none if it is unknown.
|
| 1341 |
+
|
| 1342 |
+
Explanation
|
| 1343 |
+
===========
|
| 1344 |
+
|
| 1345 |
+
A pure quaternion (also a vector quaternion) is a quaternion with scalar
|
| 1346 |
+
part equal to 0.
|
| 1347 |
+
|
| 1348 |
+
Examples
|
| 1349 |
+
========
|
| 1350 |
+
|
| 1351 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1352 |
+
>>> q = Quaternion(0, 8, 13, 12)
|
| 1353 |
+
>>> q.is_pure()
|
| 1354 |
+
True
|
| 1355 |
+
|
| 1356 |
+
See Also
|
| 1357 |
+
========
|
| 1358 |
+
scalar_part
|
| 1359 |
+
|
| 1360 |
+
"""
|
| 1361 |
+
|
| 1362 |
+
return self.a.is_zero
|
| 1363 |
+
|
| 1364 |
+
def is_zero_quaternion(self):
|
| 1365 |
+
"""
|
| 1366 |
+
Returns true if the quaternion is a zero quaternion or false if it is not a zero quaternion
|
| 1367 |
+
and None if the value is unknown.
|
| 1368 |
+
|
| 1369 |
+
Explanation
|
| 1370 |
+
===========
|
| 1371 |
+
|
| 1372 |
+
A zero quaternion is a quaternion with both scalar part and
|
| 1373 |
+
vector part equal to 0.
|
| 1374 |
+
|
| 1375 |
+
Examples
|
| 1376 |
+
========
|
| 1377 |
+
|
| 1378 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1379 |
+
>>> q = Quaternion(1, 0, 0, 0)
|
| 1380 |
+
>>> q.is_zero_quaternion()
|
| 1381 |
+
False
|
| 1382 |
+
|
| 1383 |
+
>>> q = Quaternion(0, 0, 0, 0)
|
| 1384 |
+
>>> q.is_zero_quaternion()
|
| 1385 |
+
True
|
| 1386 |
+
|
| 1387 |
+
See Also
|
| 1388 |
+
========
|
| 1389 |
+
scalar_part
|
| 1390 |
+
vector_part
|
| 1391 |
+
|
| 1392 |
+
"""
|
| 1393 |
+
|
| 1394 |
+
return self.norm().is_zero
|
| 1395 |
+
|
| 1396 |
+
def angle(self):
|
| 1397 |
+
r"""
|
| 1398 |
+
Returns the angle of the quaternion measured in the real-axis plane.
|
| 1399 |
+
|
| 1400 |
+
Explanation
|
| 1401 |
+
===========
|
| 1402 |
+
|
| 1403 |
+
Given a quaternion $q = a + bi + cj + dk$ where $a$, $b$, $c$ and $d$
|
| 1404 |
+
are real numbers, returns the angle of the quaternion given by
|
| 1405 |
+
|
| 1406 |
+
.. math::
|
| 1407 |
+
\theta := 2 \operatorname{atan_2}\left(\sqrt{b^2 + c^2 + d^2}, {a}\right)
|
| 1408 |
+
|
| 1409 |
+
Examples
|
| 1410 |
+
========
|
| 1411 |
+
|
| 1412 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1413 |
+
>>> q = Quaternion(1, 4, 4, 4)
|
| 1414 |
+
>>> q.angle()
|
| 1415 |
+
2*atan(4*sqrt(3))
|
| 1416 |
+
|
| 1417 |
+
"""
|
| 1418 |
+
|
| 1419 |
+
return 2 * atan2(self.vector_part().norm(), self.scalar_part())
|
| 1420 |
+
|
| 1421 |
+
|
| 1422 |
+
def arc_coplanar(self, other):
|
| 1423 |
+
"""
|
| 1424 |
+
Returns True if the transformation arcs represented by the input quaternions happen in the same plane.
|
| 1425 |
+
|
| 1426 |
+
Explanation
|
| 1427 |
+
===========
|
| 1428 |
+
|
| 1429 |
+
Two quaternions are said to be coplanar (in this arc sense) when their axes are parallel.
|
| 1430 |
+
The plane of a quaternion is the one normal to its axis.
|
| 1431 |
+
|
| 1432 |
+
Parameters
|
| 1433 |
+
==========
|
| 1434 |
+
|
| 1435 |
+
other : a Quaternion
|
| 1436 |
+
|
| 1437 |
+
Returns
|
| 1438 |
+
=======
|
| 1439 |
+
|
| 1440 |
+
True : if the planes of the two quaternions are the same, apart from its orientation/sign.
|
| 1441 |
+
False : if the planes of the two quaternions are not the same, apart from its orientation/sign.
|
| 1442 |
+
None : if plane of either of the quaternion is unknown.
|
| 1443 |
+
|
| 1444 |
+
Examples
|
| 1445 |
+
========
|
| 1446 |
+
|
| 1447 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1448 |
+
>>> q1 = Quaternion(1, 4, 4, 4)
|
| 1449 |
+
>>> q2 = Quaternion(3, 8, 8, 8)
|
| 1450 |
+
>>> Quaternion.arc_coplanar(q1, q2)
|
| 1451 |
+
True
|
| 1452 |
+
|
| 1453 |
+
>>> q1 = Quaternion(2, 8, 13, 12)
|
| 1454 |
+
>>> Quaternion.arc_coplanar(q1, q2)
|
| 1455 |
+
False
|
| 1456 |
+
|
| 1457 |
+
See Also
|
| 1458 |
+
========
|
| 1459 |
+
|
| 1460 |
+
vector_coplanar
|
| 1461 |
+
is_pure
|
| 1462 |
+
|
| 1463 |
+
"""
|
| 1464 |
+
if (self.is_zero_quaternion()) or (other.is_zero_quaternion()):
|
| 1465 |
+
raise ValueError('Neither of the given quaternions can be 0')
|
| 1466 |
+
|
| 1467 |
+
return fuzzy_or([(self.axis() - other.axis()).is_zero_quaternion(), (self.axis() + other.axis()).is_zero_quaternion()])
|
| 1468 |
+
|
| 1469 |
+
@classmethod
|
| 1470 |
+
def vector_coplanar(cls, q1, q2, q3):
|
| 1471 |
+
r"""
|
| 1472 |
+
Returns True if the axis of the pure quaternions seen as 3D vectors
|
| 1473 |
+
``q1``, ``q2``, and ``q3`` are coplanar.
|
| 1474 |
+
|
| 1475 |
+
Explanation
|
| 1476 |
+
===========
|
| 1477 |
+
|
| 1478 |
+
Three pure quaternions are vector coplanar if the quaternions seen as 3D vectors are coplanar.
|
| 1479 |
+
|
| 1480 |
+
Parameters
|
| 1481 |
+
==========
|
| 1482 |
+
|
| 1483 |
+
q1
|
| 1484 |
+
A pure Quaternion.
|
| 1485 |
+
q2
|
| 1486 |
+
A pure Quaternion.
|
| 1487 |
+
q3
|
| 1488 |
+
A pure Quaternion.
|
| 1489 |
+
|
| 1490 |
+
Returns
|
| 1491 |
+
=======
|
| 1492 |
+
|
| 1493 |
+
True : if the axis of the pure quaternions seen as 3D vectors
|
| 1494 |
+
q1, q2, and q3 are coplanar.
|
| 1495 |
+
False : if the axis of the pure quaternions seen as 3D vectors
|
| 1496 |
+
q1, q2, and q3 are not coplanar.
|
| 1497 |
+
None : if the axis of the pure quaternions seen as 3D vectors
|
| 1498 |
+
q1, q2, and q3 are coplanar is unknown.
|
| 1499 |
+
|
| 1500 |
+
Examples
|
| 1501 |
+
========
|
| 1502 |
+
|
| 1503 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1504 |
+
>>> q1 = Quaternion(0, 4, 4, 4)
|
| 1505 |
+
>>> q2 = Quaternion(0, 8, 8, 8)
|
| 1506 |
+
>>> q3 = Quaternion(0, 24, 24, 24)
|
| 1507 |
+
>>> Quaternion.vector_coplanar(q1, q2, q3)
|
| 1508 |
+
True
|
| 1509 |
+
|
| 1510 |
+
>>> q1 = Quaternion(0, 8, 16, 8)
|
| 1511 |
+
>>> q2 = Quaternion(0, 8, 3, 12)
|
| 1512 |
+
>>> Quaternion.vector_coplanar(q1, q2, q3)
|
| 1513 |
+
False
|
| 1514 |
+
|
| 1515 |
+
See Also
|
| 1516 |
+
========
|
| 1517 |
+
|
| 1518 |
+
axis
|
| 1519 |
+
is_pure
|
| 1520 |
+
|
| 1521 |
+
"""
|
| 1522 |
+
|
| 1523 |
+
if fuzzy_not(q1.is_pure()) or fuzzy_not(q2.is_pure()) or fuzzy_not(q3.is_pure()):
|
| 1524 |
+
raise ValueError('The given quaternions must be pure')
|
| 1525 |
+
|
| 1526 |
+
M = Matrix([[q1.b, q1.c, q1.d], [q2.b, q2.c, q2.d], [q3.b, q3.c, q3.d]]).det()
|
| 1527 |
+
return M.is_zero
|
| 1528 |
+
|
| 1529 |
+
def parallel(self, other):
|
| 1530 |
+
"""
|
| 1531 |
+
Returns True if the two pure quaternions seen as 3D vectors are parallel.
|
| 1532 |
+
|
| 1533 |
+
Explanation
|
| 1534 |
+
===========
|
| 1535 |
+
|
| 1536 |
+
Two pure quaternions are called parallel when their vector product is commutative which
|
| 1537 |
+
implies that the quaternions seen as 3D vectors have same direction.
|
| 1538 |
+
|
| 1539 |
+
Parameters
|
| 1540 |
+
==========
|
| 1541 |
+
|
| 1542 |
+
other : a Quaternion
|
| 1543 |
+
|
| 1544 |
+
Returns
|
| 1545 |
+
=======
|
| 1546 |
+
|
| 1547 |
+
True : if the two pure quaternions seen as 3D vectors are parallel.
|
| 1548 |
+
False : if the two pure quaternions seen as 3D vectors are not parallel.
|
| 1549 |
+
None : if the two pure quaternions seen as 3D vectors are parallel is unknown.
|
| 1550 |
+
|
| 1551 |
+
Examples
|
| 1552 |
+
========
|
| 1553 |
+
|
| 1554 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1555 |
+
>>> q = Quaternion(0, 4, 4, 4)
|
| 1556 |
+
>>> q1 = Quaternion(0, 8, 8, 8)
|
| 1557 |
+
>>> q.parallel(q1)
|
| 1558 |
+
True
|
| 1559 |
+
|
| 1560 |
+
>>> q1 = Quaternion(0, 8, 13, 12)
|
| 1561 |
+
>>> q.parallel(q1)
|
| 1562 |
+
False
|
| 1563 |
+
|
| 1564 |
+
"""
|
| 1565 |
+
|
| 1566 |
+
if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()):
|
| 1567 |
+
raise ValueError('The provided quaternions must be pure')
|
| 1568 |
+
|
| 1569 |
+
return (self*other - other*self).is_zero_quaternion()
|
| 1570 |
+
|
| 1571 |
+
def orthogonal(self, other):
|
| 1572 |
+
"""
|
| 1573 |
+
Returns the orthogonality of two quaternions.
|
| 1574 |
+
|
| 1575 |
+
Explanation
|
| 1576 |
+
===========
|
| 1577 |
+
|
| 1578 |
+
Two pure quaternions are called orthogonal when their product is anti-commutative.
|
| 1579 |
+
|
| 1580 |
+
Parameters
|
| 1581 |
+
==========
|
| 1582 |
+
|
| 1583 |
+
other : a Quaternion
|
| 1584 |
+
|
| 1585 |
+
Returns
|
| 1586 |
+
=======
|
| 1587 |
+
|
| 1588 |
+
True : if the two pure quaternions seen as 3D vectors are orthogonal.
|
| 1589 |
+
False : if the two pure quaternions seen as 3D vectors are not orthogonal.
|
| 1590 |
+
None : if the two pure quaternions seen as 3D vectors are orthogonal is unknown.
|
| 1591 |
+
|
| 1592 |
+
Examples
|
| 1593 |
+
========
|
| 1594 |
+
|
| 1595 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1596 |
+
>>> q = Quaternion(0, 4, 4, 4)
|
| 1597 |
+
>>> q1 = Quaternion(0, 8, 8, 8)
|
| 1598 |
+
>>> q.orthogonal(q1)
|
| 1599 |
+
False
|
| 1600 |
+
|
| 1601 |
+
>>> q1 = Quaternion(0, 2, 2, 0)
|
| 1602 |
+
>>> q = Quaternion(0, 2, -2, 0)
|
| 1603 |
+
>>> q.orthogonal(q1)
|
| 1604 |
+
True
|
| 1605 |
+
|
| 1606 |
+
"""
|
| 1607 |
+
|
| 1608 |
+
if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()):
|
| 1609 |
+
raise ValueError('The given quaternions must be pure')
|
| 1610 |
+
|
| 1611 |
+
return (self*other + other*self).is_zero_quaternion()
|
| 1612 |
+
|
| 1613 |
+
def index_vector(self):
|
| 1614 |
+
r"""
|
| 1615 |
+
Returns the index vector of the quaternion.
|
| 1616 |
+
|
| 1617 |
+
Explanation
|
| 1618 |
+
===========
|
| 1619 |
+
|
| 1620 |
+
The index vector is given by $\mathbf{T}(q)$, the norm (or magnitude) of
|
| 1621 |
+
the quaternion $q$, multiplied by $\mathbf{Ax}(q)$, the axis of $q$.
|
| 1622 |
+
|
| 1623 |
+
Returns
|
| 1624 |
+
=======
|
| 1625 |
+
|
| 1626 |
+
Quaternion: representing index vector of the provided quaternion.
|
| 1627 |
+
|
| 1628 |
+
Examples
|
| 1629 |
+
========
|
| 1630 |
+
|
| 1631 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1632 |
+
>>> q = Quaternion(2, 4, 2, 4)
|
| 1633 |
+
>>> q.index_vector()
|
| 1634 |
+
0 + 4*sqrt(10)/3*i + 2*sqrt(10)/3*j + 4*sqrt(10)/3*k
|
| 1635 |
+
|
| 1636 |
+
See Also
|
| 1637 |
+
========
|
| 1638 |
+
|
| 1639 |
+
axis
|
| 1640 |
+
norm
|
| 1641 |
+
|
| 1642 |
+
"""
|
| 1643 |
+
|
| 1644 |
+
return self.norm() * self.axis()
|
| 1645 |
+
|
| 1646 |
+
def mensor(self):
|
| 1647 |
+
"""
|
| 1648 |
+
Returns the natural logarithm of the norm(magnitude) of the quaternion.
|
| 1649 |
+
|
| 1650 |
+
Examples
|
| 1651 |
+
========
|
| 1652 |
+
|
| 1653 |
+
>>> from sympy.algebras.quaternion import Quaternion
|
| 1654 |
+
>>> q = Quaternion(2, 4, 2, 4)
|
| 1655 |
+
>>> q.mensor()
|
| 1656 |
+
log(2*sqrt(10))
|
| 1657 |
+
>>> q.norm()
|
| 1658 |
+
2*sqrt(10)
|
| 1659 |
+
|
| 1660 |
+
See Also
|
| 1661 |
+
========
|
| 1662 |
+
|
| 1663 |
+
norm
|
| 1664 |
+
|
| 1665 |
+
"""
|
| 1666 |
+
|
| 1667 |
+
return ln(self.norm())
|
pllava/lib/python3.10/site-packages/sympy/algebras/tests/__init__.py
ADDED
|
File without changes
|
pllava/lib/python3.10/site-packages/sympy/algebras/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (172 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (484 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/calculus.cpython-310.pyc
ADDED
|
Binary file (6.36 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/common.cpython-310.pyc
ADDED
|
Binary file (4.62 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/ntheory.cpython-310.pyc
ADDED
|
Binary file (6.03 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/order.cpython-310.pyc
ADDED
|
Binary file (10.3 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/sets.cpython-310.pyc
ADDED
|
Binary file (17.9 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/categories/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Category Theory module.
|
| 3 |
+
|
| 4 |
+
Provides some of the fundamental category-theory-related classes,
|
| 5 |
+
including categories, morphisms, diagrams. Functors are not
|
| 6 |
+
implemented yet.
|
| 7 |
+
|
| 8 |
+
The general reference work this module tries to follow is
|
| 9 |
+
|
| 10 |
+
[JoyOfCats] J. Adamek, H. Herrlich. G. E. Strecker: Abstract and
|
| 11 |
+
Concrete Categories. The Joy of Cats.
|
| 12 |
+
|
| 13 |
+
The latest version of this book should be available for free download
|
| 14 |
+
from
|
| 15 |
+
|
| 16 |
+
katmat.math.uni-bremen.de/acc/acc.pdf
|
| 17 |
+
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from .baseclasses import (Object, Morphism, IdentityMorphism,
|
| 21 |
+
NamedMorphism, CompositeMorphism, Category,
|
| 22 |
+
Diagram)
|
| 23 |
+
|
| 24 |
+
from .diagram_drawing import (DiagramGrid, XypicDiagramDrawer,
|
| 25 |
+
xypic_draw_diagram, preview_diagram)
|
| 26 |
+
|
| 27 |
+
__all__ = [
|
| 28 |
+
'Object', 'Morphism', 'IdentityMorphism', 'NamedMorphism',
|
| 29 |
+
'CompositeMorphism', 'Category', 'Diagram',
|
| 30 |
+
|
| 31 |
+
'DiagramGrid', 'XypicDiagramDrawer', 'xypic_draw_diagram',
|
| 32 |
+
'preview_diagram',
|
| 33 |
+
]
|
pllava/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.04 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc
ADDED
|
Binary file (28.2 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc
ADDED
|
Binary file (65.4 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/categories/baseclasses.py
ADDED
|
@@ -0,0 +1,978 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import S, Basic, Dict, Symbol, Tuple, sympify
|
| 2 |
+
from sympy.core.symbol import Str
|
| 3 |
+
from sympy.sets import Set, FiniteSet, EmptySet
|
| 4 |
+
from sympy.utilities.iterables import iterable
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Class(Set):
|
| 8 |
+
r"""
|
| 9 |
+
The base class for any kind of class in the set-theoretic sense.
|
| 10 |
+
|
| 11 |
+
Explanation
|
| 12 |
+
===========
|
| 13 |
+
|
| 14 |
+
In axiomatic set theories, everything is a class. A class which
|
| 15 |
+
can be a member of another class is a set. A class which is not a
|
| 16 |
+
member of another class is a proper class. The class `\{1, 2\}`
|
| 17 |
+
is a set; the class of all sets is a proper class.
|
| 18 |
+
|
| 19 |
+
This class is essentially a synonym for :class:`sympy.core.Set`.
|
| 20 |
+
The goal of this class is to assure easier migration to the
|
| 21 |
+
eventual proper implementation of set theory.
|
| 22 |
+
"""
|
| 23 |
+
is_proper = False
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Object(Symbol):
|
| 27 |
+
"""
|
| 28 |
+
The base class for any kind of object in an abstract category.
|
| 29 |
+
|
| 30 |
+
Explanation
|
| 31 |
+
===========
|
| 32 |
+
|
| 33 |
+
While technically any instance of :class:`~.Basic` will do, this
|
| 34 |
+
class is the recommended way to create abstract objects in
|
| 35 |
+
abstract categories.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Morphism(Basic):
|
| 40 |
+
"""
|
| 41 |
+
The base class for any morphism in an abstract category.
|
| 42 |
+
|
| 43 |
+
Explanation
|
| 44 |
+
===========
|
| 45 |
+
|
| 46 |
+
In abstract categories, a morphism is an arrow between two
|
| 47 |
+
category objects. The object where the arrow starts is called the
|
| 48 |
+
domain, while the object where the arrow ends is called the
|
| 49 |
+
codomain.
|
| 50 |
+
|
| 51 |
+
Two morphisms between the same pair of objects are considered to
|
| 52 |
+
be the same morphisms. To distinguish between morphisms between
|
| 53 |
+
the same objects use :class:`NamedMorphism`.
|
| 54 |
+
|
| 55 |
+
It is prohibited to instantiate this class. Use one of the
|
| 56 |
+
derived classes instead.
|
| 57 |
+
|
| 58 |
+
See Also
|
| 59 |
+
========
|
| 60 |
+
|
| 61 |
+
IdentityMorphism, NamedMorphism, CompositeMorphism
|
| 62 |
+
"""
|
| 63 |
+
def __new__(cls, domain, codomain):
|
| 64 |
+
raise(NotImplementedError(
|
| 65 |
+
"Cannot instantiate Morphism. Use derived classes instead."))
|
| 66 |
+
|
| 67 |
+
@property
|
| 68 |
+
def domain(self):
|
| 69 |
+
"""
|
| 70 |
+
Returns the domain of the morphism.
|
| 71 |
+
|
| 72 |
+
Examples
|
| 73 |
+
========
|
| 74 |
+
|
| 75 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 76 |
+
>>> A = Object("A")
|
| 77 |
+
>>> B = Object("B")
|
| 78 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 79 |
+
>>> f.domain
|
| 80 |
+
Object("A")
|
| 81 |
+
|
| 82 |
+
"""
|
| 83 |
+
return self.args[0]
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def codomain(self):
|
| 87 |
+
"""
|
| 88 |
+
Returns the codomain of the morphism.
|
| 89 |
+
|
| 90 |
+
Examples
|
| 91 |
+
========
|
| 92 |
+
|
| 93 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 94 |
+
>>> A = Object("A")
|
| 95 |
+
>>> B = Object("B")
|
| 96 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 97 |
+
>>> f.codomain
|
| 98 |
+
Object("B")
|
| 99 |
+
|
| 100 |
+
"""
|
| 101 |
+
return self.args[1]
|
| 102 |
+
|
| 103 |
+
def compose(self, other):
|
| 104 |
+
r"""
|
| 105 |
+
Composes self with the supplied morphism.
|
| 106 |
+
|
| 107 |
+
The order of elements in the composition is the usual order,
|
| 108 |
+
i.e., to construct `g\circ f` use ``g.compose(f)``.
|
| 109 |
+
|
| 110 |
+
Examples
|
| 111 |
+
========
|
| 112 |
+
|
| 113 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 114 |
+
>>> A = Object("A")
|
| 115 |
+
>>> B = Object("B")
|
| 116 |
+
>>> C = Object("C")
|
| 117 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 118 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 119 |
+
>>> g * f
|
| 120 |
+
CompositeMorphism((NamedMorphism(Object("A"), Object("B"), "f"),
|
| 121 |
+
NamedMorphism(Object("B"), Object("C"), "g")))
|
| 122 |
+
>>> (g * f).domain
|
| 123 |
+
Object("A")
|
| 124 |
+
>>> (g * f).codomain
|
| 125 |
+
Object("C")
|
| 126 |
+
|
| 127 |
+
"""
|
| 128 |
+
return CompositeMorphism(other, self)
|
| 129 |
+
|
| 130 |
+
def __mul__(self, other):
|
| 131 |
+
r"""
|
| 132 |
+
Composes self with the supplied morphism.
|
| 133 |
+
|
| 134 |
+
The semantics of this operation is given by the following
|
| 135 |
+
equation: ``g * f == g.compose(f)`` for composable morphisms
|
| 136 |
+
``g`` and ``f``.
|
| 137 |
+
|
| 138 |
+
See Also
|
| 139 |
+
========
|
| 140 |
+
|
| 141 |
+
compose
|
| 142 |
+
"""
|
| 143 |
+
return self.compose(other)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class IdentityMorphism(Morphism):
|
| 147 |
+
"""
|
| 148 |
+
Represents an identity morphism.
|
| 149 |
+
|
| 150 |
+
Explanation
|
| 151 |
+
===========
|
| 152 |
+
|
| 153 |
+
An identity morphism is a morphism with equal domain and codomain,
|
| 154 |
+
which acts as an identity with respect to composition.
|
| 155 |
+
|
| 156 |
+
Examples
|
| 157 |
+
========
|
| 158 |
+
|
| 159 |
+
>>> from sympy.categories import Object, NamedMorphism, IdentityMorphism
|
| 160 |
+
>>> A = Object("A")
|
| 161 |
+
>>> B = Object("B")
|
| 162 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 163 |
+
>>> id_A = IdentityMorphism(A)
|
| 164 |
+
>>> id_B = IdentityMorphism(B)
|
| 165 |
+
>>> f * id_A == f
|
| 166 |
+
True
|
| 167 |
+
>>> id_B * f == f
|
| 168 |
+
True
|
| 169 |
+
|
| 170 |
+
See Also
|
| 171 |
+
========
|
| 172 |
+
|
| 173 |
+
Morphism
|
| 174 |
+
"""
|
| 175 |
+
def __new__(cls, domain):
|
| 176 |
+
return Basic.__new__(cls, domain)
|
| 177 |
+
|
| 178 |
+
@property
|
| 179 |
+
def codomain(self):
|
| 180 |
+
return self.domain
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class NamedMorphism(Morphism):
|
| 184 |
+
"""
|
| 185 |
+
Represents a morphism which has a name.
|
| 186 |
+
|
| 187 |
+
Explanation
|
| 188 |
+
===========
|
| 189 |
+
|
| 190 |
+
Names are used to distinguish between morphisms which have the
|
| 191 |
+
same domain and codomain: two named morphisms are equal if they
|
| 192 |
+
have the same domains, codomains, and names.
|
| 193 |
+
|
| 194 |
+
Examples
|
| 195 |
+
========
|
| 196 |
+
|
| 197 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 198 |
+
>>> A = Object("A")
|
| 199 |
+
>>> B = Object("B")
|
| 200 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 201 |
+
>>> f
|
| 202 |
+
NamedMorphism(Object("A"), Object("B"), "f")
|
| 203 |
+
>>> f.name
|
| 204 |
+
'f'
|
| 205 |
+
|
| 206 |
+
See Also
|
| 207 |
+
========
|
| 208 |
+
|
| 209 |
+
Morphism
|
| 210 |
+
"""
|
| 211 |
+
def __new__(cls, domain, codomain, name):
|
| 212 |
+
if not name:
|
| 213 |
+
raise ValueError("Empty morphism names not allowed.")
|
| 214 |
+
|
| 215 |
+
if not isinstance(name, Str):
|
| 216 |
+
name = Str(name)
|
| 217 |
+
|
| 218 |
+
return Basic.__new__(cls, domain, codomain, name)
|
| 219 |
+
|
| 220 |
+
@property
|
| 221 |
+
def name(self):
|
| 222 |
+
"""
|
| 223 |
+
Returns the name of the morphism.
|
| 224 |
+
|
| 225 |
+
Examples
|
| 226 |
+
========
|
| 227 |
+
|
| 228 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 229 |
+
>>> A = Object("A")
|
| 230 |
+
>>> B = Object("B")
|
| 231 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 232 |
+
>>> f.name
|
| 233 |
+
'f'
|
| 234 |
+
|
| 235 |
+
"""
|
| 236 |
+
return self.args[2].name
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class CompositeMorphism(Morphism):
|
| 240 |
+
r"""
|
| 241 |
+
Represents a morphism which is a composition of other morphisms.
|
| 242 |
+
|
| 243 |
+
Explanation
|
| 244 |
+
===========
|
| 245 |
+
|
| 246 |
+
Two composite morphisms are equal if the morphisms they were
|
| 247 |
+
obtained from (components) are the same and were listed in the
|
| 248 |
+
same order.
|
| 249 |
+
|
| 250 |
+
The arguments to the constructor for this class should be listed
|
| 251 |
+
in diagram order: to obtain the composition `g\circ f` from the
|
| 252 |
+
instances of :class:`Morphism` ``g`` and ``f`` use
|
| 253 |
+
``CompositeMorphism(f, g)``.
|
| 254 |
+
|
| 255 |
+
Examples
|
| 256 |
+
========
|
| 257 |
+
|
| 258 |
+
>>> from sympy.categories import Object, NamedMorphism, CompositeMorphism
|
| 259 |
+
>>> A = Object("A")
|
| 260 |
+
>>> B = Object("B")
|
| 261 |
+
>>> C = Object("C")
|
| 262 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 263 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 264 |
+
>>> g * f
|
| 265 |
+
CompositeMorphism((NamedMorphism(Object("A"), Object("B"), "f"),
|
| 266 |
+
NamedMorphism(Object("B"), Object("C"), "g")))
|
| 267 |
+
>>> CompositeMorphism(f, g) == g * f
|
| 268 |
+
True
|
| 269 |
+
|
| 270 |
+
"""
|
| 271 |
+
@staticmethod
|
| 272 |
+
def _add_morphism(t, morphism):
|
| 273 |
+
"""
|
| 274 |
+
Intelligently adds ``morphism`` to tuple ``t``.
|
| 275 |
+
|
| 276 |
+
Explanation
|
| 277 |
+
===========
|
| 278 |
+
|
| 279 |
+
If ``morphism`` is a composite morphism, its components are
|
| 280 |
+
added to the tuple. If ``morphism`` is an identity, nothing
|
| 281 |
+
is added to the tuple.
|
| 282 |
+
|
| 283 |
+
No composability checks are performed.
|
| 284 |
+
"""
|
| 285 |
+
if isinstance(morphism, CompositeMorphism):
|
| 286 |
+
# ``morphism`` is a composite morphism; we have to
|
| 287 |
+
# denest its components.
|
| 288 |
+
return t + morphism.components
|
| 289 |
+
elif isinstance(morphism, IdentityMorphism):
|
| 290 |
+
# ``morphism`` is an identity. Nothing happens.
|
| 291 |
+
return t
|
| 292 |
+
else:
|
| 293 |
+
return t + Tuple(morphism)
|
| 294 |
+
|
| 295 |
+
def __new__(cls, *components):
|
| 296 |
+
if components and not isinstance(components[0], Morphism):
|
| 297 |
+
# Maybe the user has explicitly supplied a list of
|
| 298 |
+
# morphisms.
|
| 299 |
+
return CompositeMorphism.__new__(cls, *components[0])
|
| 300 |
+
|
| 301 |
+
normalised_components = Tuple()
|
| 302 |
+
|
| 303 |
+
for current, following in zip(components, components[1:]):
|
| 304 |
+
if not isinstance(current, Morphism) or \
|
| 305 |
+
not isinstance(following, Morphism):
|
| 306 |
+
raise TypeError("All components must be morphisms.")
|
| 307 |
+
|
| 308 |
+
if current.codomain != following.domain:
|
| 309 |
+
raise ValueError("Uncomposable morphisms.")
|
| 310 |
+
|
| 311 |
+
normalised_components = CompositeMorphism._add_morphism(
|
| 312 |
+
normalised_components, current)
|
| 313 |
+
|
| 314 |
+
# We haven't added the last morphism to the list of normalised
|
| 315 |
+
# components. Add it now.
|
| 316 |
+
normalised_components = CompositeMorphism._add_morphism(
|
| 317 |
+
normalised_components, components[-1])
|
| 318 |
+
|
| 319 |
+
if not normalised_components:
|
| 320 |
+
# If ``normalised_components`` is empty, only identities
|
| 321 |
+
# were supplied. Since they all were composable, they are
|
| 322 |
+
# all the same identities.
|
| 323 |
+
return components[0]
|
| 324 |
+
elif len(normalised_components) == 1:
|
| 325 |
+
# No sense to construct a whole CompositeMorphism.
|
| 326 |
+
return normalised_components[0]
|
| 327 |
+
|
| 328 |
+
return Basic.__new__(cls, normalised_components)
|
| 329 |
+
|
| 330 |
+
@property
|
| 331 |
+
def components(self):
|
| 332 |
+
"""
|
| 333 |
+
Returns the components of this composite morphism.
|
| 334 |
+
|
| 335 |
+
Examples
|
| 336 |
+
========
|
| 337 |
+
|
| 338 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 339 |
+
>>> A = Object("A")
|
| 340 |
+
>>> B = Object("B")
|
| 341 |
+
>>> C = Object("C")
|
| 342 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 343 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 344 |
+
>>> (g * f).components
|
| 345 |
+
(NamedMorphism(Object("A"), Object("B"), "f"),
|
| 346 |
+
NamedMorphism(Object("B"), Object("C"), "g"))
|
| 347 |
+
|
| 348 |
+
"""
|
| 349 |
+
return self.args[0]
|
| 350 |
+
|
| 351 |
+
@property
|
| 352 |
+
def domain(self):
|
| 353 |
+
"""
|
| 354 |
+
Returns the domain of this composite morphism.
|
| 355 |
+
|
| 356 |
+
The domain of the composite morphism is the domain of its
|
| 357 |
+
first component.
|
| 358 |
+
|
| 359 |
+
Examples
|
| 360 |
+
========
|
| 361 |
+
|
| 362 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 363 |
+
>>> A = Object("A")
|
| 364 |
+
>>> B = Object("B")
|
| 365 |
+
>>> C = Object("C")
|
| 366 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 367 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 368 |
+
>>> (g * f).domain
|
| 369 |
+
Object("A")
|
| 370 |
+
|
| 371 |
+
"""
|
| 372 |
+
return self.components[0].domain
|
| 373 |
+
|
| 374 |
+
@property
|
| 375 |
+
def codomain(self):
|
| 376 |
+
"""
|
| 377 |
+
Returns the codomain of this composite morphism.
|
| 378 |
+
|
| 379 |
+
The codomain of the composite morphism is the codomain of its
|
| 380 |
+
last component.
|
| 381 |
+
|
| 382 |
+
Examples
|
| 383 |
+
========
|
| 384 |
+
|
| 385 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 386 |
+
>>> A = Object("A")
|
| 387 |
+
>>> B = Object("B")
|
| 388 |
+
>>> C = Object("C")
|
| 389 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 390 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 391 |
+
>>> (g * f).codomain
|
| 392 |
+
Object("C")
|
| 393 |
+
|
| 394 |
+
"""
|
| 395 |
+
return self.components[-1].codomain
|
| 396 |
+
|
| 397 |
+
def flatten(self, new_name):
|
| 398 |
+
"""
|
| 399 |
+
Forgets the composite structure of this morphism.
|
| 400 |
+
|
| 401 |
+
Explanation
|
| 402 |
+
===========
|
| 403 |
+
|
| 404 |
+
If ``new_name`` is not empty, returns a :class:`NamedMorphism`
|
| 405 |
+
with the supplied name, otherwise returns a :class:`Morphism`.
|
| 406 |
+
In both cases the domain of the new morphism is the domain of
|
| 407 |
+
this composite morphism and the codomain of the new morphism
|
| 408 |
+
is the codomain of this composite morphism.
|
| 409 |
+
|
| 410 |
+
Examples
|
| 411 |
+
========
|
| 412 |
+
|
| 413 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 414 |
+
>>> A = Object("A")
|
| 415 |
+
>>> B = Object("B")
|
| 416 |
+
>>> C = Object("C")
|
| 417 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 418 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 419 |
+
>>> (g * f).flatten("h")
|
| 420 |
+
NamedMorphism(Object("A"), Object("C"), "h")
|
| 421 |
+
|
| 422 |
+
"""
|
| 423 |
+
return NamedMorphism(self.domain, self.codomain, new_name)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class Category(Basic):
|
| 427 |
+
r"""
|
| 428 |
+
An (abstract) category.
|
| 429 |
+
|
| 430 |
+
Explanation
|
| 431 |
+
===========
|
| 432 |
+
|
| 433 |
+
A category [JoyOfCats] is a quadruple `\mbox{K} = (O, \hom, id,
|
| 434 |
+
\circ)` consisting of
|
| 435 |
+
|
| 436 |
+
* a (set-theoretical) class `O`, whose members are called
|
| 437 |
+
`K`-objects,
|
| 438 |
+
|
| 439 |
+
* for each pair `(A, B)` of `K`-objects, a set `\hom(A, B)` whose
|
| 440 |
+
members are called `K`-morphisms from `A` to `B`,
|
| 441 |
+
|
| 442 |
+
* for a each `K`-object `A`, a morphism `id:A\rightarrow A`,
|
| 443 |
+
called the `K`-identity of `A`,
|
| 444 |
+
|
| 445 |
+
* a composition law `\circ` associating with every `K`-morphisms
|
| 446 |
+
`f:A\rightarrow B` and `g:B\rightarrow C` a `K`-morphism `g\circ
|
| 447 |
+
f:A\rightarrow C`, called the composite of `f` and `g`.
|
| 448 |
+
|
| 449 |
+
Composition is associative, `K`-identities are identities with
|
| 450 |
+
respect to composition, and the sets `\hom(A, B)` are pairwise
|
| 451 |
+
disjoint.
|
| 452 |
+
|
| 453 |
+
This class knows nothing about its objects and morphisms.
|
| 454 |
+
Concrete cases of (abstract) categories should be implemented as
|
| 455 |
+
classes derived from this one.
|
| 456 |
+
|
| 457 |
+
Certain instances of :class:`Diagram` can be asserted to be
|
| 458 |
+
commutative in a :class:`Category` by supplying the argument
|
| 459 |
+
``commutative_diagrams`` in the constructor.
|
| 460 |
+
|
| 461 |
+
Examples
|
| 462 |
+
========
|
| 463 |
+
|
| 464 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram, Category
|
| 465 |
+
>>> from sympy import FiniteSet
|
| 466 |
+
>>> A = Object("A")
|
| 467 |
+
>>> B = Object("B")
|
| 468 |
+
>>> C = Object("C")
|
| 469 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 470 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 471 |
+
>>> d = Diagram([f, g])
|
| 472 |
+
>>> K = Category("K", commutative_diagrams=[d])
|
| 473 |
+
>>> K.commutative_diagrams == FiniteSet(d)
|
| 474 |
+
True
|
| 475 |
+
|
| 476 |
+
See Also
|
| 477 |
+
========
|
| 478 |
+
|
| 479 |
+
Diagram
|
| 480 |
+
"""
|
| 481 |
+
def __new__(cls, name, objects=EmptySet, commutative_diagrams=EmptySet):
|
| 482 |
+
if not name:
|
| 483 |
+
raise ValueError("A Category cannot have an empty name.")
|
| 484 |
+
|
| 485 |
+
if not isinstance(name, Str):
|
| 486 |
+
name = Str(name)
|
| 487 |
+
|
| 488 |
+
if not isinstance(objects, Class):
|
| 489 |
+
objects = Class(objects)
|
| 490 |
+
|
| 491 |
+
new_category = Basic.__new__(cls, name, objects,
|
| 492 |
+
FiniteSet(*commutative_diagrams))
|
| 493 |
+
return new_category
|
| 494 |
+
|
| 495 |
+
@property
|
| 496 |
+
def name(self):
|
| 497 |
+
"""
|
| 498 |
+
Returns the name of this category.
|
| 499 |
+
|
| 500 |
+
Examples
|
| 501 |
+
========
|
| 502 |
+
|
| 503 |
+
>>> from sympy.categories import Category
|
| 504 |
+
>>> K = Category("K")
|
| 505 |
+
>>> K.name
|
| 506 |
+
'K'
|
| 507 |
+
|
| 508 |
+
"""
|
| 509 |
+
return self.args[0].name
|
| 510 |
+
|
| 511 |
+
@property
|
| 512 |
+
def objects(self):
|
| 513 |
+
"""
|
| 514 |
+
Returns the class of objects of this category.
|
| 515 |
+
|
| 516 |
+
Examples
|
| 517 |
+
========
|
| 518 |
+
|
| 519 |
+
>>> from sympy.categories import Object, Category
|
| 520 |
+
>>> from sympy import FiniteSet
|
| 521 |
+
>>> A = Object("A")
|
| 522 |
+
>>> B = Object("B")
|
| 523 |
+
>>> K = Category("K", FiniteSet(A, B))
|
| 524 |
+
>>> K.objects
|
| 525 |
+
Class({Object("A"), Object("B")})
|
| 526 |
+
|
| 527 |
+
"""
|
| 528 |
+
return self.args[1]
|
| 529 |
+
|
| 530 |
+
@property
|
| 531 |
+
def commutative_diagrams(self):
|
| 532 |
+
"""
|
| 533 |
+
Returns the :class:`~.FiniteSet` of diagrams which are known to
|
| 534 |
+
be commutative in this category.
|
| 535 |
+
|
| 536 |
+
Examples
|
| 537 |
+
========
|
| 538 |
+
|
| 539 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram, Category
|
| 540 |
+
>>> from sympy import FiniteSet
|
| 541 |
+
>>> A = Object("A")
|
| 542 |
+
>>> B = Object("B")
|
| 543 |
+
>>> C = Object("C")
|
| 544 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 545 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 546 |
+
>>> d = Diagram([f, g])
|
| 547 |
+
>>> K = Category("K", commutative_diagrams=[d])
|
| 548 |
+
>>> K.commutative_diagrams == FiniteSet(d)
|
| 549 |
+
True
|
| 550 |
+
|
| 551 |
+
"""
|
| 552 |
+
return self.args[2]
|
| 553 |
+
|
| 554 |
+
def hom(self, A, B):
|
| 555 |
+
raise NotImplementedError(
|
| 556 |
+
"hom-sets are not implemented in Category.")
|
| 557 |
+
|
| 558 |
+
def all_morphisms(self):
|
| 559 |
+
raise NotImplementedError(
|
| 560 |
+
"Obtaining the class of morphisms is not implemented in Category.")
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
class Diagram(Basic):
|
| 564 |
+
r"""
|
| 565 |
+
Represents a diagram in a certain category.
|
| 566 |
+
|
| 567 |
+
Explanation
|
| 568 |
+
===========
|
| 569 |
+
|
| 570 |
+
Informally, a diagram is a collection of objects of a category and
|
| 571 |
+
certain morphisms between them. A diagram is still a monoid with
|
| 572 |
+
respect to morphism composition; i.e., identity morphisms, as well
|
| 573 |
+
as all composites of morphisms included in the diagram belong to
|
| 574 |
+
the diagram. For a more formal approach to this notion see
|
| 575 |
+
[Pare1970].
|
| 576 |
+
|
| 577 |
+
The components of composite morphisms are also added to the
|
| 578 |
+
diagram. No properties are assigned to such morphisms by default.
|
| 579 |
+
|
| 580 |
+
A commutative diagram is often accompanied by a statement of the
|
| 581 |
+
following kind: "if such morphisms with such properties exist,
|
| 582 |
+
then such morphisms which such properties exist and the diagram is
|
| 583 |
+
commutative". To represent this, an instance of :class:`Diagram`
|
| 584 |
+
includes a collection of morphisms which are the premises and
|
| 585 |
+
another collection of conclusions. ``premises`` and
|
| 586 |
+
``conclusions`` associate morphisms belonging to the corresponding
|
| 587 |
+
categories with the :class:`~.FiniteSet`'s of their properties.
|
| 588 |
+
|
| 589 |
+
The set of properties of a composite morphism is the intersection
|
| 590 |
+
of the sets of properties of its components. The domain and
|
| 591 |
+
codomain of a conclusion morphism should be among the domains and
|
| 592 |
+
codomains of the morphisms listed as the premises of a diagram.
|
| 593 |
+
|
| 594 |
+
No checks are carried out of whether the supplied object and
|
| 595 |
+
morphisms do belong to one and the same category.
|
| 596 |
+
|
| 597 |
+
Examples
|
| 598 |
+
========
|
| 599 |
+
|
| 600 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 601 |
+
>>> from sympy import pprint, default_sort_key
|
| 602 |
+
>>> A = Object("A")
|
| 603 |
+
>>> B = Object("B")
|
| 604 |
+
>>> C = Object("C")
|
| 605 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 606 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 607 |
+
>>> d = Diagram([f, g])
|
| 608 |
+
>>> premises_keys = sorted(d.premises.keys(), key=default_sort_key)
|
| 609 |
+
>>> pprint(premises_keys, use_unicode=False)
|
| 610 |
+
[g*f:A-->C, id:A-->A, id:B-->B, id:C-->C, f:A-->B, g:B-->C]
|
| 611 |
+
>>> pprint(d.premises, use_unicode=False)
|
| 612 |
+
{g*f:A-->C: EmptySet, id:A-->A: EmptySet, id:B-->B: EmptySet,
|
| 613 |
+
id:C-->C: EmptySet, f:A-->B: EmptySet, g:B-->C: EmptySet}
|
| 614 |
+
>>> d = Diagram([f, g], {g * f: "unique"})
|
| 615 |
+
>>> pprint(d.conclusions,use_unicode=False)
|
| 616 |
+
{g*f:A-->C: {unique}}
|
| 617 |
+
|
| 618 |
+
References
|
| 619 |
+
==========
|
| 620 |
+
|
| 621 |
+
[Pare1970] B. Pareigis: Categories and functors. Academic Press, 1970.
|
| 622 |
+
|
| 623 |
+
"""
|
| 624 |
+
@staticmethod
|
| 625 |
+
def _set_dict_union(dictionary, key, value):
|
| 626 |
+
"""
|
| 627 |
+
If ``key`` is in ``dictionary``, set the new value of ``key``
|
| 628 |
+
to be the union between the old value and ``value``.
|
| 629 |
+
Otherwise, set the value of ``key`` to ``value.
|
| 630 |
+
|
| 631 |
+
Returns ``True`` if the key already was in the dictionary and
|
| 632 |
+
``False`` otherwise.
|
| 633 |
+
"""
|
| 634 |
+
if key in dictionary:
|
| 635 |
+
dictionary[key] = dictionary[key] | value
|
| 636 |
+
return True
|
| 637 |
+
else:
|
| 638 |
+
dictionary[key] = value
|
| 639 |
+
return False
|
| 640 |
+
|
| 641 |
+
@staticmethod
|
| 642 |
+
def _add_morphism_closure(morphisms, morphism, props, add_identities=True,
|
| 643 |
+
recurse_composites=True):
|
| 644 |
+
"""
|
| 645 |
+
Adds a morphism and its attributes to the supplied dictionary
|
| 646 |
+
``morphisms``. If ``add_identities`` is True, also adds the
|
| 647 |
+
identity morphisms for the domain and the codomain of
|
| 648 |
+
``morphism``.
|
| 649 |
+
"""
|
| 650 |
+
if not Diagram._set_dict_union(morphisms, morphism, props):
|
| 651 |
+
# We have just added a new morphism.
|
| 652 |
+
|
| 653 |
+
if isinstance(morphism, IdentityMorphism):
|
| 654 |
+
if props:
|
| 655 |
+
# Properties for identity morphisms don't really
|
| 656 |
+
# make sense, because very much is known about
|
| 657 |
+
# identity morphisms already, so much that they
|
| 658 |
+
# are trivial. Having properties for identity
|
| 659 |
+
# morphisms would only be confusing.
|
| 660 |
+
raise ValueError(
|
| 661 |
+
"Instances of IdentityMorphism cannot have properties.")
|
| 662 |
+
return
|
| 663 |
+
|
| 664 |
+
if add_identities:
|
| 665 |
+
empty = EmptySet
|
| 666 |
+
|
| 667 |
+
id_dom = IdentityMorphism(morphism.domain)
|
| 668 |
+
id_cod = IdentityMorphism(morphism.codomain)
|
| 669 |
+
|
| 670 |
+
Diagram._set_dict_union(morphisms, id_dom, empty)
|
| 671 |
+
Diagram._set_dict_union(morphisms, id_cod, empty)
|
| 672 |
+
|
| 673 |
+
for existing_morphism, existing_props in list(morphisms.items()):
|
| 674 |
+
new_props = existing_props & props
|
| 675 |
+
if morphism.domain == existing_morphism.codomain:
|
| 676 |
+
left = morphism * existing_morphism
|
| 677 |
+
Diagram._set_dict_union(morphisms, left, new_props)
|
| 678 |
+
if morphism.codomain == existing_morphism.domain:
|
| 679 |
+
right = existing_morphism * morphism
|
| 680 |
+
Diagram._set_dict_union(morphisms, right, new_props)
|
| 681 |
+
|
| 682 |
+
if isinstance(morphism, CompositeMorphism) and recurse_composites:
|
| 683 |
+
# This is a composite morphism, add its components as
|
| 684 |
+
# well.
|
| 685 |
+
empty = EmptySet
|
| 686 |
+
for component in morphism.components:
|
| 687 |
+
Diagram._add_morphism_closure(morphisms, component, empty,
|
| 688 |
+
add_identities)
|
| 689 |
+
|
| 690 |
+
def __new__(cls, *args):
|
| 691 |
+
"""
|
| 692 |
+
Construct a new instance of Diagram.
|
| 693 |
+
|
| 694 |
+
Explanation
|
| 695 |
+
===========
|
| 696 |
+
|
| 697 |
+
If no arguments are supplied, an empty diagram is created.
|
| 698 |
+
|
| 699 |
+
If at least an argument is supplied, ``args[0]`` is
|
| 700 |
+
interpreted as the premises of the diagram. If ``args[0]`` is
|
| 701 |
+
a list, it is interpreted as a list of :class:`Morphism`'s, in
|
| 702 |
+
which each :class:`Morphism` has an empty set of properties.
|
| 703 |
+
If ``args[0]`` is a Python dictionary or a :class:`Dict`, it
|
| 704 |
+
is interpreted as a dictionary associating to some
|
| 705 |
+
:class:`Morphism`'s some properties.
|
| 706 |
+
|
| 707 |
+
If at least two arguments are supplied ``args[1]`` is
|
| 708 |
+
interpreted as the conclusions of the diagram. The type of
|
| 709 |
+
``args[1]`` is interpreted in exactly the same way as the type
|
| 710 |
+
of ``args[0]``. If only one argument is supplied, the diagram
|
| 711 |
+
has no conclusions.
|
| 712 |
+
|
| 713 |
+
Examples
|
| 714 |
+
========
|
| 715 |
+
|
| 716 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 717 |
+
>>> from sympy.categories import IdentityMorphism, Diagram
|
| 718 |
+
>>> A = Object("A")
|
| 719 |
+
>>> B = Object("B")
|
| 720 |
+
>>> C = Object("C")
|
| 721 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 722 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 723 |
+
>>> d = Diagram([f, g])
|
| 724 |
+
>>> IdentityMorphism(A) in d.premises.keys()
|
| 725 |
+
True
|
| 726 |
+
>>> g * f in d.premises.keys()
|
| 727 |
+
True
|
| 728 |
+
>>> d = Diagram([f, g], {g * f: "unique"})
|
| 729 |
+
>>> d.conclusions[g * f]
|
| 730 |
+
{unique}
|
| 731 |
+
|
| 732 |
+
"""
|
| 733 |
+
premises = {}
|
| 734 |
+
conclusions = {}
|
| 735 |
+
|
| 736 |
+
# Here we will keep track of the objects which appear in the
|
| 737 |
+
# premises.
|
| 738 |
+
objects = EmptySet
|
| 739 |
+
|
| 740 |
+
if len(args) >= 1:
|
| 741 |
+
# We've got some premises in the arguments.
|
| 742 |
+
premises_arg = args[0]
|
| 743 |
+
|
| 744 |
+
if isinstance(premises_arg, list):
|
| 745 |
+
# The user has supplied a list of morphisms, none of
|
| 746 |
+
# which have any attributes.
|
| 747 |
+
empty = EmptySet
|
| 748 |
+
|
| 749 |
+
for morphism in premises_arg:
|
| 750 |
+
objects |= FiniteSet(morphism.domain, morphism.codomain)
|
| 751 |
+
Diagram._add_morphism_closure(premises, morphism, empty)
|
| 752 |
+
elif isinstance(premises_arg, (dict, Dict)):
|
| 753 |
+
# The user has supplied a dictionary of morphisms and
|
| 754 |
+
# their properties.
|
| 755 |
+
for morphism, props in premises_arg.items():
|
| 756 |
+
objects |= FiniteSet(morphism.domain, morphism.codomain)
|
| 757 |
+
Diagram._add_morphism_closure(
|
| 758 |
+
premises, morphism, FiniteSet(*props) if iterable(props) else FiniteSet(props))
|
| 759 |
+
|
| 760 |
+
if len(args) >= 2:
|
| 761 |
+
# We also have some conclusions.
|
| 762 |
+
conclusions_arg = args[1]
|
| 763 |
+
|
| 764 |
+
if isinstance(conclusions_arg, list):
|
| 765 |
+
# The user has supplied a list of morphisms, none of
|
| 766 |
+
# which have any attributes.
|
| 767 |
+
empty = EmptySet
|
| 768 |
+
|
| 769 |
+
for morphism in conclusions_arg:
|
| 770 |
+
# Check that no new objects appear in conclusions.
|
| 771 |
+
if ((sympify(objects.contains(morphism.domain)) is S.true) and
|
| 772 |
+
(sympify(objects.contains(morphism.codomain)) is S.true)):
|
| 773 |
+
# No need to add identities and recurse
|
| 774 |
+
# composites this time.
|
| 775 |
+
Diagram._add_morphism_closure(
|
| 776 |
+
conclusions, morphism, empty, add_identities=False,
|
| 777 |
+
recurse_composites=False)
|
| 778 |
+
elif isinstance(conclusions_arg, (dict, Dict)):
|
| 779 |
+
# The user has supplied a dictionary of morphisms and
|
| 780 |
+
# their properties.
|
| 781 |
+
for morphism, props in conclusions_arg.items():
|
| 782 |
+
# Check that no new objects appear in conclusions.
|
| 783 |
+
if (morphism.domain in objects) and \
|
| 784 |
+
(morphism.codomain in objects):
|
| 785 |
+
# No need to add identities and recurse
|
| 786 |
+
# composites this time.
|
| 787 |
+
Diagram._add_morphism_closure(
|
| 788 |
+
conclusions, morphism, FiniteSet(*props) if iterable(props) else FiniteSet(props),
|
| 789 |
+
add_identities=False, recurse_composites=False)
|
| 790 |
+
|
| 791 |
+
return Basic.__new__(cls, Dict(premises), Dict(conclusions), objects)
|
| 792 |
+
|
| 793 |
+
@property
|
| 794 |
+
def premises(self):
|
| 795 |
+
"""
|
| 796 |
+
Returns the premises of this diagram.
|
| 797 |
+
|
| 798 |
+
Examples
|
| 799 |
+
========
|
| 800 |
+
|
| 801 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 802 |
+
>>> from sympy.categories import IdentityMorphism, Diagram
|
| 803 |
+
>>> from sympy import pretty
|
| 804 |
+
>>> A = Object("A")
|
| 805 |
+
>>> B = Object("B")
|
| 806 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 807 |
+
>>> id_A = IdentityMorphism(A)
|
| 808 |
+
>>> id_B = IdentityMorphism(B)
|
| 809 |
+
>>> d = Diagram([f])
|
| 810 |
+
>>> print(pretty(d.premises, use_unicode=False))
|
| 811 |
+
{id:A-->A: EmptySet, id:B-->B: EmptySet, f:A-->B: EmptySet}
|
| 812 |
+
|
| 813 |
+
"""
|
| 814 |
+
return self.args[0]
|
| 815 |
+
|
| 816 |
+
@property
|
| 817 |
+
def conclusions(self):
|
| 818 |
+
"""
|
| 819 |
+
Returns the conclusions of this diagram.
|
| 820 |
+
|
| 821 |
+
Examples
|
| 822 |
+
========
|
| 823 |
+
|
| 824 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 825 |
+
>>> from sympy.categories import IdentityMorphism, Diagram
|
| 826 |
+
>>> from sympy import FiniteSet
|
| 827 |
+
>>> A = Object("A")
|
| 828 |
+
>>> B = Object("B")
|
| 829 |
+
>>> C = Object("C")
|
| 830 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 831 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 832 |
+
>>> d = Diagram([f, g])
|
| 833 |
+
>>> IdentityMorphism(A) in d.premises.keys()
|
| 834 |
+
True
|
| 835 |
+
>>> g * f in d.premises.keys()
|
| 836 |
+
True
|
| 837 |
+
>>> d = Diagram([f, g], {g * f: "unique"})
|
| 838 |
+
>>> d.conclusions[g * f] == FiniteSet("unique")
|
| 839 |
+
True
|
| 840 |
+
|
| 841 |
+
"""
|
| 842 |
+
return self.args[1]
|
| 843 |
+
|
| 844 |
+
@property
|
| 845 |
+
def objects(self):
|
| 846 |
+
"""
|
| 847 |
+
Returns the :class:`~.FiniteSet` of objects that appear in this
|
| 848 |
+
diagram.
|
| 849 |
+
|
| 850 |
+
Examples
|
| 851 |
+
========
|
| 852 |
+
|
| 853 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 854 |
+
>>> A = Object("A")
|
| 855 |
+
>>> B = Object("B")
|
| 856 |
+
>>> C = Object("C")
|
| 857 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 858 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 859 |
+
>>> d = Diagram([f, g])
|
| 860 |
+
>>> d.objects
|
| 861 |
+
{Object("A"), Object("B"), Object("C")}
|
| 862 |
+
|
| 863 |
+
"""
|
| 864 |
+
return self.args[2]
|
| 865 |
+
|
| 866 |
+
def hom(self, A, B):
|
| 867 |
+
"""
|
| 868 |
+
Returns a 2-tuple of sets of morphisms between objects ``A`` and
|
| 869 |
+
``B``: one set of morphisms listed as premises, and the other set
|
| 870 |
+
of morphisms listed as conclusions.
|
| 871 |
+
|
| 872 |
+
Examples
|
| 873 |
+
========
|
| 874 |
+
|
| 875 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 876 |
+
>>> from sympy import pretty
|
| 877 |
+
>>> A = Object("A")
|
| 878 |
+
>>> B = Object("B")
|
| 879 |
+
>>> C = Object("C")
|
| 880 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 881 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 882 |
+
>>> d = Diagram([f, g], {g * f: "unique"})
|
| 883 |
+
>>> print(pretty(d.hom(A, C), use_unicode=False))
|
| 884 |
+
({g*f:A-->C}, {g*f:A-->C})
|
| 885 |
+
|
| 886 |
+
See Also
|
| 887 |
+
========
|
| 888 |
+
Object, Morphism
|
| 889 |
+
"""
|
| 890 |
+
premises = EmptySet
|
| 891 |
+
conclusions = EmptySet
|
| 892 |
+
|
| 893 |
+
for morphism in self.premises.keys():
|
| 894 |
+
if (morphism.domain == A) and (morphism.codomain == B):
|
| 895 |
+
premises |= FiniteSet(morphism)
|
| 896 |
+
for morphism in self.conclusions.keys():
|
| 897 |
+
if (morphism.domain == A) and (morphism.codomain == B):
|
| 898 |
+
conclusions |= FiniteSet(morphism)
|
| 899 |
+
|
| 900 |
+
return (premises, conclusions)
|
| 901 |
+
|
| 902 |
+
def is_subdiagram(self, diagram):
|
| 903 |
+
"""
|
| 904 |
+
Checks whether ``diagram`` is a subdiagram of ``self``.
|
| 905 |
+
Diagram `D'` is a subdiagram of `D` if all premises
|
| 906 |
+
(conclusions) of `D'` are contained in the premises
|
| 907 |
+
(conclusions) of `D`. The morphisms contained
|
| 908 |
+
both in `D'` and `D` should have the same properties for `D'`
|
| 909 |
+
to be a subdiagram of `D`.
|
| 910 |
+
|
| 911 |
+
Examples
|
| 912 |
+
========
|
| 913 |
+
|
| 914 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 915 |
+
>>> A = Object("A")
|
| 916 |
+
>>> B = Object("B")
|
| 917 |
+
>>> C = Object("C")
|
| 918 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 919 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 920 |
+
>>> d = Diagram([f, g], {g * f: "unique"})
|
| 921 |
+
>>> d1 = Diagram([f])
|
| 922 |
+
>>> d.is_subdiagram(d1)
|
| 923 |
+
True
|
| 924 |
+
>>> d1.is_subdiagram(d)
|
| 925 |
+
False
|
| 926 |
+
"""
|
| 927 |
+
premises = all((m in self.premises) and
|
| 928 |
+
(diagram.premises[m] == self.premises[m])
|
| 929 |
+
for m in diagram.premises)
|
| 930 |
+
if not premises:
|
| 931 |
+
return False
|
| 932 |
+
|
| 933 |
+
conclusions = all((m in self.conclusions) and
|
| 934 |
+
(diagram.conclusions[m] == self.conclusions[m])
|
| 935 |
+
for m in diagram.conclusions)
|
| 936 |
+
|
| 937 |
+
# Premises is surely ``True`` here.
|
| 938 |
+
return conclusions
|
| 939 |
+
|
| 940 |
+
def subdiagram_from_objects(self, objects):
|
| 941 |
+
"""
|
| 942 |
+
If ``objects`` is a subset of the objects of ``self``, returns
|
| 943 |
+
a diagram which has as premises all those premises of ``self``
|
| 944 |
+
which have a domains and codomains in ``objects``, likewise
|
| 945 |
+
for conclusions. Properties are preserved.
|
| 946 |
+
|
| 947 |
+
Examples
|
| 948 |
+
========
|
| 949 |
+
|
| 950 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 951 |
+
>>> from sympy import FiniteSet
|
| 952 |
+
>>> A = Object("A")
|
| 953 |
+
>>> B = Object("B")
|
| 954 |
+
>>> C = Object("C")
|
| 955 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 956 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 957 |
+
>>> d = Diagram([f, g], {f: "unique", g*f: "veryunique"})
|
| 958 |
+
>>> d1 = d.subdiagram_from_objects(FiniteSet(A, B))
|
| 959 |
+
>>> d1 == Diagram([f], {f: "unique"})
|
| 960 |
+
True
|
| 961 |
+
"""
|
| 962 |
+
if not objects.is_subset(self.objects):
|
| 963 |
+
raise ValueError(
|
| 964 |
+
"Supplied objects should all belong to the diagram.")
|
| 965 |
+
|
| 966 |
+
new_premises = {}
|
| 967 |
+
for morphism, props in self.premises.items():
|
| 968 |
+
if ((sympify(objects.contains(morphism.domain)) is S.true) and
|
| 969 |
+
(sympify(objects.contains(morphism.codomain)) is S.true)):
|
| 970 |
+
new_premises[morphism] = props
|
| 971 |
+
|
| 972 |
+
new_conclusions = {}
|
| 973 |
+
for morphism, props in self.conclusions.items():
|
| 974 |
+
if ((sympify(objects.contains(morphism.domain)) is S.true) and
|
| 975 |
+
(sympify(objects.contains(morphism.codomain)) is S.true)):
|
| 976 |
+
new_conclusions[morphism] = props
|
| 977 |
+
|
| 978 |
+
return Diagram(new_premises, new_conclusions)
|
pllava/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py
ADDED
|
@@ -0,0 +1,2582 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
This module contains the functionality to arrange the nodes of a
|
| 3 |
+
diagram on an abstract grid, and then to produce a graphical
|
| 4 |
+
representation of the grid.
|
| 5 |
+
|
| 6 |
+
The currently supported back-ends are Xy-pic [Xypic].
|
| 7 |
+
|
| 8 |
+
Layout Algorithm
|
| 9 |
+
================
|
| 10 |
+
|
| 11 |
+
This section provides an overview of the algorithms implemented in
|
| 12 |
+
:class:`DiagramGrid` to lay out diagrams.
|
| 13 |
+
|
| 14 |
+
The first step of the algorithm is the removal composite and identity
|
| 15 |
+
morphisms which do not have properties in the supplied diagram. The
|
| 16 |
+
premises and conclusions of the diagram are then merged.
|
| 17 |
+
|
| 18 |
+
The generic layout algorithm begins with the construction of the
|
| 19 |
+
"skeleton" of the diagram. The skeleton is an undirected graph which
|
| 20 |
+
has the objects of the diagram as vertices and has an (undirected)
|
| 21 |
+
edge between each pair of objects between which there exist morphisms.
|
| 22 |
+
The direction of the morphisms does not matter at this stage. The
|
| 23 |
+
skeleton also includes an edge between each pair of vertices `A` and
|
| 24 |
+
`C` such that there exists an object `B` which is connected via
|
| 25 |
+
a morphism to `A`, and via a morphism to `C`.
|
| 26 |
+
|
| 27 |
+
The skeleton constructed in this way has the property that every
|
| 28 |
+
object is a vertex of a triangle formed by three edges of the
|
| 29 |
+
skeleton. This property lies at the base of the generic layout
|
| 30 |
+
algorithm.
|
| 31 |
+
|
| 32 |
+
After the skeleton has been constructed, the algorithm lists all
|
| 33 |
+
triangles which can be formed. Note that some triangles will not have
|
| 34 |
+
all edges corresponding to morphisms which will actually be drawn.
|
| 35 |
+
Triangles which have only one edge or less which will actually be
|
| 36 |
+
drawn are immediately discarded.
|
| 37 |
+
|
| 38 |
+
The list of triangles is sorted according to the number of edges which
|
| 39 |
+
correspond to morphisms, then the triangle with the least number of such
|
| 40 |
+
edges is selected. One of such edges is picked and the corresponding
|
| 41 |
+
objects are placed horizontally, on a grid. This edge is recorded to
|
| 42 |
+
be in the fringe. The algorithm then finds a "welding" of a triangle
|
| 43 |
+
to the fringe. A welding is an edge in the fringe where a triangle
|
| 44 |
+
could be attached. If the algorithm succeeds in finding such a
|
| 45 |
+
welding, it adds to the grid that vertex of the triangle which was not
|
| 46 |
+
yet included in any edge in the fringe and records the two new edges in
|
| 47 |
+
the fringe. This process continues iteratively until all objects of
|
| 48 |
+
the diagram has been placed or until no more weldings can be found.
|
| 49 |
+
|
| 50 |
+
An edge is only removed from the fringe when a welding to this edge
|
| 51 |
+
has been found, and there is no room around this edge to place
|
| 52 |
+
another vertex.
|
| 53 |
+
|
| 54 |
+
When no more weldings can be found, but there are still triangles
|
| 55 |
+
left, the algorithm searches for a possibility of attaching one of the
|
| 56 |
+
remaining triangles to the existing structure by a vertex. If such a
|
| 57 |
+
possibility is found, the corresponding edge of the found triangle is
|
| 58 |
+
placed in the found space and the iterative process of welding
|
| 59 |
+
triangles restarts.
|
| 60 |
+
|
| 61 |
+
When logical groups are supplied, each of these groups is laid out
|
| 62 |
+
independently. Then a diagram is constructed in which groups are
|
| 63 |
+
objects and any two logical groups between which there exist morphisms
|
| 64 |
+
are connected via a morphism. This diagram is laid out. Finally,
|
| 65 |
+
the grid which includes all objects of the initial diagram is
|
| 66 |
+
constructed by replacing the cells which contain logical groups with
|
| 67 |
+
the corresponding laid out grids, and by correspondingly expanding the
|
| 68 |
+
rows and columns.
|
| 69 |
+
|
| 70 |
+
The sequential layout algorithm begins by constructing the
|
| 71 |
+
underlying undirected graph defined by the morphisms obtained after
|
| 72 |
+
simplifying premises and conclusions and merging them (see above).
|
| 73 |
+
The vertex with the minimal degree is then picked up and depth-first
|
| 74 |
+
search is started from it. All objects which are located at distance
|
| 75 |
+
`n` from the root in the depth-first search tree, are positioned in
|
| 76 |
+
the `n`-th column of the resulting grid. The sequential layout will
|
| 77 |
+
therefore attempt to lay the objects out along a line.
|
| 78 |
+
|
| 79 |
+
References
|
| 80 |
+
==========
|
| 81 |
+
|
| 82 |
+
.. [Xypic] https://xy-pic.sourceforge.net/
|
| 83 |
+
|
| 84 |
+
"""
|
| 85 |
+
from sympy.categories import (CompositeMorphism, IdentityMorphism,
|
| 86 |
+
NamedMorphism, Diagram)
|
| 87 |
+
from sympy.core import Dict, Symbol, default_sort_key
|
| 88 |
+
from sympy.printing.latex import latex
|
| 89 |
+
from sympy.sets import FiniteSet
|
| 90 |
+
from sympy.utilities.iterables import iterable
|
| 91 |
+
from sympy.utilities.decorator import doctest_depends_on
|
| 92 |
+
|
| 93 |
+
from itertools import chain
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
__doctest_requires__ = {('preview_diagram',): 'pyglet'}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class _GrowableGrid:
|
| 100 |
+
"""
|
| 101 |
+
Holds a growable grid of objects.
|
| 102 |
+
|
| 103 |
+
Explanation
|
| 104 |
+
===========
|
| 105 |
+
|
| 106 |
+
It is possible to append or prepend a row or a column to the grid
|
| 107 |
+
using the corresponding methods. Prepending rows or columns has
|
| 108 |
+
the effect of changing the coordinates of the already existing
|
| 109 |
+
elements.
|
| 110 |
+
|
| 111 |
+
This class currently represents a naive implementation of the
|
| 112 |
+
functionality with little attempt at optimisation.
|
| 113 |
+
"""
|
| 114 |
+
def __init__(self, width, height):
|
| 115 |
+
self._width = width
|
| 116 |
+
self._height = height
|
| 117 |
+
|
| 118 |
+
self._array = [[None for j in range(width)] for i in range(height)]
|
| 119 |
+
|
| 120 |
+
@property
|
| 121 |
+
def width(self):
|
| 122 |
+
return self._width
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def height(self):
|
| 126 |
+
return self._height
|
| 127 |
+
|
| 128 |
+
def __getitem__(self, i_j):
|
| 129 |
+
"""
|
| 130 |
+
Returns the element located at in the i-th line and j-th
|
| 131 |
+
column.
|
| 132 |
+
"""
|
| 133 |
+
i, j = i_j
|
| 134 |
+
return self._array[i][j]
|
| 135 |
+
|
| 136 |
+
def __setitem__(self, i_j, newvalue):
|
| 137 |
+
"""
|
| 138 |
+
Sets the element located at in the i-th line and j-th
|
| 139 |
+
column.
|
| 140 |
+
"""
|
| 141 |
+
i, j = i_j
|
| 142 |
+
self._array[i][j] = newvalue
|
| 143 |
+
|
| 144 |
+
def append_row(self):
|
| 145 |
+
"""
|
| 146 |
+
Appends an empty row to the grid.
|
| 147 |
+
"""
|
| 148 |
+
self._height += 1
|
| 149 |
+
self._array.append([None for j in range(self._width)])
|
| 150 |
+
|
| 151 |
+
def append_column(self):
|
| 152 |
+
"""
|
| 153 |
+
Appends an empty column to the grid.
|
| 154 |
+
"""
|
| 155 |
+
self._width += 1
|
| 156 |
+
for i in range(self._height):
|
| 157 |
+
self._array[i].append(None)
|
| 158 |
+
|
| 159 |
+
def prepend_row(self):
|
| 160 |
+
"""
|
| 161 |
+
Prepends the grid with an empty row.
|
| 162 |
+
"""
|
| 163 |
+
self._height += 1
|
| 164 |
+
self._array.insert(0, [None for j in range(self._width)])
|
| 165 |
+
|
| 166 |
+
def prepend_column(self):
|
| 167 |
+
"""
|
| 168 |
+
Prepends the grid with an empty column.
|
| 169 |
+
"""
|
| 170 |
+
self._width += 1
|
| 171 |
+
for i in range(self._height):
|
| 172 |
+
self._array[i].insert(0, None)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class DiagramGrid:
|
| 176 |
+
r"""
|
| 177 |
+
Constructs and holds the fitting of the diagram into a grid.
|
| 178 |
+
|
| 179 |
+
Explanation
|
| 180 |
+
===========
|
| 181 |
+
|
| 182 |
+
The mission of this class is to analyse the structure of the
|
| 183 |
+
supplied diagram and to place its objects on a grid such that,
|
| 184 |
+
when the objects and the morphisms are actually drawn, the diagram
|
| 185 |
+
would be "readable", in the sense that there will not be many
|
| 186 |
+
intersections of moprhisms. This class does not perform any
|
| 187 |
+
actual drawing. It does strive nevertheless to offer sufficient
|
| 188 |
+
metadata to draw a diagram.
|
| 189 |
+
|
| 190 |
+
Consider the following simple diagram.
|
| 191 |
+
|
| 192 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 193 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 194 |
+
>>> from sympy import pprint
|
| 195 |
+
>>> A = Object("A")
|
| 196 |
+
>>> B = Object("B")
|
| 197 |
+
>>> C = Object("C")
|
| 198 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 199 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 200 |
+
>>> diagram = Diagram([f, g])
|
| 201 |
+
|
| 202 |
+
The simplest way to have a diagram laid out is the following:
|
| 203 |
+
|
| 204 |
+
>>> grid = DiagramGrid(diagram)
|
| 205 |
+
>>> (grid.width, grid.height)
|
| 206 |
+
(2, 2)
|
| 207 |
+
>>> pprint(grid)
|
| 208 |
+
A B
|
| 209 |
+
<BLANKLINE>
|
| 210 |
+
C
|
| 211 |
+
|
| 212 |
+
Sometimes one sees the diagram as consisting of logical groups.
|
| 213 |
+
One can advise ``DiagramGrid`` as to such groups by employing the
|
| 214 |
+
``groups`` keyword argument.
|
| 215 |
+
|
| 216 |
+
Consider the following diagram:
|
| 217 |
+
|
| 218 |
+
>>> D = Object("D")
|
| 219 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 220 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 221 |
+
>>> h = NamedMorphism(D, A, "h")
|
| 222 |
+
>>> k = NamedMorphism(D, B, "k")
|
| 223 |
+
>>> diagram = Diagram([f, g, h, k])
|
| 224 |
+
|
| 225 |
+
Lay it out with generic layout:
|
| 226 |
+
|
| 227 |
+
>>> grid = DiagramGrid(diagram)
|
| 228 |
+
>>> pprint(grid)
|
| 229 |
+
A B D
|
| 230 |
+
<BLANKLINE>
|
| 231 |
+
C
|
| 232 |
+
|
| 233 |
+
Now, we can group the objects `A` and `D` to have them near one
|
| 234 |
+
another:
|
| 235 |
+
|
| 236 |
+
>>> grid = DiagramGrid(diagram, groups=[[A, D], B, C])
|
| 237 |
+
>>> pprint(grid)
|
| 238 |
+
B C
|
| 239 |
+
<BLANKLINE>
|
| 240 |
+
A D
|
| 241 |
+
|
| 242 |
+
Note how the positioning of the other objects changes.
|
| 243 |
+
|
| 244 |
+
Further indications can be supplied to the constructor of
|
| 245 |
+
:class:`DiagramGrid` using keyword arguments. The currently
|
| 246 |
+
supported hints are explained in the following paragraphs.
|
| 247 |
+
|
| 248 |
+
:class:`DiagramGrid` does not automatically guess which layout
|
| 249 |
+
would suit the supplied diagram better. Consider, for example,
|
| 250 |
+
the following linear diagram:
|
| 251 |
+
|
| 252 |
+
>>> E = Object("E")
|
| 253 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 254 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 255 |
+
>>> h = NamedMorphism(C, D, "h")
|
| 256 |
+
>>> i = NamedMorphism(D, E, "i")
|
| 257 |
+
>>> diagram = Diagram([f, g, h, i])
|
| 258 |
+
|
| 259 |
+
When laid out with the generic layout, it does not get to look
|
| 260 |
+
linear:
|
| 261 |
+
|
| 262 |
+
>>> grid = DiagramGrid(diagram)
|
| 263 |
+
>>> pprint(grid)
|
| 264 |
+
A B
|
| 265 |
+
<BLANKLINE>
|
| 266 |
+
C D
|
| 267 |
+
<BLANKLINE>
|
| 268 |
+
E
|
| 269 |
+
|
| 270 |
+
To get it laid out in a line, use ``layout="sequential"``:
|
| 271 |
+
|
| 272 |
+
>>> grid = DiagramGrid(diagram, layout="sequential")
|
| 273 |
+
>>> pprint(grid)
|
| 274 |
+
A B C D E
|
| 275 |
+
|
| 276 |
+
One may sometimes need to transpose the resulting layout. While
|
| 277 |
+
this can always be done by hand, :class:`DiagramGrid` provides a
|
| 278 |
+
hint for that purpose:
|
| 279 |
+
|
| 280 |
+
>>> grid = DiagramGrid(diagram, layout="sequential", transpose=True)
|
| 281 |
+
>>> pprint(grid)
|
| 282 |
+
A
|
| 283 |
+
<BLANKLINE>
|
| 284 |
+
B
|
| 285 |
+
<BLANKLINE>
|
| 286 |
+
C
|
| 287 |
+
<BLANKLINE>
|
| 288 |
+
D
|
| 289 |
+
<BLANKLINE>
|
| 290 |
+
E
|
| 291 |
+
|
| 292 |
+
Separate hints can also be provided for each group. For an
|
| 293 |
+
example, refer to ``tests/test_drawing.py``, and see the different
|
| 294 |
+
ways in which the five lemma [FiveLemma] can be laid out.
|
| 295 |
+
|
| 296 |
+
See Also
|
| 297 |
+
========
|
| 298 |
+
|
| 299 |
+
Diagram
|
| 300 |
+
|
| 301 |
+
References
|
| 302 |
+
==========
|
| 303 |
+
|
| 304 |
+
.. [FiveLemma] https://en.wikipedia.org/wiki/Five_lemma
|
| 305 |
+
"""
|
| 306 |
+
@staticmethod
|
| 307 |
+
def _simplify_morphisms(morphisms):
|
| 308 |
+
"""
|
| 309 |
+
Given a dictionary mapping morphisms to their properties,
|
| 310 |
+
returns a new dictionary in which there are no morphisms which
|
| 311 |
+
do not have properties, and which are compositions of other
|
| 312 |
+
morphisms included in the dictionary. Identities are dropped
|
| 313 |
+
as well.
|
| 314 |
+
"""
|
| 315 |
+
newmorphisms = {}
|
| 316 |
+
for morphism, props in morphisms.items():
|
| 317 |
+
if isinstance(morphism, CompositeMorphism) and not props:
|
| 318 |
+
continue
|
| 319 |
+
elif isinstance(morphism, IdentityMorphism):
|
| 320 |
+
continue
|
| 321 |
+
else:
|
| 322 |
+
newmorphisms[morphism] = props
|
| 323 |
+
return newmorphisms
|
| 324 |
+
|
| 325 |
+
@staticmethod
|
| 326 |
+
def _merge_premises_conclusions(premises, conclusions):
|
| 327 |
+
"""
|
| 328 |
+
Given two dictionaries of morphisms and their properties,
|
| 329 |
+
produces a single dictionary which includes elements from both
|
| 330 |
+
dictionaries. If a morphism has some properties in premises
|
| 331 |
+
and also in conclusions, the properties in conclusions take
|
| 332 |
+
priority.
|
| 333 |
+
"""
|
| 334 |
+
return dict(chain(premises.items(), conclusions.items()))
|
| 335 |
+
|
| 336 |
+
@staticmethod
|
| 337 |
+
def _juxtapose_edges(edge1, edge2):
|
| 338 |
+
"""
|
| 339 |
+
If ``edge1`` and ``edge2`` have precisely one common endpoint,
|
| 340 |
+
returns an edge which would form a triangle with ``edge1`` and
|
| 341 |
+
``edge2``.
|
| 342 |
+
|
| 343 |
+
If ``edge1`` and ``edge2`` do not have a common endpoint,
|
| 344 |
+
returns ``None``.
|
| 345 |
+
|
| 346 |
+
If ``edge1`` and ``edge`` are the same edge, returns ``None``.
|
| 347 |
+
"""
|
| 348 |
+
intersection = edge1 & edge2
|
| 349 |
+
if len(intersection) != 1:
|
| 350 |
+
# The edges either have no common points or are equal.
|
| 351 |
+
return None
|
| 352 |
+
|
| 353 |
+
# The edges have a common endpoint. Extract the different
|
| 354 |
+
# endpoints and set up the new edge.
|
| 355 |
+
return (edge1 - intersection) | (edge2 - intersection)
|
| 356 |
+
|
| 357 |
+
@staticmethod
|
| 358 |
+
def _add_edge_append(dictionary, edge, elem):
|
| 359 |
+
"""
|
| 360 |
+
If ``edge`` is not in ``dictionary``, adds ``edge`` to the
|
| 361 |
+
dictionary and sets its value to ``[elem]``. Otherwise
|
| 362 |
+
appends ``elem`` to the value of existing entry.
|
| 363 |
+
|
| 364 |
+
Note that edges are undirected, thus `(A, B) = (B, A)`.
|
| 365 |
+
"""
|
| 366 |
+
if edge in dictionary:
|
| 367 |
+
dictionary[edge].append(elem)
|
| 368 |
+
else:
|
| 369 |
+
dictionary[edge] = [elem]
|
| 370 |
+
|
| 371 |
+
@staticmethod
|
| 372 |
+
def _build_skeleton(morphisms):
|
| 373 |
+
"""
|
| 374 |
+
Creates a dictionary which maps edges to corresponding
|
| 375 |
+
morphisms. Thus for a morphism `f:A\rightarrow B`, the edge
|
| 376 |
+
`(A, B)` will be associated with `f`. This function also adds
|
| 377 |
+
to the list those edges which are formed by juxtaposition of
|
| 378 |
+
two edges already in the list. These new edges are not
|
| 379 |
+
associated with any morphism and are only added to assure that
|
| 380 |
+
the diagram can be decomposed into triangles.
|
| 381 |
+
"""
|
| 382 |
+
edges = {}
|
| 383 |
+
# Create edges for morphisms.
|
| 384 |
+
for morphism in morphisms:
|
| 385 |
+
DiagramGrid._add_edge_append(
|
| 386 |
+
edges, frozenset([morphism.domain, morphism.codomain]), morphism)
|
| 387 |
+
|
| 388 |
+
# Create new edges by juxtaposing existing edges.
|
| 389 |
+
edges1 = dict(edges)
|
| 390 |
+
for w in edges1:
|
| 391 |
+
for v in edges1:
|
| 392 |
+
wv = DiagramGrid._juxtapose_edges(w, v)
|
| 393 |
+
if wv and wv not in edges:
|
| 394 |
+
edges[wv] = []
|
| 395 |
+
|
| 396 |
+
return edges
|
| 397 |
+
|
| 398 |
+
@staticmethod
|
| 399 |
+
def _list_triangles(edges):
|
| 400 |
+
"""
|
| 401 |
+
Builds the set of triangles formed by the supplied edges. The
|
| 402 |
+
triangles are arbitrary and need not be commutative. A
|
| 403 |
+
triangle is a set that contains all three of its sides.
|
| 404 |
+
"""
|
| 405 |
+
triangles = set()
|
| 406 |
+
|
| 407 |
+
for w in edges:
|
| 408 |
+
for v in edges:
|
| 409 |
+
wv = DiagramGrid._juxtapose_edges(w, v)
|
| 410 |
+
if wv and wv in edges:
|
| 411 |
+
triangles.add(frozenset([w, v, wv]))
|
| 412 |
+
|
| 413 |
+
return triangles
|
| 414 |
+
|
| 415 |
+
@staticmethod
|
| 416 |
+
def _drop_redundant_triangles(triangles, skeleton):
|
| 417 |
+
"""
|
| 418 |
+
Returns a list which contains only those triangles who have
|
| 419 |
+
morphisms associated with at least two edges.
|
| 420 |
+
"""
|
| 421 |
+
return [tri for tri in triangles
|
| 422 |
+
if len([e for e in tri if skeleton[e]]) >= 2]
|
| 423 |
+
|
| 424 |
+
@staticmethod
|
| 425 |
+
def _morphism_length(morphism):
|
| 426 |
+
"""
|
| 427 |
+
Returns the length of a morphism. The length of a morphism is
|
| 428 |
+
the number of components it consists of. A non-composite
|
| 429 |
+
morphism is of length 1.
|
| 430 |
+
"""
|
| 431 |
+
if isinstance(morphism, CompositeMorphism):
|
| 432 |
+
return len(morphism.components)
|
| 433 |
+
else:
|
| 434 |
+
return 1
|
| 435 |
+
|
| 436 |
+
@staticmethod
|
| 437 |
+
def _compute_triangle_min_sizes(triangles, edges):
|
| 438 |
+
r"""
|
| 439 |
+
Returns a dictionary mapping triangles to their minimal sizes.
|
| 440 |
+
The minimal size of a triangle is the sum of maximal lengths
|
| 441 |
+
of morphisms associated to the sides of the triangle. The
|
| 442 |
+
length of a morphism is the number of components it consists
|
| 443 |
+
of. A non-composite morphism is of length 1.
|
| 444 |
+
|
| 445 |
+
Sorting triangles by this metric attempts to address two
|
| 446 |
+
aspects of layout. For triangles with only simple morphisms
|
| 447 |
+
in the edge, this assures that triangles with all three edges
|
| 448 |
+
visible will get typeset after triangles with less visible
|
| 449 |
+
edges, which sometimes minimizes the necessity in diagonal
|
| 450 |
+
arrows. For triangles with composite morphisms in the edges,
|
| 451 |
+
this assures that objects connected with shorter morphisms
|
| 452 |
+
will be laid out first, resulting the visual proximity of
|
| 453 |
+
those objects which are connected by shorter morphisms.
|
| 454 |
+
"""
|
| 455 |
+
triangle_sizes = {}
|
| 456 |
+
for triangle in triangles:
|
| 457 |
+
size = 0
|
| 458 |
+
for e in triangle:
|
| 459 |
+
morphisms = edges[e]
|
| 460 |
+
if morphisms:
|
| 461 |
+
size += max(DiagramGrid._morphism_length(m)
|
| 462 |
+
for m in morphisms)
|
| 463 |
+
triangle_sizes[triangle] = size
|
| 464 |
+
return triangle_sizes
|
| 465 |
+
|
| 466 |
+
@staticmethod
|
| 467 |
+
def _triangle_objects(triangle):
|
| 468 |
+
"""
|
| 469 |
+
Given a triangle, returns the objects included in it.
|
| 470 |
+
"""
|
| 471 |
+
# A triangle is a frozenset of three two-element frozensets
|
| 472 |
+
# (the edges). This chains the three edges together and
|
| 473 |
+
# creates a frozenset from the iterator, thus producing a
|
| 474 |
+
# frozenset of objects of the triangle.
|
| 475 |
+
return frozenset(chain(*tuple(triangle)))
|
| 476 |
+
|
| 477 |
+
@staticmethod
|
| 478 |
+
def _other_vertex(triangle, edge):
|
| 479 |
+
"""
|
| 480 |
+
Given a triangle and an edge of it, returns the vertex which
|
| 481 |
+
opposes the edge.
|
| 482 |
+
"""
|
| 483 |
+
# This gets the set of objects of the triangle and then
|
| 484 |
+
# subtracts the set of objects employed in ``edge`` to get the
|
| 485 |
+
# vertex opposite to ``edge``.
|
| 486 |
+
return list(DiagramGrid._triangle_objects(triangle) - set(edge))[0]
|
| 487 |
+
|
| 488 |
+
@staticmethod
|
| 489 |
+
def _empty_point(pt, grid):
|
| 490 |
+
"""
|
| 491 |
+
Checks if the cell at coordinates ``pt`` is either empty or
|
| 492 |
+
out of the bounds of the grid.
|
| 493 |
+
"""
|
| 494 |
+
if (pt[0] < 0) or (pt[1] < 0) or \
|
| 495 |
+
(pt[0] >= grid.height) or (pt[1] >= grid.width):
|
| 496 |
+
return True
|
| 497 |
+
return grid[pt] is None
|
| 498 |
+
|
| 499 |
+
@staticmethod
|
| 500 |
+
def _put_object(coords, obj, grid, fringe):
|
| 501 |
+
"""
|
| 502 |
+
Places an object at the coordinate ``cords`` in ``grid``,
|
| 503 |
+
growing the grid and updating ``fringe``, if necessary.
|
| 504 |
+
Returns (0, 0) if no row or column has been prepended, (1, 0)
|
| 505 |
+
if a row was prepended, (0, 1) if a column was prepended and
|
| 506 |
+
(1, 1) if both a column and a row were prepended.
|
| 507 |
+
"""
|
| 508 |
+
(i, j) = coords
|
| 509 |
+
offset = (0, 0)
|
| 510 |
+
if i == -1:
|
| 511 |
+
grid.prepend_row()
|
| 512 |
+
i = 0
|
| 513 |
+
offset = (1, 0)
|
| 514 |
+
for k in range(len(fringe)):
|
| 515 |
+
((i1, j1), (i2, j2)) = fringe[k]
|
| 516 |
+
fringe[k] = ((i1 + 1, j1), (i2 + 1, j2))
|
| 517 |
+
elif i == grid.height:
|
| 518 |
+
grid.append_row()
|
| 519 |
+
|
| 520 |
+
if j == -1:
|
| 521 |
+
j = 0
|
| 522 |
+
offset = (offset[0], 1)
|
| 523 |
+
grid.prepend_column()
|
| 524 |
+
for k in range(len(fringe)):
|
| 525 |
+
((i1, j1), (i2, j2)) = fringe[k]
|
| 526 |
+
fringe[k] = ((i1, j1 + 1), (i2, j2 + 1))
|
| 527 |
+
elif j == grid.width:
|
| 528 |
+
grid.append_column()
|
| 529 |
+
|
| 530 |
+
grid[i, j] = obj
|
| 531 |
+
return offset
|
| 532 |
+
|
| 533 |
+
@staticmethod
|
| 534 |
+
def _choose_target_cell(pt1, pt2, edge, obj, skeleton, grid):
|
| 535 |
+
"""
|
| 536 |
+
Given two points, ``pt1`` and ``pt2``, and the welding edge
|
| 537 |
+
``edge``, chooses one of the two points to place the opposing
|
| 538 |
+
vertex ``obj`` of the triangle. If neither of this points
|
| 539 |
+
fits, returns ``None``.
|
| 540 |
+
"""
|
| 541 |
+
pt1_empty = DiagramGrid._empty_point(pt1, grid)
|
| 542 |
+
pt2_empty = DiagramGrid._empty_point(pt2, grid)
|
| 543 |
+
|
| 544 |
+
if pt1_empty and pt2_empty:
|
| 545 |
+
# Both cells are empty. Of these two, choose that cell
|
| 546 |
+
# which will assure that a visible edge of the triangle
|
| 547 |
+
# will be drawn perpendicularly to the current welding
|
| 548 |
+
# edge.
|
| 549 |
+
|
| 550 |
+
A = grid[edge[0]]
|
| 551 |
+
|
| 552 |
+
if skeleton.get(frozenset([A, obj])):
|
| 553 |
+
return pt1
|
| 554 |
+
else:
|
| 555 |
+
return pt2
|
| 556 |
+
if pt1_empty:
|
| 557 |
+
return pt1
|
| 558 |
+
elif pt2_empty:
|
| 559 |
+
return pt2
|
| 560 |
+
else:
|
| 561 |
+
return None
|
| 562 |
+
|
| 563 |
+
@staticmethod
|
| 564 |
+
def _find_triangle_to_weld(triangles, fringe, grid):
|
| 565 |
+
"""
|
| 566 |
+
Finds, if possible, a triangle and an edge in the ``fringe`` to
|
| 567 |
+
which the triangle could be attached. Returns the tuple
|
| 568 |
+
containing the triangle and the index of the corresponding
|
| 569 |
+
edge in the ``fringe``.
|
| 570 |
+
|
| 571 |
+
This function relies on the fact that objects are unique in
|
| 572 |
+
the diagram.
|
| 573 |
+
"""
|
| 574 |
+
for triangle in triangles:
|
| 575 |
+
for (a, b) in fringe:
|
| 576 |
+
if frozenset([grid[a], grid[b]]) in triangle:
|
| 577 |
+
return (triangle, (a, b))
|
| 578 |
+
return None
|
| 579 |
+
|
| 580 |
+
@staticmethod
|
| 581 |
+
def _weld_triangle(tri, welding_edge, fringe, grid, skeleton):
|
| 582 |
+
"""
|
| 583 |
+
If possible, welds the triangle ``tri`` to ``fringe`` and
|
| 584 |
+
returns ``False``. If this method encounters a degenerate
|
| 585 |
+
situation in the fringe and corrects it such that a restart of
|
| 586 |
+
the search is required, it returns ``True`` (which means that
|
| 587 |
+
a restart in finding triangle weldings is required).
|
| 588 |
+
|
| 589 |
+
A degenerate situation is a situation when an edge listed in
|
| 590 |
+
the fringe does not belong to the visual boundary of the
|
| 591 |
+
diagram.
|
| 592 |
+
"""
|
| 593 |
+
a, b = welding_edge
|
| 594 |
+
target_cell = None
|
| 595 |
+
|
| 596 |
+
obj = DiagramGrid._other_vertex(tri, (grid[a], grid[b]))
|
| 597 |
+
|
| 598 |
+
# We now have a triangle and an edge where it can be welded to
|
| 599 |
+
# the fringe. Decide where to place the other vertex of the
|
| 600 |
+
# triangle and check for degenerate situations en route.
|
| 601 |
+
|
| 602 |
+
if (abs(a[0] - b[0]) == 1) and (abs(a[1] - b[1]) == 1):
|
| 603 |
+
# A diagonal edge.
|
| 604 |
+
target_cell = (a[0], b[1])
|
| 605 |
+
if grid[target_cell]:
|
| 606 |
+
# That cell is already occupied.
|
| 607 |
+
target_cell = (b[0], a[1])
|
| 608 |
+
|
| 609 |
+
if grid[target_cell]:
|
| 610 |
+
# Degenerate situation, this edge is not
|
| 611 |
+
# on the actual fringe. Correct the
|
| 612 |
+
# fringe and go on.
|
| 613 |
+
fringe.remove((a, b))
|
| 614 |
+
return True
|
| 615 |
+
elif a[0] == b[0]:
|
| 616 |
+
# A horizontal edge. We first attempt to build the
|
| 617 |
+
# triangle in the downward direction.
|
| 618 |
+
|
| 619 |
+
down_left = a[0] + 1, a[1]
|
| 620 |
+
down_right = a[0] + 1, b[1]
|
| 621 |
+
|
| 622 |
+
target_cell = DiagramGrid._choose_target_cell(
|
| 623 |
+
down_left, down_right, (a, b), obj, skeleton, grid)
|
| 624 |
+
|
| 625 |
+
if not target_cell:
|
| 626 |
+
# No room below this edge. Check above.
|
| 627 |
+
up_left = a[0] - 1, a[1]
|
| 628 |
+
up_right = a[0] - 1, b[1]
|
| 629 |
+
|
| 630 |
+
target_cell = DiagramGrid._choose_target_cell(
|
| 631 |
+
up_left, up_right, (a, b), obj, skeleton, grid)
|
| 632 |
+
|
| 633 |
+
if not target_cell:
|
| 634 |
+
# This edge is not in the fringe, remove it
|
| 635 |
+
# and restart.
|
| 636 |
+
fringe.remove((a, b))
|
| 637 |
+
return True
|
| 638 |
+
elif a[1] == b[1]:
|
| 639 |
+
# A vertical edge. We will attempt to place the other
|
| 640 |
+
# vertex of the triangle to the right of this edge.
|
| 641 |
+
right_up = a[0], a[1] + 1
|
| 642 |
+
right_down = b[0], a[1] + 1
|
| 643 |
+
|
| 644 |
+
target_cell = DiagramGrid._choose_target_cell(
|
| 645 |
+
right_up, right_down, (a, b), obj, skeleton, grid)
|
| 646 |
+
|
| 647 |
+
if not target_cell:
|
| 648 |
+
# No room to the left. See what's to the right.
|
| 649 |
+
left_up = a[0], a[1] - 1
|
| 650 |
+
left_down = b[0], a[1] - 1
|
| 651 |
+
|
| 652 |
+
target_cell = DiagramGrid._choose_target_cell(
|
| 653 |
+
left_up, left_down, (a, b), obj, skeleton, grid)
|
| 654 |
+
|
| 655 |
+
if not target_cell:
|
| 656 |
+
# This edge is not in the fringe, remove it
|
| 657 |
+
# and restart.
|
| 658 |
+
fringe.remove((a, b))
|
| 659 |
+
return True
|
| 660 |
+
|
| 661 |
+
# We now know where to place the other vertex of the
|
| 662 |
+
# triangle.
|
| 663 |
+
offset = DiagramGrid._put_object(target_cell, obj, grid, fringe)
|
| 664 |
+
|
| 665 |
+
# Take care of the displacement of coordinates if a row or
|
| 666 |
+
# a column was prepended.
|
| 667 |
+
target_cell = (target_cell[0] + offset[0],
|
| 668 |
+
target_cell[1] + offset[1])
|
| 669 |
+
a = (a[0] + offset[0], a[1] + offset[1])
|
| 670 |
+
b = (b[0] + offset[0], b[1] + offset[1])
|
| 671 |
+
|
| 672 |
+
fringe.extend([(a, target_cell), (b, target_cell)])
|
| 673 |
+
|
| 674 |
+
# No restart is required.
|
| 675 |
+
return False
|
| 676 |
+
|
| 677 |
+
@staticmethod
|
| 678 |
+
def _triangle_key(tri, triangle_sizes):
|
| 679 |
+
"""
|
| 680 |
+
Returns a key for the supplied triangle. It should be the
|
| 681 |
+
same independently of the hash randomisation.
|
| 682 |
+
"""
|
| 683 |
+
objects = sorted(
|
| 684 |
+
DiagramGrid._triangle_objects(tri), key=default_sort_key)
|
| 685 |
+
return (triangle_sizes[tri], default_sort_key(objects))
|
| 686 |
+
|
| 687 |
+
@staticmethod
|
| 688 |
+
def _pick_root_edge(tri, skeleton):
|
| 689 |
+
"""
|
| 690 |
+
For a given triangle always picks the same root edge. The
|
| 691 |
+
root edge is the edge that will be placed first on the grid.
|
| 692 |
+
"""
|
| 693 |
+
candidates = [sorted(e, key=default_sort_key)
|
| 694 |
+
for e in tri if skeleton[e]]
|
| 695 |
+
sorted_candidates = sorted(candidates, key=default_sort_key)
|
| 696 |
+
# Don't forget to assure the proper ordering of the vertices
|
| 697 |
+
# in this edge.
|
| 698 |
+
return tuple(sorted(sorted_candidates[0], key=default_sort_key))
|
| 699 |
+
|
| 700 |
+
@staticmethod
|
| 701 |
+
def _drop_irrelevant_triangles(triangles, placed_objects):
|
| 702 |
+
"""
|
| 703 |
+
Returns only those triangles whose set of objects is not
|
| 704 |
+
completely included in ``placed_objects``.
|
| 705 |
+
"""
|
| 706 |
+
return [tri for tri in triangles if not placed_objects.issuperset(
|
| 707 |
+
DiagramGrid._triangle_objects(tri))]
|
| 708 |
+
|
| 709 |
+
@staticmethod
|
| 710 |
+
def _grow_pseudopod(triangles, fringe, grid, skeleton, placed_objects):
|
| 711 |
+
"""
|
| 712 |
+
Starting from an object in the existing structure on the ``grid``,
|
| 713 |
+
adds an edge to which a triangle from ``triangles`` could be
|
| 714 |
+
welded. If this method has found a way to do so, it returns
|
| 715 |
+
the object it has just added.
|
| 716 |
+
|
| 717 |
+
This method should be applied when ``_weld_triangle`` cannot
|
| 718 |
+
find weldings any more.
|
| 719 |
+
"""
|
| 720 |
+
for i in range(grid.height):
|
| 721 |
+
for j in range(grid.width):
|
| 722 |
+
obj = grid[i, j]
|
| 723 |
+
if not obj:
|
| 724 |
+
continue
|
| 725 |
+
|
| 726 |
+
# Here we need to choose a triangle which has only
|
| 727 |
+
# ``obj`` in common with the existing structure. The
|
| 728 |
+
# situations when this is not possible should be
|
| 729 |
+
# handled elsewhere.
|
| 730 |
+
|
| 731 |
+
def good_triangle(tri):
|
| 732 |
+
objs = DiagramGrid._triangle_objects(tri)
|
| 733 |
+
return obj in objs and \
|
| 734 |
+
placed_objects & (objs - {obj}) == set()
|
| 735 |
+
|
| 736 |
+
tris = [tri for tri in triangles if good_triangle(tri)]
|
| 737 |
+
if not tris:
|
| 738 |
+
# This object is not interesting.
|
| 739 |
+
continue
|
| 740 |
+
|
| 741 |
+
# Pick the "simplest" of the triangles which could be
|
| 742 |
+
# attached. Remember that the list of triangles is
|
| 743 |
+
# sorted according to their "simplicity" (see
|
| 744 |
+
# _compute_triangle_min_sizes for the metric).
|
| 745 |
+
#
|
| 746 |
+
# Note that ``tris`` are sequentially built from
|
| 747 |
+
# ``triangles``, so we don't have to worry about hash
|
| 748 |
+
# randomisation.
|
| 749 |
+
tri = tris[0]
|
| 750 |
+
|
| 751 |
+
# We have found a triangle which could be attached to
|
| 752 |
+
# the existing structure by a vertex.
|
| 753 |
+
|
| 754 |
+
candidates = sorted([e for e in tri if skeleton[e]],
|
| 755 |
+
key=lambda e: FiniteSet(*e).sort_key())
|
| 756 |
+
edges = [e for e in candidates if obj in e]
|
| 757 |
+
|
| 758 |
+
# Note that a meaningful edge (i.e., and edge that is
|
| 759 |
+
# associated with a morphism) containing ``obj``
|
| 760 |
+
# always exists. That's because all triangles are
|
| 761 |
+
# guaranteed to have at least two meaningful edges.
|
| 762 |
+
# See _drop_redundant_triangles.
|
| 763 |
+
|
| 764 |
+
# Get the object at the other end of the edge.
|
| 765 |
+
edge = edges[0]
|
| 766 |
+
other_obj = tuple(edge - frozenset([obj]))[0]
|
| 767 |
+
|
| 768 |
+
# Now check for free directions. When checking for
|
| 769 |
+
# free directions, prefer the horizontal and vertical
|
| 770 |
+
# directions.
|
| 771 |
+
neighbours = [(i - 1, j), (i, j + 1), (i + 1, j), (i, j - 1),
|
| 772 |
+
(i - 1, j - 1), (i - 1, j + 1), (i + 1, j - 1), (i + 1, j + 1)]
|
| 773 |
+
|
| 774 |
+
for pt in neighbours:
|
| 775 |
+
if DiagramGrid._empty_point(pt, grid):
|
| 776 |
+
# We have a found a place to grow the
|
| 777 |
+
# pseudopod into.
|
| 778 |
+
offset = DiagramGrid._put_object(
|
| 779 |
+
pt, other_obj, grid, fringe)
|
| 780 |
+
|
| 781 |
+
i += offset[0]
|
| 782 |
+
j += offset[1]
|
| 783 |
+
pt = (pt[0] + offset[0], pt[1] + offset[1])
|
| 784 |
+
fringe.append(((i, j), pt))
|
| 785 |
+
|
| 786 |
+
return other_obj
|
| 787 |
+
|
| 788 |
+
# This diagram is actually cooler that I can handle. Fail cowardly.
|
| 789 |
+
return None
|
| 790 |
+
|
| 791 |
+
@staticmethod
|
| 792 |
+
def _handle_groups(diagram, groups, merged_morphisms, hints):
|
| 793 |
+
"""
|
| 794 |
+
Given the slightly preprocessed morphisms of the diagram,
|
| 795 |
+
produces a grid laid out according to ``groups``.
|
| 796 |
+
|
| 797 |
+
If a group has hints, it is laid out with those hints only,
|
| 798 |
+
without any influence from ``hints``. Otherwise, it is laid
|
| 799 |
+
out with ``hints``.
|
| 800 |
+
"""
|
| 801 |
+
def lay_out_group(group, local_hints):
|
| 802 |
+
"""
|
| 803 |
+
If ``group`` is a set of objects, uses a ``DiagramGrid``
|
| 804 |
+
to lay it out and returns the grid. Otherwise returns the
|
| 805 |
+
object (i.e., ``group``). If ``local_hints`` is not
|
| 806 |
+
empty, it is supplied to ``DiagramGrid`` as the dictionary
|
| 807 |
+
of hints. Otherwise, the ``hints`` argument of
|
| 808 |
+
``_handle_groups`` is used.
|
| 809 |
+
"""
|
| 810 |
+
if isinstance(group, FiniteSet):
|
| 811 |
+
# Set up the corresponding object-to-group
|
| 812 |
+
# mappings.
|
| 813 |
+
for obj in group:
|
| 814 |
+
obj_groups[obj] = group
|
| 815 |
+
|
| 816 |
+
# Lay out the current group.
|
| 817 |
+
if local_hints:
|
| 818 |
+
groups_grids[group] = DiagramGrid(
|
| 819 |
+
diagram.subdiagram_from_objects(group), **local_hints)
|
| 820 |
+
else:
|
| 821 |
+
groups_grids[group] = DiagramGrid(
|
| 822 |
+
diagram.subdiagram_from_objects(group), **hints)
|
| 823 |
+
else:
|
| 824 |
+
obj_groups[group] = group
|
| 825 |
+
|
| 826 |
+
def group_to_finiteset(group):
|
| 827 |
+
"""
|
| 828 |
+
Converts ``group`` to a :class:``FiniteSet`` if it is an
|
| 829 |
+
iterable.
|
| 830 |
+
"""
|
| 831 |
+
if iterable(group):
|
| 832 |
+
return FiniteSet(*group)
|
| 833 |
+
else:
|
| 834 |
+
return group
|
| 835 |
+
|
| 836 |
+
obj_groups = {}
|
| 837 |
+
groups_grids = {}
|
| 838 |
+
|
| 839 |
+
# We would like to support various containers to represent
|
| 840 |
+
# groups. To achieve that, before laying each group out, it
|
| 841 |
+
# should be converted to a FiniteSet, because that is what the
|
| 842 |
+
# following code expects.
|
| 843 |
+
|
| 844 |
+
if isinstance(groups, (dict, Dict)):
|
| 845 |
+
finiteset_groups = {}
|
| 846 |
+
for group, local_hints in groups.items():
|
| 847 |
+
finiteset_group = group_to_finiteset(group)
|
| 848 |
+
finiteset_groups[finiteset_group] = local_hints
|
| 849 |
+
lay_out_group(group, local_hints)
|
| 850 |
+
groups = finiteset_groups
|
| 851 |
+
else:
|
| 852 |
+
finiteset_groups = []
|
| 853 |
+
for group in groups:
|
| 854 |
+
finiteset_group = group_to_finiteset(group)
|
| 855 |
+
finiteset_groups.append(finiteset_group)
|
| 856 |
+
lay_out_group(finiteset_group, None)
|
| 857 |
+
groups = finiteset_groups
|
| 858 |
+
|
| 859 |
+
new_morphisms = []
|
| 860 |
+
for morphism in merged_morphisms:
|
| 861 |
+
dom = obj_groups[morphism.domain]
|
| 862 |
+
cod = obj_groups[morphism.codomain]
|
| 863 |
+
# Note that we are not really interested in morphisms
|
| 864 |
+
# which do not employ two different groups, because
|
| 865 |
+
# these do not influence the layout.
|
| 866 |
+
if dom != cod:
|
| 867 |
+
# These are essentially unnamed morphisms; they are
|
| 868 |
+
# not going to mess in the final layout. By giving
|
| 869 |
+
# them the same names, we avoid unnecessary
|
| 870 |
+
# duplicates.
|
| 871 |
+
new_morphisms.append(NamedMorphism(dom, cod, "dummy"))
|
| 872 |
+
|
| 873 |
+
# Lay out the new diagram. Since these are dummy morphisms,
|
| 874 |
+
# properties and conclusions are irrelevant.
|
| 875 |
+
top_grid = DiagramGrid(Diagram(new_morphisms))
|
| 876 |
+
|
| 877 |
+
# We now have to substitute the groups with the corresponding
|
| 878 |
+
# grids, laid out at the beginning of this function. Compute
|
| 879 |
+
# the size of each row and column in the grid, so that all
|
| 880 |
+
# nested grids fit.
|
| 881 |
+
|
| 882 |
+
def group_size(group):
|
| 883 |
+
"""
|
| 884 |
+
For the supplied group (or object, eventually), returns
|
| 885 |
+
the size of the cell that will hold this group (object).
|
| 886 |
+
"""
|
| 887 |
+
if group in groups_grids:
|
| 888 |
+
grid = groups_grids[group]
|
| 889 |
+
return (grid.height, grid.width)
|
| 890 |
+
else:
|
| 891 |
+
return (1, 1)
|
| 892 |
+
|
| 893 |
+
row_heights = [max(group_size(top_grid[i, j])[0]
|
| 894 |
+
for j in range(top_grid.width))
|
| 895 |
+
for i in range(top_grid.height)]
|
| 896 |
+
|
| 897 |
+
column_widths = [max(group_size(top_grid[i, j])[1]
|
| 898 |
+
for i in range(top_grid.height))
|
| 899 |
+
for j in range(top_grid.width)]
|
| 900 |
+
|
| 901 |
+
grid = _GrowableGrid(sum(column_widths), sum(row_heights))
|
| 902 |
+
|
| 903 |
+
real_row = 0
|
| 904 |
+
real_column = 0
|
| 905 |
+
for logical_row in range(top_grid.height):
|
| 906 |
+
for logical_column in range(top_grid.width):
|
| 907 |
+
obj = top_grid[logical_row, logical_column]
|
| 908 |
+
|
| 909 |
+
if obj in groups_grids:
|
| 910 |
+
# This is a group. Copy the corresponding grid in
|
| 911 |
+
# place.
|
| 912 |
+
local_grid = groups_grids[obj]
|
| 913 |
+
for i in range(local_grid.height):
|
| 914 |
+
for j in range(local_grid.width):
|
| 915 |
+
grid[real_row + i,
|
| 916 |
+
real_column + j] = local_grid[i, j]
|
| 917 |
+
else:
|
| 918 |
+
# This is an object. Just put it there.
|
| 919 |
+
grid[real_row, real_column] = obj
|
| 920 |
+
|
| 921 |
+
real_column += column_widths[logical_column]
|
| 922 |
+
real_column = 0
|
| 923 |
+
real_row += row_heights[logical_row]
|
| 924 |
+
|
| 925 |
+
return grid
|
| 926 |
+
|
| 927 |
+
@staticmethod
|
| 928 |
+
def _generic_layout(diagram, merged_morphisms):
|
| 929 |
+
"""
|
| 930 |
+
Produces the generic layout for the supplied diagram.
|
| 931 |
+
"""
|
| 932 |
+
all_objects = set(diagram.objects)
|
| 933 |
+
if len(all_objects) == 1:
|
| 934 |
+
# There only one object in the diagram, just put in on 1x1
|
| 935 |
+
# grid.
|
| 936 |
+
grid = _GrowableGrid(1, 1)
|
| 937 |
+
grid[0, 0] = tuple(all_objects)[0]
|
| 938 |
+
return grid
|
| 939 |
+
|
| 940 |
+
skeleton = DiagramGrid._build_skeleton(merged_morphisms)
|
| 941 |
+
|
| 942 |
+
grid = _GrowableGrid(2, 1)
|
| 943 |
+
|
| 944 |
+
if len(skeleton) == 1:
|
| 945 |
+
# This diagram contains only one morphism. Draw it
|
| 946 |
+
# horizontally.
|
| 947 |
+
objects = sorted(all_objects, key=default_sort_key)
|
| 948 |
+
grid[0, 0] = objects[0]
|
| 949 |
+
grid[0, 1] = objects[1]
|
| 950 |
+
|
| 951 |
+
return grid
|
| 952 |
+
|
| 953 |
+
triangles = DiagramGrid._list_triangles(skeleton)
|
| 954 |
+
triangles = DiagramGrid._drop_redundant_triangles(triangles, skeleton)
|
| 955 |
+
triangle_sizes = DiagramGrid._compute_triangle_min_sizes(
|
| 956 |
+
triangles, skeleton)
|
| 957 |
+
|
| 958 |
+
triangles = sorted(triangles, key=lambda tri:
|
| 959 |
+
DiagramGrid._triangle_key(tri, triangle_sizes))
|
| 960 |
+
|
| 961 |
+
# Place the first edge on the grid.
|
| 962 |
+
root_edge = DiagramGrid._pick_root_edge(triangles[0], skeleton)
|
| 963 |
+
grid[0, 0], grid[0, 1] = root_edge
|
| 964 |
+
fringe = [((0, 0), (0, 1))]
|
| 965 |
+
|
| 966 |
+
# Record which objects we now have on the grid.
|
| 967 |
+
placed_objects = set(root_edge)
|
| 968 |
+
|
| 969 |
+
while placed_objects != all_objects:
|
| 970 |
+
welding = DiagramGrid._find_triangle_to_weld(
|
| 971 |
+
triangles, fringe, grid)
|
| 972 |
+
|
| 973 |
+
if welding:
|
| 974 |
+
(triangle, welding_edge) = welding
|
| 975 |
+
|
| 976 |
+
restart_required = DiagramGrid._weld_triangle(
|
| 977 |
+
triangle, welding_edge, fringe, grid, skeleton)
|
| 978 |
+
if restart_required:
|
| 979 |
+
continue
|
| 980 |
+
|
| 981 |
+
placed_objects.update(
|
| 982 |
+
DiagramGrid._triangle_objects(triangle))
|
| 983 |
+
else:
|
| 984 |
+
# No more weldings found. Try to attach triangles by
|
| 985 |
+
# vertices.
|
| 986 |
+
new_obj = DiagramGrid._grow_pseudopod(
|
| 987 |
+
triangles, fringe, grid, skeleton, placed_objects)
|
| 988 |
+
|
| 989 |
+
if not new_obj:
|
| 990 |
+
# No more triangles can be attached, not even by
|
| 991 |
+
# the edge. We will set up a new diagram out of
|
| 992 |
+
# what has been left, laid it out independently,
|
| 993 |
+
# and then attach it to this one.
|
| 994 |
+
|
| 995 |
+
remaining_objects = all_objects - placed_objects
|
| 996 |
+
|
| 997 |
+
remaining_diagram = diagram.subdiagram_from_objects(
|
| 998 |
+
FiniteSet(*remaining_objects))
|
| 999 |
+
remaining_grid = DiagramGrid(remaining_diagram)
|
| 1000 |
+
|
| 1001 |
+
# Now, let's glue ``remaining_grid`` to ``grid``.
|
| 1002 |
+
final_width = grid.width + remaining_grid.width
|
| 1003 |
+
final_height = max(grid.height, remaining_grid.height)
|
| 1004 |
+
final_grid = _GrowableGrid(final_width, final_height)
|
| 1005 |
+
|
| 1006 |
+
for i in range(grid.width):
|
| 1007 |
+
for j in range(grid.height):
|
| 1008 |
+
final_grid[i, j] = grid[i, j]
|
| 1009 |
+
|
| 1010 |
+
start_j = grid.width
|
| 1011 |
+
for i in range(remaining_grid.height):
|
| 1012 |
+
for j in range(remaining_grid.width):
|
| 1013 |
+
final_grid[i, start_j + j] = remaining_grid[i, j]
|
| 1014 |
+
|
| 1015 |
+
return final_grid
|
| 1016 |
+
|
| 1017 |
+
placed_objects.add(new_obj)
|
| 1018 |
+
|
| 1019 |
+
triangles = DiagramGrid._drop_irrelevant_triangles(
|
| 1020 |
+
triangles, placed_objects)
|
| 1021 |
+
|
| 1022 |
+
return grid
|
| 1023 |
+
|
| 1024 |
+
@staticmethod
|
| 1025 |
+
def _get_undirected_graph(objects, merged_morphisms):
|
| 1026 |
+
"""
|
| 1027 |
+
Given the objects and the relevant morphisms of a diagram,
|
| 1028 |
+
returns the adjacency lists of the underlying undirected
|
| 1029 |
+
graph.
|
| 1030 |
+
"""
|
| 1031 |
+
adjlists = {}
|
| 1032 |
+
for obj in objects:
|
| 1033 |
+
adjlists[obj] = []
|
| 1034 |
+
|
| 1035 |
+
for morphism in merged_morphisms:
|
| 1036 |
+
adjlists[morphism.domain].append(morphism.codomain)
|
| 1037 |
+
adjlists[morphism.codomain].append(morphism.domain)
|
| 1038 |
+
|
| 1039 |
+
# Assure that the objects in the adjacency list are always in
|
| 1040 |
+
# the same order.
|
| 1041 |
+
for obj in adjlists.keys():
|
| 1042 |
+
adjlists[obj].sort(key=default_sort_key)
|
| 1043 |
+
|
| 1044 |
+
return adjlists
|
| 1045 |
+
|
| 1046 |
+
@staticmethod
|
| 1047 |
+
def _sequential_layout(diagram, merged_morphisms):
|
| 1048 |
+
r"""
|
| 1049 |
+
Lays out the diagram in "sequential" layout. This method
|
| 1050 |
+
will attempt to produce a result as close to a line as
|
| 1051 |
+
possible. For linear diagrams, the result will actually be a
|
| 1052 |
+
line.
|
| 1053 |
+
"""
|
| 1054 |
+
objects = diagram.objects
|
| 1055 |
+
sorted_objects = sorted(objects, key=default_sort_key)
|
| 1056 |
+
|
| 1057 |
+
# Set up the adjacency lists of the underlying undirected
|
| 1058 |
+
# graph of ``merged_morphisms``.
|
| 1059 |
+
adjlists = DiagramGrid._get_undirected_graph(objects, merged_morphisms)
|
| 1060 |
+
|
| 1061 |
+
root = min(sorted_objects, key=lambda x: len(adjlists[x]))
|
| 1062 |
+
grid = _GrowableGrid(1, 1)
|
| 1063 |
+
grid[0, 0] = root
|
| 1064 |
+
|
| 1065 |
+
placed_objects = {root}
|
| 1066 |
+
|
| 1067 |
+
def place_objects(pt, placed_objects):
|
| 1068 |
+
"""
|
| 1069 |
+
Does depth-first search in the underlying graph of the
|
| 1070 |
+
diagram and places the objects en route.
|
| 1071 |
+
"""
|
| 1072 |
+
# We will start placing new objects from here.
|
| 1073 |
+
new_pt = (pt[0], pt[1] + 1)
|
| 1074 |
+
|
| 1075 |
+
for adjacent_obj in adjlists[grid[pt]]:
|
| 1076 |
+
if adjacent_obj in placed_objects:
|
| 1077 |
+
# This object has already been placed.
|
| 1078 |
+
continue
|
| 1079 |
+
|
| 1080 |
+
DiagramGrid._put_object(new_pt, adjacent_obj, grid, [])
|
| 1081 |
+
placed_objects.add(adjacent_obj)
|
| 1082 |
+
placed_objects.update(place_objects(new_pt, placed_objects))
|
| 1083 |
+
|
| 1084 |
+
new_pt = (new_pt[0] + 1, new_pt[1])
|
| 1085 |
+
|
| 1086 |
+
return placed_objects
|
| 1087 |
+
|
| 1088 |
+
place_objects((0, 0), placed_objects)
|
| 1089 |
+
|
| 1090 |
+
return grid
|
| 1091 |
+
|
| 1092 |
+
@staticmethod
|
| 1093 |
+
def _drop_inessential_morphisms(merged_morphisms):
|
| 1094 |
+
r"""
|
| 1095 |
+
Removes those morphisms which should appear in the diagram,
|
| 1096 |
+
but which have no relevance to object layout.
|
| 1097 |
+
|
| 1098 |
+
Currently this removes "loop" morphisms: the non-identity
|
| 1099 |
+
morphisms with the same domains and codomains.
|
| 1100 |
+
"""
|
| 1101 |
+
morphisms = [m for m in merged_morphisms if m.domain != m.codomain]
|
| 1102 |
+
return morphisms
|
| 1103 |
+
|
| 1104 |
+
@staticmethod
|
| 1105 |
+
def _get_connected_components(objects, merged_morphisms):
|
| 1106 |
+
"""
|
| 1107 |
+
Given a container of morphisms, returns a list of connected
|
| 1108 |
+
components formed by these morphisms. A connected component
|
| 1109 |
+
is represented by a diagram consisting of the corresponding
|
| 1110 |
+
morphisms.
|
| 1111 |
+
"""
|
| 1112 |
+
component_index = {}
|
| 1113 |
+
for o in objects:
|
| 1114 |
+
component_index[o] = None
|
| 1115 |
+
|
| 1116 |
+
# Get the underlying undirected graph of the diagram.
|
| 1117 |
+
adjlist = DiagramGrid._get_undirected_graph(objects, merged_morphisms)
|
| 1118 |
+
|
| 1119 |
+
def traverse_component(object, current_index):
|
| 1120 |
+
"""
|
| 1121 |
+
Does a depth-first search traversal of the component
|
| 1122 |
+
containing ``object``.
|
| 1123 |
+
"""
|
| 1124 |
+
component_index[object] = current_index
|
| 1125 |
+
for o in adjlist[object]:
|
| 1126 |
+
if component_index[o] is None:
|
| 1127 |
+
traverse_component(o, current_index)
|
| 1128 |
+
|
| 1129 |
+
# Traverse all components.
|
| 1130 |
+
current_index = 0
|
| 1131 |
+
for o in adjlist:
|
| 1132 |
+
if component_index[o] is None:
|
| 1133 |
+
traverse_component(o, current_index)
|
| 1134 |
+
current_index += 1
|
| 1135 |
+
|
| 1136 |
+
# List the objects of the components.
|
| 1137 |
+
component_objects = [[] for i in range(current_index)]
|
| 1138 |
+
for o, idx in component_index.items():
|
| 1139 |
+
component_objects[idx].append(o)
|
| 1140 |
+
|
| 1141 |
+
# Finally, list the morphisms belonging to each component.
|
| 1142 |
+
#
|
| 1143 |
+
# Note: If some objects are isolated, they will not get any
|
| 1144 |
+
# morphisms at this stage, and since the layout algorithm
|
| 1145 |
+
# relies, we are essentially going to lose this object.
|
| 1146 |
+
# Therefore, check if there are isolated objects and, for each
|
| 1147 |
+
# of them, provide the trivial identity morphism. It will get
|
| 1148 |
+
# discarded later, but the object will be there.
|
| 1149 |
+
|
| 1150 |
+
component_morphisms = []
|
| 1151 |
+
for component in component_objects:
|
| 1152 |
+
current_morphisms = {}
|
| 1153 |
+
for m in merged_morphisms:
|
| 1154 |
+
if (m.domain in component) and (m.codomain in component):
|
| 1155 |
+
current_morphisms[m] = merged_morphisms[m]
|
| 1156 |
+
|
| 1157 |
+
if len(component) == 1:
|
| 1158 |
+
# Let's add an identity morphism, for the sake of
|
| 1159 |
+
# surely having morphisms in this component.
|
| 1160 |
+
current_morphisms[IdentityMorphism(component[0])] = FiniteSet()
|
| 1161 |
+
|
| 1162 |
+
component_morphisms.append(Diagram(current_morphisms))
|
| 1163 |
+
|
| 1164 |
+
return component_morphisms
|
| 1165 |
+
|
| 1166 |
+
def __init__(self, diagram, groups=None, **hints):
|
| 1167 |
+
premises = DiagramGrid._simplify_morphisms(diagram.premises)
|
| 1168 |
+
conclusions = DiagramGrid._simplify_morphisms(diagram.conclusions)
|
| 1169 |
+
all_merged_morphisms = DiagramGrid._merge_premises_conclusions(
|
| 1170 |
+
premises, conclusions)
|
| 1171 |
+
merged_morphisms = DiagramGrid._drop_inessential_morphisms(
|
| 1172 |
+
all_merged_morphisms)
|
| 1173 |
+
|
| 1174 |
+
# Store the merged morphisms for later use.
|
| 1175 |
+
self._morphisms = all_merged_morphisms
|
| 1176 |
+
|
| 1177 |
+
components = DiagramGrid._get_connected_components(
|
| 1178 |
+
diagram.objects, all_merged_morphisms)
|
| 1179 |
+
|
| 1180 |
+
if groups and (groups != diagram.objects):
|
| 1181 |
+
# Lay out the diagram according to the groups.
|
| 1182 |
+
self._grid = DiagramGrid._handle_groups(
|
| 1183 |
+
diagram, groups, merged_morphisms, hints)
|
| 1184 |
+
elif len(components) > 1:
|
| 1185 |
+
# Note that we check for connectedness _before_ checking
|
| 1186 |
+
# the layout hints because the layout strategies don't
|
| 1187 |
+
# know how to deal with disconnected diagrams.
|
| 1188 |
+
|
| 1189 |
+
# The diagram is disconnected. Lay out the components
|
| 1190 |
+
# independently.
|
| 1191 |
+
grids = []
|
| 1192 |
+
|
| 1193 |
+
# Sort the components to eventually get the grids arranged
|
| 1194 |
+
# in a fixed, hash-independent order.
|
| 1195 |
+
components = sorted(components, key=default_sort_key)
|
| 1196 |
+
|
| 1197 |
+
for component in components:
|
| 1198 |
+
grid = DiagramGrid(component, **hints)
|
| 1199 |
+
grids.append(grid)
|
| 1200 |
+
|
| 1201 |
+
# Throw the grids together, in a line.
|
| 1202 |
+
total_width = sum(g.width for g in grids)
|
| 1203 |
+
total_height = max(g.height for g in grids)
|
| 1204 |
+
|
| 1205 |
+
grid = _GrowableGrid(total_width, total_height)
|
| 1206 |
+
start_j = 0
|
| 1207 |
+
for g in grids:
|
| 1208 |
+
for i in range(g.height):
|
| 1209 |
+
for j in range(g.width):
|
| 1210 |
+
grid[i, start_j + j] = g[i, j]
|
| 1211 |
+
|
| 1212 |
+
start_j += g.width
|
| 1213 |
+
|
| 1214 |
+
self._grid = grid
|
| 1215 |
+
elif "layout" in hints:
|
| 1216 |
+
if hints["layout"] == "sequential":
|
| 1217 |
+
self._grid = DiagramGrid._sequential_layout(
|
| 1218 |
+
diagram, merged_morphisms)
|
| 1219 |
+
else:
|
| 1220 |
+
self._grid = DiagramGrid._generic_layout(diagram, merged_morphisms)
|
| 1221 |
+
|
| 1222 |
+
if hints.get("transpose"):
|
| 1223 |
+
# Transpose the resulting grid.
|
| 1224 |
+
grid = _GrowableGrid(self._grid.height, self._grid.width)
|
| 1225 |
+
for i in range(self._grid.height):
|
| 1226 |
+
for j in range(self._grid.width):
|
| 1227 |
+
grid[j, i] = self._grid[i, j]
|
| 1228 |
+
self._grid = grid
|
| 1229 |
+
|
| 1230 |
+
@property
|
| 1231 |
+
def width(self):
|
| 1232 |
+
"""
|
| 1233 |
+
Returns the number of columns in this diagram layout.
|
| 1234 |
+
|
| 1235 |
+
Examples
|
| 1236 |
+
========
|
| 1237 |
+
|
| 1238 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 1239 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 1240 |
+
>>> A = Object("A")
|
| 1241 |
+
>>> B = Object("B")
|
| 1242 |
+
>>> C = Object("C")
|
| 1243 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1244 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1245 |
+
>>> diagram = Diagram([f, g])
|
| 1246 |
+
>>> grid = DiagramGrid(diagram)
|
| 1247 |
+
>>> grid.width
|
| 1248 |
+
2
|
| 1249 |
+
|
| 1250 |
+
"""
|
| 1251 |
+
return self._grid.width
|
| 1252 |
+
|
| 1253 |
+
@property
|
| 1254 |
+
def height(self):
|
| 1255 |
+
"""
|
| 1256 |
+
Returns the number of rows in this diagram layout.
|
| 1257 |
+
|
| 1258 |
+
Examples
|
| 1259 |
+
========
|
| 1260 |
+
|
| 1261 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 1262 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 1263 |
+
>>> A = Object("A")
|
| 1264 |
+
>>> B = Object("B")
|
| 1265 |
+
>>> C = Object("C")
|
| 1266 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1267 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1268 |
+
>>> diagram = Diagram([f, g])
|
| 1269 |
+
>>> grid = DiagramGrid(diagram)
|
| 1270 |
+
>>> grid.height
|
| 1271 |
+
2
|
| 1272 |
+
|
| 1273 |
+
"""
|
| 1274 |
+
return self._grid.height
|
| 1275 |
+
|
| 1276 |
+
def __getitem__(self, i_j):
|
| 1277 |
+
"""
|
| 1278 |
+
Returns the object placed in the row ``i`` and column ``j``.
|
| 1279 |
+
The indices are 0-based.
|
| 1280 |
+
|
| 1281 |
+
Examples
|
| 1282 |
+
========
|
| 1283 |
+
|
| 1284 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 1285 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 1286 |
+
>>> A = Object("A")
|
| 1287 |
+
>>> B = Object("B")
|
| 1288 |
+
>>> C = Object("C")
|
| 1289 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1290 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1291 |
+
>>> diagram = Diagram([f, g])
|
| 1292 |
+
>>> grid = DiagramGrid(diagram)
|
| 1293 |
+
>>> (grid[0, 0], grid[0, 1])
|
| 1294 |
+
(Object("A"), Object("B"))
|
| 1295 |
+
>>> (grid[1, 0], grid[1, 1])
|
| 1296 |
+
(None, Object("C"))
|
| 1297 |
+
|
| 1298 |
+
"""
|
| 1299 |
+
i, j = i_j
|
| 1300 |
+
return self._grid[i, j]
|
| 1301 |
+
|
| 1302 |
+
@property
|
| 1303 |
+
def morphisms(self):
|
| 1304 |
+
"""
|
| 1305 |
+
Returns those morphisms (and their properties) which are
|
| 1306 |
+
sufficiently meaningful to be drawn.
|
| 1307 |
+
|
| 1308 |
+
Examples
|
| 1309 |
+
========
|
| 1310 |
+
|
| 1311 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 1312 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 1313 |
+
>>> A = Object("A")
|
| 1314 |
+
>>> B = Object("B")
|
| 1315 |
+
>>> C = Object("C")
|
| 1316 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1317 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1318 |
+
>>> diagram = Diagram([f, g])
|
| 1319 |
+
>>> grid = DiagramGrid(diagram)
|
| 1320 |
+
>>> grid.morphisms
|
| 1321 |
+
{NamedMorphism(Object("A"), Object("B"), "f"): EmptySet,
|
| 1322 |
+
NamedMorphism(Object("B"), Object("C"), "g"): EmptySet}
|
| 1323 |
+
|
| 1324 |
+
"""
|
| 1325 |
+
return self._morphisms
|
| 1326 |
+
|
| 1327 |
+
def __str__(self):
|
| 1328 |
+
"""
|
| 1329 |
+
Produces a string representation of this class.
|
| 1330 |
+
|
| 1331 |
+
This method returns a string representation of the underlying
|
| 1332 |
+
list of lists of objects.
|
| 1333 |
+
|
| 1334 |
+
Examples
|
| 1335 |
+
========
|
| 1336 |
+
|
| 1337 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 1338 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 1339 |
+
>>> A = Object("A")
|
| 1340 |
+
>>> B = Object("B")
|
| 1341 |
+
>>> C = Object("C")
|
| 1342 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1343 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1344 |
+
>>> diagram = Diagram([f, g])
|
| 1345 |
+
>>> grid = DiagramGrid(diagram)
|
| 1346 |
+
>>> print(grid)
|
| 1347 |
+
[[Object("A"), Object("B")],
|
| 1348 |
+
[None, Object("C")]]
|
| 1349 |
+
|
| 1350 |
+
"""
|
| 1351 |
+
return repr(self._grid._array)
|
| 1352 |
+
|
| 1353 |
+
|
| 1354 |
+
class ArrowStringDescription:
|
| 1355 |
+
r"""
|
| 1356 |
+
Stores the information necessary for producing an Xy-pic
|
| 1357 |
+
description of an arrow.
|
| 1358 |
+
|
| 1359 |
+
The principal goal of this class is to abstract away the string
|
| 1360 |
+
representation of an arrow and to also provide the functionality
|
| 1361 |
+
to produce the actual Xy-pic string.
|
| 1362 |
+
|
| 1363 |
+
``unit`` sets the unit which will be used to specify the amount of
|
| 1364 |
+
curving and other distances. ``horizontal_direction`` should be a
|
| 1365 |
+
string of ``"r"`` or ``"l"`` specifying the horizontal offset of the
|
| 1366 |
+
target cell of the arrow relatively to the current one.
|
| 1367 |
+
``vertical_direction`` should specify the vertical offset using a
|
| 1368 |
+
series of either ``"d"`` or ``"u"``. ``label_position`` should be
|
| 1369 |
+
either ``"^"``, ``"_"``, or ``"|"`` to specify that the label should
|
| 1370 |
+
be positioned above the arrow, below the arrow or just over the arrow,
|
| 1371 |
+
in a break. Note that the notions "above" and "below" are relative
|
| 1372 |
+
to arrow direction. ``label`` stores the morphism label.
|
| 1373 |
+
|
| 1374 |
+
This works as follows (disregard the yet unexplained arguments):
|
| 1375 |
+
|
| 1376 |
+
>>> from sympy.categories.diagram_drawing import ArrowStringDescription
|
| 1377 |
+
>>> astr = ArrowStringDescription(
|
| 1378 |
+
... unit="mm", curving=None, curving_amount=None,
|
| 1379 |
+
... looping_start=None, looping_end=None, horizontal_direction="d",
|
| 1380 |
+
... vertical_direction="r", label_position="_", label="f")
|
| 1381 |
+
>>> print(str(astr))
|
| 1382 |
+
\ar[dr]_{f}
|
| 1383 |
+
|
| 1384 |
+
``curving`` should be one of ``"^"``, ``"_"`` to specify in which
|
| 1385 |
+
direction the arrow is going to curve. ``curving_amount`` is a number
|
| 1386 |
+
describing how many ``unit``'s the morphism is going to curve:
|
| 1387 |
+
|
| 1388 |
+
>>> astr = ArrowStringDescription(
|
| 1389 |
+
... unit="mm", curving="^", curving_amount=12,
|
| 1390 |
+
... looping_start=None, looping_end=None, horizontal_direction="d",
|
| 1391 |
+
... vertical_direction="r", label_position="_", label="f")
|
| 1392 |
+
>>> print(str(astr))
|
| 1393 |
+
\ar@/^12mm/[dr]_{f}
|
| 1394 |
+
|
| 1395 |
+
``looping_start`` and ``looping_end`` are currently only used for
|
| 1396 |
+
loop morphisms, those which have the same domain and codomain.
|
| 1397 |
+
These two attributes should store a valid Xy-pic direction and
|
| 1398 |
+
specify, correspondingly, the direction the arrow gets out into
|
| 1399 |
+
and the direction the arrow gets back from:
|
| 1400 |
+
|
| 1401 |
+
>>> astr = ArrowStringDescription(
|
| 1402 |
+
... unit="mm", curving=None, curving_amount=None,
|
| 1403 |
+
... looping_start="u", looping_end="l", horizontal_direction="",
|
| 1404 |
+
... vertical_direction="", label_position="_", label="f")
|
| 1405 |
+
>>> print(str(astr))
|
| 1406 |
+
\ar@(u,l)[]_{f}
|
| 1407 |
+
|
| 1408 |
+
``label_displacement`` controls how far the arrow label is from
|
| 1409 |
+
the ends of the arrow. For example, to position the arrow label
|
| 1410 |
+
near the arrow head, use ">":
|
| 1411 |
+
|
| 1412 |
+
>>> astr = ArrowStringDescription(
|
| 1413 |
+
... unit="mm", curving="^", curving_amount=12,
|
| 1414 |
+
... looping_start=None, looping_end=None, horizontal_direction="d",
|
| 1415 |
+
... vertical_direction="r", label_position="_", label="f")
|
| 1416 |
+
>>> astr.label_displacement = ">"
|
| 1417 |
+
>>> print(str(astr))
|
| 1418 |
+
\ar@/^12mm/[dr]_>{f}
|
| 1419 |
+
|
| 1420 |
+
Finally, ``arrow_style`` is used to specify the arrow style. To
|
| 1421 |
+
get a dashed arrow, for example, use "{-->}" as arrow style:
|
| 1422 |
+
|
| 1423 |
+
>>> astr = ArrowStringDescription(
|
| 1424 |
+
... unit="mm", curving="^", curving_amount=12,
|
| 1425 |
+
... looping_start=None, looping_end=None, horizontal_direction="d",
|
| 1426 |
+
... vertical_direction="r", label_position="_", label="f")
|
| 1427 |
+
>>> astr.arrow_style = "{-->}"
|
| 1428 |
+
>>> print(str(astr))
|
| 1429 |
+
\ar@/^12mm/@{-->}[dr]_{f}
|
| 1430 |
+
|
| 1431 |
+
Notes
|
| 1432 |
+
=====
|
| 1433 |
+
|
| 1434 |
+
Instances of :class:`ArrowStringDescription` will be constructed
|
| 1435 |
+
by :class:`XypicDiagramDrawer` and provided for further use in
|
| 1436 |
+
formatters. The user is not expected to construct instances of
|
| 1437 |
+
:class:`ArrowStringDescription` themselves.
|
| 1438 |
+
|
| 1439 |
+
To be able to properly utilise this class, the reader is encouraged
|
| 1440 |
+
to checkout the Xy-pic user guide, available at [Xypic].
|
| 1441 |
+
|
| 1442 |
+
See Also
|
| 1443 |
+
========
|
| 1444 |
+
|
| 1445 |
+
XypicDiagramDrawer
|
| 1446 |
+
|
| 1447 |
+
References
|
| 1448 |
+
==========
|
| 1449 |
+
|
| 1450 |
+
.. [Xypic] https://xy-pic.sourceforge.net/
|
| 1451 |
+
"""
|
| 1452 |
+
def __init__(self, unit, curving, curving_amount, looping_start,
|
| 1453 |
+
looping_end, horizontal_direction, vertical_direction,
|
| 1454 |
+
label_position, label):
|
| 1455 |
+
self.unit = unit
|
| 1456 |
+
self.curving = curving
|
| 1457 |
+
self.curving_amount = curving_amount
|
| 1458 |
+
self.looping_start = looping_start
|
| 1459 |
+
self.looping_end = looping_end
|
| 1460 |
+
self.horizontal_direction = horizontal_direction
|
| 1461 |
+
self.vertical_direction = vertical_direction
|
| 1462 |
+
self.label_position = label_position
|
| 1463 |
+
self.label = label
|
| 1464 |
+
|
| 1465 |
+
self.label_displacement = ""
|
| 1466 |
+
self.arrow_style = ""
|
| 1467 |
+
|
| 1468 |
+
# This flag shows that the position of the label of this
|
| 1469 |
+
# morphism was set while typesetting a curved morphism and
|
| 1470 |
+
# should not be modified later.
|
| 1471 |
+
self.forced_label_position = False
|
| 1472 |
+
|
| 1473 |
+
def __str__(self):
|
| 1474 |
+
if self.curving:
|
| 1475 |
+
curving_str = "@/%s%d%s/" % (self.curving, self.curving_amount,
|
| 1476 |
+
self.unit)
|
| 1477 |
+
else:
|
| 1478 |
+
curving_str = ""
|
| 1479 |
+
|
| 1480 |
+
if self.looping_start and self.looping_end:
|
| 1481 |
+
looping_str = "@(%s,%s)" % (self.looping_start, self.looping_end)
|
| 1482 |
+
else:
|
| 1483 |
+
looping_str = ""
|
| 1484 |
+
|
| 1485 |
+
if self.arrow_style:
|
| 1486 |
+
|
| 1487 |
+
style_str = "@" + self.arrow_style
|
| 1488 |
+
else:
|
| 1489 |
+
style_str = ""
|
| 1490 |
+
|
| 1491 |
+
return "\\ar%s%s%s[%s%s]%s%s{%s}" % \
|
| 1492 |
+
(curving_str, looping_str, style_str, self.horizontal_direction,
|
| 1493 |
+
self.vertical_direction, self.label_position,
|
| 1494 |
+
self.label_displacement, self.label)
|
| 1495 |
+
|
| 1496 |
+
|
| 1497 |
+
class XypicDiagramDrawer:
|
| 1498 |
+
r"""
|
| 1499 |
+
Given a :class:`~.Diagram` and the corresponding
|
| 1500 |
+
:class:`DiagramGrid`, produces the Xy-pic representation of the
|
| 1501 |
+
diagram.
|
| 1502 |
+
|
| 1503 |
+
The most important method in this class is ``draw``. Consider the
|
| 1504 |
+
following triangle diagram:
|
| 1505 |
+
|
| 1506 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 1507 |
+
>>> from sympy.categories import DiagramGrid, XypicDiagramDrawer
|
| 1508 |
+
>>> A = Object("A")
|
| 1509 |
+
>>> B = Object("B")
|
| 1510 |
+
>>> C = Object("C")
|
| 1511 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1512 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1513 |
+
>>> diagram = Diagram([f, g], {g * f: "unique"})
|
| 1514 |
+
|
| 1515 |
+
To draw this diagram, its objects need to be laid out with a
|
| 1516 |
+
:class:`DiagramGrid`::
|
| 1517 |
+
|
| 1518 |
+
>>> grid = DiagramGrid(diagram)
|
| 1519 |
+
|
| 1520 |
+
Finally, the drawing:
|
| 1521 |
+
|
| 1522 |
+
>>> drawer = XypicDiagramDrawer()
|
| 1523 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1524 |
+
\xymatrix{
|
| 1525 |
+
A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 1526 |
+
C &
|
| 1527 |
+
}
|
| 1528 |
+
|
| 1529 |
+
For further details see the docstring of this method.
|
| 1530 |
+
|
| 1531 |
+
To control the appearance of the arrows, formatters are used. The
|
| 1532 |
+
dictionary ``arrow_formatters`` maps morphisms to formatter
|
| 1533 |
+
functions. A formatter is accepts an
|
| 1534 |
+
:class:`ArrowStringDescription` and is allowed to modify any of
|
| 1535 |
+
the arrow properties exposed thereby. For example, to have all
|
| 1536 |
+
morphisms with the property ``unique`` appear as dashed arrows,
|
| 1537 |
+
and to have their names prepended with `\exists !`, the following
|
| 1538 |
+
should be done:
|
| 1539 |
+
|
| 1540 |
+
>>> def formatter(astr):
|
| 1541 |
+
... astr.label = r"\exists !" + astr.label
|
| 1542 |
+
... astr.arrow_style = "{-->}"
|
| 1543 |
+
>>> drawer.arrow_formatters["unique"] = formatter
|
| 1544 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1545 |
+
\xymatrix{
|
| 1546 |
+
A \ar@{-->}[d]_{\exists !g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 1547 |
+
C &
|
| 1548 |
+
}
|
| 1549 |
+
|
| 1550 |
+
To modify the appearance of all arrows in the diagram, set
|
| 1551 |
+
``default_arrow_formatter``. For example, to place all morphism
|
| 1552 |
+
labels a little bit farther from the arrow head so that they look
|
| 1553 |
+
more centred, do as follows:
|
| 1554 |
+
|
| 1555 |
+
>>> def default_formatter(astr):
|
| 1556 |
+
... astr.label_displacement = "(0.45)"
|
| 1557 |
+
>>> drawer.default_arrow_formatter = default_formatter
|
| 1558 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1559 |
+
\xymatrix{
|
| 1560 |
+
A \ar@{-->}[d]_(0.45){\exists !g\circ f} \ar[r]^(0.45){f} & B \ar[ld]^(0.45){g} \\
|
| 1561 |
+
C &
|
| 1562 |
+
}
|
| 1563 |
+
|
| 1564 |
+
In some diagrams some morphisms are drawn as curved arrows.
|
| 1565 |
+
Consider the following diagram:
|
| 1566 |
+
|
| 1567 |
+
>>> D = Object("D")
|
| 1568 |
+
>>> E = Object("E")
|
| 1569 |
+
>>> h = NamedMorphism(D, A, "h")
|
| 1570 |
+
>>> k = NamedMorphism(D, B, "k")
|
| 1571 |
+
>>> diagram = Diagram([f, g, h, k])
|
| 1572 |
+
>>> grid = DiagramGrid(diagram)
|
| 1573 |
+
>>> drawer = XypicDiagramDrawer()
|
| 1574 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1575 |
+
\xymatrix{
|
| 1576 |
+
A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_3mm/[ll]_{h} \\
|
| 1577 |
+
& C &
|
| 1578 |
+
}
|
| 1579 |
+
|
| 1580 |
+
To control how far the morphisms are curved by default, one can
|
| 1581 |
+
use the ``unit`` and ``default_curving_amount`` attributes:
|
| 1582 |
+
|
| 1583 |
+
>>> drawer.unit = "cm"
|
| 1584 |
+
>>> drawer.default_curving_amount = 1
|
| 1585 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1586 |
+
\xymatrix{
|
| 1587 |
+
A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_1cm/[ll]_{h} \\
|
| 1588 |
+
& C &
|
| 1589 |
+
}
|
| 1590 |
+
|
| 1591 |
+
In some diagrams, there are multiple curved morphisms between the
|
| 1592 |
+
same two objects. To control by how much the curving changes
|
| 1593 |
+
between two such successive morphisms, use
|
| 1594 |
+
``default_curving_step``:
|
| 1595 |
+
|
| 1596 |
+
>>> drawer.default_curving_step = 1
|
| 1597 |
+
>>> h1 = NamedMorphism(A, D, "h1")
|
| 1598 |
+
>>> diagram = Diagram([f, g, h, k, h1])
|
| 1599 |
+
>>> grid = DiagramGrid(diagram)
|
| 1600 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1601 |
+
\xymatrix{
|
| 1602 |
+
A \ar[r]_{f} \ar@/^1cm/[rr]^{h_{1}} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_2cm/[ll]_{h} \\
|
| 1603 |
+
& C &
|
| 1604 |
+
}
|
| 1605 |
+
|
| 1606 |
+
The default value of ``default_curving_step`` is 4 units.
|
| 1607 |
+
|
| 1608 |
+
See Also
|
| 1609 |
+
========
|
| 1610 |
+
|
| 1611 |
+
draw, ArrowStringDescription
|
| 1612 |
+
"""
|
| 1613 |
+
def __init__(self):
|
| 1614 |
+
self.unit = "mm"
|
| 1615 |
+
self.default_curving_amount = 3
|
| 1616 |
+
self.default_curving_step = 4
|
| 1617 |
+
|
| 1618 |
+
# This dictionary maps properties to the corresponding arrow
|
| 1619 |
+
# formatters.
|
| 1620 |
+
self.arrow_formatters = {}
|
| 1621 |
+
|
| 1622 |
+
# This is the default arrow formatter which will be applied to
|
| 1623 |
+
# each arrow independently of its properties.
|
| 1624 |
+
self.default_arrow_formatter = None
|
| 1625 |
+
|
| 1626 |
+
@staticmethod
|
| 1627 |
+
def _process_loop_morphism(i, j, grid, morphisms_str_info, object_coords):
|
| 1628 |
+
"""
|
| 1629 |
+
Produces the information required for constructing the string
|
| 1630 |
+
representation of a loop morphism. This function is invoked
|
| 1631 |
+
from ``_process_morphism``.
|
| 1632 |
+
|
| 1633 |
+
See Also
|
| 1634 |
+
========
|
| 1635 |
+
|
| 1636 |
+
_process_morphism
|
| 1637 |
+
"""
|
| 1638 |
+
curving = ""
|
| 1639 |
+
label_pos = "^"
|
| 1640 |
+
looping_start = ""
|
| 1641 |
+
looping_end = ""
|
| 1642 |
+
|
| 1643 |
+
# This is a loop morphism. Count how many morphisms stick
|
| 1644 |
+
# in each of the four quadrants. Note that straight
|
| 1645 |
+
# vertical and horizontal morphisms count in two quadrants
|
| 1646 |
+
# at the same time (i.e., a morphism going up counts both
|
| 1647 |
+
# in the first and the second quadrants).
|
| 1648 |
+
|
| 1649 |
+
# The usual numbering (counterclockwise) of quadrants
|
| 1650 |
+
# applies.
|
| 1651 |
+
quadrant = [0, 0, 0, 0]
|
| 1652 |
+
|
| 1653 |
+
obj = grid[i, j]
|
| 1654 |
+
|
| 1655 |
+
for m, m_str_info in morphisms_str_info.items():
|
| 1656 |
+
if (m.domain == obj) and (m.codomain == obj):
|
| 1657 |
+
# That's another loop morphism. Check how it
|
| 1658 |
+
# loops and mark the corresponding quadrants as
|
| 1659 |
+
# busy.
|
| 1660 |
+
(l_s, l_e) = (m_str_info.looping_start, m_str_info.looping_end)
|
| 1661 |
+
|
| 1662 |
+
if (l_s, l_e) == ("r", "u"):
|
| 1663 |
+
quadrant[0] += 1
|
| 1664 |
+
elif (l_s, l_e) == ("u", "l"):
|
| 1665 |
+
quadrant[1] += 1
|
| 1666 |
+
elif (l_s, l_e) == ("l", "d"):
|
| 1667 |
+
quadrant[2] += 1
|
| 1668 |
+
elif (l_s, l_e) == ("d", "r"):
|
| 1669 |
+
quadrant[3] += 1
|
| 1670 |
+
|
| 1671 |
+
continue
|
| 1672 |
+
if m.domain == obj:
|
| 1673 |
+
(end_i, end_j) = object_coords[m.codomain]
|
| 1674 |
+
goes_out = True
|
| 1675 |
+
elif m.codomain == obj:
|
| 1676 |
+
(end_i, end_j) = object_coords[m.domain]
|
| 1677 |
+
goes_out = False
|
| 1678 |
+
else:
|
| 1679 |
+
continue
|
| 1680 |
+
|
| 1681 |
+
d_i = end_i - i
|
| 1682 |
+
d_j = end_j - j
|
| 1683 |
+
m_curving = m_str_info.curving
|
| 1684 |
+
|
| 1685 |
+
if (d_i != 0) and (d_j != 0):
|
| 1686 |
+
# This is really a diagonal morphism. Detect the
|
| 1687 |
+
# quadrant.
|
| 1688 |
+
if (d_i > 0) and (d_j > 0):
|
| 1689 |
+
quadrant[0] += 1
|
| 1690 |
+
elif (d_i > 0) and (d_j < 0):
|
| 1691 |
+
quadrant[1] += 1
|
| 1692 |
+
elif (d_i < 0) and (d_j < 0):
|
| 1693 |
+
quadrant[2] += 1
|
| 1694 |
+
elif (d_i < 0) and (d_j > 0):
|
| 1695 |
+
quadrant[3] += 1
|
| 1696 |
+
elif d_i == 0:
|
| 1697 |
+
# Knowing where the other end of the morphism is
|
| 1698 |
+
# and which way it goes, we now have to decide
|
| 1699 |
+
# which quadrant is now the upper one and which is
|
| 1700 |
+
# the lower one.
|
| 1701 |
+
if d_j > 0:
|
| 1702 |
+
if goes_out:
|
| 1703 |
+
upper_quadrant = 0
|
| 1704 |
+
lower_quadrant = 3
|
| 1705 |
+
else:
|
| 1706 |
+
upper_quadrant = 3
|
| 1707 |
+
lower_quadrant = 0
|
| 1708 |
+
else:
|
| 1709 |
+
if goes_out:
|
| 1710 |
+
upper_quadrant = 2
|
| 1711 |
+
lower_quadrant = 1
|
| 1712 |
+
else:
|
| 1713 |
+
upper_quadrant = 1
|
| 1714 |
+
lower_quadrant = 2
|
| 1715 |
+
|
| 1716 |
+
if m_curving:
|
| 1717 |
+
if m_curving == "^":
|
| 1718 |
+
quadrant[upper_quadrant] += 1
|
| 1719 |
+
elif m_curving == "_":
|
| 1720 |
+
quadrant[lower_quadrant] += 1
|
| 1721 |
+
else:
|
| 1722 |
+
# This morphism counts in both upper and lower
|
| 1723 |
+
# quadrants.
|
| 1724 |
+
quadrant[upper_quadrant] += 1
|
| 1725 |
+
quadrant[lower_quadrant] += 1
|
| 1726 |
+
elif d_j == 0:
|
| 1727 |
+
# Knowing where the other end of the morphism is
|
| 1728 |
+
# and which way it goes, we now have to decide
|
| 1729 |
+
# which quadrant is now the left one and which is
|
| 1730 |
+
# the right one.
|
| 1731 |
+
if d_i < 0:
|
| 1732 |
+
if goes_out:
|
| 1733 |
+
left_quadrant = 1
|
| 1734 |
+
right_quadrant = 0
|
| 1735 |
+
else:
|
| 1736 |
+
left_quadrant = 0
|
| 1737 |
+
right_quadrant = 1
|
| 1738 |
+
else:
|
| 1739 |
+
if goes_out:
|
| 1740 |
+
left_quadrant = 3
|
| 1741 |
+
right_quadrant = 2
|
| 1742 |
+
else:
|
| 1743 |
+
left_quadrant = 2
|
| 1744 |
+
right_quadrant = 3
|
| 1745 |
+
|
| 1746 |
+
if m_curving:
|
| 1747 |
+
if m_curving == "^":
|
| 1748 |
+
quadrant[left_quadrant] += 1
|
| 1749 |
+
elif m_curving == "_":
|
| 1750 |
+
quadrant[right_quadrant] += 1
|
| 1751 |
+
else:
|
| 1752 |
+
# This morphism counts in both upper and lower
|
| 1753 |
+
# quadrants.
|
| 1754 |
+
quadrant[left_quadrant] += 1
|
| 1755 |
+
quadrant[right_quadrant] += 1
|
| 1756 |
+
|
| 1757 |
+
# Pick the freest quadrant to curve our morphism into.
|
| 1758 |
+
freest_quadrant = 0
|
| 1759 |
+
for i in range(4):
|
| 1760 |
+
if quadrant[i] < quadrant[freest_quadrant]:
|
| 1761 |
+
freest_quadrant = i
|
| 1762 |
+
|
| 1763 |
+
# Now set up proper looping.
|
| 1764 |
+
(looping_start, looping_end) = [("r", "u"), ("u", "l"), ("l", "d"),
|
| 1765 |
+
("d", "r")][freest_quadrant]
|
| 1766 |
+
|
| 1767 |
+
return (curving, label_pos, looping_start, looping_end)
|
| 1768 |
+
|
| 1769 |
+
@staticmethod
|
| 1770 |
+
def _process_horizontal_morphism(i, j, target_j, grid, morphisms_str_info,
|
| 1771 |
+
object_coords):
|
| 1772 |
+
"""
|
| 1773 |
+
Produces the information required for constructing the string
|
| 1774 |
+
representation of a horizontal morphism. This function is
|
| 1775 |
+
invoked from ``_process_morphism``.
|
| 1776 |
+
|
| 1777 |
+
See Also
|
| 1778 |
+
========
|
| 1779 |
+
|
| 1780 |
+
_process_morphism
|
| 1781 |
+
"""
|
| 1782 |
+
# The arrow is horizontal. Check if it goes from left to
|
| 1783 |
+
# right (``backwards == False``) or from right to left
|
| 1784 |
+
# (``backwards == True``).
|
| 1785 |
+
backwards = False
|
| 1786 |
+
start = j
|
| 1787 |
+
end = target_j
|
| 1788 |
+
if end < start:
|
| 1789 |
+
(start, end) = (end, start)
|
| 1790 |
+
backwards = True
|
| 1791 |
+
|
| 1792 |
+
# Let's see which objects are there between ``start`` and
|
| 1793 |
+
# ``end``, and then count how many morphisms stick out
|
| 1794 |
+
# upwards, and how many stick out downwards.
|
| 1795 |
+
#
|
| 1796 |
+
# For example, consider the situation:
|
| 1797 |
+
#
|
| 1798 |
+
# B1 C1
|
| 1799 |
+
# | |
|
| 1800 |
+
# A--B--C--D
|
| 1801 |
+
# |
|
| 1802 |
+
# B2
|
| 1803 |
+
#
|
| 1804 |
+
# Between the objects `A` and `D` there are two objects:
|
| 1805 |
+
# `B` and `C`. Further, there are two morphisms which
|
| 1806 |
+
# stick out upward (the ones between `B1` and `B` and
|
| 1807 |
+
# between `C` and `C1`) and one morphism which sticks out
|
| 1808 |
+
# downward (the one between `B and `B2`).
|
| 1809 |
+
#
|
| 1810 |
+
# We need this information to decide how to curve the
|
| 1811 |
+
# arrow between `A` and `D`. First of all, since there
|
| 1812 |
+
# are two objects between `A` and `D``, we must curve the
|
| 1813 |
+
# arrow. Then, we will have it curve downward, because
|
| 1814 |
+
# there is more space (less morphisms stick out downward
|
| 1815 |
+
# than upward).
|
| 1816 |
+
up = []
|
| 1817 |
+
down = []
|
| 1818 |
+
straight_horizontal = []
|
| 1819 |
+
for k in range(start + 1, end):
|
| 1820 |
+
obj = grid[i, k]
|
| 1821 |
+
if not obj:
|
| 1822 |
+
continue
|
| 1823 |
+
|
| 1824 |
+
for m in morphisms_str_info:
|
| 1825 |
+
if m.domain == obj:
|
| 1826 |
+
(end_i, end_j) = object_coords[m.codomain]
|
| 1827 |
+
elif m.codomain == obj:
|
| 1828 |
+
(end_i, end_j) = object_coords[m.domain]
|
| 1829 |
+
else:
|
| 1830 |
+
continue
|
| 1831 |
+
|
| 1832 |
+
if end_i > i:
|
| 1833 |
+
down.append(m)
|
| 1834 |
+
elif end_i < i:
|
| 1835 |
+
up.append(m)
|
| 1836 |
+
elif not morphisms_str_info[m].curving:
|
| 1837 |
+
# This is a straight horizontal morphism,
|
| 1838 |
+
# because it has no curving.
|
| 1839 |
+
straight_horizontal.append(m)
|
| 1840 |
+
|
| 1841 |
+
if len(up) < len(down):
|
| 1842 |
+
# More morphisms stick out downward than upward, let's
|
| 1843 |
+
# curve the morphism up.
|
| 1844 |
+
if backwards:
|
| 1845 |
+
curving = "_"
|
| 1846 |
+
label_pos = "_"
|
| 1847 |
+
else:
|
| 1848 |
+
curving = "^"
|
| 1849 |
+
label_pos = "^"
|
| 1850 |
+
|
| 1851 |
+
# Assure that the straight horizontal morphisms have
|
| 1852 |
+
# their labels on the lower side of the arrow.
|
| 1853 |
+
for m in straight_horizontal:
|
| 1854 |
+
(i1, j1) = object_coords[m.domain]
|
| 1855 |
+
(i2, j2) = object_coords[m.codomain]
|
| 1856 |
+
|
| 1857 |
+
m_str_info = morphisms_str_info[m]
|
| 1858 |
+
if j1 < j2:
|
| 1859 |
+
m_str_info.label_position = "_"
|
| 1860 |
+
else:
|
| 1861 |
+
m_str_info.label_position = "^"
|
| 1862 |
+
|
| 1863 |
+
# Don't allow any further modifications of the
|
| 1864 |
+
# position of this label.
|
| 1865 |
+
m_str_info.forced_label_position = True
|
| 1866 |
+
else:
|
| 1867 |
+
# More morphisms stick out downward than upward, let's
|
| 1868 |
+
# curve the morphism up.
|
| 1869 |
+
if backwards:
|
| 1870 |
+
curving = "^"
|
| 1871 |
+
label_pos = "^"
|
| 1872 |
+
else:
|
| 1873 |
+
curving = "_"
|
| 1874 |
+
label_pos = "_"
|
| 1875 |
+
|
| 1876 |
+
# Assure that the straight horizontal morphisms have
|
| 1877 |
+
# their labels on the upper side of the arrow.
|
| 1878 |
+
for m in straight_horizontal:
|
| 1879 |
+
(i1, j1) = object_coords[m.domain]
|
| 1880 |
+
(i2, j2) = object_coords[m.codomain]
|
| 1881 |
+
|
| 1882 |
+
m_str_info = morphisms_str_info[m]
|
| 1883 |
+
if j1 < j2:
|
| 1884 |
+
m_str_info.label_position = "^"
|
| 1885 |
+
else:
|
| 1886 |
+
m_str_info.label_position = "_"
|
| 1887 |
+
|
| 1888 |
+
# Don't allow any further modifications of the
|
| 1889 |
+
# position of this label.
|
| 1890 |
+
m_str_info.forced_label_position = True
|
| 1891 |
+
|
| 1892 |
+
return (curving, label_pos)
|
| 1893 |
+
|
| 1894 |
+
@staticmethod
|
| 1895 |
+
def _process_vertical_morphism(i, j, target_i, grid, morphisms_str_info,
|
| 1896 |
+
object_coords):
|
| 1897 |
+
"""
|
| 1898 |
+
Produces the information required for constructing the string
|
| 1899 |
+
representation of a vertical morphism. This function is
|
| 1900 |
+
invoked from ``_process_morphism``.
|
| 1901 |
+
|
| 1902 |
+
See Also
|
| 1903 |
+
========
|
| 1904 |
+
|
| 1905 |
+
_process_morphism
|
| 1906 |
+
"""
|
| 1907 |
+
# This arrow is vertical. Check if it goes from top to
|
| 1908 |
+
# bottom (``backwards == False``) or from bottom to top
|
| 1909 |
+
# (``backwards == True``).
|
| 1910 |
+
backwards = False
|
| 1911 |
+
start = i
|
| 1912 |
+
end = target_i
|
| 1913 |
+
if end < start:
|
| 1914 |
+
(start, end) = (end, start)
|
| 1915 |
+
backwards = True
|
| 1916 |
+
|
| 1917 |
+
# Let's see which objects are there between ``start`` and
|
| 1918 |
+
# ``end``, and then count how many morphisms stick out to
|
| 1919 |
+
# the left, and how many stick out to the right.
|
| 1920 |
+
#
|
| 1921 |
+
# See the corresponding comment in the previous branch of
|
| 1922 |
+
# this if-statement for more details.
|
| 1923 |
+
left = []
|
| 1924 |
+
right = []
|
| 1925 |
+
straight_vertical = []
|
| 1926 |
+
for k in range(start + 1, end):
|
| 1927 |
+
obj = grid[k, j]
|
| 1928 |
+
if not obj:
|
| 1929 |
+
continue
|
| 1930 |
+
|
| 1931 |
+
for m in morphisms_str_info:
|
| 1932 |
+
if m.domain == obj:
|
| 1933 |
+
(end_i, end_j) = object_coords[m.codomain]
|
| 1934 |
+
elif m.codomain == obj:
|
| 1935 |
+
(end_i, end_j) = object_coords[m.domain]
|
| 1936 |
+
else:
|
| 1937 |
+
continue
|
| 1938 |
+
|
| 1939 |
+
if end_j > j:
|
| 1940 |
+
right.append(m)
|
| 1941 |
+
elif end_j < j:
|
| 1942 |
+
left.append(m)
|
| 1943 |
+
elif not morphisms_str_info[m].curving:
|
| 1944 |
+
# This is a straight vertical morphism,
|
| 1945 |
+
# because it has no curving.
|
| 1946 |
+
straight_vertical.append(m)
|
| 1947 |
+
|
| 1948 |
+
if len(left) < len(right):
|
| 1949 |
+
# More morphisms stick out to the left than to the
|
| 1950 |
+
# right, let's curve the morphism to the right.
|
| 1951 |
+
if backwards:
|
| 1952 |
+
curving = "^"
|
| 1953 |
+
label_pos = "^"
|
| 1954 |
+
else:
|
| 1955 |
+
curving = "_"
|
| 1956 |
+
label_pos = "_"
|
| 1957 |
+
|
| 1958 |
+
# Assure that the straight vertical morphisms have
|
| 1959 |
+
# their labels on the left side of the arrow.
|
| 1960 |
+
for m in straight_vertical:
|
| 1961 |
+
(i1, j1) = object_coords[m.domain]
|
| 1962 |
+
(i2, j2) = object_coords[m.codomain]
|
| 1963 |
+
|
| 1964 |
+
m_str_info = morphisms_str_info[m]
|
| 1965 |
+
if i1 < i2:
|
| 1966 |
+
m_str_info.label_position = "^"
|
| 1967 |
+
else:
|
| 1968 |
+
m_str_info.label_position = "_"
|
| 1969 |
+
|
| 1970 |
+
# Don't allow any further modifications of the
|
| 1971 |
+
# position of this label.
|
| 1972 |
+
m_str_info.forced_label_position = True
|
| 1973 |
+
else:
|
| 1974 |
+
# More morphisms stick out to the right than to the
|
| 1975 |
+
# left, let's curve the morphism to the left.
|
| 1976 |
+
if backwards:
|
| 1977 |
+
curving = "_"
|
| 1978 |
+
label_pos = "_"
|
| 1979 |
+
else:
|
| 1980 |
+
curving = "^"
|
| 1981 |
+
label_pos = "^"
|
| 1982 |
+
|
| 1983 |
+
# Assure that the straight vertical morphisms have
|
| 1984 |
+
# their labels on the right side of the arrow.
|
| 1985 |
+
for m in straight_vertical:
|
| 1986 |
+
(i1, j1) = object_coords[m.domain]
|
| 1987 |
+
(i2, j2) = object_coords[m.codomain]
|
| 1988 |
+
|
| 1989 |
+
m_str_info = morphisms_str_info[m]
|
| 1990 |
+
if i1 < i2:
|
| 1991 |
+
m_str_info.label_position = "_"
|
| 1992 |
+
else:
|
| 1993 |
+
m_str_info.label_position = "^"
|
| 1994 |
+
|
| 1995 |
+
# Don't allow any further modifications of the
|
| 1996 |
+
# position of this label.
|
| 1997 |
+
m_str_info.forced_label_position = True
|
| 1998 |
+
|
| 1999 |
+
return (curving, label_pos)
|
| 2000 |
+
|
| 2001 |
+
def _process_morphism(self, diagram, grid, morphism, object_coords,
|
| 2002 |
+
morphisms, morphisms_str_info):
|
| 2003 |
+
"""
|
| 2004 |
+
Given the required information, produces the string
|
| 2005 |
+
representation of ``morphism``.
|
| 2006 |
+
"""
|
| 2007 |
+
def repeat_string_cond(times, str_gt, str_lt):
|
| 2008 |
+
"""
|
| 2009 |
+
If ``times > 0``, repeats ``str_gt`` ``times`` times.
|
| 2010 |
+
Otherwise, repeats ``str_lt`` ``-times`` times.
|
| 2011 |
+
"""
|
| 2012 |
+
if times > 0:
|
| 2013 |
+
return str_gt * times
|
| 2014 |
+
else:
|
| 2015 |
+
return str_lt * (-times)
|
| 2016 |
+
|
| 2017 |
+
def count_morphisms_undirected(A, B):
|
| 2018 |
+
"""
|
| 2019 |
+
Counts how many processed morphisms there are between the
|
| 2020 |
+
two supplied objects.
|
| 2021 |
+
"""
|
| 2022 |
+
return len([m for m in morphisms_str_info
|
| 2023 |
+
if {m.domain, m.codomain} == {A, B}])
|
| 2024 |
+
|
| 2025 |
+
def count_morphisms_filtered(dom, cod, curving):
|
| 2026 |
+
"""
|
| 2027 |
+
Counts the processed morphisms which go out of ``dom``
|
| 2028 |
+
into ``cod`` with curving ``curving``.
|
| 2029 |
+
"""
|
| 2030 |
+
return len([m for m, m_str_info in morphisms_str_info.items()
|
| 2031 |
+
if (m.domain, m.codomain) == (dom, cod) and
|
| 2032 |
+
(m_str_info.curving == curving)])
|
| 2033 |
+
|
| 2034 |
+
(i, j) = object_coords[morphism.domain]
|
| 2035 |
+
(target_i, target_j) = object_coords[morphism.codomain]
|
| 2036 |
+
|
| 2037 |
+
# We now need to determine the direction of
|
| 2038 |
+
# the arrow.
|
| 2039 |
+
delta_i = target_i - i
|
| 2040 |
+
delta_j = target_j - j
|
| 2041 |
+
vertical_direction = repeat_string_cond(delta_i,
|
| 2042 |
+
"d", "u")
|
| 2043 |
+
horizontal_direction = repeat_string_cond(delta_j,
|
| 2044 |
+
"r", "l")
|
| 2045 |
+
|
| 2046 |
+
curving = ""
|
| 2047 |
+
label_pos = "^"
|
| 2048 |
+
looping_start = ""
|
| 2049 |
+
looping_end = ""
|
| 2050 |
+
|
| 2051 |
+
if (delta_i == 0) and (delta_j == 0):
|
| 2052 |
+
# This is a loop morphism.
|
| 2053 |
+
(curving, label_pos, looping_start,
|
| 2054 |
+
looping_end) = XypicDiagramDrawer._process_loop_morphism(
|
| 2055 |
+
i, j, grid, morphisms_str_info, object_coords)
|
| 2056 |
+
elif (delta_i == 0) and (abs(j - target_j) > 1):
|
| 2057 |
+
# This is a horizontal morphism.
|
| 2058 |
+
(curving, label_pos) = XypicDiagramDrawer._process_horizontal_morphism(
|
| 2059 |
+
i, j, target_j, grid, morphisms_str_info, object_coords)
|
| 2060 |
+
elif (delta_j == 0) and (abs(i - target_i) > 1):
|
| 2061 |
+
# This is a vertical morphism.
|
| 2062 |
+
(curving, label_pos) = XypicDiagramDrawer._process_vertical_morphism(
|
| 2063 |
+
i, j, target_i, grid, morphisms_str_info, object_coords)
|
| 2064 |
+
|
| 2065 |
+
count = count_morphisms_undirected(morphism.domain, morphism.codomain)
|
| 2066 |
+
curving_amount = ""
|
| 2067 |
+
if curving:
|
| 2068 |
+
# This morphisms should be curved anyway.
|
| 2069 |
+
curving_amount = self.default_curving_amount + count * \
|
| 2070 |
+
self.default_curving_step
|
| 2071 |
+
elif count:
|
| 2072 |
+
# There are no objects between the domain and codomain of
|
| 2073 |
+
# the current morphism, but this is not there already are
|
| 2074 |
+
# some morphisms with the same domain and codomain, so we
|
| 2075 |
+
# have to curve this one.
|
| 2076 |
+
curving = "^"
|
| 2077 |
+
filtered_morphisms = count_morphisms_filtered(
|
| 2078 |
+
morphism.domain, morphism.codomain, curving)
|
| 2079 |
+
curving_amount = self.default_curving_amount + \
|
| 2080 |
+
filtered_morphisms * \
|
| 2081 |
+
self.default_curving_step
|
| 2082 |
+
|
| 2083 |
+
# Let's now get the name of the morphism.
|
| 2084 |
+
morphism_name = ""
|
| 2085 |
+
if isinstance(morphism, IdentityMorphism):
|
| 2086 |
+
morphism_name = "id_{%s}" + latex(grid[i, j])
|
| 2087 |
+
elif isinstance(morphism, CompositeMorphism):
|
| 2088 |
+
component_names = [latex(Symbol(component.name)) for
|
| 2089 |
+
component in morphism.components]
|
| 2090 |
+
component_names.reverse()
|
| 2091 |
+
morphism_name = "\\circ ".join(component_names)
|
| 2092 |
+
elif isinstance(morphism, NamedMorphism):
|
| 2093 |
+
morphism_name = latex(Symbol(morphism.name))
|
| 2094 |
+
|
| 2095 |
+
return ArrowStringDescription(
|
| 2096 |
+
self.unit, curving, curving_amount, looping_start,
|
| 2097 |
+
looping_end, horizontal_direction, vertical_direction,
|
| 2098 |
+
label_pos, morphism_name)
|
| 2099 |
+
|
| 2100 |
+
@staticmethod
|
| 2101 |
+
def _check_free_space_horizontal(dom_i, dom_j, cod_j, grid):
|
| 2102 |
+
"""
|
| 2103 |
+
For a horizontal morphism, checks whether there is free space
|
| 2104 |
+
(i.e., space not occupied by any objects) above the morphism
|
| 2105 |
+
or below it.
|
| 2106 |
+
"""
|
| 2107 |
+
if dom_j < cod_j:
|
| 2108 |
+
(start, end) = (dom_j, cod_j)
|
| 2109 |
+
backwards = False
|
| 2110 |
+
else:
|
| 2111 |
+
(start, end) = (cod_j, dom_j)
|
| 2112 |
+
backwards = True
|
| 2113 |
+
|
| 2114 |
+
# Check for free space above.
|
| 2115 |
+
if dom_i == 0:
|
| 2116 |
+
free_up = True
|
| 2117 |
+
else:
|
| 2118 |
+
free_up = all(grid[dom_i - 1, j] for j in
|
| 2119 |
+
range(start, end + 1))
|
| 2120 |
+
|
| 2121 |
+
# Check for free space below.
|
| 2122 |
+
if dom_i == grid.height - 1:
|
| 2123 |
+
free_down = True
|
| 2124 |
+
else:
|
| 2125 |
+
free_down = not any(grid[dom_i + 1, j] for j in
|
| 2126 |
+
range(start, end + 1))
|
| 2127 |
+
|
| 2128 |
+
return (free_up, free_down, backwards)
|
| 2129 |
+
|
| 2130 |
+
@staticmethod
|
| 2131 |
+
def _check_free_space_vertical(dom_i, cod_i, dom_j, grid):
|
| 2132 |
+
"""
|
| 2133 |
+
For a vertical morphism, checks whether there is free space
|
| 2134 |
+
(i.e., space not occupied by any objects) to the left of the
|
| 2135 |
+
morphism or to the right of it.
|
| 2136 |
+
"""
|
| 2137 |
+
if dom_i < cod_i:
|
| 2138 |
+
(start, end) = (dom_i, cod_i)
|
| 2139 |
+
backwards = False
|
| 2140 |
+
else:
|
| 2141 |
+
(start, end) = (cod_i, dom_i)
|
| 2142 |
+
backwards = True
|
| 2143 |
+
|
| 2144 |
+
# Check if there's space to the left.
|
| 2145 |
+
if dom_j == 0:
|
| 2146 |
+
free_left = True
|
| 2147 |
+
else:
|
| 2148 |
+
free_left = not any(grid[i, dom_j - 1] for i in
|
| 2149 |
+
range(start, end + 1))
|
| 2150 |
+
|
| 2151 |
+
if dom_j == grid.width - 1:
|
| 2152 |
+
free_right = True
|
| 2153 |
+
else:
|
| 2154 |
+
free_right = not any(grid[i, dom_j + 1] for i in
|
| 2155 |
+
range(start, end + 1))
|
| 2156 |
+
|
| 2157 |
+
return (free_left, free_right, backwards)
|
| 2158 |
+
|
| 2159 |
+
@staticmethod
|
| 2160 |
+
def _check_free_space_diagonal(dom_i, cod_i, dom_j, cod_j, grid):
|
| 2161 |
+
"""
|
| 2162 |
+
For a diagonal morphism, checks whether there is free space
|
| 2163 |
+
(i.e., space not occupied by any objects) above the morphism
|
| 2164 |
+
or below it.
|
| 2165 |
+
"""
|
| 2166 |
+
def abs_xrange(start, end):
|
| 2167 |
+
if start < end:
|
| 2168 |
+
return range(start, end + 1)
|
| 2169 |
+
else:
|
| 2170 |
+
return range(end, start + 1)
|
| 2171 |
+
|
| 2172 |
+
if dom_i < cod_i and dom_j < cod_j:
|
| 2173 |
+
# This morphism goes from top-left to
|
| 2174 |
+
# bottom-right.
|
| 2175 |
+
(start_i, start_j) = (dom_i, dom_j)
|
| 2176 |
+
(end_i, end_j) = (cod_i, cod_j)
|
| 2177 |
+
backwards = False
|
| 2178 |
+
elif dom_i > cod_i and dom_j > cod_j:
|
| 2179 |
+
# This morphism goes from bottom-right to
|
| 2180 |
+
# top-left.
|
| 2181 |
+
(start_i, start_j) = (cod_i, cod_j)
|
| 2182 |
+
(end_i, end_j) = (dom_i, dom_j)
|
| 2183 |
+
backwards = True
|
| 2184 |
+
if dom_i < cod_i and dom_j > cod_j:
|
| 2185 |
+
# This morphism goes from top-right to
|
| 2186 |
+
# bottom-left.
|
| 2187 |
+
(start_i, start_j) = (dom_i, dom_j)
|
| 2188 |
+
(end_i, end_j) = (cod_i, cod_j)
|
| 2189 |
+
backwards = True
|
| 2190 |
+
elif dom_i > cod_i and dom_j < cod_j:
|
| 2191 |
+
# This morphism goes from bottom-left to
|
| 2192 |
+
# top-right.
|
| 2193 |
+
(start_i, start_j) = (cod_i, cod_j)
|
| 2194 |
+
(end_i, end_j) = (dom_i, dom_j)
|
| 2195 |
+
backwards = False
|
| 2196 |
+
|
| 2197 |
+
# This is an attempt at a fast and furious strategy to
|
| 2198 |
+
# decide where there is free space on the two sides of
|
| 2199 |
+
# a diagonal morphism. For a diagonal morphism
|
| 2200 |
+
# starting at ``(start_i, start_j)`` and ending at
|
| 2201 |
+
# ``(end_i, end_j)`` the rectangle defined by these
|
| 2202 |
+
# two points is considered. The slope of the diagonal
|
| 2203 |
+
# ``alpha`` is then computed. Then, for every cell
|
| 2204 |
+
# ``(i, j)`` within the rectangle, the slope
|
| 2205 |
+
# ``alpha1`` of the line through ``(start_i,
|
| 2206 |
+
# start_j)`` and ``(i, j)`` is considered. If
|
| 2207 |
+
# ``alpha1`` is between 0 and ``alpha``, the point
|
| 2208 |
+
# ``(i, j)`` is above the diagonal, if ``alpha1`` is
|
| 2209 |
+
# between ``alpha`` and infinity, the point is below
|
| 2210 |
+
# the diagonal. Also note that, with some beforehand
|
| 2211 |
+
# precautions, this trick works for both the main and
|
| 2212 |
+
# the secondary diagonals of the rectangle.
|
| 2213 |
+
|
| 2214 |
+
# I have considered the possibility to only follow the
|
| 2215 |
+
# shorter diagonals immediately above and below the
|
| 2216 |
+
# main (or secondary) diagonal. This, however,
|
| 2217 |
+
# wouldn't have resulted in much performance gain or
|
| 2218 |
+
# better detection of outer edges, because of
|
| 2219 |
+
# relatively small sizes of diagram grids, while the
|
| 2220 |
+
# code would have become harder to understand.
|
| 2221 |
+
|
| 2222 |
+
alpha = float(end_i - start_i)/(end_j - start_j)
|
| 2223 |
+
free_up = True
|
| 2224 |
+
free_down = True
|
| 2225 |
+
for i in abs_xrange(start_i, end_i):
|
| 2226 |
+
if not free_up and not free_down:
|
| 2227 |
+
break
|
| 2228 |
+
|
| 2229 |
+
for j in abs_xrange(start_j, end_j):
|
| 2230 |
+
if not free_up and not free_down:
|
| 2231 |
+
break
|
| 2232 |
+
|
| 2233 |
+
if (i, j) == (start_i, start_j):
|
| 2234 |
+
continue
|
| 2235 |
+
|
| 2236 |
+
if j == start_j:
|
| 2237 |
+
alpha1 = "inf"
|
| 2238 |
+
else:
|
| 2239 |
+
alpha1 = float(i - start_i)/(j - start_j)
|
| 2240 |
+
|
| 2241 |
+
if grid[i, j]:
|
| 2242 |
+
if (alpha1 == "inf") or (abs(alpha1) > abs(alpha)):
|
| 2243 |
+
free_down = False
|
| 2244 |
+
elif abs(alpha1) < abs(alpha):
|
| 2245 |
+
free_up = False
|
| 2246 |
+
|
| 2247 |
+
return (free_up, free_down, backwards)
|
| 2248 |
+
|
| 2249 |
+
def _push_labels_out(self, morphisms_str_info, grid, object_coords):
|
| 2250 |
+
"""
|
| 2251 |
+
For all straight morphisms which form the visual boundary of
|
| 2252 |
+
the laid out diagram, puts their labels on their outer sides.
|
| 2253 |
+
"""
|
| 2254 |
+
def set_label_position(free1, free2, pos1, pos2, backwards, m_str_info):
|
| 2255 |
+
"""
|
| 2256 |
+
Given the information about room available to one side and
|
| 2257 |
+
to the other side of a morphism (``free1`` and ``free2``),
|
| 2258 |
+
sets the position of the morphism label in such a way that
|
| 2259 |
+
it is on the freer side. This latter operations involves
|
| 2260 |
+
choice between ``pos1`` and ``pos2``, taking ``backwards``
|
| 2261 |
+
in consideration.
|
| 2262 |
+
|
| 2263 |
+
Thus this function will do nothing if either both ``free1
|
| 2264 |
+
== True`` and ``free2 == True`` or both ``free1 == False``
|
| 2265 |
+
and ``free2 == False``. In either case, choosing one side
|
| 2266 |
+
over the other presents no advantage.
|
| 2267 |
+
"""
|
| 2268 |
+
if backwards:
|
| 2269 |
+
(pos1, pos2) = (pos2, pos1)
|
| 2270 |
+
|
| 2271 |
+
if free1 and not free2:
|
| 2272 |
+
m_str_info.label_position = pos1
|
| 2273 |
+
elif free2 and not free1:
|
| 2274 |
+
m_str_info.label_position = pos2
|
| 2275 |
+
|
| 2276 |
+
for m, m_str_info in morphisms_str_info.items():
|
| 2277 |
+
if m_str_info.curving or m_str_info.forced_label_position:
|
| 2278 |
+
# This is either a curved morphism, and curved
|
| 2279 |
+
# morphisms have other magic, or the position of this
|
| 2280 |
+
# label has already been fixed.
|
| 2281 |
+
continue
|
| 2282 |
+
|
| 2283 |
+
if m.domain == m.codomain:
|
| 2284 |
+
# This is a loop morphism, their labels, again have a
|
| 2285 |
+
# different magic.
|
| 2286 |
+
continue
|
| 2287 |
+
|
| 2288 |
+
(dom_i, dom_j) = object_coords[m.domain]
|
| 2289 |
+
(cod_i, cod_j) = object_coords[m.codomain]
|
| 2290 |
+
|
| 2291 |
+
if dom_i == cod_i:
|
| 2292 |
+
# Horizontal morphism.
|
| 2293 |
+
(free_up, free_down,
|
| 2294 |
+
backwards) = XypicDiagramDrawer._check_free_space_horizontal(
|
| 2295 |
+
dom_i, dom_j, cod_j, grid)
|
| 2296 |
+
|
| 2297 |
+
set_label_position(free_up, free_down, "^", "_",
|
| 2298 |
+
backwards, m_str_info)
|
| 2299 |
+
elif dom_j == cod_j:
|
| 2300 |
+
# Vertical morphism.
|
| 2301 |
+
(free_left, free_right,
|
| 2302 |
+
backwards) = XypicDiagramDrawer._check_free_space_vertical(
|
| 2303 |
+
dom_i, cod_i, dom_j, grid)
|
| 2304 |
+
|
| 2305 |
+
set_label_position(free_left, free_right, "_", "^",
|
| 2306 |
+
backwards, m_str_info)
|
| 2307 |
+
else:
|
| 2308 |
+
# A diagonal morphism.
|
| 2309 |
+
(free_up, free_down,
|
| 2310 |
+
backwards) = XypicDiagramDrawer._check_free_space_diagonal(
|
| 2311 |
+
dom_i, cod_i, dom_j, cod_j, grid)
|
| 2312 |
+
|
| 2313 |
+
set_label_position(free_up, free_down, "^", "_",
|
| 2314 |
+
backwards, m_str_info)
|
| 2315 |
+
|
| 2316 |
+
@staticmethod
|
| 2317 |
+
def _morphism_sort_key(morphism, object_coords):
|
| 2318 |
+
"""
|
| 2319 |
+
Provides a morphism sorting key such that horizontal or
|
| 2320 |
+
vertical morphisms between neighbouring objects come
|
| 2321 |
+
first, then horizontal or vertical morphisms between more
|
| 2322 |
+
far away objects, and finally, all other morphisms.
|
| 2323 |
+
"""
|
| 2324 |
+
(i, j) = object_coords[morphism.domain]
|
| 2325 |
+
(target_i, target_j) = object_coords[morphism.codomain]
|
| 2326 |
+
|
| 2327 |
+
if morphism.domain == morphism.codomain:
|
| 2328 |
+
# Loop morphisms should get after diagonal morphisms
|
| 2329 |
+
# so that the proper direction in which to curve the
|
| 2330 |
+
# loop can be determined.
|
| 2331 |
+
return (3, 0, default_sort_key(morphism))
|
| 2332 |
+
|
| 2333 |
+
if target_i == i:
|
| 2334 |
+
return (1, abs(target_j - j), default_sort_key(morphism))
|
| 2335 |
+
|
| 2336 |
+
if target_j == j:
|
| 2337 |
+
return (1, abs(target_i - i), default_sort_key(morphism))
|
| 2338 |
+
|
| 2339 |
+
# Diagonal morphism.
|
| 2340 |
+
return (2, 0, default_sort_key(morphism))
|
| 2341 |
+
|
| 2342 |
+
@staticmethod
|
| 2343 |
+
def _build_xypic_string(diagram, grid, morphisms,
|
| 2344 |
+
morphisms_str_info, diagram_format):
|
| 2345 |
+
"""
|
| 2346 |
+
Given a collection of :class:`ArrowStringDescription`
|
| 2347 |
+
describing the morphisms of a diagram and the object layout
|
| 2348 |
+
information of a diagram, produces the final Xy-pic picture.
|
| 2349 |
+
"""
|
| 2350 |
+
# Build the mapping between objects and morphisms which have
|
| 2351 |
+
# them as domains.
|
| 2352 |
+
object_morphisms = {}
|
| 2353 |
+
for obj in diagram.objects:
|
| 2354 |
+
object_morphisms[obj] = []
|
| 2355 |
+
for morphism in morphisms:
|
| 2356 |
+
object_morphisms[morphism.domain].append(morphism)
|
| 2357 |
+
|
| 2358 |
+
result = "\\xymatrix%s{\n" % diagram_format
|
| 2359 |
+
|
| 2360 |
+
for i in range(grid.height):
|
| 2361 |
+
for j in range(grid.width):
|
| 2362 |
+
obj = grid[i, j]
|
| 2363 |
+
if obj:
|
| 2364 |
+
result += latex(obj) + " "
|
| 2365 |
+
|
| 2366 |
+
morphisms_to_draw = object_morphisms[obj]
|
| 2367 |
+
for morphism in morphisms_to_draw:
|
| 2368 |
+
result += str(morphisms_str_info[morphism]) + " "
|
| 2369 |
+
|
| 2370 |
+
# Don't put the & after the last column.
|
| 2371 |
+
if j < grid.width - 1:
|
| 2372 |
+
result += "& "
|
| 2373 |
+
|
| 2374 |
+
# Don't put the line break after the last row.
|
| 2375 |
+
if i < grid.height - 1:
|
| 2376 |
+
result += "\\\\"
|
| 2377 |
+
result += "\n"
|
| 2378 |
+
|
| 2379 |
+
result += "}\n"
|
| 2380 |
+
|
| 2381 |
+
return result
|
| 2382 |
+
|
| 2383 |
+
def draw(self, diagram, grid, masked=None, diagram_format=""):
|
| 2384 |
+
r"""
|
| 2385 |
+
Returns the Xy-pic representation of ``diagram`` laid out in
|
| 2386 |
+
``grid``.
|
| 2387 |
+
|
| 2388 |
+
Consider the following simple triangle diagram.
|
| 2389 |
+
|
| 2390 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 2391 |
+
>>> from sympy.categories import DiagramGrid, XypicDiagramDrawer
|
| 2392 |
+
>>> A = Object("A")
|
| 2393 |
+
>>> B = Object("B")
|
| 2394 |
+
>>> C = Object("C")
|
| 2395 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 2396 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 2397 |
+
>>> diagram = Diagram([f, g], {g * f: "unique"})
|
| 2398 |
+
|
| 2399 |
+
To draw this diagram, its objects need to be laid out with a
|
| 2400 |
+
:class:`DiagramGrid`::
|
| 2401 |
+
|
| 2402 |
+
>>> grid = DiagramGrid(diagram)
|
| 2403 |
+
|
| 2404 |
+
Finally, the drawing:
|
| 2405 |
+
|
| 2406 |
+
>>> drawer = XypicDiagramDrawer()
|
| 2407 |
+
>>> print(drawer.draw(diagram, grid))
|
| 2408 |
+
\xymatrix{
|
| 2409 |
+
A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 2410 |
+
C &
|
| 2411 |
+
}
|
| 2412 |
+
|
| 2413 |
+
The argument ``masked`` can be used to skip morphisms in the
|
| 2414 |
+
presentation of the diagram:
|
| 2415 |
+
|
| 2416 |
+
>>> print(drawer.draw(diagram, grid, masked=[g * f]))
|
| 2417 |
+
\xymatrix{
|
| 2418 |
+
A \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 2419 |
+
C &
|
| 2420 |
+
}
|
| 2421 |
+
|
| 2422 |
+
Finally, the ``diagram_format`` argument can be used to
|
| 2423 |
+
specify the format string of the diagram. For example, to
|
| 2424 |
+
increase the spacing by 1 cm, proceeding as follows:
|
| 2425 |
+
|
| 2426 |
+
>>> print(drawer.draw(diagram, grid, diagram_format="@+1cm"))
|
| 2427 |
+
\xymatrix@+1cm{
|
| 2428 |
+
A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 2429 |
+
C &
|
| 2430 |
+
}
|
| 2431 |
+
|
| 2432 |
+
"""
|
| 2433 |
+
# This method works in several steps. It starts by removing
|
| 2434 |
+
# the masked morphisms, if necessary, and then maps objects to
|
| 2435 |
+
# their positions in the grid (coordinate tuples). Remember
|
| 2436 |
+
# that objects are unique in ``Diagram`` and in the layout
|
| 2437 |
+
# produced by ``DiagramGrid``, so every object is mapped to a
|
| 2438 |
+
# single coordinate pair.
|
| 2439 |
+
#
|
| 2440 |
+
# The next step is the central step and is concerned with
|
| 2441 |
+
# analysing the morphisms of the diagram and deciding how to
|
| 2442 |
+
# draw them. For example, how to curve the arrows is decided
|
| 2443 |
+
# at this step. The bulk of the analysis is implemented in
|
| 2444 |
+
# ``_process_morphism``, to the result of which the
|
| 2445 |
+
# appropriate formatters are applied.
|
| 2446 |
+
#
|
| 2447 |
+
# The result of the previous step is a list of
|
| 2448 |
+
# ``ArrowStringDescription``. After the analysis and
|
| 2449 |
+
# application of formatters, some extra logic tries to assure
|
| 2450 |
+
# better positioning of morphism labels (for example, an
|
| 2451 |
+
# attempt is made to avoid the situations when arrows cross
|
| 2452 |
+
# labels). This functionality constitutes the next step and
|
| 2453 |
+
# is implemented in ``_push_labels_out``. Note that label
|
| 2454 |
+
# positions which have been set via a formatter are not
|
| 2455 |
+
# affected in this step.
|
| 2456 |
+
#
|
| 2457 |
+
# Finally, at the closing step, the array of
|
| 2458 |
+
# ``ArrowStringDescription`` and the layout information
|
| 2459 |
+
# incorporated in ``DiagramGrid`` are combined to produce the
|
| 2460 |
+
# resulting Xy-pic picture. This part of code lies in
|
| 2461 |
+
# ``_build_xypic_string``.
|
| 2462 |
+
|
| 2463 |
+
if not masked:
|
| 2464 |
+
morphisms_props = grid.morphisms
|
| 2465 |
+
else:
|
| 2466 |
+
morphisms_props = {}
|
| 2467 |
+
for m, props in grid.morphisms.items():
|
| 2468 |
+
if m in masked:
|
| 2469 |
+
continue
|
| 2470 |
+
morphisms_props[m] = props
|
| 2471 |
+
|
| 2472 |
+
# Build the mapping between objects and their position in the
|
| 2473 |
+
# grid.
|
| 2474 |
+
object_coords = {}
|
| 2475 |
+
for i in range(grid.height):
|
| 2476 |
+
for j in range(grid.width):
|
| 2477 |
+
if grid[i, j]:
|
| 2478 |
+
object_coords[grid[i, j]] = (i, j)
|
| 2479 |
+
|
| 2480 |
+
morphisms = sorted(morphisms_props,
|
| 2481 |
+
key=lambda m: XypicDiagramDrawer._morphism_sort_key(
|
| 2482 |
+
m, object_coords))
|
| 2483 |
+
|
| 2484 |
+
# Build the tuples defining the string representations of
|
| 2485 |
+
# morphisms.
|
| 2486 |
+
morphisms_str_info = {}
|
| 2487 |
+
for morphism in morphisms:
|
| 2488 |
+
string_description = self._process_morphism(
|
| 2489 |
+
diagram, grid, morphism, object_coords, morphisms,
|
| 2490 |
+
morphisms_str_info)
|
| 2491 |
+
|
| 2492 |
+
if self.default_arrow_formatter:
|
| 2493 |
+
self.default_arrow_formatter(string_description)
|
| 2494 |
+
|
| 2495 |
+
for prop in morphisms_props[morphism]:
|
| 2496 |
+
# prop is a Symbol. TODO: Find out why.
|
| 2497 |
+
if prop.name in self.arrow_formatters:
|
| 2498 |
+
formatter = self.arrow_formatters[prop.name]
|
| 2499 |
+
formatter(string_description)
|
| 2500 |
+
|
| 2501 |
+
morphisms_str_info[morphism] = string_description
|
| 2502 |
+
|
| 2503 |
+
# Reposition the labels a bit.
|
| 2504 |
+
self._push_labels_out(morphisms_str_info, grid, object_coords)
|
| 2505 |
+
|
| 2506 |
+
return XypicDiagramDrawer._build_xypic_string(
|
| 2507 |
+
diagram, grid, morphisms, morphisms_str_info, diagram_format)
|
| 2508 |
+
|
| 2509 |
+
|
| 2510 |
+
def xypic_draw_diagram(diagram, masked=None, diagram_format="",
|
| 2511 |
+
groups=None, **hints):
|
| 2512 |
+
r"""
|
| 2513 |
+
Provides a shortcut combining :class:`DiagramGrid` and
|
| 2514 |
+
:class:`XypicDiagramDrawer`. Returns an Xy-pic presentation of
|
| 2515 |
+
``diagram``. The argument ``masked`` is a list of morphisms which
|
| 2516 |
+
will be not be drawn. The argument ``diagram_format`` is the
|
| 2517 |
+
format string inserted after "\xymatrix". ``groups`` should be a
|
| 2518 |
+
set of logical groups. The ``hints`` will be passed directly to
|
| 2519 |
+
the constructor of :class:`DiagramGrid`.
|
| 2520 |
+
|
| 2521 |
+
For more information about the arguments, see the docstrings of
|
| 2522 |
+
:class:`DiagramGrid` and ``XypicDiagramDrawer.draw``.
|
| 2523 |
+
|
| 2524 |
+
Examples
|
| 2525 |
+
========
|
| 2526 |
+
|
| 2527 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 2528 |
+
>>> from sympy.categories import xypic_draw_diagram
|
| 2529 |
+
>>> A = Object("A")
|
| 2530 |
+
>>> B = Object("B")
|
| 2531 |
+
>>> C = Object("C")
|
| 2532 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 2533 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 2534 |
+
>>> diagram = Diagram([f, g], {g * f: "unique"})
|
| 2535 |
+
>>> print(xypic_draw_diagram(diagram))
|
| 2536 |
+
\xymatrix{
|
| 2537 |
+
A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 2538 |
+
C &
|
| 2539 |
+
}
|
| 2540 |
+
|
| 2541 |
+
See Also
|
| 2542 |
+
========
|
| 2543 |
+
|
| 2544 |
+
XypicDiagramDrawer, DiagramGrid
|
| 2545 |
+
"""
|
| 2546 |
+
grid = DiagramGrid(diagram, groups, **hints)
|
| 2547 |
+
drawer = XypicDiagramDrawer()
|
| 2548 |
+
return drawer.draw(diagram, grid, masked, diagram_format)
|
| 2549 |
+
|
| 2550 |
+
|
| 2551 |
+
@doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',))
|
| 2552 |
+
def preview_diagram(diagram, masked=None, diagram_format="", groups=None,
|
| 2553 |
+
output='png', viewer=None, euler=True, **hints):
|
| 2554 |
+
"""
|
| 2555 |
+
Combines the functionality of ``xypic_draw_diagram`` and
|
| 2556 |
+
``sympy.printing.preview``. The arguments ``masked``,
|
| 2557 |
+
``diagram_format``, ``groups``, and ``hints`` are passed to
|
| 2558 |
+
``xypic_draw_diagram``, while ``output``, ``viewer, and ``euler``
|
| 2559 |
+
are passed to ``preview``.
|
| 2560 |
+
|
| 2561 |
+
Examples
|
| 2562 |
+
========
|
| 2563 |
+
|
| 2564 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 2565 |
+
>>> from sympy.categories import preview_diagram
|
| 2566 |
+
>>> A = Object("A")
|
| 2567 |
+
>>> B = Object("B")
|
| 2568 |
+
>>> C = Object("C")
|
| 2569 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 2570 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 2571 |
+
>>> d = Diagram([f, g], {g * f: "unique"})
|
| 2572 |
+
>>> preview_diagram(d)
|
| 2573 |
+
|
| 2574 |
+
See Also
|
| 2575 |
+
========
|
| 2576 |
+
|
| 2577 |
+
XypicDiagramDrawer
|
| 2578 |
+
"""
|
| 2579 |
+
from sympy.printing import preview
|
| 2580 |
+
latex_output = xypic_draw_diagram(diagram, masked, diagram_format,
|
| 2581 |
+
groups, **hints)
|
| 2582 |
+
preview(latex_output, output, viewer, euler, ("xypic",))
|
pllava/lib/python3.10/site-packages/sympy/categories/tests/__init__.py
ADDED
|
File without changes
|
pllava/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (174 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc
ADDED
|
Binary file (4.98 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc
ADDED
|
Binary file (17.5 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/categories/tests/test_baseclasses.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.categories import (Object, Morphism, IdentityMorphism,
|
| 2 |
+
NamedMorphism, CompositeMorphism,
|
| 3 |
+
Diagram, Category)
|
| 4 |
+
from sympy.categories.baseclasses import Class
|
| 5 |
+
from sympy.testing.pytest import raises
|
| 6 |
+
from sympy.core.containers import (Dict, Tuple)
|
| 7 |
+
from sympy.sets import EmptySet
|
| 8 |
+
from sympy.sets.sets import FiniteSet
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_morphisms():
|
| 12 |
+
A = Object("A")
|
| 13 |
+
B = Object("B")
|
| 14 |
+
C = Object("C")
|
| 15 |
+
D = Object("D")
|
| 16 |
+
|
| 17 |
+
# Test the base morphism.
|
| 18 |
+
f = NamedMorphism(A, B, "f")
|
| 19 |
+
assert f.domain == A
|
| 20 |
+
assert f.codomain == B
|
| 21 |
+
assert f == NamedMorphism(A, B, "f")
|
| 22 |
+
|
| 23 |
+
# Test identities.
|
| 24 |
+
id_A = IdentityMorphism(A)
|
| 25 |
+
id_B = IdentityMorphism(B)
|
| 26 |
+
assert id_A.domain == A
|
| 27 |
+
assert id_A.codomain == A
|
| 28 |
+
assert id_A == IdentityMorphism(A)
|
| 29 |
+
assert id_A != id_B
|
| 30 |
+
|
| 31 |
+
# Test named morphisms.
|
| 32 |
+
g = NamedMorphism(B, C, "g")
|
| 33 |
+
assert g.name == "g"
|
| 34 |
+
assert g != f
|
| 35 |
+
assert g == NamedMorphism(B, C, "g")
|
| 36 |
+
assert g != NamedMorphism(B, C, "f")
|
| 37 |
+
|
| 38 |
+
# Test composite morphisms.
|
| 39 |
+
assert f == CompositeMorphism(f)
|
| 40 |
+
|
| 41 |
+
k = g.compose(f)
|
| 42 |
+
assert k.domain == A
|
| 43 |
+
assert k.codomain == C
|
| 44 |
+
assert k.components == Tuple(f, g)
|
| 45 |
+
assert g * f == k
|
| 46 |
+
assert CompositeMorphism(f, g) == k
|
| 47 |
+
|
| 48 |
+
assert CompositeMorphism(g * f) == g * f
|
| 49 |
+
|
| 50 |
+
# Test the associativity of composition.
|
| 51 |
+
h = NamedMorphism(C, D, "h")
|
| 52 |
+
|
| 53 |
+
p = h * g
|
| 54 |
+
u = h * g * f
|
| 55 |
+
|
| 56 |
+
assert h * k == u
|
| 57 |
+
assert p * f == u
|
| 58 |
+
assert CompositeMorphism(f, g, h) == u
|
| 59 |
+
|
| 60 |
+
# Test flattening.
|
| 61 |
+
u2 = u.flatten("u")
|
| 62 |
+
assert isinstance(u2, NamedMorphism)
|
| 63 |
+
assert u2.name == "u"
|
| 64 |
+
assert u2.domain == A
|
| 65 |
+
assert u2.codomain == D
|
| 66 |
+
|
| 67 |
+
# Test identities.
|
| 68 |
+
assert f * id_A == f
|
| 69 |
+
assert id_B * f == f
|
| 70 |
+
assert id_A * id_A == id_A
|
| 71 |
+
assert CompositeMorphism(id_A) == id_A
|
| 72 |
+
|
| 73 |
+
# Test bad compositions.
|
| 74 |
+
raises(ValueError, lambda: f * g)
|
| 75 |
+
|
| 76 |
+
raises(TypeError, lambda: f.compose(None))
|
| 77 |
+
raises(TypeError, lambda: id_A.compose(None))
|
| 78 |
+
raises(TypeError, lambda: f * None)
|
| 79 |
+
raises(TypeError, lambda: id_A * None)
|
| 80 |
+
|
| 81 |
+
raises(TypeError, lambda: CompositeMorphism(f, None, 1))
|
| 82 |
+
|
| 83 |
+
raises(ValueError, lambda: NamedMorphism(A, B, ""))
|
| 84 |
+
raises(NotImplementedError, lambda: Morphism(A, B))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_diagram():
|
| 88 |
+
A = Object("A")
|
| 89 |
+
B = Object("B")
|
| 90 |
+
C = Object("C")
|
| 91 |
+
|
| 92 |
+
f = NamedMorphism(A, B, "f")
|
| 93 |
+
g = NamedMorphism(B, C, "g")
|
| 94 |
+
id_A = IdentityMorphism(A)
|
| 95 |
+
id_B = IdentityMorphism(B)
|
| 96 |
+
|
| 97 |
+
empty = EmptySet
|
| 98 |
+
|
| 99 |
+
# Test the addition of identities.
|
| 100 |
+
d1 = Diagram([f])
|
| 101 |
+
|
| 102 |
+
assert d1.objects == FiniteSet(A, B)
|
| 103 |
+
assert d1.hom(A, B) == (FiniteSet(f), empty)
|
| 104 |
+
assert d1.hom(A, A) == (FiniteSet(id_A), empty)
|
| 105 |
+
assert d1.hom(B, B) == (FiniteSet(id_B), empty)
|
| 106 |
+
|
| 107 |
+
assert d1 == Diagram([id_A, f])
|
| 108 |
+
assert d1 == Diagram([f, f])
|
| 109 |
+
|
| 110 |
+
# Test the addition of composites.
|
| 111 |
+
d2 = Diagram([f, g])
|
| 112 |
+
homAC = d2.hom(A, C)[0]
|
| 113 |
+
|
| 114 |
+
assert d2.objects == FiniteSet(A, B, C)
|
| 115 |
+
assert g * f in d2.premises.keys()
|
| 116 |
+
assert homAC == FiniteSet(g * f)
|
| 117 |
+
|
| 118 |
+
# Test equality, inequality and hash.
|
| 119 |
+
d11 = Diagram([f])
|
| 120 |
+
|
| 121 |
+
assert d1 == d11
|
| 122 |
+
assert d1 != d2
|
| 123 |
+
assert hash(d1) == hash(d11)
|
| 124 |
+
|
| 125 |
+
d11 = Diagram({f: "unique"})
|
| 126 |
+
assert d1 != d11
|
| 127 |
+
|
| 128 |
+
# Make sure that (re-)adding composites (with new properties)
|
| 129 |
+
# works as expected.
|
| 130 |
+
d = Diagram([f, g], {g * f: "unique"})
|
| 131 |
+
assert d.conclusions == Dict({g * f: FiniteSet("unique")})
|
| 132 |
+
|
| 133 |
+
# Check the hom-sets when there are premises and conclusions.
|
| 134 |
+
assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f))
|
| 135 |
+
d = Diagram([f, g], [g * f])
|
| 136 |
+
assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f))
|
| 137 |
+
|
| 138 |
+
# Check how the properties of composite morphisms are computed.
|
| 139 |
+
d = Diagram({f: ["unique", "isomorphism"], g: "unique"})
|
| 140 |
+
assert d.premises[g * f] == FiniteSet("unique")
|
| 141 |
+
|
| 142 |
+
# Check that conclusion morphisms with new objects are not allowed.
|
| 143 |
+
d = Diagram([f], [g])
|
| 144 |
+
assert d.conclusions == Dict({})
|
| 145 |
+
|
| 146 |
+
# Test an empty diagram.
|
| 147 |
+
d = Diagram()
|
| 148 |
+
assert d.premises == Dict({})
|
| 149 |
+
assert d.conclusions == Dict({})
|
| 150 |
+
assert d.objects == empty
|
| 151 |
+
|
| 152 |
+
# Check a SymPy Dict object.
|
| 153 |
+
d = Diagram(Dict({f: FiniteSet("unique", "isomorphism"), g: "unique"}))
|
| 154 |
+
assert d.premises[g * f] == FiniteSet("unique")
|
| 155 |
+
|
| 156 |
+
# Check the addition of components of composite morphisms.
|
| 157 |
+
d = Diagram([g * f])
|
| 158 |
+
assert f in d.premises
|
| 159 |
+
assert g in d.premises
|
| 160 |
+
|
| 161 |
+
# Check subdiagrams.
|
| 162 |
+
d = Diagram([f, g], {g * f: "unique"})
|
| 163 |
+
|
| 164 |
+
d1 = Diagram([f])
|
| 165 |
+
assert d.is_subdiagram(d1)
|
| 166 |
+
assert not d1.is_subdiagram(d)
|
| 167 |
+
|
| 168 |
+
d = Diagram([NamedMorphism(B, A, "f'")])
|
| 169 |
+
assert not d.is_subdiagram(d1)
|
| 170 |
+
assert not d1.is_subdiagram(d)
|
| 171 |
+
|
| 172 |
+
d1 = Diagram([f, g], {g * f: ["unique", "something"]})
|
| 173 |
+
assert not d.is_subdiagram(d1)
|
| 174 |
+
assert not d1.is_subdiagram(d)
|
| 175 |
+
|
| 176 |
+
d = Diagram({f: "blooh"})
|
| 177 |
+
d1 = Diagram({f: "bleeh"})
|
| 178 |
+
assert not d.is_subdiagram(d1)
|
| 179 |
+
assert not d1.is_subdiagram(d)
|
| 180 |
+
|
| 181 |
+
d = Diagram([f, g], {f: "unique", g * f: "veryunique"})
|
| 182 |
+
d1 = d.subdiagram_from_objects(FiniteSet(A, B))
|
| 183 |
+
assert d1 == Diagram([f], {f: "unique"})
|
| 184 |
+
raises(ValueError, lambda: d.subdiagram_from_objects(FiniteSet(A,
|
| 185 |
+
Object("D"))))
|
| 186 |
+
|
| 187 |
+
raises(ValueError, lambda: Diagram({IdentityMorphism(A): "unique"}))
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_category():
|
| 191 |
+
A = Object("A")
|
| 192 |
+
B = Object("B")
|
| 193 |
+
C = Object("C")
|
| 194 |
+
|
| 195 |
+
f = NamedMorphism(A, B, "f")
|
| 196 |
+
g = NamedMorphism(B, C, "g")
|
| 197 |
+
|
| 198 |
+
d1 = Diagram([f, g])
|
| 199 |
+
d2 = Diagram([f])
|
| 200 |
+
|
| 201 |
+
objects = d1.objects | d2.objects
|
| 202 |
+
|
| 203 |
+
K = Category("K", objects, commutative_diagrams=[d1, d2])
|
| 204 |
+
|
| 205 |
+
assert K.name == "K"
|
| 206 |
+
assert K.objects == Class(objects)
|
| 207 |
+
assert K.commutative_diagrams == FiniteSet(d1, d2)
|
| 208 |
+
|
| 209 |
+
raises(ValueError, lambda: Category(""))
|
pllava/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py
ADDED
|
@@ -0,0 +1,919 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.categories.diagram_drawing import _GrowableGrid, ArrowStringDescription
|
| 2 |
+
from sympy.categories import (DiagramGrid, Object, NamedMorphism,
|
| 3 |
+
Diagram, XypicDiagramDrawer, xypic_draw_diagram)
|
| 4 |
+
from sympy.sets.sets import FiniteSet
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_GrowableGrid():
|
| 8 |
+
grid = _GrowableGrid(1, 2)
|
| 9 |
+
|
| 10 |
+
# Check dimensions.
|
| 11 |
+
assert grid.width == 1
|
| 12 |
+
assert grid.height == 2
|
| 13 |
+
|
| 14 |
+
# Check initialization of elements.
|
| 15 |
+
assert grid[0, 0] is None
|
| 16 |
+
assert grid[1, 0] is None
|
| 17 |
+
|
| 18 |
+
# Check assignment to elements.
|
| 19 |
+
grid[0, 0] = 1
|
| 20 |
+
grid[1, 0] = "two"
|
| 21 |
+
|
| 22 |
+
assert grid[0, 0] == 1
|
| 23 |
+
assert grid[1, 0] == "two"
|
| 24 |
+
|
| 25 |
+
# Check appending a row.
|
| 26 |
+
grid.append_row()
|
| 27 |
+
|
| 28 |
+
assert grid.width == 1
|
| 29 |
+
assert grid.height == 3
|
| 30 |
+
|
| 31 |
+
assert grid[0, 0] == 1
|
| 32 |
+
assert grid[1, 0] == "two"
|
| 33 |
+
assert grid[2, 0] is None
|
| 34 |
+
|
| 35 |
+
# Check appending a column.
|
| 36 |
+
grid.append_column()
|
| 37 |
+
assert grid.width == 2
|
| 38 |
+
assert grid.height == 3
|
| 39 |
+
|
| 40 |
+
assert grid[0, 0] == 1
|
| 41 |
+
assert grid[1, 0] == "two"
|
| 42 |
+
assert grid[2, 0] is None
|
| 43 |
+
|
| 44 |
+
assert grid[0, 1] is None
|
| 45 |
+
assert grid[1, 1] is None
|
| 46 |
+
assert grid[2, 1] is None
|
| 47 |
+
|
| 48 |
+
grid = _GrowableGrid(1, 2)
|
| 49 |
+
grid[0, 0] = 1
|
| 50 |
+
grid[1, 0] = "two"
|
| 51 |
+
|
| 52 |
+
# Check prepending a row.
|
| 53 |
+
grid.prepend_row()
|
| 54 |
+
assert grid.width == 1
|
| 55 |
+
assert grid.height == 3
|
| 56 |
+
|
| 57 |
+
assert grid[0, 0] is None
|
| 58 |
+
assert grid[1, 0] == 1
|
| 59 |
+
assert grid[2, 0] == "two"
|
| 60 |
+
|
| 61 |
+
# Check prepending a column.
|
| 62 |
+
grid.prepend_column()
|
| 63 |
+
assert grid.width == 2
|
| 64 |
+
assert grid.height == 3
|
| 65 |
+
|
| 66 |
+
assert grid[0, 0] is None
|
| 67 |
+
assert grid[1, 0] is None
|
| 68 |
+
assert grid[2, 0] is None
|
| 69 |
+
|
| 70 |
+
assert grid[0, 1] is None
|
| 71 |
+
assert grid[1, 1] == 1
|
| 72 |
+
assert grid[2, 1] == "two"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_DiagramGrid():
|
| 76 |
+
# Set up some objects and morphisms.
|
| 77 |
+
A = Object("A")
|
| 78 |
+
B = Object("B")
|
| 79 |
+
C = Object("C")
|
| 80 |
+
D = Object("D")
|
| 81 |
+
E = Object("E")
|
| 82 |
+
|
| 83 |
+
f = NamedMorphism(A, B, "f")
|
| 84 |
+
g = NamedMorphism(B, C, "g")
|
| 85 |
+
h = NamedMorphism(D, A, "h")
|
| 86 |
+
k = NamedMorphism(D, B, "k")
|
| 87 |
+
|
| 88 |
+
# A one-morphism diagram.
|
| 89 |
+
d = Diagram([f])
|
| 90 |
+
grid = DiagramGrid(d)
|
| 91 |
+
|
| 92 |
+
assert grid.width == 2
|
| 93 |
+
assert grid.height == 1
|
| 94 |
+
assert grid[0, 0] == A
|
| 95 |
+
assert grid[0, 1] == B
|
| 96 |
+
assert grid.morphisms == {f: FiniteSet()}
|
| 97 |
+
|
| 98 |
+
# A triangle.
|
| 99 |
+
d = Diagram([f, g], {g * f: "unique"})
|
| 100 |
+
grid = DiagramGrid(d)
|
| 101 |
+
|
| 102 |
+
assert grid.width == 2
|
| 103 |
+
assert grid.height == 2
|
| 104 |
+
assert grid[0, 0] == A
|
| 105 |
+
assert grid[0, 1] == B
|
| 106 |
+
assert grid[1, 0] == C
|
| 107 |
+
assert grid[1, 1] is None
|
| 108 |
+
assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(),
|
| 109 |
+
g * f: FiniteSet("unique")}
|
| 110 |
+
|
| 111 |
+
# A triangle with a "loop" morphism.
|
| 112 |
+
l_A = NamedMorphism(A, A, "l_A")
|
| 113 |
+
d = Diagram([f, g, l_A])
|
| 114 |
+
grid = DiagramGrid(d)
|
| 115 |
+
|
| 116 |
+
assert grid.width == 2
|
| 117 |
+
assert grid.height == 2
|
| 118 |
+
assert grid[0, 0] == A
|
| 119 |
+
assert grid[0, 1] == B
|
| 120 |
+
assert grid[1, 0] is None
|
| 121 |
+
assert grid[1, 1] == C
|
| 122 |
+
assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), l_A: FiniteSet()}
|
| 123 |
+
|
| 124 |
+
# A simple diagram.
|
| 125 |
+
d = Diagram([f, g, h, k])
|
| 126 |
+
grid = DiagramGrid(d)
|
| 127 |
+
|
| 128 |
+
assert grid.width == 3
|
| 129 |
+
assert grid.height == 2
|
| 130 |
+
assert grid[0, 0] == A
|
| 131 |
+
assert grid[0, 1] == B
|
| 132 |
+
assert grid[0, 2] == D
|
| 133 |
+
assert grid[1, 0] is None
|
| 134 |
+
assert grid[1, 1] == C
|
| 135 |
+
assert grid[1, 2] is None
|
| 136 |
+
assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
|
| 137 |
+
k: FiniteSet()}
|
| 138 |
+
|
| 139 |
+
assert str(grid) == '[[Object("A"), Object("B"), Object("D")], ' \
|
| 140 |
+
'[None, Object("C"), None]]'
|
| 141 |
+
|
| 142 |
+
# A chain of morphisms.
|
| 143 |
+
f = NamedMorphism(A, B, "f")
|
| 144 |
+
g = NamedMorphism(B, C, "g")
|
| 145 |
+
h = NamedMorphism(C, D, "h")
|
| 146 |
+
k = NamedMorphism(D, E, "k")
|
| 147 |
+
d = Diagram([f, g, h, k])
|
| 148 |
+
grid = DiagramGrid(d)
|
| 149 |
+
|
| 150 |
+
assert grid.width == 3
|
| 151 |
+
assert grid.height == 3
|
| 152 |
+
assert grid[0, 0] == A
|
| 153 |
+
assert grid[0, 1] == B
|
| 154 |
+
assert grid[0, 2] is None
|
| 155 |
+
assert grid[1, 0] is None
|
| 156 |
+
assert grid[1, 1] == C
|
| 157 |
+
assert grid[1, 2] == D
|
| 158 |
+
assert grid[2, 0] is None
|
| 159 |
+
assert grid[2, 1] is None
|
| 160 |
+
assert grid[2, 2] == E
|
| 161 |
+
assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
|
| 162 |
+
k: FiniteSet()}
|
| 163 |
+
|
| 164 |
+
# A square.
|
| 165 |
+
f = NamedMorphism(A, B, "f")
|
| 166 |
+
g = NamedMorphism(B, D, "g")
|
| 167 |
+
h = NamedMorphism(A, C, "h")
|
| 168 |
+
k = NamedMorphism(C, D, "k")
|
| 169 |
+
d = Diagram([f, g, h, k])
|
| 170 |
+
grid = DiagramGrid(d)
|
| 171 |
+
|
| 172 |
+
assert grid.width == 2
|
| 173 |
+
assert grid.height == 2
|
| 174 |
+
assert grid[0, 0] == A
|
| 175 |
+
assert grid[0, 1] == B
|
| 176 |
+
assert grid[1, 0] == C
|
| 177 |
+
assert grid[1, 1] == D
|
| 178 |
+
assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
|
| 179 |
+
k: FiniteSet()}
|
| 180 |
+
|
| 181 |
+
# A strange diagram which resulted from a typo when creating a
|
| 182 |
+
# test for five lemma, but which allowed to stop one extra problem
|
| 183 |
+
# in the algorithm.
|
| 184 |
+
A = Object("A")
|
| 185 |
+
B = Object("B")
|
| 186 |
+
C = Object("C")
|
| 187 |
+
D = Object("D")
|
| 188 |
+
E = Object("E")
|
| 189 |
+
A_ = Object("A'")
|
| 190 |
+
B_ = Object("B'")
|
| 191 |
+
C_ = Object("C'")
|
| 192 |
+
D_ = Object("D'")
|
| 193 |
+
E_ = Object("E'")
|
| 194 |
+
|
| 195 |
+
f = NamedMorphism(A, B, "f")
|
| 196 |
+
g = NamedMorphism(B, C, "g")
|
| 197 |
+
h = NamedMorphism(C, D, "h")
|
| 198 |
+
i = NamedMorphism(D, E, "i")
|
| 199 |
+
|
| 200 |
+
# These 4 morphisms should be between primed objects.
|
| 201 |
+
j = NamedMorphism(A, B, "j")
|
| 202 |
+
k = NamedMorphism(B, C, "k")
|
| 203 |
+
l = NamedMorphism(C, D, "l")
|
| 204 |
+
m = NamedMorphism(D, E, "m")
|
| 205 |
+
|
| 206 |
+
o = NamedMorphism(A, A_, "o")
|
| 207 |
+
p = NamedMorphism(B, B_, "p")
|
| 208 |
+
q = NamedMorphism(C, C_, "q")
|
| 209 |
+
r = NamedMorphism(D, D_, "r")
|
| 210 |
+
s = NamedMorphism(E, E_, "s")
|
| 211 |
+
|
| 212 |
+
d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s])
|
| 213 |
+
grid = DiagramGrid(d)
|
| 214 |
+
|
| 215 |
+
assert grid.width == 3
|
| 216 |
+
assert grid.height == 4
|
| 217 |
+
assert grid[0, 0] is None
|
| 218 |
+
assert grid[0, 1] == A
|
| 219 |
+
assert grid[0, 2] == A_
|
| 220 |
+
assert grid[1, 0] == C
|
| 221 |
+
assert grid[1, 1] == B
|
| 222 |
+
assert grid[1, 2] == B_
|
| 223 |
+
assert grid[2, 0] == C_
|
| 224 |
+
assert grid[2, 1] == D
|
| 225 |
+
assert grid[2, 2] == D_
|
| 226 |
+
assert grid[3, 0] is None
|
| 227 |
+
assert grid[3, 1] == E
|
| 228 |
+
assert grid[3, 2] == E_
|
| 229 |
+
|
| 230 |
+
morphisms = {}
|
| 231 |
+
for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]:
|
| 232 |
+
morphisms[m] = FiniteSet()
|
| 233 |
+
assert grid.morphisms == morphisms
|
| 234 |
+
|
| 235 |
+
# A cube.
|
| 236 |
+
A1 = Object("A1")
|
| 237 |
+
A2 = Object("A2")
|
| 238 |
+
A3 = Object("A3")
|
| 239 |
+
A4 = Object("A4")
|
| 240 |
+
A5 = Object("A5")
|
| 241 |
+
A6 = Object("A6")
|
| 242 |
+
A7 = Object("A7")
|
| 243 |
+
A8 = Object("A8")
|
| 244 |
+
|
| 245 |
+
# The top face of the cube.
|
| 246 |
+
f1 = NamedMorphism(A1, A2, "f1")
|
| 247 |
+
f2 = NamedMorphism(A1, A3, "f2")
|
| 248 |
+
f3 = NamedMorphism(A2, A4, "f3")
|
| 249 |
+
f4 = NamedMorphism(A3, A4, "f3")
|
| 250 |
+
|
| 251 |
+
# The bottom face of the cube.
|
| 252 |
+
f5 = NamedMorphism(A5, A6, "f5")
|
| 253 |
+
f6 = NamedMorphism(A5, A7, "f6")
|
| 254 |
+
f7 = NamedMorphism(A6, A8, "f7")
|
| 255 |
+
f8 = NamedMorphism(A7, A8, "f8")
|
| 256 |
+
|
| 257 |
+
# The remaining morphisms.
|
| 258 |
+
f9 = NamedMorphism(A1, A5, "f9")
|
| 259 |
+
f10 = NamedMorphism(A2, A6, "f10")
|
| 260 |
+
f11 = NamedMorphism(A3, A7, "f11")
|
| 261 |
+
f12 = NamedMorphism(A4, A8, "f11")
|
| 262 |
+
|
| 263 |
+
d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12])
|
| 264 |
+
grid = DiagramGrid(d)
|
| 265 |
+
|
| 266 |
+
assert grid.width == 4
|
| 267 |
+
assert grid.height == 3
|
| 268 |
+
assert grid[0, 0] is None
|
| 269 |
+
assert grid[0, 1] == A5
|
| 270 |
+
assert grid[0, 2] == A6
|
| 271 |
+
assert grid[0, 3] is None
|
| 272 |
+
assert grid[1, 0] is None
|
| 273 |
+
assert grid[1, 1] == A1
|
| 274 |
+
assert grid[1, 2] == A2
|
| 275 |
+
assert grid[1, 3] is None
|
| 276 |
+
assert grid[2, 0] == A7
|
| 277 |
+
assert grid[2, 1] == A3
|
| 278 |
+
assert grid[2, 2] == A4
|
| 279 |
+
assert grid[2, 3] == A8
|
| 280 |
+
|
| 281 |
+
morphisms = {}
|
| 282 |
+
for m in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12]:
|
| 283 |
+
morphisms[m] = FiniteSet()
|
| 284 |
+
assert grid.morphisms == morphisms
|
| 285 |
+
|
| 286 |
+
# A line diagram.
|
| 287 |
+
A = Object("A")
|
| 288 |
+
B = Object("B")
|
| 289 |
+
C = Object("C")
|
| 290 |
+
D = Object("D")
|
| 291 |
+
E = Object("E")
|
| 292 |
+
|
| 293 |
+
f = NamedMorphism(A, B, "f")
|
| 294 |
+
g = NamedMorphism(B, C, "g")
|
| 295 |
+
h = NamedMorphism(C, D, "h")
|
| 296 |
+
i = NamedMorphism(D, E, "i")
|
| 297 |
+
d = Diagram([f, g, h, i])
|
| 298 |
+
grid = DiagramGrid(d, layout="sequential")
|
| 299 |
+
|
| 300 |
+
assert grid.width == 5
|
| 301 |
+
assert grid.height == 1
|
| 302 |
+
assert grid[0, 0] == A
|
| 303 |
+
assert grid[0, 1] == B
|
| 304 |
+
assert grid[0, 2] == C
|
| 305 |
+
assert grid[0, 3] == D
|
| 306 |
+
assert grid[0, 4] == E
|
| 307 |
+
assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
|
| 308 |
+
i: FiniteSet()}
|
| 309 |
+
|
| 310 |
+
# Test the transposed version.
|
| 311 |
+
grid = DiagramGrid(d, layout="sequential", transpose=True)
|
| 312 |
+
|
| 313 |
+
assert grid.width == 1
|
| 314 |
+
assert grid.height == 5
|
| 315 |
+
assert grid[0, 0] == A
|
| 316 |
+
assert grid[1, 0] == B
|
| 317 |
+
assert grid[2, 0] == C
|
| 318 |
+
assert grid[3, 0] == D
|
| 319 |
+
assert grid[4, 0] == E
|
| 320 |
+
assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
|
| 321 |
+
i: FiniteSet()}
|
| 322 |
+
|
| 323 |
+
# A pullback.
|
| 324 |
+
m1 = NamedMorphism(A, B, "m1")
|
| 325 |
+
m2 = NamedMorphism(A, C, "m2")
|
| 326 |
+
s1 = NamedMorphism(B, D, "s1")
|
| 327 |
+
s2 = NamedMorphism(C, D, "s2")
|
| 328 |
+
f1 = NamedMorphism(E, B, "f1")
|
| 329 |
+
f2 = NamedMorphism(E, C, "f2")
|
| 330 |
+
g = NamedMorphism(E, A, "g")
|
| 331 |
+
|
| 332 |
+
d = Diagram([m1, m2, s1, s2, f1, f2], {g: "unique"})
|
| 333 |
+
grid = DiagramGrid(d)
|
| 334 |
+
|
| 335 |
+
assert grid.width == 3
|
| 336 |
+
assert grid.height == 2
|
| 337 |
+
assert grid[0, 0] == A
|
| 338 |
+
assert grid[0, 1] == B
|
| 339 |
+
assert grid[0, 2] == E
|
| 340 |
+
assert grid[1, 0] == C
|
| 341 |
+
assert grid[1, 1] == D
|
| 342 |
+
assert grid[1, 2] is None
|
| 343 |
+
|
| 344 |
+
morphisms = {g: FiniteSet("unique")}
|
| 345 |
+
for m in [m1, m2, s1, s2, f1, f2]:
|
| 346 |
+
morphisms[m] = FiniteSet()
|
| 347 |
+
assert grid.morphisms == morphisms
|
| 348 |
+
|
| 349 |
+
# Test the pullback with sequential layout, just for stress
|
| 350 |
+
# testing.
|
| 351 |
+
grid = DiagramGrid(d, layout="sequential")
|
| 352 |
+
|
| 353 |
+
assert grid.width == 5
|
| 354 |
+
assert grid.height == 1
|
| 355 |
+
assert grid[0, 0] == D
|
| 356 |
+
assert grid[0, 1] == B
|
| 357 |
+
assert grid[0, 2] == A
|
| 358 |
+
assert grid[0, 3] == C
|
| 359 |
+
assert grid[0, 4] == E
|
| 360 |
+
assert grid.morphisms == morphisms
|
| 361 |
+
|
| 362 |
+
# Test a pullback with object grouping.
|
| 363 |
+
grid = DiagramGrid(d, groups=FiniteSet(E, FiniteSet(A, B, C, D)))
|
| 364 |
+
|
| 365 |
+
assert grid.width == 3
|
| 366 |
+
assert grid.height == 2
|
| 367 |
+
assert grid[0, 0] == E
|
| 368 |
+
assert grid[0, 1] == A
|
| 369 |
+
assert grid[0, 2] == B
|
| 370 |
+
assert grid[1, 0] is None
|
| 371 |
+
assert grid[1, 1] == C
|
| 372 |
+
assert grid[1, 2] == D
|
| 373 |
+
assert grid.morphisms == morphisms
|
| 374 |
+
|
| 375 |
+
# Five lemma, actually.
|
| 376 |
+
A = Object("A")
|
| 377 |
+
B = Object("B")
|
| 378 |
+
C = Object("C")
|
| 379 |
+
D = Object("D")
|
| 380 |
+
E = Object("E")
|
| 381 |
+
A_ = Object("A'")
|
| 382 |
+
B_ = Object("B'")
|
| 383 |
+
C_ = Object("C'")
|
| 384 |
+
D_ = Object("D'")
|
| 385 |
+
E_ = Object("E'")
|
| 386 |
+
|
| 387 |
+
f = NamedMorphism(A, B, "f")
|
| 388 |
+
g = NamedMorphism(B, C, "g")
|
| 389 |
+
h = NamedMorphism(C, D, "h")
|
| 390 |
+
i = NamedMorphism(D, E, "i")
|
| 391 |
+
|
| 392 |
+
j = NamedMorphism(A_, B_, "j")
|
| 393 |
+
k = NamedMorphism(B_, C_, "k")
|
| 394 |
+
l = NamedMorphism(C_, D_, "l")
|
| 395 |
+
m = NamedMorphism(D_, E_, "m")
|
| 396 |
+
|
| 397 |
+
o = NamedMorphism(A, A_, "o")
|
| 398 |
+
p = NamedMorphism(B, B_, "p")
|
| 399 |
+
q = NamedMorphism(C, C_, "q")
|
| 400 |
+
r = NamedMorphism(D, D_, "r")
|
| 401 |
+
s = NamedMorphism(E, E_, "s")
|
| 402 |
+
|
| 403 |
+
d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s])
|
| 404 |
+
grid = DiagramGrid(d)
|
| 405 |
+
|
| 406 |
+
assert grid.width == 5
|
| 407 |
+
assert grid.height == 3
|
| 408 |
+
assert grid[0, 0] is None
|
| 409 |
+
assert grid[0, 1] == A
|
| 410 |
+
assert grid[0, 2] == A_
|
| 411 |
+
assert grid[0, 3] is None
|
| 412 |
+
assert grid[0, 4] is None
|
| 413 |
+
assert grid[1, 0] == C
|
| 414 |
+
assert grid[1, 1] == B
|
| 415 |
+
assert grid[1, 2] == B_
|
| 416 |
+
assert grid[1, 3] == C_
|
| 417 |
+
assert grid[1, 4] is None
|
| 418 |
+
assert grid[2, 0] == D
|
| 419 |
+
assert grid[2, 1] == E
|
| 420 |
+
assert grid[2, 2] is None
|
| 421 |
+
assert grid[2, 3] == D_
|
| 422 |
+
assert grid[2, 4] == E_
|
| 423 |
+
|
| 424 |
+
morphisms = {}
|
| 425 |
+
for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]:
|
| 426 |
+
morphisms[m] = FiniteSet()
|
| 427 |
+
assert grid.morphisms == morphisms
|
| 428 |
+
|
| 429 |
+
# Test the five lemma with object grouping.
|
| 430 |
+
grid = DiagramGrid(d, FiniteSet(
|
| 431 |
+
FiniteSet(A, B, C, D, E), FiniteSet(A_, B_, C_, D_, E_)))
|
| 432 |
+
|
| 433 |
+
assert grid.width == 6
|
| 434 |
+
assert grid.height == 3
|
| 435 |
+
assert grid[0, 0] == A
|
| 436 |
+
assert grid[0, 1] == B
|
| 437 |
+
assert grid[0, 2] is None
|
| 438 |
+
assert grid[0, 3] == A_
|
| 439 |
+
assert grid[0, 4] == B_
|
| 440 |
+
assert grid[0, 5] is None
|
| 441 |
+
assert grid[1, 0] is None
|
| 442 |
+
assert grid[1, 1] == C
|
| 443 |
+
assert grid[1, 2] == D
|
| 444 |
+
assert grid[1, 3] is None
|
| 445 |
+
assert grid[1, 4] == C_
|
| 446 |
+
assert grid[1, 5] == D_
|
| 447 |
+
assert grid[2, 0] is None
|
| 448 |
+
assert grid[2, 1] is None
|
| 449 |
+
assert grid[2, 2] == E
|
| 450 |
+
assert grid[2, 3] is None
|
| 451 |
+
assert grid[2, 4] is None
|
| 452 |
+
assert grid[2, 5] == E_
|
| 453 |
+
assert grid.morphisms == morphisms
|
| 454 |
+
|
| 455 |
+
# Test the five lemma with object grouping, but mixing containers
|
| 456 |
+
# to represent groups.
|
| 457 |
+
grid = DiagramGrid(d, [(A, B, C, D, E), {A_, B_, C_, D_, E_}])
|
| 458 |
+
|
| 459 |
+
assert grid.width == 6
|
| 460 |
+
assert grid.height == 3
|
| 461 |
+
assert grid[0, 0] == A
|
| 462 |
+
assert grid[0, 1] == B
|
| 463 |
+
assert grid[0, 2] is None
|
| 464 |
+
assert grid[0, 3] == A_
|
| 465 |
+
assert grid[0, 4] == B_
|
| 466 |
+
assert grid[0, 5] is None
|
| 467 |
+
assert grid[1, 0] is None
|
| 468 |
+
assert grid[1, 1] == C
|
| 469 |
+
assert grid[1, 2] == D
|
| 470 |
+
assert grid[1, 3] is None
|
| 471 |
+
assert grid[1, 4] == C_
|
| 472 |
+
assert grid[1, 5] == D_
|
| 473 |
+
assert grid[2, 0] is None
|
| 474 |
+
assert grid[2, 1] is None
|
| 475 |
+
assert grid[2, 2] == E
|
| 476 |
+
assert grid[2, 3] is None
|
| 477 |
+
assert grid[2, 4] is None
|
| 478 |
+
assert grid[2, 5] == E_
|
| 479 |
+
assert grid.morphisms == morphisms
|
| 480 |
+
|
| 481 |
+
# Test the five lemma with object grouping and hints.
|
| 482 |
+
grid = DiagramGrid(d, {
|
| 483 |
+
FiniteSet(A, B, C, D, E): {"layout": "sequential",
|
| 484 |
+
"transpose": True},
|
| 485 |
+
FiniteSet(A_, B_, C_, D_, E_): {"layout": "sequential",
|
| 486 |
+
"transpose": True}},
|
| 487 |
+
transpose=True)
|
| 488 |
+
|
| 489 |
+
assert grid.width == 5
|
| 490 |
+
assert grid.height == 2
|
| 491 |
+
assert grid[0, 0] == A
|
| 492 |
+
assert grid[0, 1] == B
|
| 493 |
+
assert grid[0, 2] == C
|
| 494 |
+
assert grid[0, 3] == D
|
| 495 |
+
assert grid[0, 4] == E
|
| 496 |
+
assert grid[1, 0] == A_
|
| 497 |
+
assert grid[1, 1] == B_
|
| 498 |
+
assert grid[1, 2] == C_
|
| 499 |
+
assert grid[1, 3] == D_
|
| 500 |
+
assert grid[1, 4] == E_
|
| 501 |
+
assert grid.morphisms == morphisms
|
| 502 |
+
|
| 503 |
+
# A two-triangle disconnected diagram.
|
| 504 |
+
f = NamedMorphism(A, B, "f")
|
| 505 |
+
g = NamedMorphism(B, C, "g")
|
| 506 |
+
f_ = NamedMorphism(A_, B_, "f")
|
| 507 |
+
g_ = NamedMorphism(B_, C_, "g")
|
| 508 |
+
d = Diagram([f, g, f_, g_], {g * f: "unique", g_ * f_: "unique"})
|
| 509 |
+
grid = DiagramGrid(d)
|
| 510 |
+
|
| 511 |
+
assert grid.width == 4
|
| 512 |
+
assert grid.height == 2
|
| 513 |
+
assert grid[0, 0] == A
|
| 514 |
+
assert grid[0, 1] == B
|
| 515 |
+
assert grid[0, 2] == A_
|
| 516 |
+
assert grid[0, 3] == B_
|
| 517 |
+
assert grid[1, 0] == C
|
| 518 |
+
assert grid[1, 1] is None
|
| 519 |
+
assert grid[1, 2] == C_
|
| 520 |
+
assert grid[1, 3] is None
|
| 521 |
+
assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), f_: FiniteSet(),
|
| 522 |
+
g_: FiniteSet(), g * f: FiniteSet("unique"),
|
| 523 |
+
g_ * f_: FiniteSet("unique")}
|
| 524 |
+
|
| 525 |
+
# A two-morphism disconnected diagram.
|
| 526 |
+
f = NamedMorphism(A, B, "f")
|
| 527 |
+
g = NamedMorphism(C, D, "g")
|
| 528 |
+
d = Diagram([f, g])
|
| 529 |
+
grid = DiagramGrid(d)
|
| 530 |
+
|
| 531 |
+
assert grid.width == 4
|
| 532 |
+
assert grid.height == 1
|
| 533 |
+
assert grid[0, 0] == A
|
| 534 |
+
assert grid[0, 1] == B
|
| 535 |
+
assert grid[0, 2] == C
|
| 536 |
+
assert grid[0, 3] == D
|
| 537 |
+
assert grid.morphisms == {f: FiniteSet(), g: FiniteSet()}
|
| 538 |
+
|
| 539 |
+
# Test a one-object diagram.
|
| 540 |
+
f = NamedMorphism(A, A, "f")
|
| 541 |
+
d = Diagram([f])
|
| 542 |
+
grid = DiagramGrid(d)
|
| 543 |
+
|
| 544 |
+
assert grid.width == 1
|
| 545 |
+
assert grid.height == 1
|
| 546 |
+
assert grid[0, 0] == A
|
| 547 |
+
|
| 548 |
+
# Test a two-object disconnected diagram.
|
| 549 |
+
g = NamedMorphism(B, B, "g")
|
| 550 |
+
d = Diagram([f, g])
|
| 551 |
+
grid = DiagramGrid(d)
|
| 552 |
+
|
| 553 |
+
assert grid.width == 2
|
| 554 |
+
assert grid.height == 1
|
| 555 |
+
assert grid[0, 0] == A
|
| 556 |
+
assert grid[0, 1] == B
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def test_DiagramGrid_pseudopod():
|
| 560 |
+
# Test a diagram in which even growing a pseudopod does not
|
| 561 |
+
# eventually help.
|
| 562 |
+
A = Object("A")
|
| 563 |
+
B = Object("B")
|
| 564 |
+
C = Object("C")
|
| 565 |
+
D = Object("D")
|
| 566 |
+
E = Object("E")
|
| 567 |
+
F = Object("F")
|
| 568 |
+
A_ = Object("A'")
|
| 569 |
+
B_ = Object("B'")
|
| 570 |
+
C_ = Object("C'")
|
| 571 |
+
D_ = Object("D'")
|
| 572 |
+
E_ = Object("E'")
|
| 573 |
+
|
| 574 |
+
f1 = NamedMorphism(A, B, "f1")
|
| 575 |
+
f2 = NamedMorphism(A, C, "f2")
|
| 576 |
+
f3 = NamedMorphism(A, D, "f3")
|
| 577 |
+
f4 = NamedMorphism(A, E, "f4")
|
| 578 |
+
f5 = NamedMorphism(A, A_, "f5")
|
| 579 |
+
f6 = NamedMorphism(A, B_, "f6")
|
| 580 |
+
f7 = NamedMorphism(A, C_, "f7")
|
| 581 |
+
f8 = NamedMorphism(A, D_, "f8")
|
| 582 |
+
f9 = NamedMorphism(A, E_, "f9")
|
| 583 |
+
f10 = NamedMorphism(A, F, "f10")
|
| 584 |
+
d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10])
|
| 585 |
+
grid = DiagramGrid(d)
|
| 586 |
+
|
| 587 |
+
assert grid.width == 5
|
| 588 |
+
assert grid.height == 3
|
| 589 |
+
assert grid[0, 0] == E
|
| 590 |
+
assert grid[0, 1] == C
|
| 591 |
+
assert grid[0, 2] == C_
|
| 592 |
+
assert grid[0, 3] == E_
|
| 593 |
+
assert grid[0, 4] == F
|
| 594 |
+
assert grid[1, 0] == D
|
| 595 |
+
assert grid[1, 1] == A
|
| 596 |
+
assert grid[1, 2] == A_
|
| 597 |
+
assert grid[1, 3] is None
|
| 598 |
+
assert grid[1, 4] is None
|
| 599 |
+
assert grid[2, 0] == D_
|
| 600 |
+
assert grid[2, 1] == B
|
| 601 |
+
assert grid[2, 2] == B_
|
| 602 |
+
assert grid[2, 3] is None
|
| 603 |
+
assert grid[2, 4] is None
|
| 604 |
+
|
| 605 |
+
morphisms = {}
|
| 606 |
+
for f in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]:
|
| 607 |
+
morphisms[f] = FiniteSet()
|
| 608 |
+
assert grid.morphisms == morphisms
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def test_ArrowStringDescription():
|
| 612 |
+
astr = ArrowStringDescription("cm", "", None, "", "", "d", "r", "_", "f")
|
| 613 |
+
assert str(astr) == "\\ar[dr]_{f}"
|
| 614 |
+
|
| 615 |
+
astr = ArrowStringDescription("cm", "", 12, "", "", "d", "r", "_", "f")
|
| 616 |
+
assert str(astr) == "\\ar[dr]_{f}"
|
| 617 |
+
|
| 618 |
+
astr = ArrowStringDescription("cm", "^", 12, "", "", "d", "r", "_", "f")
|
| 619 |
+
assert str(astr) == "\\ar@/^12cm/[dr]_{f}"
|
| 620 |
+
|
| 621 |
+
astr = ArrowStringDescription("cm", "", 12, "r", "", "d", "r", "_", "f")
|
| 622 |
+
assert str(astr) == "\\ar[dr]_{f}"
|
| 623 |
+
|
| 624 |
+
astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
|
| 625 |
+
assert str(astr) == "\\ar@(r,u)[dr]_{f}"
|
| 626 |
+
|
| 627 |
+
astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
|
| 628 |
+
assert str(astr) == "\\ar@(r,u)[dr]_{f}"
|
| 629 |
+
|
| 630 |
+
astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
|
| 631 |
+
astr.arrow_style = "{-->}"
|
| 632 |
+
assert str(astr) == "\\ar@(r,u)@{-->}[dr]_{f}"
|
| 633 |
+
|
| 634 |
+
astr = ArrowStringDescription("cm", "_", 12, "", "", "d", "r", "_", "f")
|
| 635 |
+
astr.arrow_style = "{-->}"
|
| 636 |
+
assert str(astr) == "\\ar@/_12cm/@{-->}[dr]_{f}"
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def test_XypicDiagramDrawer_line():
|
| 640 |
+
# A linear diagram.
|
| 641 |
+
A = Object("A")
|
| 642 |
+
B = Object("B")
|
| 643 |
+
C = Object("C")
|
| 644 |
+
D = Object("D")
|
| 645 |
+
E = Object("E")
|
| 646 |
+
|
| 647 |
+
f = NamedMorphism(A, B, "f")
|
| 648 |
+
g = NamedMorphism(B, C, "g")
|
| 649 |
+
h = NamedMorphism(C, D, "h")
|
| 650 |
+
i = NamedMorphism(D, E, "i")
|
| 651 |
+
d = Diagram([f, g, h, i])
|
| 652 |
+
grid = DiagramGrid(d, layout="sequential")
|
| 653 |
+
drawer = XypicDiagramDrawer()
|
| 654 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 655 |
+
"A \\ar[r]^{f} & B \\ar[r]^{g} & C \\ar[r]^{h} & D \\ar[r]^{i} & E \n" \
|
| 656 |
+
"}\n"
|
| 657 |
+
|
| 658 |
+
# The same diagram, transposed.
|
| 659 |
+
grid = DiagramGrid(d, layout="sequential", transpose=True)
|
| 660 |
+
drawer = XypicDiagramDrawer()
|
| 661 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 662 |
+
"A \\ar[d]^{f} \\\\\n" \
|
| 663 |
+
"B \\ar[d]^{g} \\\\\n" \
|
| 664 |
+
"C \\ar[d]^{h} \\\\\n" \
|
| 665 |
+
"D \\ar[d]^{i} \\\\\n" \
|
| 666 |
+
"E \n" \
|
| 667 |
+
"}\n"
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def test_XypicDiagramDrawer_triangle():
|
| 671 |
+
# A triangle diagram.
|
| 672 |
+
A = Object("A")
|
| 673 |
+
B = Object("B")
|
| 674 |
+
C = Object("C")
|
| 675 |
+
f = NamedMorphism(A, B, "f")
|
| 676 |
+
g = NamedMorphism(B, C, "g")
|
| 677 |
+
|
| 678 |
+
d = Diagram([f, g], {g * f: "unique"})
|
| 679 |
+
grid = DiagramGrid(d)
|
| 680 |
+
drawer = XypicDiagramDrawer()
|
| 681 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 682 |
+
"A \\ar[d]_{g\\circ f} \\ar[r]^{f} & B \\ar[ld]^{g} \\\\\n" \
|
| 683 |
+
"C & \n" \
|
| 684 |
+
"}\n"
|
| 685 |
+
|
| 686 |
+
# The same diagram, transposed.
|
| 687 |
+
grid = DiagramGrid(d, transpose=True)
|
| 688 |
+
drawer = XypicDiagramDrawer()
|
| 689 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 690 |
+
"A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \
|
| 691 |
+
"B \\ar[ru]_{g} & \n" \
|
| 692 |
+
"}\n"
|
| 693 |
+
|
| 694 |
+
# The same diagram, with a masked morphism.
|
| 695 |
+
assert drawer.draw(d, grid, masked=[g]) == "\\xymatrix{\n" \
|
| 696 |
+
"A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \
|
| 697 |
+
"B & \n" \
|
| 698 |
+
"}\n"
|
| 699 |
+
|
| 700 |
+
# The same diagram with a formatter for "unique".
|
| 701 |
+
def formatter(astr):
|
| 702 |
+
astr.label = "\\exists !" + astr.label
|
| 703 |
+
astr.arrow_style = "{-->}"
|
| 704 |
+
|
| 705 |
+
drawer.arrow_formatters["unique"] = formatter
|
| 706 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 707 |
+
"A \\ar@{-->}[r]^{\\exists !g\\circ f} \\ar[d]_{f} & C \\\\\n" \
|
| 708 |
+
"B \\ar[ru]_{g} & \n" \
|
| 709 |
+
"}\n"
|
| 710 |
+
|
| 711 |
+
# The same diagram with a default formatter.
|
| 712 |
+
def default_formatter(astr):
|
| 713 |
+
astr.label_displacement = "(0.45)"
|
| 714 |
+
|
| 715 |
+
drawer.default_arrow_formatter = default_formatter
|
| 716 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 717 |
+
"A \\ar@{-->}[r]^(0.45){\\exists !g\\circ f} \\ar[d]_(0.45){f} & C \\\\\n" \
|
| 718 |
+
"B \\ar[ru]_(0.45){g} & \n" \
|
| 719 |
+
"}\n"
|
| 720 |
+
|
| 721 |
+
# A triangle diagram with a lot of morphisms between the same
|
| 722 |
+
# objects.
|
| 723 |
+
f1 = NamedMorphism(B, A, "f1")
|
| 724 |
+
f2 = NamedMorphism(A, B, "f2")
|
| 725 |
+
g1 = NamedMorphism(C, B, "g1")
|
| 726 |
+
g2 = NamedMorphism(B, C, "g2")
|
| 727 |
+
d = Diagram([f, f1, f2, g, g1, g2], {f1 * g1: "unique", g2 * f2: "unique"})
|
| 728 |
+
|
| 729 |
+
grid = DiagramGrid(d, transpose=True)
|
| 730 |
+
drawer = XypicDiagramDrawer()
|
| 731 |
+
assert drawer.draw(d, grid, masked=[f1*g1*g2*f2, g2*f2*f1*g1]) == \
|
| 732 |
+
"\\xymatrix{\n" \
|
| 733 |
+
"A \\ar[r]^{g_{2}\\circ f_{2}} \\ar[d]_{f} \\ar@/^3mm/[d]^{f_{2}} " \
|
| 734 |
+
"& C \\ar@/^3mm/[l]^{f_{1}\\circ g_{1}} \\ar@/^3mm/[ld]^{g_{1}} \\\\\n" \
|
| 735 |
+
"B \\ar@/^3mm/[u]^{f_{1}} \\ar[ru]_{g} \\ar@/^3mm/[ru]^{g_{2}} & \n" \
|
| 736 |
+
"}\n"
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def test_XypicDiagramDrawer_cube():
|
| 740 |
+
# A cube diagram.
|
| 741 |
+
A1 = Object("A1")
|
| 742 |
+
A2 = Object("A2")
|
| 743 |
+
A3 = Object("A3")
|
| 744 |
+
A4 = Object("A4")
|
| 745 |
+
A5 = Object("A5")
|
| 746 |
+
A6 = Object("A6")
|
| 747 |
+
A7 = Object("A7")
|
| 748 |
+
A8 = Object("A8")
|
| 749 |
+
|
| 750 |
+
# The top face of the cube.
|
| 751 |
+
f1 = NamedMorphism(A1, A2, "f1")
|
| 752 |
+
f2 = NamedMorphism(A1, A3, "f2")
|
| 753 |
+
f3 = NamedMorphism(A2, A4, "f3")
|
| 754 |
+
f4 = NamedMorphism(A3, A4, "f3")
|
| 755 |
+
|
| 756 |
+
# The bottom face of the cube.
|
| 757 |
+
f5 = NamedMorphism(A5, A6, "f5")
|
| 758 |
+
f6 = NamedMorphism(A5, A7, "f6")
|
| 759 |
+
f7 = NamedMorphism(A6, A8, "f7")
|
| 760 |
+
f8 = NamedMorphism(A7, A8, "f8")
|
| 761 |
+
|
| 762 |
+
# The remaining morphisms.
|
| 763 |
+
f9 = NamedMorphism(A1, A5, "f9")
|
| 764 |
+
f10 = NamedMorphism(A2, A6, "f10")
|
| 765 |
+
f11 = NamedMorphism(A3, A7, "f11")
|
| 766 |
+
f12 = NamedMorphism(A4, A8, "f11")
|
| 767 |
+
|
| 768 |
+
d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12])
|
| 769 |
+
grid = DiagramGrid(d)
|
| 770 |
+
drawer = XypicDiagramDrawer()
|
| 771 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 772 |
+
"& A_{5} \\ar[r]^{f_{5}} \\ar[ldd]_{f_{6}} & A_{6} \\ar[rdd]^{f_{7}} " \
|
| 773 |
+
"& \\\\\n" \
|
| 774 |
+
"& A_{1} \\ar[r]^{f_{1}} \\ar[d]^{f_{2}} \\ar[u]^{f_{9}} & A_{2} " \
|
| 775 |
+
"\\ar[d]^{f_{3}} \\ar[u]_{f_{10}} & \\\\\n" \
|
| 776 |
+
"A_{7} \\ar@/_3mm/[rrr]_{f_{8}} & A_{3} \\ar[r]^{f_{3}} \\ar[l]_{f_{11}} " \
|
| 777 |
+
"& A_{4} \\ar[r]^{f_{11}} & A_{8} \n" \
|
| 778 |
+
"}\n"
|
| 779 |
+
|
| 780 |
+
# The same diagram, transposed.
|
| 781 |
+
grid = DiagramGrid(d, transpose=True)
|
| 782 |
+
drawer = XypicDiagramDrawer()
|
| 783 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 784 |
+
"& & A_{7} \\ar@/^3mm/[ddd]^{f_{8}} \\\\\n" \
|
| 785 |
+
"A_{5} \\ar[d]_{f_{5}} \\ar[rru]^{f_{6}} & A_{1} \\ar[d]^{f_{1}} " \
|
| 786 |
+
"\\ar[r]^{f_{2}} \\ar[l]^{f_{9}} & A_{3} \\ar[d]_{f_{3}} " \
|
| 787 |
+
"\\ar[u]^{f_{11}} \\\\\n" \
|
| 788 |
+
"A_{6} \\ar[rrd]_{f_{7}} & A_{2} \\ar[r]^{f_{3}} \\ar[l]^{f_{10}} " \
|
| 789 |
+
"& A_{4} \\ar[d]_{f_{11}} \\\\\n" \
|
| 790 |
+
"& & A_{8} \n" \
|
| 791 |
+
"}\n"
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
def test_XypicDiagramDrawer_curved_and_loops():
|
| 795 |
+
# A simple diagram, with a curved arrow.
|
| 796 |
+
A = Object("A")
|
| 797 |
+
B = Object("B")
|
| 798 |
+
C = Object("C")
|
| 799 |
+
D = Object("D")
|
| 800 |
+
|
| 801 |
+
f = NamedMorphism(A, B, "f")
|
| 802 |
+
g = NamedMorphism(B, C, "g")
|
| 803 |
+
h = NamedMorphism(D, A, "h")
|
| 804 |
+
k = NamedMorphism(D, B, "k")
|
| 805 |
+
d = Diagram([f, g, h, k])
|
| 806 |
+
grid = DiagramGrid(d)
|
| 807 |
+
drawer = XypicDiagramDrawer()
|
| 808 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 809 |
+
"A \\ar[r]_{f} & B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_3mm/[ll]_{h} \\\\\n" \
|
| 810 |
+
"& C & \n" \
|
| 811 |
+
"}\n"
|
| 812 |
+
|
| 813 |
+
# The same diagram, transposed.
|
| 814 |
+
grid = DiagramGrid(d, transpose=True)
|
| 815 |
+
drawer = XypicDiagramDrawer()
|
| 816 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 817 |
+
"A \\ar[d]^{f} & \\\\\n" \
|
| 818 |
+
"B \\ar[r]^{g} & C \\\\\n" \
|
| 819 |
+
"D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \
|
| 820 |
+
"}\n"
|
| 821 |
+
|
| 822 |
+
# The same diagram, larger and rotated.
|
| 823 |
+
assert drawer.draw(d, grid, diagram_format="@+1cm@dr") == \
|
| 824 |
+
"\\xymatrix@+1cm@dr{\n" \
|
| 825 |
+
"A \\ar[d]^{f} & \\\\\n" \
|
| 826 |
+
"B \\ar[r]^{g} & C \\\\\n" \
|
| 827 |
+
"D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \
|
| 828 |
+
"}\n"
|
| 829 |
+
|
| 830 |
+
# A simple diagram with three curved arrows.
|
| 831 |
+
h1 = NamedMorphism(D, A, "h1")
|
| 832 |
+
h2 = NamedMorphism(A, D, "h2")
|
| 833 |
+
k = NamedMorphism(D, B, "k")
|
| 834 |
+
d = Diagram([f, g, h, k, h1, h2])
|
| 835 |
+
grid = DiagramGrid(d)
|
| 836 |
+
drawer = XypicDiagramDrawer()
|
| 837 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 838 |
+
"A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \
|
| 839 |
+
"\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\\\\n" \
|
| 840 |
+
"& C & \n" \
|
| 841 |
+
"}\n"
|
| 842 |
+
|
| 843 |
+
# The same diagram, transposed.
|
| 844 |
+
grid = DiagramGrid(d, transpose=True)
|
| 845 |
+
drawer = XypicDiagramDrawer()
|
| 846 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 847 |
+
"A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} & \\\\\n" \
|
| 848 |
+
"B \\ar[r]^{g} & C \\\\\n" \
|
| 849 |
+
"D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} & \n" \
|
| 850 |
+
"}\n"
|
| 851 |
+
|
| 852 |
+
# The same diagram, with "loop" morphisms.
|
| 853 |
+
l_A = NamedMorphism(A, A, "l_A")
|
| 854 |
+
l_D = NamedMorphism(D, D, "l_D")
|
| 855 |
+
l_C = NamedMorphism(C, C, "l_C")
|
| 856 |
+
d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C])
|
| 857 |
+
grid = DiagramGrid(d)
|
| 858 |
+
drawer = XypicDiagramDrawer()
|
| 859 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 860 |
+
"A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \
|
| 861 |
+
"& B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_7mm/[ll]_{h} " \
|
| 862 |
+
"\\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} \\\\\n" \
|
| 863 |
+
"& C \\ar@(l,d)[]^{l_{C}} & \n" \
|
| 864 |
+
"}\n"
|
| 865 |
+
|
| 866 |
+
# The same diagram with "loop" morphisms, transposed.
|
| 867 |
+
grid = DiagramGrid(d, transpose=True)
|
| 868 |
+
drawer = XypicDiagramDrawer()
|
| 869 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 870 |
+
"A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} & \\\\\n" \
|
| 871 |
+
"B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\\\\n" \
|
| 872 |
+
"D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \
|
| 873 |
+
"\\ar@(l,d)[]^{l_{D}} & \n" \
|
| 874 |
+
"}\n"
|
| 875 |
+
|
| 876 |
+
# The same diagram with two "loop" morphisms per object.
|
| 877 |
+
l_A_ = NamedMorphism(A, A, "n_A")
|
| 878 |
+
l_D_ = NamedMorphism(D, D, "n_D")
|
| 879 |
+
l_C_ = NamedMorphism(C, C, "n_C")
|
| 880 |
+
d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C, l_A_, l_D_, l_C_])
|
| 881 |
+
grid = DiagramGrid(d)
|
| 882 |
+
drawer = XypicDiagramDrawer()
|
| 883 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 884 |
+
"A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \
|
| 885 |
+
"\\ar@/^3mm/@(l,d)[]^{n_{A}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \
|
| 886 |
+
"\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} " \
|
| 887 |
+
"\\ar@/^3mm/@(d,r)[]^{n_{D}} \\\\\n" \
|
| 888 |
+
"& C \\ar@(l,d)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} & \n" \
|
| 889 |
+
"}\n"
|
| 890 |
+
|
| 891 |
+
# The same diagram with two "loop" morphisms per object, transposed.
|
| 892 |
+
grid = DiagramGrid(d, transpose=True)
|
| 893 |
+
drawer = XypicDiagramDrawer()
|
| 894 |
+
assert drawer.draw(d, grid) == "\\xymatrix{\n" \
|
| 895 |
+
"A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} " \
|
| 896 |
+
"\\ar@/^3mm/@(u,l)[]^{n_{A}} & \\\\\n" \
|
| 897 |
+
"B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} \\\\\n" \
|
| 898 |
+
"D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \
|
| 899 |
+
"\\ar@(l,d)[]^{l_{D}} \\ar@/^3mm/@(d,r)[]^{n_{D}} & \n" \
|
| 900 |
+
"}\n"
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
def test_xypic_draw_diagram():
|
| 904 |
+
# A linear diagram.
|
| 905 |
+
A = Object("A")
|
| 906 |
+
B = Object("B")
|
| 907 |
+
C = Object("C")
|
| 908 |
+
D = Object("D")
|
| 909 |
+
E = Object("E")
|
| 910 |
+
|
| 911 |
+
f = NamedMorphism(A, B, "f")
|
| 912 |
+
g = NamedMorphism(B, C, "g")
|
| 913 |
+
h = NamedMorphism(C, D, "h")
|
| 914 |
+
i = NamedMorphism(D, E, "i")
|
| 915 |
+
d = Diagram([f, g, h, i])
|
| 916 |
+
|
| 917 |
+
grid = DiagramGrid(d, layout="sequential")
|
| 918 |
+
drawer = XypicDiagramDrawer()
|
| 919 |
+
assert drawer.draw(d, grid) == xypic_draw_diagram(d, layout="sequential")
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .diffgeom import (
|
| 2 |
+
BaseCovarDerivativeOp, BaseScalarField, BaseVectorField, Commutator,
|
| 3 |
+
contravariant_order, CoordSystem, CoordinateSymbol,
|
| 4 |
+
CovarDerivativeOp, covariant_order, Differential, intcurve_diffequ,
|
| 5 |
+
intcurve_series, LieDerivative, Manifold, metric_to_Christoffel_1st,
|
| 6 |
+
metric_to_Christoffel_2nd, metric_to_Ricci_components,
|
| 7 |
+
metric_to_Riemann_components, Patch, Point, TensorProduct, twoform_to_matrix,
|
| 8 |
+
vectors_in_basis, WedgeProduct,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
'BaseCovarDerivativeOp', 'BaseScalarField', 'BaseVectorField', 'Commutator',
|
| 13 |
+
'contravariant_order', 'CoordSystem', 'CoordinateSymbol',
|
| 14 |
+
'CovarDerivativeOp', 'covariant_order', 'Differential', 'intcurve_diffequ',
|
| 15 |
+
'intcurve_series', 'LieDerivative', 'Manifold', 'metric_to_Christoffel_1st',
|
| 16 |
+
'metric_to_Christoffel_2nd', 'metric_to_Ricci_components',
|
| 17 |
+
'metric_to_Riemann_components', 'Patch', 'Point', 'TensorProduct',
|
| 18 |
+
'twoform_to_matrix', 'vectors_in_basis', 'WedgeProduct',
|
| 19 |
+
]
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (846 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/diffgeom.cpython-310.pyc
ADDED
|
Binary file (76.2 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from functools import reduce
|
| 5 |
+
from itertools import permutations
|
| 6 |
+
|
| 7 |
+
from sympy.combinatorics import Permutation
|
| 8 |
+
from sympy.core import (
|
| 9 |
+
Basic, Expr, Function, diff,
|
| 10 |
+
Pow, Mul, Add, Lambda, S, Tuple, Dict
|
| 11 |
+
)
|
| 12 |
+
from sympy.core.cache import cacheit
|
| 13 |
+
|
| 14 |
+
from sympy.core.symbol import Symbol, Dummy
|
| 15 |
+
from sympy.core.symbol import Str
|
| 16 |
+
from sympy.core.sympify import _sympify
|
| 17 |
+
from sympy.functions import factorial
|
| 18 |
+
from sympy.matrices import ImmutableDenseMatrix as Matrix
|
| 19 |
+
from sympy.solvers import solve
|
| 20 |
+
|
| 21 |
+
from sympy.utilities.exceptions import (sympy_deprecation_warning,
|
| 22 |
+
SymPyDeprecationWarning,
|
| 23 |
+
ignore_warnings)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# TODO you are a bit excessive in the use of Dummies
|
| 27 |
+
# TODO dummy point, literal field
|
| 28 |
+
# TODO too often one needs to call doit or simplify on the output, check the
|
| 29 |
+
# tests and find out why
|
| 30 |
+
from sympy.tensor.array import ImmutableDenseNDimArray
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Manifold(Basic):
|
| 34 |
+
"""
|
| 35 |
+
A mathematical manifold.
|
| 36 |
+
|
| 37 |
+
Explanation
|
| 38 |
+
===========
|
| 39 |
+
|
| 40 |
+
A manifold is a topological space that locally resembles
|
| 41 |
+
Euclidean space near each point [1].
|
| 42 |
+
This class does not provide any means to study the topological
|
| 43 |
+
characteristics of the manifold that it represents, though.
|
| 44 |
+
|
| 45 |
+
Parameters
|
| 46 |
+
==========
|
| 47 |
+
|
| 48 |
+
name : str
|
| 49 |
+
The name of the manifold.
|
| 50 |
+
|
| 51 |
+
dim : int
|
| 52 |
+
The dimension of the manifold.
|
| 53 |
+
|
| 54 |
+
Examples
|
| 55 |
+
========
|
| 56 |
+
|
| 57 |
+
>>> from sympy.diffgeom import Manifold
|
| 58 |
+
>>> m = Manifold('M', 2)
|
| 59 |
+
>>> m
|
| 60 |
+
M
|
| 61 |
+
>>> m.dim
|
| 62 |
+
2
|
| 63 |
+
|
| 64 |
+
References
|
| 65 |
+
==========
|
| 66 |
+
|
| 67 |
+
.. [1] https://en.wikipedia.org/wiki/Manifold
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __new__(cls, name, dim, **kwargs):
|
| 71 |
+
if not isinstance(name, Str):
|
| 72 |
+
name = Str(name)
|
| 73 |
+
dim = _sympify(dim)
|
| 74 |
+
obj = super().__new__(cls, name, dim)
|
| 75 |
+
|
| 76 |
+
obj.patches = _deprecated_list(
|
| 77 |
+
"""
|
| 78 |
+
Manifold.patches is deprecated. The Manifold object is now
|
| 79 |
+
immutable. Instead use a separate list to keep track of the
|
| 80 |
+
patches.
|
| 81 |
+
""", [])
|
| 82 |
+
return obj
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def name(self):
|
| 86 |
+
return self.args[0]
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def dim(self):
|
| 90 |
+
return self.args[1]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class Patch(Basic):
|
| 94 |
+
"""
|
| 95 |
+
A patch on a manifold.
|
| 96 |
+
|
| 97 |
+
Explanation
|
| 98 |
+
===========
|
| 99 |
+
|
| 100 |
+
Coordinate patch, or patch in short, is a simply-connected open set around
|
| 101 |
+
a point in the manifold [1]. On a manifold one can have many patches that
|
| 102 |
+
do not always include the whole manifold. On these patches coordinate
|
| 103 |
+
charts can be defined that permit the parameterization of any point on the
|
| 104 |
+
patch in terms of a tuple of real numbers (the coordinates).
|
| 105 |
+
|
| 106 |
+
This class does not provide any means to study the topological
|
| 107 |
+
characteristics of the patch that it represents.
|
| 108 |
+
|
| 109 |
+
Parameters
|
| 110 |
+
==========
|
| 111 |
+
|
| 112 |
+
name : str
|
| 113 |
+
The name of the patch.
|
| 114 |
+
|
| 115 |
+
manifold : Manifold
|
| 116 |
+
The manifold on which the patch is defined.
|
| 117 |
+
|
| 118 |
+
Examples
|
| 119 |
+
========
|
| 120 |
+
|
| 121 |
+
>>> from sympy.diffgeom import Manifold, Patch
|
| 122 |
+
>>> m = Manifold('M', 2)
|
| 123 |
+
>>> p = Patch('P', m)
|
| 124 |
+
>>> p
|
| 125 |
+
P
|
| 126 |
+
>>> p.dim
|
| 127 |
+
2
|
| 128 |
+
|
| 129 |
+
References
|
| 130 |
+
==========
|
| 131 |
+
|
| 132 |
+
.. [1] G. Sussman, J. Wisdom, W. Farr, Functional Differential Geometry
|
| 133 |
+
(2013)
|
| 134 |
+
|
| 135 |
+
"""
|
| 136 |
+
def __new__(cls, name, manifold, **kwargs):
|
| 137 |
+
if not isinstance(name, Str):
|
| 138 |
+
name = Str(name)
|
| 139 |
+
obj = super().__new__(cls, name, manifold)
|
| 140 |
+
|
| 141 |
+
obj.manifold.patches.append(obj) # deprecated
|
| 142 |
+
obj.coord_systems = _deprecated_list(
|
| 143 |
+
"""
|
| 144 |
+
Patch.coord_systms is deprecated. The Patch class is now
|
| 145 |
+
immutable. Instead use a separate list to keep track of coordinate
|
| 146 |
+
systems.
|
| 147 |
+
""", [])
|
| 148 |
+
return obj
|
| 149 |
+
|
| 150 |
+
@property
|
| 151 |
+
def name(self):
|
| 152 |
+
return self.args[0]
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def manifold(self):
|
| 156 |
+
return self.args[1]
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def dim(self):
|
| 160 |
+
return self.manifold.dim
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class CoordSystem(Basic):
|
| 164 |
+
"""
|
| 165 |
+
A coordinate system defined on the patch.
|
| 166 |
+
|
| 167 |
+
Explanation
|
| 168 |
+
===========
|
| 169 |
+
|
| 170 |
+
Coordinate system is a system that uses one or more coordinates to uniquely
|
| 171 |
+
determine the position of the points or other geometric elements on a
|
| 172 |
+
manifold [1].
|
| 173 |
+
|
| 174 |
+
By passing ``Symbols`` to *symbols* parameter, user can define the name and
|
| 175 |
+
assumptions of coordinate symbols of the coordinate system. If not passed,
|
| 176 |
+
these symbols are generated automatically and are assumed to be real valued.
|
| 177 |
+
|
| 178 |
+
By passing *relations* parameter, user can define the transform relations of
|
| 179 |
+
coordinate systems. Inverse transformation and indirect transformation can
|
| 180 |
+
be found automatically. If this parameter is not passed, coordinate
|
| 181 |
+
transformation cannot be done.
|
| 182 |
+
|
| 183 |
+
Parameters
|
| 184 |
+
==========
|
| 185 |
+
|
| 186 |
+
name : str
|
| 187 |
+
The name of the coordinate system.
|
| 188 |
+
|
| 189 |
+
patch : Patch
|
| 190 |
+
The patch where the coordinate system is defined.
|
| 191 |
+
|
| 192 |
+
symbols : list of Symbols, optional
|
| 193 |
+
Defines the names and assumptions of coordinate symbols.
|
| 194 |
+
|
| 195 |
+
relations : dict, optional
|
| 196 |
+
Key is a tuple of two strings, who are the names of the systems where
|
| 197 |
+
the coordinates transform from and transform to.
|
| 198 |
+
Value is a tuple of the symbols before transformation and a tuple of
|
| 199 |
+
the expressions after transformation.
|
| 200 |
+
|
| 201 |
+
Examples
|
| 202 |
+
========
|
| 203 |
+
|
| 204 |
+
We define two-dimensional Cartesian coordinate system and polar coordinate
|
| 205 |
+
system.
|
| 206 |
+
|
| 207 |
+
>>> from sympy import symbols, pi, sqrt, atan2, cos, sin
|
| 208 |
+
>>> from sympy.diffgeom import Manifold, Patch, CoordSystem
|
| 209 |
+
>>> m = Manifold('M', 2)
|
| 210 |
+
>>> p = Patch('P', m)
|
| 211 |
+
>>> x, y = symbols('x y', real=True)
|
| 212 |
+
>>> r, theta = symbols('r theta', nonnegative=True)
|
| 213 |
+
>>> relation_dict = {
|
| 214 |
+
... ('Car2D', 'Pol'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))],
|
| 215 |
+
... ('Pol', 'Car2D'): [(r, theta), (r*cos(theta), r*sin(theta))]
|
| 216 |
+
... }
|
| 217 |
+
>>> Car2D = CoordSystem('Car2D', p, (x, y), relation_dict)
|
| 218 |
+
>>> Pol = CoordSystem('Pol', p, (r, theta), relation_dict)
|
| 219 |
+
|
| 220 |
+
``symbols`` property returns ``CoordinateSymbol`` instances. These symbols
|
| 221 |
+
are not same with the symbols used to construct the coordinate system.
|
| 222 |
+
|
| 223 |
+
>>> Car2D
|
| 224 |
+
Car2D
|
| 225 |
+
>>> Car2D.dim
|
| 226 |
+
2
|
| 227 |
+
>>> Car2D.symbols
|
| 228 |
+
(x, y)
|
| 229 |
+
>>> _[0].func
|
| 230 |
+
<class 'sympy.diffgeom.diffgeom.CoordinateSymbol'>
|
| 231 |
+
|
| 232 |
+
``transformation()`` method returns the transformation function from
|
| 233 |
+
one coordinate system to another. ``transform()`` method returns the
|
| 234 |
+
transformed coordinates.
|
| 235 |
+
|
| 236 |
+
>>> Car2D.transformation(Pol)
|
| 237 |
+
Lambda((x, y), Matrix([
|
| 238 |
+
[sqrt(x**2 + y**2)],
|
| 239 |
+
[ atan2(y, x)]]))
|
| 240 |
+
>>> Car2D.transform(Pol)
|
| 241 |
+
Matrix([
|
| 242 |
+
[sqrt(x**2 + y**2)],
|
| 243 |
+
[ atan2(y, x)]])
|
| 244 |
+
>>> Car2D.transform(Pol, [1, 2])
|
| 245 |
+
Matrix([
|
| 246 |
+
[sqrt(5)],
|
| 247 |
+
[atan(2)]])
|
| 248 |
+
|
| 249 |
+
``jacobian()`` method returns the Jacobian matrix of coordinate
|
| 250 |
+
transformation between two systems. ``jacobian_determinant()`` method
|
| 251 |
+
returns the Jacobian determinant of coordinate transformation between two
|
| 252 |
+
systems.
|
| 253 |
+
|
| 254 |
+
>>> Pol.jacobian(Car2D)
|
| 255 |
+
Matrix([
|
| 256 |
+
[cos(theta), -r*sin(theta)],
|
| 257 |
+
[sin(theta), r*cos(theta)]])
|
| 258 |
+
>>> Pol.jacobian(Car2D, [1, pi/2])
|
| 259 |
+
Matrix([
|
| 260 |
+
[0, -1],
|
| 261 |
+
[1, 0]])
|
| 262 |
+
>>> Car2D.jacobian_determinant(Pol)
|
| 263 |
+
1/sqrt(x**2 + y**2)
|
| 264 |
+
>>> Car2D.jacobian_determinant(Pol, [1,0])
|
| 265 |
+
1
|
| 266 |
+
|
| 267 |
+
References
|
| 268 |
+
==========
|
| 269 |
+
|
| 270 |
+
.. [1] https://en.wikipedia.org/wiki/Coordinate_system
|
| 271 |
+
|
| 272 |
+
"""
|
| 273 |
+
def __new__(cls, name, patch, symbols=None, relations={}, **kwargs):
|
| 274 |
+
if not isinstance(name, Str):
|
| 275 |
+
name = Str(name)
|
| 276 |
+
|
| 277 |
+
# canonicallize the symbols
|
| 278 |
+
if symbols is None:
|
| 279 |
+
names = kwargs.get('names', None)
|
| 280 |
+
if names is None:
|
| 281 |
+
symbols = Tuple(
|
| 282 |
+
*[Symbol('%s_%s' % (name.name, i), real=True)
|
| 283 |
+
for i in range(patch.dim)]
|
| 284 |
+
)
|
| 285 |
+
else:
|
| 286 |
+
sympy_deprecation_warning(
|
| 287 |
+
f"""
|
| 288 |
+
The 'names' argument to CoordSystem is deprecated. Use 'symbols' instead. That
|
| 289 |
+
is, replace
|
| 290 |
+
|
| 291 |
+
CoordSystem(..., names={names})
|
| 292 |
+
|
| 293 |
+
with
|
| 294 |
+
|
| 295 |
+
CoordSystem(..., symbols=[{', '.join(["Symbol(" + repr(n) + ", real=True)" for n in names])}])
|
| 296 |
+
""",
|
| 297 |
+
deprecated_since_version="1.7",
|
| 298 |
+
active_deprecations_target="deprecated-diffgeom-mutable",
|
| 299 |
+
)
|
| 300 |
+
symbols = Tuple(
|
| 301 |
+
*[Symbol(n, real=True) for n in names]
|
| 302 |
+
)
|
| 303 |
+
else:
|
| 304 |
+
syms = []
|
| 305 |
+
for s in symbols:
|
| 306 |
+
if isinstance(s, Symbol):
|
| 307 |
+
syms.append(Symbol(s.name, **s._assumptions.generator))
|
| 308 |
+
elif isinstance(s, str):
|
| 309 |
+
sympy_deprecation_warning(
|
| 310 |
+
f"""
|
| 311 |
+
|
| 312 |
+
Passing a string as the coordinate symbol name to CoordSystem is deprecated.
|
| 313 |
+
Pass a Symbol with the appropriate name and assumptions instead.
|
| 314 |
+
|
| 315 |
+
That is, replace {s} with Symbol({s!r}, real=True).
|
| 316 |
+
""",
|
| 317 |
+
|
| 318 |
+
deprecated_since_version="1.7",
|
| 319 |
+
active_deprecations_target="deprecated-diffgeom-mutable",
|
| 320 |
+
)
|
| 321 |
+
syms.append(Symbol(s, real=True))
|
| 322 |
+
symbols = Tuple(*syms)
|
| 323 |
+
|
| 324 |
+
# canonicallize the relations
|
| 325 |
+
rel_temp = {}
|
| 326 |
+
for k,v in relations.items():
|
| 327 |
+
s1, s2 = k
|
| 328 |
+
if not isinstance(s1, Str):
|
| 329 |
+
s1 = Str(s1)
|
| 330 |
+
if not isinstance(s2, Str):
|
| 331 |
+
s2 = Str(s2)
|
| 332 |
+
key = Tuple(s1, s2)
|
| 333 |
+
|
| 334 |
+
# Old version used Lambda as a value.
|
| 335 |
+
if isinstance(v, Lambda):
|
| 336 |
+
v = (tuple(v.signature), tuple(v.expr))
|
| 337 |
+
else:
|
| 338 |
+
v = (tuple(v[0]), tuple(v[1]))
|
| 339 |
+
rel_temp[key] = v
|
| 340 |
+
relations = Dict(rel_temp)
|
| 341 |
+
|
| 342 |
+
# construct the object
|
| 343 |
+
obj = super().__new__(cls, name, patch, symbols, relations)
|
| 344 |
+
|
| 345 |
+
# Add deprecated attributes
|
| 346 |
+
obj.transforms = _deprecated_dict(
|
| 347 |
+
"""
|
| 348 |
+
CoordSystem.transforms is deprecated. The CoordSystem class is now
|
| 349 |
+
immutable. Use the 'relations' keyword argument to the
|
| 350 |
+
CoordSystems() constructor to specify relations.
|
| 351 |
+
""", {})
|
| 352 |
+
obj._names = [str(n) for n in symbols]
|
| 353 |
+
obj.patch.coord_systems.append(obj) # deprecated
|
| 354 |
+
obj._dummies = [Dummy(str(n)) for n in symbols] # deprecated
|
| 355 |
+
obj._dummy = Dummy()
|
| 356 |
+
|
| 357 |
+
return obj
|
| 358 |
+
|
| 359 |
+
@property
|
| 360 |
+
def name(self):
|
| 361 |
+
return self.args[0]
|
| 362 |
+
|
| 363 |
+
@property
|
| 364 |
+
def patch(self):
|
| 365 |
+
return self.args[1]
|
| 366 |
+
|
| 367 |
+
@property
|
| 368 |
+
def manifold(self):
|
| 369 |
+
return self.patch.manifold
|
| 370 |
+
|
| 371 |
+
@property
|
| 372 |
+
def symbols(self):
|
| 373 |
+
return tuple(CoordinateSymbol(self, i, **s._assumptions.generator)
|
| 374 |
+
for i,s in enumerate(self.args[2]))
|
| 375 |
+
|
| 376 |
+
@property
|
| 377 |
+
def relations(self):
|
| 378 |
+
return self.args[3]
|
| 379 |
+
|
| 380 |
+
@property
|
| 381 |
+
def dim(self):
|
| 382 |
+
return self.patch.dim
|
| 383 |
+
|
| 384 |
+
##########################################################################
|
| 385 |
+
# Finding transformation relation
|
| 386 |
+
##########################################################################
|
| 387 |
+
|
| 388 |
+
def transformation(self, sys):
|
| 389 |
+
"""
|
| 390 |
+
Return coordinate transformation function from *self* to *sys*.
|
| 391 |
+
|
| 392 |
+
Parameters
|
| 393 |
+
==========
|
| 394 |
+
|
| 395 |
+
sys : CoordSystem
|
| 396 |
+
|
| 397 |
+
Returns
|
| 398 |
+
=======
|
| 399 |
+
|
| 400 |
+
sympy.Lambda
|
| 401 |
+
|
| 402 |
+
Examples
|
| 403 |
+
========
|
| 404 |
+
|
| 405 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
| 406 |
+
>>> R2_r.transformation(R2_p)
|
| 407 |
+
Lambda((x, y), Matrix([
|
| 408 |
+
[sqrt(x**2 + y**2)],
|
| 409 |
+
[ atan2(y, x)]]))
|
| 410 |
+
|
| 411 |
+
"""
|
| 412 |
+
signature = self.args[2]
|
| 413 |
+
|
| 414 |
+
key = Tuple(self.name, sys.name)
|
| 415 |
+
if self == sys:
|
| 416 |
+
expr = Matrix(self.symbols)
|
| 417 |
+
elif key in self.relations:
|
| 418 |
+
expr = Matrix(self.relations[key][1])
|
| 419 |
+
elif key[::-1] in self.relations:
|
| 420 |
+
expr = Matrix(self._inverse_transformation(sys, self))
|
| 421 |
+
else:
|
| 422 |
+
expr = Matrix(self._indirect_transformation(self, sys))
|
| 423 |
+
return Lambda(signature, expr)
|
| 424 |
+
|
| 425 |
+
@staticmethod
|
| 426 |
+
def _solve_inverse(sym1, sym2, exprs, sys1_name, sys2_name):
|
| 427 |
+
ret = solve(
|
| 428 |
+
[t[0] - t[1] for t in zip(sym2, exprs)],
|
| 429 |
+
list(sym1), dict=True)
|
| 430 |
+
|
| 431 |
+
if len(ret) == 0:
|
| 432 |
+
temp = "Cannot solve inverse relation from {} to {}."
|
| 433 |
+
raise NotImplementedError(temp.format(sys1_name, sys2_name))
|
| 434 |
+
elif len(ret) > 1:
|
| 435 |
+
temp = "Obtained multiple inverse relation from {} to {}."
|
| 436 |
+
raise ValueError(temp.format(sys1_name, sys2_name))
|
| 437 |
+
|
| 438 |
+
return ret[0]
|
| 439 |
+
|
| 440 |
+
@classmethod
|
| 441 |
+
def _inverse_transformation(cls, sys1, sys2):
|
| 442 |
+
# Find the transformation relation from sys2 to sys1
|
| 443 |
+
forward = sys1.transform(sys2)
|
| 444 |
+
inv_results = cls._solve_inverse(sys1.symbols, sys2.symbols, forward,
|
| 445 |
+
sys1.name, sys2.name)
|
| 446 |
+
signature = tuple(sys1.symbols)
|
| 447 |
+
return [inv_results[s] for s in signature]
|
| 448 |
+
|
| 449 |
+
@classmethod
|
| 450 |
+
@cacheit
|
| 451 |
+
def _indirect_transformation(cls, sys1, sys2):
|
| 452 |
+
# Find the transformation relation between two indirectly connected
|
| 453 |
+
# coordinate systems
|
| 454 |
+
rel = sys1.relations
|
| 455 |
+
path = cls._dijkstra(sys1, sys2)
|
| 456 |
+
|
| 457 |
+
transforms = []
|
| 458 |
+
for s1, s2 in zip(path, path[1:]):
|
| 459 |
+
if (s1, s2) in rel:
|
| 460 |
+
transforms.append(rel[(s1, s2)])
|
| 461 |
+
else:
|
| 462 |
+
sym2, inv_exprs = rel[(s2, s1)]
|
| 463 |
+
sym1 = tuple(Dummy() for i in sym2)
|
| 464 |
+
ret = cls._solve_inverse(sym2, sym1, inv_exprs, s2, s1)
|
| 465 |
+
ret = tuple(ret[s] for s in sym2)
|
| 466 |
+
transforms.append((sym1, ret))
|
| 467 |
+
syms = sys1.args[2]
|
| 468 |
+
exprs = syms
|
| 469 |
+
for newsyms, newexprs in transforms:
|
| 470 |
+
exprs = tuple(e.subs(zip(newsyms, exprs)) for e in newexprs)
|
| 471 |
+
return exprs
|
| 472 |
+
|
| 473 |
+
@staticmethod
|
| 474 |
+
def _dijkstra(sys1, sys2):
|
| 475 |
+
# Use Dijkstra algorithm to find the shortest path between two indirectly-connected
|
| 476 |
+
# coordinate systems
|
| 477 |
+
# return value is the list of the names of the systems.
|
| 478 |
+
relations = sys1.relations
|
| 479 |
+
graph = {}
|
| 480 |
+
for s1, s2 in relations.keys():
|
| 481 |
+
if s1 not in graph:
|
| 482 |
+
graph[s1] = {s2}
|
| 483 |
+
else:
|
| 484 |
+
graph[s1].add(s2)
|
| 485 |
+
if s2 not in graph:
|
| 486 |
+
graph[s2] = {s1}
|
| 487 |
+
else:
|
| 488 |
+
graph[s2].add(s1)
|
| 489 |
+
|
| 490 |
+
path_dict = {sys:[0, [], 0] for sys in graph} # minimum distance, path, times of visited
|
| 491 |
+
|
| 492 |
+
def visit(sys):
|
| 493 |
+
path_dict[sys][2] = 1
|
| 494 |
+
for newsys in graph[sys]:
|
| 495 |
+
distance = path_dict[sys][0] + 1
|
| 496 |
+
if path_dict[newsys][0] >= distance or not path_dict[newsys][1]:
|
| 497 |
+
path_dict[newsys][0] = distance
|
| 498 |
+
path_dict[newsys][1] = list(path_dict[sys][1])
|
| 499 |
+
path_dict[newsys][1].append(sys)
|
| 500 |
+
|
| 501 |
+
visit(sys1.name)
|
| 502 |
+
|
| 503 |
+
while True:
|
| 504 |
+
min_distance = max(path_dict.values(), key=lambda x:x[0])[0]
|
| 505 |
+
newsys = None
|
| 506 |
+
for sys, lst in path_dict.items():
|
| 507 |
+
if 0 < lst[0] <= min_distance and not lst[2]:
|
| 508 |
+
min_distance = lst[0]
|
| 509 |
+
newsys = sys
|
| 510 |
+
if newsys is None:
|
| 511 |
+
break
|
| 512 |
+
visit(newsys)
|
| 513 |
+
|
| 514 |
+
result = path_dict[sys2.name][1]
|
| 515 |
+
result.append(sys2.name)
|
| 516 |
+
|
| 517 |
+
if result == [sys2.name]:
|
| 518 |
+
raise KeyError("Two coordinate systems are not connected.")
|
| 519 |
+
return result
|
| 520 |
+
|
| 521 |
+
def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=False):
|
| 522 |
+
sympy_deprecation_warning(
|
| 523 |
+
"""
|
| 524 |
+
The CoordSystem.connect_to() method is deprecated. Instead,
|
| 525 |
+
generate a new instance of CoordSystem with the 'relations'
|
| 526 |
+
keyword argument (CoordSystem classes are now immutable).
|
| 527 |
+
""",
|
| 528 |
+
deprecated_since_version="1.7",
|
| 529 |
+
active_deprecations_target="deprecated-diffgeom-mutable",
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
from_coords, to_exprs = dummyfy(from_coords, to_exprs)
|
| 533 |
+
self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs)
|
| 534 |
+
|
| 535 |
+
if inverse:
|
| 536 |
+
to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs)
|
| 537 |
+
|
| 538 |
+
if fill_in_gaps:
|
| 539 |
+
self._fill_gaps_in_transformations()
|
| 540 |
+
|
| 541 |
+
@staticmethod
|
| 542 |
+
def _inv_transf(from_coords, to_exprs):
|
| 543 |
+
# Will be removed when connect_to is removed
|
| 544 |
+
inv_from = [i.as_dummy() for i in from_coords]
|
| 545 |
+
inv_to = solve(
|
| 546 |
+
[t[0] - t[1] for t in zip(inv_from, to_exprs)],
|
| 547 |
+
list(from_coords), dict=True)[0]
|
| 548 |
+
inv_to = [inv_to[fc] for fc in from_coords]
|
| 549 |
+
return Matrix(inv_from), Matrix(inv_to)
|
| 550 |
+
|
| 551 |
+
@staticmethod
|
| 552 |
+
def _fill_gaps_in_transformations():
|
| 553 |
+
# Will be removed when connect_to is removed
|
| 554 |
+
raise NotImplementedError
|
| 555 |
+
|
| 556 |
+
##########################################################################
|
| 557 |
+
# Coordinate transformations
|
| 558 |
+
##########################################################################
|
| 559 |
+
|
| 560 |
+
def transform(self, sys, coordinates=None):
|
| 561 |
+
"""
|
| 562 |
+
Return the result of coordinate transformation from *self* to *sys*.
|
| 563 |
+
If coordinates are not given, coordinate symbols of *self* are used.
|
| 564 |
+
|
| 565 |
+
Parameters
|
| 566 |
+
==========
|
| 567 |
+
|
| 568 |
+
sys : CoordSystem
|
| 569 |
+
|
| 570 |
+
coordinates : Any iterable, optional.
|
| 571 |
+
|
| 572 |
+
Returns
|
| 573 |
+
=======
|
| 574 |
+
|
| 575 |
+
sympy.ImmutableDenseMatrix containing CoordinateSymbol
|
| 576 |
+
|
| 577 |
+
Examples
|
| 578 |
+
========
|
| 579 |
+
|
| 580 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
| 581 |
+
>>> R2_r.transform(R2_p)
|
| 582 |
+
Matrix([
|
| 583 |
+
[sqrt(x**2 + y**2)],
|
| 584 |
+
[ atan2(y, x)]])
|
| 585 |
+
>>> R2_r.transform(R2_p, [0, 1])
|
| 586 |
+
Matrix([
|
| 587 |
+
[ 1],
|
| 588 |
+
[pi/2]])
|
| 589 |
+
|
| 590 |
+
"""
|
| 591 |
+
if coordinates is None:
|
| 592 |
+
coordinates = self.symbols
|
| 593 |
+
if self != sys:
|
| 594 |
+
transf = self.transformation(sys)
|
| 595 |
+
coordinates = transf(*coordinates)
|
| 596 |
+
else:
|
| 597 |
+
coordinates = Matrix(coordinates)
|
| 598 |
+
return coordinates
|
| 599 |
+
|
| 600 |
+
def coord_tuple_transform_to(self, to_sys, coords):
|
| 601 |
+
"""Transform ``coords`` to coord system ``to_sys``."""
|
| 602 |
+
sympy_deprecation_warning(
|
| 603 |
+
"""
|
| 604 |
+
The CoordSystem.coord_tuple_transform_to() method is deprecated.
|
| 605 |
+
Use the CoordSystem.transform() method instead.
|
| 606 |
+
""",
|
| 607 |
+
deprecated_since_version="1.7",
|
| 608 |
+
active_deprecations_target="deprecated-diffgeom-mutable",
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
coords = Matrix(coords)
|
| 612 |
+
if self != to_sys:
|
| 613 |
+
with ignore_warnings(SymPyDeprecationWarning):
|
| 614 |
+
transf = self.transforms[to_sys]
|
| 615 |
+
coords = transf[1].subs(list(zip(transf[0], coords)))
|
| 616 |
+
return coords
|
| 617 |
+
|
| 618 |
+
def jacobian(self, sys, coordinates=None):
|
| 619 |
+
"""
|
| 620 |
+
Return the jacobian matrix of a transformation on given coordinates.
|
| 621 |
+
If coordinates are not given, coordinate symbols of *self* are used.
|
| 622 |
+
|
| 623 |
+
Parameters
|
| 624 |
+
==========
|
| 625 |
+
|
| 626 |
+
sys : CoordSystem
|
| 627 |
+
|
| 628 |
+
coordinates : Any iterable, optional.
|
| 629 |
+
|
| 630 |
+
Returns
|
| 631 |
+
=======
|
| 632 |
+
|
| 633 |
+
sympy.ImmutableDenseMatrix
|
| 634 |
+
|
| 635 |
+
Examples
|
| 636 |
+
========
|
| 637 |
+
|
| 638 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
| 639 |
+
>>> R2_p.jacobian(R2_r)
|
| 640 |
+
Matrix([
|
| 641 |
+
[cos(theta), -rho*sin(theta)],
|
| 642 |
+
[sin(theta), rho*cos(theta)]])
|
| 643 |
+
>>> R2_p.jacobian(R2_r, [1, 0])
|
| 644 |
+
Matrix([
|
| 645 |
+
[1, 0],
|
| 646 |
+
[0, 1]])
|
| 647 |
+
|
| 648 |
+
"""
|
| 649 |
+
result = self.transform(sys).jacobian(self.symbols)
|
| 650 |
+
if coordinates is not None:
|
| 651 |
+
result = result.subs(list(zip(self.symbols, coordinates)))
|
| 652 |
+
return result
|
| 653 |
+
jacobian_matrix = jacobian
|
| 654 |
+
|
| 655 |
+
def jacobian_determinant(self, sys, coordinates=None):
|
| 656 |
+
"""
|
| 657 |
+
Return the jacobian determinant of a transformation on given
|
| 658 |
+
coordinates. If coordinates are not given, coordinate symbols of *self*
|
| 659 |
+
are used.
|
| 660 |
+
|
| 661 |
+
Parameters
|
| 662 |
+
==========
|
| 663 |
+
|
| 664 |
+
sys : CoordSystem
|
| 665 |
+
|
| 666 |
+
coordinates : Any iterable, optional.
|
| 667 |
+
|
| 668 |
+
Returns
|
| 669 |
+
=======
|
| 670 |
+
|
| 671 |
+
sympy.Expr
|
| 672 |
+
|
| 673 |
+
Examples
|
| 674 |
+
========
|
| 675 |
+
|
| 676 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
| 677 |
+
>>> R2_r.jacobian_determinant(R2_p)
|
| 678 |
+
1/sqrt(x**2 + y**2)
|
| 679 |
+
>>> R2_r.jacobian_determinant(R2_p, [1, 0])
|
| 680 |
+
1
|
| 681 |
+
|
| 682 |
+
"""
|
| 683 |
+
return self.jacobian(sys, coordinates).det()
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
##########################################################################
|
| 687 |
+
# Points
|
| 688 |
+
##########################################################################
|
| 689 |
+
|
| 690 |
+
def point(self, coords):
|
| 691 |
+
"""Create a ``Point`` with coordinates given in this coord system."""
|
| 692 |
+
return Point(self, coords)
|
| 693 |
+
|
| 694 |
+
def point_to_coords(self, point):
|
| 695 |
+
"""Calculate the coordinates of a point in this coord system."""
|
| 696 |
+
return point.coords(self)
|
| 697 |
+
|
| 698 |
+
##########################################################################
|
| 699 |
+
# Base fields.
|
| 700 |
+
##########################################################################
|
| 701 |
+
|
| 702 |
+
def base_scalar(self, coord_index):
|
| 703 |
+
"""Return ``BaseScalarField`` that takes a point and returns one of the coordinates."""
|
| 704 |
+
return BaseScalarField(self, coord_index)
|
| 705 |
+
coord_function = base_scalar
|
| 706 |
+
|
| 707 |
+
def base_scalars(self):
|
| 708 |
+
"""Returns a list of all coordinate functions.
|
| 709 |
+
For more details see the ``base_scalar`` method of this class."""
|
| 710 |
+
return [self.base_scalar(i) for i in range(self.dim)]
|
| 711 |
+
coord_functions = base_scalars
|
| 712 |
+
|
| 713 |
+
def base_vector(self, coord_index):
|
| 714 |
+
"""Return a basis vector field.
|
| 715 |
+
The basis vector field for this coordinate system. It is also an
|
| 716 |
+
operator on scalar fields."""
|
| 717 |
+
return BaseVectorField(self, coord_index)
|
| 718 |
+
|
| 719 |
+
def base_vectors(self):
|
| 720 |
+
"""Returns a list of all base vectors.
|
| 721 |
+
For more details see the ``base_vector`` method of this class."""
|
| 722 |
+
return [self.base_vector(i) for i in range(self.dim)]
|
| 723 |
+
|
| 724 |
+
def base_oneform(self, coord_index):
|
| 725 |
+
"""Return a basis 1-form field.
|
| 726 |
+
The basis one-form field for this coordinate system. It is also an
|
| 727 |
+
operator on vector fields."""
|
| 728 |
+
return Differential(self.coord_function(coord_index))
|
| 729 |
+
|
| 730 |
+
def base_oneforms(self):
|
| 731 |
+
"""Returns a list of all base oneforms.
|
| 732 |
+
For more details see the ``base_oneform`` method of this class."""
|
| 733 |
+
return [self.base_oneform(i) for i in range(self.dim)]
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
class CoordinateSymbol(Symbol):
|
| 737 |
+
"""A symbol which denotes an abstract value of i-th coordinate of
|
| 738 |
+
the coordinate system with given context.
|
| 739 |
+
|
| 740 |
+
Explanation
|
| 741 |
+
===========
|
| 742 |
+
|
| 743 |
+
Each coordinates in coordinate system are represented by unique symbol,
|
| 744 |
+
such as x, y, z in Cartesian coordinate system.
|
| 745 |
+
|
| 746 |
+
You may not construct this class directly. Instead, use `symbols` method
|
| 747 |
+
of CoordSystem.
|
| 748 |
+
|
| 749 |
+
Parameters
|
| 750 |
+
==========
|
| 751 |
+
|
| 752 |
+
coord_sys : CoordSystem
|
| 753 |
+
|
| 754 |
+
index : integer
|
| 755 |
+
|
| 756 |
+
Examples
|
| 757 |
+
========
|
| 758 |
+
|
| 759 |
+
>>> from sympy import symbols, Lambda, Matrix, sqrt, atan2, cos, sin
|
| 760 |
+
>>> from sympy.diffgeom import Manifold, Patch, CoordSystem
|
| 761 |
+
>>> m = Manifold('M', 2)
|
| 762 |
+
>>> p = Patch('P', m)
|
| 763 |
+
>>> x, y = symbols('x y', real=True)
|
| 764 |
+
>>> r, theta = symbols('r theta', nonnegative=True)
|
| 765 |
+
>>> relation_dict = {
|
| 766 |
+
... ('Car2D', 'Pol'): Lambda((x, y), Matrix([sqrt(x**2 + y**2), atan2(y, x)])),
|
| 767 |
+
... ('Pol', 'Car2D'): Lambda((r, theta), Matrix([r*cos(theta), r*sin(theta)]))
|
| 768 |
+
... }
|
| 769 |
+
>>> Car2D = CoordSystem('Car2D', p, [x, y], relation_dict)
|
| 770 |
+
>>> Pol = CoordSystem('Pol', p, [r, theta], relation_dict)
|
| 771 |
+
>>> x, y = Car2D.symbols
|
| 772 |
+
|
| 773 |
+
``CoordinateSymbol`` contains its coordinate symbol and index.
|
| 774 |
+
|
| 775 |
+
>>> x.name
|
| 776 |
+
'x'
|
| 777 |
+
>>> x.coord_sys == Car2D
|
| 778 |
+
True
|
| 779 |
+
>>> x.index
|
| 780 |
+
0
|
| 781 |
+
>>> x.is_real
|
| 782 |
+
True
|
| 783 |
+
|
| 784 |
+
You can transform ``CoordinateSymbol`` into other coordinate system using
|
| 785 |
+
``rewrite()`` method.
|
| 786 |
+
|
| 787 |
+
>>> x.rewrite(Pol)
|
| 788 |
+
r*cos(theta)
|
| 789 |
+
>>> sqrt(x**2 + y**2).rewrite(Pol).simplify()
|
| 790 |
+
r
|
| 791 |
+
|
| 792 |
+
"""
|
| 793 |
+
def __new__(cls, coord_sys, index, **assumptions):
|
| 794 |
+
name = coord_sys.args[2][index].name
|
| 795 |
+
obj = super().__new__(cls, name, **assumptions)
|
| 796 |
+
obj.coord_sys = coord_sys
|
| 797 |
+
obj.index = index
|
| 798 |
+
return obj
|
| 799 |
+
|
| 800 |
+
def __getnewargs__(self):
|
| 801 |
+
return (self.coord_sys, self.index)
|
| 802 |
+
|
| 803 |
+
def _hashable_content(self):
|
| 804 |
+
return (
|
| 805 |
+
self.coord_sys, self.index
|
| 806 |
+
) + tuple(sorted(self.assumptions0.items()))
|
| 807 |
+
|
| 808 |
+
def _eval_rewrite(self, rule, args, **hints):
|
| 809 |
+
if isinstance(rule, CoordSystem):
|
| 810 |
+
return rule.transform(self.coord_sys)[self.index]
|
| 811 |
+
return super()._eval_rewrite(rule, args, **hints)
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
class Point(Basic):
|
| 815 |
+
"""Point defined in a coordinate system.
|
| 816 |
+
|
| 817 |
+
Explanation
|
| 818 |
+
===========
|
| 819 |
+
|
| 820 |
+
Mathematically, point is defined in the manifold and does not have any coordinates
|
| 821 |
+
by itself. Coordinate system is what imbues the coordinates to the point by coordinate
|
| 822 |
+
chart. However, due to the difficulty of realizing such logic, you must supply
|
| 823 |
+
a coordinate system and coordinates to define a Point here.
|
| 824 |
+
|
| 825 |
+
The usage of this object after its definition is independent of the
|
| 826 |
+
coordinate system that was used in order to define it, however due to
|
| 827 |
+
limitations in the simplification routines you can arrive at complicated
|
| 828 |
+
expressions if you use inappropriate coordinate systems.
|
| 829 |
+
|
| 830 |
+
Parameters
|
| 831 |
+
==========
|
| 832 |
+
|
| 833 |
+
coord_sys : CoordSystem
|
| 834 |
+
|
| 835 |
+
coords : list
|
| 836 |
+
The coordinates of the point.
|
| 837 |
+
|
| 838 |
+
Examples
|
| 839 |
+
========
|
| 840 |
+
|
| 841 |
+
>>> from sympy import pi
|
| 842 |
+
>>> from sympy.diffgeom import Point
|
| 843 |
+
>>> from sympy.diffgeom.rn import R2, R2_r, R2_p
|
| 844 |
+
>>> rho, theta = R2_p.symbols
|
| 845 |
+
|
| 846 |
+
>>> p = Point(R2_p, [rho, 3*pi/4])
|
| 847 |
+
|
| 848 |
+
>>> p.manifold == R2
|
| 849 |
+
True
|
| 850 |
+
|
| 851 |
+
>>> p.coords()
|
| 852 |
+
Matrix([
|
| 853 |
+
[ rho],
|
| 854 |
+
[3*pi/4]])
|
| 855 |
+
>>> p.coords(R2_r)
|
| 856 |
+
Matrix([
|
| 857 |
+
[-sqrt(2)*rho/2],
|
| 858 |
+
[ sqrt(2)*rho/2]])
|
| 859 |
+
|
| 860 |
+
"""
|
| 861 |
+
|
| 862 |
+
def __new__(cls, coord_sys, coords, **kwargs):
|
| 863 |
+
coords = Matrix(coords)
|
| 864 |
+
obj = super().__new__(cls, coord_sys, coords)
|
| 865 |
+
obj._coord_sys = coord_sys
|
| 866 |
+
obj._coords = coords
|
| 867 |
+
return obj
|
| 868 |
+
|
| 869 |
+
@property
|
| 870 |
+
def patch(self):
|
| 871 |
+
return self._coord_sys.patch
|
| 872 |
+
|
| 873 |
+
@property
|
| 874 |
+
def manifold(self):
|
| 875 |
+
return self._coord_sys.manifold
|
| 876 |
+
|
| 877 |
+
@property
|
| 878 |
+
def dim(self):
|
| 879 |
+
return self.manifold.dim
|
| 880 |
+
|
| 881 |
+
def coords(self, sys=None):
|
| 882 |
+
"""
|
| 883 |
+
Coordinates of the point in given coordinate system. If coordinate system
|
| 884 |
+
is not passed, it returns the coordinates in the coordinate system in which
|
| 885 |
+
the poin was defined.
|
| 886 |
+
"""
|
| 887 |
+
if sys is None:
|
| 888 |
+
return self._coords
|
| 889 |
+
else:
|
| 890 |
+
return self._coord_sys.transform(sys, self._coords)
|
| 891 |
+
|
| 892 |
+
@property
|
| 893 |
+
def free_symbols(self):
|
| 894 |
+
return self._coords.free_symbols
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
class BaseScalarField(Expr):
|
| 898 |
+
"""Base scalar field over a manifold for a given coordinate system.
|
| 899 |
+
|
| 900 |
+
Explanation
|
| 901 |
+
===========
|
| 902 |
+
|
| 903 |
+
A scalar field takes a point as an argument and returns a scalar.
|
| 904 |
+
A base scalar field of a coordinate system takes a point and returns one of
|
| 905 |
+
the coordinates of that point in the coordinate system in question.
|
| 906 |
+
|
| 907 |
+
To define a scalar field you need to choose the coordinate system and the
|
| 908 |
+
index of the coordinate.
|
| 909 |
+
|
| 910 |
+
The use of the scalar field after its definition is independent of the
|
| 911 |
+
coordinate system in which it was defined, however due to limitations in
|
| 912 |
+
the simplification routines you may arrive at more complicated
|
| 913 |
+
expression if you use unappropriate coordinate systems.
|
| 914 |
+
You can build complicated scalar fields by just building up SymPy
|
| 915 |
+
expressions containing ``BaseScalarField`` instances.
|
| 916 |
+
|
| 917 |
+
Parameters
|
| 918 |
+
==========
|
| 919 |
+
|
| 920 |
+
coord_sys : CoordSystem
|
| 921 |
+
|
| 922 |
+
index : integer
|
| 923 |
+
|
| 924 |
+
Examples
|
| 925 |
+
========
|
| 926 |
+
|
| 927 |
+
>>> from sympy import Function, pi
|
| 928 |
+
>>> from sympy.diffgeom import BaseScalarField
|
| 929 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
| 930 |
+
>>> rho, _ = R2_p.symbols
|
| 931 |
+
>>> point = R2_p.point([rho, 0])
|
| 932 |
+
>>> fx, fy = R2_r.base_scalars()
|
| 933 |
+
>>> ftheta = BaseScalarField(R2_r, 1)
|
| 934 |
+
|
| 935 |
+
>>> fx(point)
|
| 936 |
+
rho
|
| 937 |
+
>>> fy(point)
|
| 938 |
+
0
|
| 939 |
+
|
| 940 |
+
>>> (fx**2+fy**2).rcall(point)
|
| 941 |
+
rho**2
|
| 942 |
+
|
| 943 |
+
>>> g = Function('g')
|
| 944 |
+
>>> fg = g(ftheta-pi)
|
| 945 |
+
>>> fg.rcall(point)
|
| 946 |
+
g(-pi)
|
| 947 |
+
|
| 948 |
+
"""
|
| 949 |
+
|
| 950 |
+
is_commutative = True
|
| 951 |
+
|
| 952 |
+
def __new__(cls, coord_sys, index, **kwargs):
|
| 953 |
+
index = _sympify(index)
|
| 954 |
+
obj = super().__new__(cls, coord_sys, index)
|
| 955 |
+
obj._coord_sys = coord_sys
|
| 956 |
+
obj._index = index
|
| 957 |
+
return obj
|
| 958 |
+
|
| 959 |
+
@property
|
| 960 |
+
def coord_sys(self):
|
| 961 |
+
return self.args[0]
|
| 962 |
+
|
| 963 |
+
@property
|
| 964 |
+
def index(self):
|
| 965 |
+
return self.args[1]
|
| 966 |
+
|
| 967 |
+
@property
|
| 968 |
+
def patch(self):
|
| 969 |
+
return self.coord_sys.patch
|
| 970 |
+
|
| 971 |
+
@property
|
| 972 |
+
def manifold(self):
|
| 973 |
+
return self.coord_sys.manifold
|
| 974 |
+
|
| 975 |
+
@property
|
| 976 |
+
def dim(self):
|
| 977 |
+
return self.manifold.dim
|
| 978 |
+
|
| 979 |
+
def __call__(self, *args):
|
| 980 |
+
"""Evaluating the field at a point or doing nothing.
|
| 981 |
+
If the argument is a ``Point`` instance, the field is evaluated at that
|
| 982 |
+
point. The field is returned itself if the argument is any other
|
| 983 |
+
object. It is so in order to have working recursive calling mechanics
|
| 984 |
+
for all fields (check the ``__call__`` method of ``Expr``).
|
| 985 |
+
"""
|
| 986 |
+
point = args[0]
|
| 987 |
+
if len(args) != 1 or not isinstance(point, Point):
|
| 988 |
+
return self
|
| 989 |
+
coords = point.coords(self._coord_sys)
|
| 990 |
+
# XXX Calling doit is necessary with all the Subs expressions
|
| 991 |
+
# XXX Calling simplify is necessary with all the trig expressions
|
| 992 |
+
return simplify(coords[self._index]).doit()
|
| 993 |
+
|
| 994 |
+
# XXX Workaround for limitations on the content of args
|
| 995 |
+
free_symbols: set[Any] = set()
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
class BaseVectorField(Expr):
|
| 999 |
+
r"""Base vector field over a manifold for a given coordinate system.
|
| 1000 |
+
|
| 1001 |
+
Explanation
|
| 1002 |
+
===========
|
| 1003 |
+
|
| 1004 |
+
A vector field is an operator taking a scalar field and returning a
|
| 1005 |
+
directional derivative (which is also a scalar field).
|
| 1006 |
+
A base vector field is the same type of operator, however the derivation is
|
| 1007 |
+
specifically done with respect to a chosen coordinate.
|
| 1008 |
+
|
| 1009 |
+
To define a base vector field you need to choose the coordinate system and
|
| 1010 |
+
the index of the coordinate.
|
| 1011 |
+
|
| 1012 |
+
The use of the vector field after its definition is independent of the
|
| 1013 |
+
coordinate system in which it was defined, however due to limitations in the
|
| 1014 |
+
simplification routines you may arrive at more complicated expression if you
|
| 1015 |
+
use unappropriate coordinate systems.
|
| 1016 |
+
|
| 1017 |
+
Parameters
|
| 1018 |
+
==========
|
| 1019 |
+
coord_sys : CoordSystem
|
| 1020 |
+
|
| 1021 |
+
index : integer
|
| 1022 |
+
|
| 1023 |
+
Examples
|
| 1024 |
+
========
|
| 1025 |
+
|
| 1026 |
+
>>> from sympy import Function
|
| 1027 |
+
>>> from sympy.diffgeom.rn import R2_p, R2_r
|
| 1028 |
+
>>> from sympy.diffgeom import BaseVectorField
|
| 1029 |
+
>>> from sympy import pprint
|
| 1030 |
+
|
| 1031 |
+
>>> x, y = R2_r.symbols
|
| 1032 |
+
>>> rho, theta = R2_p.symbols
|
| 1033 |
+
>>> fx, fy = R2_r.base_scalars()
|
| 1034 |
+
>>> point_p = R2_p.point([rho, theta])
|
| 1035 |
+
>>> point_r = R2_r.point([x, y])
|
| 1036 |
+
|
| 1037 |
+
>>> g = Function('g')
|
| 1038 |
+
>>> s_field = g(fx, fy)
|
| 1039 |
+
|
| 1040 |
+
>>> v = BaseVectorField(R2_r, 1)
|
| 1041 |
+
>>> pprint(v(s_field))
|
| 1042 |
+
/ d \|
|
| 1043 |
+
|---(g(x, xi))||
|
| 1044 |
+
\dxi /|xi=y
|
| 1045 |
+
>>> pprint(v(s_field).rcall(point_r).doit())
|
| 1046 |
+
d
|
| 1047 |
+
--(g(x, y))
|
| 1048 |
+
dy
|
| 1049 |
+
>>> pprint(v(s_field).rcall(point_p))
|
| 1050 |
+
/ d \|
|
| 1051 |
+
|---(g(rho*cos(theta), xi))||
|
| 1052 |
+
\dxi /|xi=rho*sin(theta)
|
| 1053 |
+
|
| 1054 |
+
"""
|
| 1055 |
+
|
| 1056 |
+
is_commutative = False
|
| 1057 |
+
|
| 1058 |
+
def __new__(cls, coord_sys, index, **kwargs):
|
| 1059 |
+
index = _sympify(index)
|
| 1060 |
+
obj = super().__new__(cls, coord_sys, index)
|
| 1061 |
+
obj._coord_sys = coord_sys
|
| 1062 |
+
obj._index = index
|
| 1063 |
+
return obj
|
| 1064 |
+
|
| 1065 |
+
@property
|
| 1066 |
+
def coord_sys(self):
|
| 1067 |
+
return self.args[0]
|
| 1068 |
+
|
| 1069 |
+
@property
|
| 1070 |
+
def index(self):
|
| 1071 |
+
return self.args[1]
|
| 1072 |
+
|
| 1073 |
+
@property
|
| 1074 |
+
def patch(self):
|
| 1075 |
+
return self.coord_sys.patch
|
| 1076 |
+
|
| 1077 |
+
@property
|
| 1078 |
+
def manifold(self):
|
| 1079 |
+
return self.coord_sys.manifold
|
| 1080 |
+
|
| 1081 |
+
@property
|
| 1082 |
+
def dim(self):
|
| 1083 |
+
return self.manifold.dim
|
| 1084 |
+
|
| 1085 |
+
def __call__(self, scalar_field):
|
| 1086 |
+
"""Apply on a scalar field.
|
| 1087 |
+
The action of a vector field on a scalar field is a directional
|
| 1088 |
+
differentiation.
|
| 1089 |
+
If the argument is not a scalar field an error is raised.
|
| 1090 |
+
"""
|
| 1091 |
+
if covariant_order(scalar_field) or contravariant_order(scalar_field):
|
| 1092 |
+
raise ValueError('Only scalar fields can be supplied as arguments to vector fields.')
|
| 1093 |
+
|
| 1094 |
+
if scalar_field is None:
|
| 1095 |
+
return self
|
| 1096 |
+
|
| 1097 |
+
base_scalars = list(scalar_field.atoms(BaseScalarField))
|
| 1098 |
+
|
| 1099 |
+
# First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r)
|
| 1100 |
+
d_var = self._coord_sys._dummy
|
| 1101 |
+
# TODO: you need a real dummy function for the next line
|
| 1102 |
+
d_funcs = [Function('_#_%s' % i)(d_var) for i,
|
| 1103 |
+
b in enumerate(base_scalars)]
|
| 1104 |
+
d_result = scalar_field.subs(list(zip(base_scalars, d_funcs)))
|
| 1105 |
+
d_result = d_result.diff(d_var)
|
| 1106 |
+
|
| 1107 |
+
# Second step: e_x(x) -> 1 and e_x(r) -> cos(atan2(x, y))
|
| 1108 |
+
coords = self._coord_sys.symbols
|
| 1109 |
+
d_funcs_deriv = [f.diff(d_var) for f in d_funcs]
|
| 1110 |
+
d_funcs_deriv_sub = []
|
| 1111 |
+
for b in base_scalars:
|
| 1112 |
+
jac = self._coord_sys.jacobian(b._coord_sys, coords)
|
| 1113 |
+
d_funcs_deriv_sub.append(jac[b._index, self._index])
|
| 1114 |
+
d_result = d_result.subs(list(zip(d_funcs_deriv, d_funcs_deriv_sub)))
|
| 1115 |
+
|
| 1116 |
+
# Remove the dummies
|
| 1117 |
+
result = d_result.subs(list(zip(d_funcs, base_scalars)))
|
| 1118 |
+
result = result.subs(list(zip(coords, self._coord_sys.coord_functions())))
|
| 1119 |
+
return result.doit()
|
| 1120 |
+
|
| 1121 |
+
|
| 1122 |
+
def _find_coords(expr):
|
| 1123 |
+
# Finds CoordinateSystems existing in expr
|
| 1124 |
+
fields = expr.atoms(BaseScalarField, BaseVectorField)
|
| 1125 |
+
return {f._coord_sys for f in fields}
|
| 1126 |
+
|
| 1127 |
+
|
| 1128 |
+
class Commutator(Expr):
|
| 1129 |
+
r"""Commutator of two vector fields.
|
| 1130 |
+
|
| 1131 |
+
Explanation
|
| 1132 |
+
===========
|
| 1133 |
+
|
| 1134 |
+
The commutator of two vector fields `v_1` and `v_2` is defined as the
|
| 1135 |
+
vector field `[v_1, v_2]` that evaluated on each scalar field `f` is equal
|
| 1136 |
+
to `v_1(v_2(f)) - v_2(v_1(f))`.
|
| 1137 |
+
|
| 1138 |
+
Examples
|
| 1139 |
+
========
|
| 1140 |
+
|
| 1141 |
+
|
| 1142 |
+
>>> from sympy.diffgeom.rn import R2_p, R2_r
|
| 1143 |
+
>>> from sympy.diffgeom import Commutator
|
| 1144 |
+
>>> from sympy import simplify
|
| 1145 |
+
|
| 1146 |
+
>>> fx, fy = R2_r.base_scalars()
|
| 1147 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
| 1148 |
+
>>> e_r = R2_p.base_vector(0)
|
| 1149 |
+
|
| 1150 |
+
>>> c_xy = Commutator(e_x, e_y)
|
| 1151 |
+
>>> c_xr = Commutator(e_x, e_r)
|
| 1152 |
+
>>> c_xy
|
| 1153 |
+
0
|
| 1154 |
+
|
| 1155 |
+
Unfortunately, the current code is not able to compute everything:
|
| 1156 |
+
|
| 1157 |
+
>>> c_xr
|
| 1158 |
+
Commutator(e_x, e_rho)
|
| 1159 |
+
>>> simplify(c_xr(fy**2))
|
| 1160 |
+
-2*cos(theta)*y**2/(x**2 + y**2)
|
| 1161 |
+
|
| 1162 |
+
"""
|
| 1163 |
+
def __new__(cls, v1, v2):
|
| 1164 |
+
if (covariant_order(v1) or contravariant_order(v1) != 1
|
| 1165 |
+
or covariant_order(v2) or contravariant_order(v2) != 1):
|
| 1166 |
+
raise ValueError(
|
| 1167 |
+
'Only commutators of vector fields are supported.')
|
| 1168 |
+
if v1 == v2:
|
| 1169 |
+
return S.Zero
|
| 1170 |
+
coord_sys = set().union(*[_find_coords(v) for v in (v1, v2)])
|
| 1171 |
+
if len(coord_sys) == 1:
|
| 1172 |
+
# Only one coordinate systems is used, hence it is easy enough to
|
| 1173 |
+
# actually evaluate the commutator.
|
| 1174 |
+
if all(isinstance(v, BaseVectorField) for v in (v1, v2)):
|
| 1175 |
+
return S.Zero
|
| 1176 |
+
bases_1, bases_2 = [list(v.atoms(BaseVectorField))
|
| 1177 |
+
for v in (v1, v2)]
|
| 1178 |
+
coeffs_1 = [v1.expand().coeff(b) for b in bases_1]
|
| 1179 |
+
coeffs_2 = [v2.expand().coeff(b) for b in bases_2]
|
| 1180 |
+
res = 0
|
| 1181 |
+
for c1, b1 in zip(coeffs_1, bases_1):
|
| 1182 |
+
for c2, b2 in zip(coeffs_2, bases_2):
|
| 1183 |
+
res += c1*b1(c2)*b2 - c2*b2(c1)*b1
|
| 1184 |
+
return res
|
| 1185 |
+
else:
|
| 1186 |
+
obj = super().__new__(cls, v1, v2)
|
| 1187 |
+
obj._v1 = v1 # deprecated assignment
|
| 1188 |
+
obj._v2 = v2 # deprecated assignment
|
| 1189 |
+
return obj
|
| 1190 |
+
|
| 1191 |
+
@property
|
| 1192 |
+
def v1(self):
|
| 1193 |
+
return self.args[0]
|
| 1194 |
+
|
| 1195 |
+
@property
|
| 1196 |
+
def v2(self):
|
| 1197 |
+
return self.args[1]
|
| 1198 |
+
|
| 1199 |
+
def __call__(self, scalar_field):
|
| 1200 |
+
"""Apply on a scalar field.
|
| 1201 |
+
If the argument is not a scalar field an error is raised.
|
| 1202 |
+
"""
|
| 1203 |
+
return self.v1(self.v2(scalar_field)) - self.v2(self.v1(scalar_field))
|
| 1204 |
+
|
| 1205 |
+
|
| 1206 |
+
class Differential(Expr):
|
| 1207 |
+
r"""Return the differential (exterior derivative) of a form field.
|
| 1208 |
+
|
| 1209 |
+
Explanation
|
| 1210 |
+
===========
|
| 1211 |
+
|
| 1212 |
+
The differential of a form (i.e. the exterior derivative) has a complicated
|
| 1213 |
+
definition in the general case.
|
| 1214 |
+
The differential `df` of the 0-form `f` is defined for any vector field `v`
|
| 1215 |
+
as `df(v) = v(f)`.
|
| 1216 |
+
|
| 1217 |
+
Examples
|
| 1218 |
+
========
|
| 1219 |
+
|
| 1220 |
+
>>> from sympy import Function
|
| 1221 |
+
>>> from sympy.diffgeom.rn import R2_r
|
| 1222 |
+
>>> from sympy.diffgeom import Differential
|
| 1223 |
+
>>> from sympy import pprint
|
| 1224 |
+
|
| 1225 |
+
>>> fx, fy = R2_r.base_scalars()
|
| 1226 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
| 1227 |
+
>>> g = Function('g')
|
| 1228 |
+
>>> s_field = g(fx, fy)
|
| 1229 |
+
>>> dg = Differential(s_field)
|
| 1230 |
+
|
| 1231 |
+
>>> dg
|
| 1232 |
+
d(g(x, y))
|
| 1233 |
+
>>> pprint(dg(e_x))
|
| 1234 |
+
/ d \|
|
| 1235 |
+
|---(g(xi, y))||
|
| 1236 |
+
\dxi /|xi=x
|
| 1237 |
+
>>> pprint(dg(e_y))
|
| 1238 |
+
/ d \|
|
| 1239 |
+
|---(g(x, xi))||
|
| 1240 |
+
\dxi /|xi=y
|
| 1241 |
+
|
| 1242 |
+
Applying the exterior derivative operator twice always results in:
|
| 1243 |
+
|
| 1244 |
+
>>> Differential(dg)
|
| 1245 |
+
0
|
| 1246 |
+
"""
|
| 1247 |
+
|
| 1248 |
+
is_commutative = False
|
| 1249 |
+
|
| 1250 |
+
def __new__(cls, form_field):
|
| 1251 |
+
if contravariant_order(form_field):
|
| 1252 |
+
raise ValueError(
|
| 1253 |
+
'A vector field was supplied as an argument to Differential.')
|
| 1254 |
+
if isinstance(form_field, Differential):
|
| 1255 |
+
return S.Zero
|
| 1256 |
+
else:
|
| 1257 |
+
obj = super().__new__(cls, form_field)
|
| 1258 |
+
obj._form_field = form_field # deprecated assignment
|
| 1259 |
+
return obj
|
| 1260 |
+
|
| 1261 |
+
@property
|
| 1262 |
+
def form_field(self):
|
| 1263 |
+
return self.args[0]
|
| 1264 |
+
|
| 1265 |
+
def __call__(self, *vector_fields):
|
| 1266 |
+
"""Apply on a list of vector_fields.
|
| 1267 |
+
|
| 1268 |
+
Explanation
|
| 1269 |
+
===========
|
| 1270 |
+
|
| 1271 |
+
If the number of vector fields supplied is not equal to 1 + the order of
|
| 1272 |
+
the form field inside the differential the result is undefined.
|
| 1273 |
+
|
| 1274 |
+
For 1-forms (i.e. differentials of scalar fields) the evaluation is
|
| 1275 |
+
done as `df(v)=v(f)`. However if `v` is ``None`` instead of a vector
|
| 1276 |
+
field, the differential is returned unchanged. This is done in order to
|
| 1277 |
+
permit partial contractions for higher forms.
|
| 1278 |
+
|
| 1279 |
+
In the general case the evaluation is done by applying the form field
|
| 1280 |
+
inside the differential on a list with one less elements than the number
|
| 1281 |
+
of elements in the original list. Lowering the number of vector fields
|
| 1282 |
+
is achieved through replacing each pair of fields by their
|
| 1283 |
+
commutator.
|
| 1284 |
+
|
| 1285 |
+
If the arguments are not vectors or ``None``s an error is raised.
|
| 1286 |
+
"""
|
| 1287 |
+
if any((contravariant_order(a) != 1 or covariant_order(a)) and a is not None
|
| 1288 |
+
for a in vector_fields):
|
| 1289 |
+
raise ValueError('The arguments supplied to Differential should be vector fields or Nones.')
|
| 1290 |
+
k = len(vector_fields)
|
| 1291 |
+
if k == 1:
|
| 1292 |
+
if vector_fields[0]:
|
| 1293 |
+
return vector_fields[0].rcall(self._form_field)
|
| 1294 |
+
return self
|
| 1295 |
+
else:
|
| 1296 |
+
# For higher form it is more complicated:
|
| 1297 |
+
# Invariant formula:
|
| 1298 |
+
# https://en.wikipedia.org/wiki/Exterior_derivative#Invariant_formula
|
| 1299 |
+
# df(v1, ... vn) = +/- vi(f(v1..no i..vn))
|
| 1300 |
+
# +/- f([vi,vj],v1..no i, no j..vn)
|
| 1301 |
+
f = self._form_field
|
| 1302 |
+
v = vector_fields
|
| 1303 |
+
ret = 0
|
| 1304 |
+
for i in range(k):
|
| 1305 |
+
t = v[i].rcall(f.rcall(*v[:i] + v[i + 1:]))
|
| 1306 |
+
ret += (-1)**i*t
|
| 1307 |
+
for j in range(i + 1, k):
|
| 1308 |
+
c = Commutator(v[i], v[j])
|
| 1309 |
+
if c: # TODO this is ugly - the Commutator can be Zero and
|
| 1310 |
+
# this causes the next line to fail
|
| 1311 |
+
t = f.rcall(*(c,) + v[:i] + v[i + 1:j] + v[j + 1:])
|
| 1312 |
+
ret += (-1)**(i + j)*t
|
| 1313 |
+
return ret
|
| 1314 |
+
|
| 1315 |
+
|
| 1316 |
+
class TensorProduct(Expr):
|
| 1317 |
+
"""Tensor product of forms.
|
| 1318 |
+
|
| 1319 |
+
Explanation
|
| 1320 |
+
===========
|
| 1321 |
+
|
| 1322 |
+
The tensor product permits the creation of multilinear functionals (i.e.
|
| 1323 |
+
higher order tensors) out of lower order fields (e.g. 1-forms and vector
|
| 1324 |
+
fields). However, the higher tensors thus created lack the interesting
|
| 1325 |
+
features provided by the other type of product, the wedge product, namely
|
| 1326 |
+
they are not antisymmetric and hence are not form fields.
|
| 1327 |
+
|
| 1328 |
+
Examples
|
| 1329 |
+
========
|
| 1330 |
+
|
| 1331 |
+
>>> from sympy.diffgeom.rn import R2_r
|
| 1332 |
+
>>> from sympy.diffgeom import TensorProduct
|
| 1333 |
+
|
| 1334 |
+
>>> fx, fy = R2_r.base_scalars()
|
| 1335 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
| 1336 |
+
>>> dx, dy = R2_r.base_oneforms()
|
| 1337 |
+
|
| 1338 |
+
>>> TensorProduct(dx, dy)(e_x, e_y)
|
| 1339 |
+
1
|
| 1340 |
+
>>> TensorProduct(dx, dy)(e_y, e_x)
|
| 1341 |
+
0
|
| 1342 |
+
>>> TensorProduct(dx, fx*dy)(fx*e_x, e_y)
|
| 1343 |
+
x**2
|
| 1344 |
+
>>> TensorProduct(e_x, e_y)(fx**2, fy**2)
|
| 1345 |
+
4*x*y
|
| 1346 |
+
>>> TensorProduct(e_y, dx)(fy)
|
| 1347 |
+
dx
|
| 1348 |
+
|
| 1349 |
+
You can nest tensor products.
|
| 1350 |
+
|
| 1351 |
+
>>> tp1 = TensorProduct(dx, dy)
|
| 1352 |
+
>>> TensorProduct(tp1, dx)(e_x, e_y, e_x)
|
| 1353 |
+
1
|
| 1354 |
+
|
| 1355 |
+
You can make partial contraction for instance when 'raising an index'.
|
| 1356 |
+
Putting ``None`` in the second argument of ``rcall`` means that the
|
| 1357 |
+
respective position in the tensor product is left as it is.
|
| 1358 |
+
|
| 1359 |
+
>>> TP = TensorProduct
|
| 1360 |
+
>>> metric = TP(dx, dx) + 3*TP(dy, dy)
|
| 1361 |
+
>>> metric.rcall(e_y, None)
|
| 1362 |
+
3*dy
|
| 1363 |
+
|
| 1364 |
+
Or automatically pad the args with ``None`` without specifying them.
|
| 1365 |
+
|
| 1366 |
+
>>> metric.rcall(e_y)
|
| 1367 |
+
3*dy
|
| 1368 |
+
|
| 1369 |
+
"""
|
| 1370 |
+
def __new__(cls, *args):
|
| 1371 |
+
scalar = Mul(*[m for m in args if covariant_order(m) + contravariant_order(m) == 0])
|
| 1372 |
+
multifields = [m for m in args if covariant_order(m) + contravariant_order(m)]
|
| 1373 |
+
if multifields:
|
| 1374 |
+
if len(multifields) == 1:
|
| 1375 |
+
return scalar*multifields[0]
|
| 1376 |
+
return scalar*super().__new__(cls, *multifields)
|
| 1377 |
+
else:
|
| 1378 |
+
return scalar
|
| 1379 |
+
|
| 1380 |
+
def __call__(self, *fields):
|
| 1381 |
+
"""Apply on a list of fields.
|
| 1382 |
+
|
| 1383 |
+
If the number of input fields supplied is not equal to the order of
|
| 1384 |
+
the tensor product field, the list of arguments is padded with ``None``'s.
|
| 1385 |
+
|
| 1386 |
+
The list of arguments is divided in sublists depending on the order of
|
| 1387 |
+
the forms inside the tensor product. The sublists are provided as
|
| 1388 |
+
arguments to these forms and the resulting expressions are given to the
|
| 1389 |
+
constructor of ``TensorProduct``.
|
| 1390 |
+
|
| 1391 |
+
"""
|
| 1392 |
+
tot_order = covariant_order(self) + contravariant_order(self)
|
| 1393 |
+
tot_args = len(fields)
|
| 1394 |
+
if tot_args != tot_order:
|
| 1395 |
+
fields = list(fields) + [None]*(tot_order - tot_args)
|
| 1396 |
+
orders = [covariant_order(f) + contravariant_order(f) for f in self._args]
|
| 1397 |
+
indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)]
|
| 1398 |
+
fields = [fields[i:j] for i, j in zip([0] + indices, indices + [None])]
|
| 1399 |
+
multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, fields)]
|
| 1400 |
+
return TensorProduct(*multipliers)
|
| 1401 |
+
|
| 1402 |
+
|
| 1403 |
+
class WedgeProduct(TensorProduct):
|
| 1404 |
+
"""Wedge product of forms.
|
| 1405 |
+
|
| 1406 |
+
Explanation
|
| 1407 |
+
===========
|
| 1408 |
+
|
| 1409 |
+
In the context of integration only completely antisymmetric forms make
|
| 1410 |
+
sense. The wedge product permits the creation of such forms.
|
| 1411 |
+
|
| 1412 |
+
Examples
|
| 1413 |
+
========
|
| 1414 |
+
|
| 1415 |
+
>>> from sympy.diffgeom.rn import R2_r
|
| 1416 |
+
>>> from sympy.diffgeom import WedgeProduct
|
| 1417 |
+
|
| 1418 |
+
>>> fx, fy = R2_r.base_scalars()
|
| 1419 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
| 1420 |
+
>>> dx, dy = R2_r.base_oneforms()
|
| 1421 |
+
|
| 1422 |
+
>>> WedgeProduct(dx, dy)(e_x, e_y)
|
| 1423 |
+
1
|
| 1424 |
+
>>> WedgeProduct(dx, dy)(e_y, e_x)
|
| 1425 |
+
-1
|
| 1426 |
+
>>> WedgeProduct(dx, fx*dy)(fx*e_x, e_y)
|
| 1427 |
+
x**2
|
| 1428 |
+
>>> WedgeProduct(e_x, e_y)(fy, None)
|
| 1429 |
+
-e_x
|
| 1430 |
+
|
| 1431 |
+
You can nest wedge products.
|
| 1432 |
+
|
| 1433 |
+
>>> wp1 = WedgeProduct(dx, dy)
|
| 1434 |
+
>>> WedgeProduct(wp1, dx)(e_x, e_y, e_x)
|
| 1435 |
+
0
|
| 1436 |
+
|
| 1437 |
+
"""
|
| 1438 |
+
# TODO the calculation of signatures is slow
|
| 1439 |
+
# TODO you do not need all these permutations (neither the prefactor)
|
| 1440 |
+
def __call__(self, *fields):
|
| 1441 |
+
"""Apply on a list of vector_fields.
|
| 1442 |
+
The expression is rewritten internally in terms of tensor products and evaluated."""
|
| 1443 |
+
orders = (covariant_order(e) + contravariant_order(e) for e in self.args)
|
| 1444 |
+
mul = 1/Mul(*(factorial(o) for o in orders))
|
| 1445 |
+
perms = permutations(fields)
|
| 1446 |
+
perms_par = (Permutation(
|
| 1447 |
+
p).signature() for p in permutations(range(len(fields))))
|
| 1448 |
+
tensor_prod = TensorProduct(*self.args)
|
| 1449 |
+
return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)])
|
| 1450 |
+
|
| 1451 |
+
|
| 1452 |
+
class LieDerivative(Expr):
|
| 1453 |
+
"""Lie derivative with respect to a vector field.
|
| 1454 |
+
|
| 1455 |
+
Explanation
|
| 1456 |
+
===========
|
| 1457 |
+
|
| 1458 |
+
The transport operator that defines the Lie derivative is the pushforward of
|
| 1459 |
+
the field to be derived along the integral curve of the field with respect
|
| 1460 |
+
to which one derives.
|
| 1461 |
+
|
| 1462 |
+
Examples
|
| 1463 |
+
========
|
| 1464 |
+
|
| 1465 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
| 1466 |
+
>>> from sympy.diffgeom import (LieDerivative, TensorProduct)
|
| 1467 |
+
|
| 1468 |
+
>>> fx, fy = R2_r.base_scalars()
|
| 1469 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
| 1470 |
+
>>> e_rho, e_theta = R2_p.base_vectors()
|
| 1471 |
+
>>> dx, dy = R2_r.base_oneforms()
|
| 1472 |
+
|
| 1473 |
+
>>> LieDerivative(e_x, fy)
|
| 1474 |
+
0
|
| 1475 |
+
>>> LieDerivative(e_x, fx)
|
| 1476 |
+
1
|
| 1477 |
+
>>> LieDerivative(e_x, e_x)
|
| 1478 |
+
0
|
| 1479 |
+
|
| 1480 |
+
The Lie derivative of a tensor field by another tensor field is equal to
|
| 1481 |
+
their commutator:
|
| 1482 |
+
|
| 1483 |
+
>>> LieDerivative(e_x, e_rho)
|
| 1484 |
+
Commutator(e_x, e_rho)
|
| 1485 |
+
>>> LieDerivative(e_x + e_y, fx)
|
| 1486 |
+
1
|
| 1487 |
+
|
| 1488 |
+
>>> tp = TensorProduct(dx, dy)
|
| 1489 |
+
>>> LieDerivative(e_x, tp)
|
| 1490 |
+
LieDerivative(e_x, TensorProduct(dx, dy))
|
| 1491 |
+
>>> LieDerivative(e_x, tp)
|
| 1492 |
+
LieDerivative(e_x, TensorProduct(dx, dy))
|
| 1493 |
+
|
| 1494 |
+
"""
|
| 1495 |
+
def __new__(cls, v_field, expr):
|
| 1496 |
+
expr_form_ord = covariant_order(expr)
|
| 1497 |
+
if contravariant_order(v_field) != 1 or covariant_order(v_field):
|
| 1498 |
+
raise ValueError('Lie derivatives are defined only with respect to'
|
| 1499 |
+
' vector fields. The supplied argument was not a '
|
| 1500 |
+
'vector field.')
|
| 1501 |
+
if expr_form_ord > 0:
|
| 1502 |
+
obj = super().__new__(cls, v_field, expr)
|
| 1503 |
+
# deprecated assignments
|
| 1504 |
+
obj._v_field = v_field
|
| 1505 |
+
obj._expr = expr
|
| 1506 |
+
return obj
|
| 1507 |
+
if expr.atoms(BaseVectorField):
|
| 1508 |
+
return Commutator(v_field, expr)
|
| 1509 |
+
else:
|
| 1510 |
+
return v_field.rcall(expr)
|
| 1511 |
+
|
| 1512 |
+
@property
|
| 1513 |
+
def v_field(self):
|
| 1514 |
+
return self.args[0]
|
| 1515 |
+
|
| 1516 |
+
@property
|
| 1517 |
+
def expr(self):
|
| 1518 |
+
return self.args[1]
|
| 1519 |
+
|
| 1520 |
+
def __call__(self, *args):
|
| 1521 |
+
v = self.v_field
|
| 1522 |
+
expr = self.expr
|
| 1523 |
+
lead_term = v(expr(*args))
|
| 1524 |
+
rest = Add(*[Mul(*args[:i] + (Commutator(v, args[i]),) + args[i + 1:])
|
| 1525 |
+
for i in range(len(args))])
|
| 1526 |
+
return lead_term - rest
|
| 1527 |
+
|
| 1528 |
+
|
| 1529 |
+
class BaseCovarDerivativeOp(Expr):
|
| 1530 |
+
"""Covariant derivative operator with respect to a base vector.
|
| 1531 |
+
|
| 1532 |
+
Examples
|
| 1533 |
+
========
|
| 1534 |
+
|
| 1535 |
+
>>> from sympy.diffgeom.rn import R2_r
|
| 1536 |
+
>>> from sympy.diffgeom import BaseCovarDerivativeOp
|
| 1537 |
+
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
|
| 1538 |
+
|
| 1539 |
+
>>> TP = TensorProduct
|
| 1540 |
+
>>> fx, fy = R2_r.base_scalars()
|
| 1541 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
| 1542 |
+
>>> dx, dy = R2_r.base_oneforms()
|
| 1543 |
+
|
| 1544 |
+
>>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
|
| 1545 |
+
>>> ch
|
| 1546 |
+
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
|
| 1547 |
+
>>> cvd = BaseCovarDerivativeOp(R2_r, 0, ch)
|
| 1548 |
+
>>> cvd(fx)
|
| 1549 |
+
1
|
| 1550 |
+
>>> cvd(fx*e_x)
|
| 1551 |
+
e_x
|
| 1552 |
+
"""
|
| 1553 |
+
|
| 1554 |
+
def __new__(cls, coord_sys, index, christoffel):
|
| 1555 |
+
index = _sympify(index)
|
| 1556 |
+
christoffel = ImmutableDenseNDimArray(christoffel)
|
| 1557 |
+
obj = super().__new__(cls, coord_sys, index, christoffel)
|
| 1558 |
+
# deprecated assignments
|
| 1559 |
+
obj._coord_sys = coord_sys
|
| 1560 |
+
obj._index = index
|
| 1561 |
+
obj._christoffel = christoffel
|
| 1562 |
+
return obj
|
| 1563 |
+
|
| 1564 |
+
@property
|
| 1565 |
+
def coord_sys(self):
|
| 1566 |
+
return self.args[0]
|
| 1567 |
+
|
| 1568 |
+
@property
|
| 1569 |
+
def index(self):
|
| 1570 |
+
return self.args[1]
|
| 1571 |
+
|
| 1572 |
+
@property
|
| 1573 |
+
def christoffel(self):
|
| 1574 |
+
return self.args[2]
|
| 1575 |
+
|
| 1576 |
+
def __call__(self, field):
|
| 1577 |
+
"""Apply on a scalar field.
|
| 1578 |
+
|
| 1579 |
+
The action of a vector field on a scalar field is a directional
|
| 1580 |
+
differentiation.
|
| 1581 |
+
If the argument is not a scalar field the behaviour is undefined.
|
| 1582 |
+
"""
|
| 1583 |
+
if covariant_order(field) != 0:
|
| 1584 |
+
raise NotImplementedError()
|
| 1585 |
+
|
| 1586 |
+
field = vectors_in_basis(field, self._coord_sys)
|
| 1587 |
+
|
| 1588 |
+
wrt_vector = self._coord_sys.base_vector(self._index)
|
| 1589 |
+
wrt_scalar = self._coord_sys.coord_function(self._index)
|
| 1590 |
+
vectors = list(field.atoms(BaseVectorField))
|
| 1591 |
+
|
| 1592 |
+
# First step: replace all vectors with something susceptible to
|
| 1593 |
+
# derivation and do the derivation
|
| 1594 |
+
# TODO: you need a real dummy function for the next line
|
| 1595 |
+
d_funcs = [Function('_#_%s' % i)(wrt_scalar) for i,
|
| 1596 |
+
b in enumerate(vectors)]
|
| 1597 |
+
d_result = field.subs(list(zip(vectors, d_funcs)))
|
| 1598 |
+
d_result = wrt_vector(d_result)
|
| 1599 |
+
|
| 1600 |
+
# Second step: backsubstitute the vectors in
|
| 1601 |
+
d_result = d_result.subs(list(zip(d_funcs, vectors)))
|
| 1602 |
+
|
| 1603 |
+
# Third step: evaluate the derivatives of the vectors
|
| 1604 |
+
derivs = []
|
| 1605 |
+
for v in vectors:
|
| 1606 |
+
d = Add(*[(self._christoffel[k, wrt_vector._index, v._index]
|
| 1607 |
+
*v._coord_sys.base_vector(k))
|
| 1608 |
+
for k in range(v._coord_sys.dim)])
|
| 1609 |
+
derivs.append(d)
|
| 1610 |
+
to_subs = [wrt_vector(d) for d in d_funcs]
|
| 1611 |
+
# XXX: This substitution can fail when there are Dummy symbols and the
|
| 1612 |
+
# cache is disabled: https://github.com/sympy/sympy/issues/17794
|
| 1613 |
+
result = d_result.subs(list(zip(to_subs, derivs)))
|
| 1614 |
+
|
| 1615 |
+
# Remove the dummies
|
| 1616 |
+
result = result.subs(list(zip(d_funcs, vectors)))
|
| 1617 |
+
return result.doit()
|
| 1618 |
+
|
| 1619 |
+
|
| 1620 |
+
class CovarDerivativeOp(Expr):
|
| 1621 |
+
"""Covariant derivative operator.
|
| 1622 |
+
|
| 1623 |
+
Examples
|
| 1624 |
+
========
|
| 1625 |
+
|
| 1626 |
+
>>> from sympy.diffgeom.rn import R2_r
|
| 1627 |
+
>>> from sympy.diffgeom import CovarDerivativeOp
|
| 1628 |
+
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
|
| 1629 |
+
>>> TP = TensorProduct
|
| 1630 |
+
>>> fx, fy = R2_r.base_scalars()
|
| 1631 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
| 1632 |
+
>>> dx, dy = R2_r.base_oneforms()
|
| 1633 |
+
>>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
|
| 1634 |
+
|
| 1635 |
+
>>> ch
|
| 1636 |
+
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
|
| 1637 |
+
>>> cvd = CovarDerivativeOp(fx*e_x, ch)
|
| 1638 |
+
>>> cvd(fx)
|
| 1639 |
+
x
|
| 1640 |
+
>>> cvd(fx*e_x)
|
| 1641 |
+
x*e_x
|
| 1642 |
+
|
| 1643 |
+
"""
|
| 1644 |
+
|
| 1645 |
+
def __new__(cls, wrt, christoffel):
|
| 1646 |
+
if len({v._coord_sys for v in wrt.atoms(BaseVectorField)}) > 1:
|
| 1647 |
+
raise NotImplementedError()
|
| 1648 |
+
if contravariant_order(wrt) != 1 or covariant_order(wrt):
|
| 1649 |
+
raise ValueError('Covariant derivatives are defined only with '
|
| 1650 |
+
'respect to vector fields. The supplied argument '
|
| 1651 |
+
'was not a vector field.')
|
| 1652 |
+
christoffel = ImmutableDenseNDimArray(christoffel)
|
| 1653 |
+
obj = super().__new__(cls, wrt, christoffel)
|
| 1654 |
+
# deprecated assignments
|
| 1655 |
+
obj._wrt = wrt
|
| 1656 |
+
obj._christoffel = christoffel
|
| 1657 |
+
return obj
|
| 1658 |
+
|
| 1659 |
+
@property
|
| 1660 |
+
def wrt(self):
|
| 1661 |
+
return self.args[0]
|
| 1662 |
+
|
| 1663 |
+
@property
|
| 1664 |
+
def christoffel(self):
|
| 1665 |
+
return self.args[1]
|
| 1666 |
+
|
| 1667 |
+
def __call__(self, field):
|
| 1668 |
+
vectors = list(self._wrt.atoms(BaseVectorField))
|
| 1669 |
+
base_ops = [BaseCovarDerivativeOp(v._coord_sys, v._index, self._christoffel)
|
| 1670 |
+
for v in vectors]
|
| 1671 |
+
return self._wrt.subs(list(zip(vectors, base_ops))).rcall(field)
|
| 1672 |
+
|
| 1673 |
+
|
| 1674 |
+
###############################################################################
|
| 1675 |
+
# Integral curves on vector fields
|
| 1676 |
+
###############################################################################
|
| 1677 |
+
def intcurve_series(vector_field, param, start_point, n=6, coord_sys=None, coeffs=False):
|
| 1678 |
+
r"""Return the series expansion for an integral curve of the field.
|
| 1679 |
+
|
| 1680 |
+
Explanation
|
| 1681 |
+
===========
|
| 1682 |
+
|
| 1683 |
+
Integral curve is a function `\gamma` taking a parameter in `R` to a point
|
| 1684 |
+
in the manifold. It verifies the equation:
|
| 1685 |
+
|
| 1686 |
+
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
|
| 1687 |
+
|
| 1688 |
+
where the given ``vector_field`` is denoted as `V`. This holds for any
|
| 1689 |
+
value `t` for the parameter and any scalar field `f`.
|
| 1690 |
+
|
| 1691 |
+
This equation can also be decomposed of a basis of coordinate functions
|
| 1692 |
+
`V(f_i)\big(\gamma(t)\big) = \frac{d}{dt}f_i\big(\gamma(t)\big) \quad \forall i`
|
| 1693 |
+
|
| 1694 |
+
This function returns a series expansion of `\gamma(t)` in terms of the
|
| 1695 |
+
coordinate system ``coord_sys``. The equations and expansions are necessarily
|
| 1696 |
+
done in coordinate-system-dependent way as there is no other way to
|
| 1697 |
+
represent movement between points on the manifold (i.e. there is no such
|
| 1698 |
+
thing as a difference of points for a general manifold).
|
| 1699 |
+
|
| 1700 |
+
Parameters
|
| 1701 |
+
==========
|
| 1702 |
+
vector_field
|
| 1703 |
+
the vector field for which an integral curve will be given
|
| 1704 |
+
|
| 1705 |
+
param
|
| 1706 |
+
the argument of the function `\gamma` from R to the curve
|
| 1707 |
+
|
| 1708 |
+
start_point
|
| 1709 |
+
the point which corresponds to `\gamma(0)`
|
| 1710 |
+
|
| 1711 |
+
n
|
| 1712 |
+
the order to which to expand
|
| 1713 |
+
|
| 1714 |
+
coord_sys
|
| 1715 |
+
the coordinate system in which to expand
|
| 1716 |
+
coeffs (default False) - if True return a list of elements of the expansion
|
| 1717 |
+
|
| 1718 |
+
Examples
|
| 1719 |
+
========
|
| 1720 |
+
|
| 1721 |
+
Use the predefined R2 manifold:
|
| 1722 |
+
|
| 1723 |
+
>>> from sympy.abc import t, x, y
|
| 1724 |
+
>>> from sympy.diffgeom.rn import R2_p, R2_r
|
| 1725 |
+
>>> from sympy.diffgeom import intcurve_series
|
| 1726 |
+
|
| 1727 |
+
Specify a starting point and a vector field:
|
| 1728 |
+
|
| 1729 |
+
>>> start_point = R2_r.point([x, y])
|
| 1730 |
+
>>> vector_field = R2_r.e_x
|
| 1731 |
+
|
| 1732 |
+
Calculate the series:
|
| 1733 |
+
|
| 1734 |
+
>>> intcurve_series(vector_field, t, start_point, n=3)
|
| 1735 |
+
Matrix([
|
| 1736 |
+
[t + x],
|
| 1737 |
+
[ y]])
|
| 1738 |
+
|
| 1739 |
+
Or get the elements of the expansion in a list:
|
| 1740 |
+
|
| 1741 |
+
>>> series = intcurve_series(vector_field, t, start_point, n=3, coeffs=True)
|
| 1742 |
+
>>> series[0]
|
| 1743 |
+
Matrix([
|
| 1744 |
+
[x],
|
| 1745 |
+
[y]])
|
| 1746 |
+
>>> series[1]
|
| 1747 |
+
Matrix([
|
| 1748 |
+
[t],
|
| 1749 |
+
[0]])
|
| 1750 |
+
>>> series[2]
|
| 1751 |
+
Matrix([
|
| 1752 |
+
[0],
|
| 1753 |
+
[0]])
|
| 1754 |
+
|
| 1755 |
+
The series in the polar coordinate system:
|
| 1756 |
+
|
| 1757 |
+
>>> series = intcurve_series(vector_field, t, start_point,
|
| 1758 |
+
... n=3, coord_sys=R2_p, coeffs=True)
|
| 1759 |
+
>>> series[0]
|
| 1760 |
+
Matrix([
|
| 1761 |
+
[sqrt(x**2 + y**2)],
|
| 1762 |
+
[ atan2(y, x)]])
|
| 1763 |
+
>>> series[1]
|
| 1764 |
+
Matrix([
|
| 1765 |
+
[t*x/sqrt(x**2 + y**2)],
|
| 1766 |
+
[ -t*y/(x**2 + y**2)]])
|
| 1767 |
+
>>> series[2]
|
| 1768 |
+
Matrix([
|
| 1769 |
+
[t**2*(-x**2/(x**2 + y**2)**(3/2) + 1/sqrt(x**2 + y**2))/2],
|
| 1770 |
+
[ t**2*x*y/(x**2 + y**2)**2]])
|
| 1771 |
+
|
| 1772 |
+
See Also
|
| 1773 |
+
========
|
| 1774 |
+
|
| 1775 |
+
intcurve_diffequ
|
| 1776 |
+
|
| 1777 |
+
"""
|
| 1778 |
+
if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
|
| 1779 |
+
raise ValueError('The supplied field was not a vector field.')
|
| 1780 |
+
|
| 1781 |
+
def iter_vfield(scalar_field, i):
|
| 1782 |
+
"""Return ``vector_field`` called `i` times on ``scalar_field``."""
|
| 1783 |
+
return reduce(lambda s, v: v.rcall(s), [vector_field, ]*i, scalar_field)
|
| 1784 |
+
|
| 1785 |
+
def taylor_terms_per_coord(coord_function):
|
| 1786 |
+
"""Return the series for one of the coordinates."""
|
| 1787 |
+
return [param**i*iter_vfield(coord_function, i).rcall(start_point)/factorial(i)
|
| 1788 |
+
for i in range(n)]
|
| 1789 |
+
coord_sys = coord_sys if coord_sys else start_point._coord_sys
|
| 1790 |
+
coord_functions = coord_sys.coord_functions()
|
| 1791 |
+
taylor_terms = [taylor_terms_per_coord(f) for f in coord_functions]
|
| 1792 |
+
if coeffs:
|
| 1793 |
+
return [Matrix(t) for t in zip(*taylor_terms)]
|
| 1794 |
+
else:
|
| 1795 |
+
return Matrix([sum(c) for c in taylor_terms])
|
| 1796 |
+
|
| 1797 |
+
|
| 1798 |
+
def intcurve_diffequ(vector_field, param, start_point, coord_sys=None):
|
| 1799 |
+
r"""Return the differential equation for an integral curve of the field.
|
| 1800 |
+
|
| 1801 |
+
Explanation
|
| 1802 |
+
===========
|
| 1803 |
+
|
| 1804 |
+
Integral curve is a function `\gamma` taking a parameter in `R` to a point
|
| 1805 |
+
in the manifold. It verifies the equation:
|
| 1806 |
+
|
| 1807 |
+
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
|
| 1808 |
+
|
| 1809 |
+
where the given ``vector_field`` is denoted as `V`. This holds for any
|
| 1810 |
+
value `t` for the parameter and any scalar field `f`.
|
| 1811 |
+
|
| 1812 |
+
This function returns the differential equation of `\gamma(t)` in terms of the
|
| 1813 |
+
coordinate system ``coord_sys``. The equations and expansions are necessarily
|
| 1814 |
+
done in coordinate-system-dependent way as there is no other way to
|
| 1815 |
+
represent movement between points on the manifold (i.e. there is no such
|
| 1816 |
+
thing as a difference of points for a general manifold).
|
| 1817 |
+
|
| 1818 |
+
Parameters
|
| 1819 |
+
==========
|
| 1820 |
+
|
| 1821 |
+
vector_field
|
| 1822 |
+
the vector field for which an integral curve will be given
|
| 1823 |
+
|
| 1824 |
+
param
|
| 1825 |
+
the argument of the function `\gamma` from R to the curve
|
| 1826 |
+
|
| 1827 |
+
start_point
|
| 1828 |
+
the point which corresponds to `\gamma(0)`
|
| 1829 |
+
|
| 1830 |
+
coord_sys
|
| 1831 |
+
the coordinate system in which to give the equations
|
| 1832 |
+
|
| 1833 |
+
Returns
|
| 1834 |
+
=======
|
| 1835 |
+
|
| 1836 |
+
a tuple of (equations, initial conditions)
|
| 1837 |
+
|
| 1838 |
+
Examples
|
| 1839 |
+
========
|
| 1840 |
+
|
| 1841 |
+
Use the predefined R2 manifold:
|
| 1842 |
+
|
| 1843 |
+
>>> from sympy.abc import t
|
| 1844 |
+
>>> from sympy.diffgeom.rn import R2, R2_p, R2_r
|
| 1845 |
+
>>> from sympy.diffgeom import intcurve_diffequ
|
| 1846 |
+
|
| 1847 |
+
Specify a starting point and a vector field:
|
| 1848 |
+
|
| 1849 |
+
>>> start_point = R2_r.point([0, 1])
|
| 1850 |
+
>>> vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
|
| 1851 |
+
|
| 1852 |
+
Get the equation:
|
| 1853 |
+
|
| 1854 |
+
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point)
|
| 1855 |
+
>>> equations
|
| 1856 |
+
[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]
|
| 1857 |
+
>>> init_cond
|
| 1858 |
+
[f_0(0), f_1(0) - 1]
|
| 1859 |
+
|
| 1860 |
+
The series in the polar coordinate system:
|
| 1861 |
+
|
| 1862 |
+
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p)
|
| 1863 |
+
>>> equations
|
| 1864 |
+
[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]
|
| 1865 |
+
>>> init_cond
|
| 1866 |
+
[f_0(0) - 1, f_1(0) - pi/2]
|
| 1867 |
+
|
| 1868 |
+
See Also
|
| 1869 |
+
========
|
| 1870 |
+
|
| 1871 |
+
intcurve_series
|
| 1872 |
+
|
| 1873 |
+
"""
|
| 1874 |
+
if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
|
| 1875 |
+
raise ValueError('The supplied field was not a vector field.')
|
| 1876 |
+
coord_sys = coord_sys if coord_sys else start_point._coord_sys
|
| 1877 |
+
gammas = [Function('f_%d' % i)(param) for i in range(
|
| 1878 |
+
start_point._coord_sys.dim)]
|
| 1879 |
+
arbitrary_p = Point(coord_sys, gammas)
|
| 1880 |
+
coord_functions = coord_sys.coord_functions()
|
| 1881 |
+
equations = [simplify(diff(cf.rcall(arbitrary_p), param) - vector_field.rcall(cf).rcall(arbitrary_p))
|
| 1882 |
+
for cf in coord_functions]
|
| 1883 |
+
init_cond = [simplify(cf.rcall(arbitrary_p).subs(param, 0) - cf.rcall(start_point))
|
| 1884 |
+
for cf in coord_functions]
|
| 1885 |
+
return equations, init_cond
|
| 1886 |
+
|
| 1887 |
+
|
| 1888 |
+
###############################################################################
|
| 1889 |
+
# Helpers
|
| 1890 |
+
###############################################################################
|
| 1891 |
+
def dummyfy(args, exprs):
|
| 1892 |
+
# TODO Is this a good idea?
|
| 1893 |
+
d_args = Matrix([s.as_dummy() for s in args])
|
| 1894 |
+
reps = dict(zip(args, d_args))
|
| 1895 |
+
d_exprs = Matrix([_sympify(expr).subs(reps) for expr in exprs])
|
| 1896 |
+
return d_args, d_exprs
|
| 1897 |
+
|
| 1898 |
+
###############################################################################
|
| 1899 |
+
# Helpers
|
| 1900 |
+
###############################################################################
|
| 1901 |
+
def contravariant_order(expr, _strict=False):
|
| 1902 |
+
"""Return the contravariant order of an expression.
|
| 1903 |
+
|
| 1904 |
+
Examples
|
| 1905 |
+
========
|
| 1906 |
+
|
| 1907 |
+
>>> from sympy.diffgeom import contravariant_order
|
| 1908 |
+
>>> from sympy.diffgeom.rn import R2
|
| 1909 |
+
>>> from sympy.abc import a
|
| 1910 |
+
|
| 1911 |
+
>>> contravariant_order(a)
|
| 1912 |
+
0
|
| 1913 |
+
>>> contravariant_order(a*R2.x + 2)
|
| 1914 |
+
0
|
| 1915 |
+
>>> contravariant_order(a*R2.x*R2.e_y + R2.e_x)
|
| 1916 |
+
1
|
| 1917 |
+
|
| 1918 |
+
"""
|
| 1919 |
+
# TODO move some of this to class methods.
|
| 1920 |
+
# TODO rewrite using the .as_blah_blah methods
|
| 1921 |
+
if isinstance(expr, Add):
|
| 1922 |
+
orders = [contravariant_order(e) for e in expr.args]
|
| 1923 |
+
if len(set(orders)) != 1:
|
| 1924 |
+
raise ValueError('Misformed expression containing contravariant fields of varying order.')
|
| 1925 |
+
return orders[0]
|
| 1926 |
+
elif isinstance(expr, Mul):
|
| 1927 |
+
orders = [contravariant_order(e) for e in expr.args]
|
| 1928 |
+
not_zero = [o for o in orders if o != 0]
|
| 1929 |
+
if len(not_zero) > 1:
|
| 1930 |
+
raise ValueError('Misformed expression containing multiplication between vectors.')
|
| 1931 |
+
return 0 if not not_zero else not_zero[0]
|
| 1932 |
+
elif isinstance(expr, Pow):
|
| 1933 |
+
if covariant_order(expr.base) or covariant_order(expr.exp):
|
| 1934 |
+
raise ValueError(
|
| 1935 |
+
'Misformed expression containing a power of a vector.')
|
| 1936 |
+
return 0
|
| 1937 |
+
elif isinstance(expr, BaseVectorField):
|
| 1938 |
+
return 1
|
| 1939 |
+
elif isinstance(expr, TensorProduct):
|
| 1940 |
+
return sum(contravariant_order(a) for a in expr.args)
|
| 1941 |
+
elif not _strict or expr.atoms(BaseScalarField):
|
| 1942 |
+
return 0
|
| 1943 |
+
else: # If it does not contain anything related to the diffgeom module and it is _strict
|
| 1944 |
+
return -1
|
| 1945 |
+
|
| 1946 |
+
|
| 1947 |
+
def covariant_order(expr, _strict=False):
|
| 1948 |
+
"""Return the covariant order of an expression.
|
| 1949 |
+
|
| 1950 |
+
Examples
|
| 1951 |
+
========
|
| 1952 |
+
|
| 1953 |
+
>>> from sympy.diffgeom import covariant_order
|
| 1954 |
+
>>> from sympy.diffgeom.rn import R2
|
| 1955 |
+
>>> from sympy.abc import a
|
| 1956 |
+
|
| 1957 |
+
>>> covariant_order(a)
|
| 1958 |
+
0
|
| 1959 |
+
>>> covariant_order(a*R2.x + 2)
|
| 1960 |
+
0
|
| 1961 |
+
>>> covariant_order(a*R2.x*R2.dy + R2.dx)
|
| 1962 |
+
1
|
| 1963 |
+
|
| 1964 |
+
"""
|
| 1965 |
+
# TODO move some of this to class methods.
|
| 1966 |
+
# TODO rewrite using the .as_blah_blah methods
|
| 1967 |
+
if isinstance(expr, Add):
|
| 1968 |
+
orders = [covariant_order(e) for e in expr.args]
|
| 1969 |
+
if len(set(orders)) != 1:
|
| 1970 |
+
raise ValueError('Misformed expression containing form fields of varying order.')
|
| 1971 |
+
return orders[0]
|
| 1972 |
+
elif isinstance(expr, Mul):
|
| 1973 |
+
orders = [covariant_order(e) for e in expr.args]
|
| 1974 |
+
not_zero = [o for o in orders if o != 0]
|
| 1975 |
+
if len(not_zero) > 1:
|
| 1976 |
+
raise ValueError('Misformed expression containing multiplication between forms.')
|
| 1977 |
+
return 0 if not not_zero else not_zero[0]
|
| 1978 |
+
elif isinstance(expr, Pow):
|
| 1979 |
+
if covariant_order(expr.base) or covariant_order(expr.exp):
|
| 1980 |
+
raise ValueError(
|
| 1981 |
+
'Misformed expression containing a power of a form.')
|
| 1982 |
+
return 0
|
| 1983 |
+
elif isinstance(expr, Differential):
|
| 1984 |
+
return covariant_order(*expr.args) + 1
|
| 1985 |
+
elif isinstance(expr, TensorProduct):
|
| 1986 |
+
return sum(covariant_order(a) for a in expr.args)
|
| 1987 |
+
elif not _strict or expr.atoms(BaseScalarField):
|
| 1988 |
+
return 0
|
| 1989 |
+
else: # If it does not contain anything related to the diffgeom module and it is _strict
|
| 1990 |
+
return -1
|
| 1991 |
+
|
| 1992 |
+
|
| 1993 |
+
###############################################################################
|
| 1994 |
+
# Coordinate transformation functions
|
| 1995 |
+
###############################################################################
|
| 1996 |
+
def vectors_in_basis(expr, to_sys):
|
| 1997 |
+
"""Transform all base vectors in base vectors of a specified coord basis.
|
| 1998 |
+
While the new base vectors are in the new coordinate system basis, any
|
| 1999 |
+
coefficients are kept in the old system.
|
| 2000 |
+
|
| 2001 |
+
Examples
|
| 2002 |
+
========
|
| 2003 |
+
|
| 2004 |
+
>>> from sympy.diffgeom import vectors_in_basis
|
| 2005 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
| 2006 |
+
|
| 2007 |
+
>>> vectors_in_basis(R2_r.e_x, R2_p)
|
| 2008 |
+
-y*e_theta/(x**2 + y**2) + x*e_rho/sqrt(x**2 + y**2)
|
| 2009 |
+
>>> vectors_in_basis(R2_p.e_r, R2_r)
|
| 2010 |
+
sin(theta)*e_y + cos(theta)*e_x
|
| 2011 |
+
|
| 2012 |
+
"""
|
| 2013 |
+
vectors = list(expr.atoms(BaseVectorField))
|
| 2014 |
+
new_vectors = []
|
| 2015 |
+
for v in vectors:
|
| 2016 |
+
cs = v._coord_sys
|
| 2017 |
+
jac = cs.jacobian(to_sys, cs.coord_functions())
|
| 2018 |
+
new = (jac.T*Matrix(to_sys.base_vectors()))[v._index]
|
| 2019 |
+
new_vectors.append(new)
|
| 2020 |
+
return expr.subs(list(zip(vectors, new_vectors)))
|
| 2021 |
+
|
| 2022 |
+
|
| 2023 |
+
###############################################################################
|
| 2024 |
+
# Coordinate-dependent functions
|
| 2025 |
+
###############################################################################
|
| 2026 |
+
def twoform_to_matrix(expr):
|
| 2027 |
+
"""Return the matrix representing the twoform.
|
| 2028 |
+
|
| 2029 |
+
For the twoform `w` return the matrix `M` such that `M[i,j]=w(e_i, e_j)`,
|
| 2030 |
+
where `e_i` is the i-th base vector field for the coordinate system in
|
| 2031 |
+
which the expression of `w` is given.
|
| 2032 |
+
|
| 2033 |
+
Examples
|
| 2034 |
+
========
|
| 2035 |
+
|
| 2036 |
+
>>> from sympy.diffgeom.rn import R2
|
| 2037 |
+
>>> from sympy.diffgeom import twoform_to_matrix, TensorProduct
|
| 2038 |
+
>>> TP = TensorProduct
|
| 2039 |
+
|
| 2040 |
+
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
| 2041 |
+
Matrix([
|
| 2042 |
+
[1, 0],
|
| 2043 |
+
[0, 1]])
|
| 2044 |
+
>>> twoform_to_matrix(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
| 2045 |
+
Matrix([
|
| 2046 |
+
[x, 0],
|
| 2047 |
+
[0, 1]])
|
| 2048 |
+
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy) - TP(R2.dx, R2.dy)/2)
|
| 2049 |
+
Matrix([
|
| 2050 |
+
[ 1, 0],
|
| 2051 |
+
[-1/2, 1]])
|
| 2052 |
+
|
| 2053 |
+
"""
|
| 2054 |
+
if covariant_order(expr) != 2 or contravariant_order(expr):
|
| 2055 |
+
raise ValueError('The input expression is not a two-form.')
|
| 2056 |
+
coord_sys = _find_coords(expr)
|
| 2057 |
+
if len(coord_sys) != 1:
|
| 2058 |
+
raise ValueError('The input expression concerns more than one '
|
| 2059 |
+
'coordinate systems, hence there is no unambiguous '
|
| 2060 |
+
'way to choose a coordinate system for the matrix.')
|
| 2061 |
+
coord_sys = coord_sys.pop()
|
| 2062 |
+
vectors = coord_sys.base_vectors()
|
| 2063 |
+
expr = expr.expand()
|
| 2064 |
+
matrix_content = [[expr.rcall(v1, v2) for v1 in vectors]
|
| 2065 |
+
for v2 in vectors]
|
| 2066 |
+
return Matrix(matrix_content)
|
| 2067 |
+
|
| 2068 |
+
|
| 2069 |
+
def metric_to_Christoffel_1st(expr):
|
| 2070 |
+
"""Return the nested list of Christoffel symbols for the given metric.
|
| 2071 |
+
This returns the Christoffel symbol of first kind that represents the
|
| 2072 |
+
Levi-Civita connection for the given metric.
|
| 2073 |
+
|
| 2074 |
+
Examples
|
| 2075 |
+
========
|
| 2076 |
+
|
| 2077 |
+
>>> from sympy.diffgeom.rn import R2
|
| 2078 |
+
>>> from sympy.diffgeom import metric_to_Christoffel_1st, TensorProduct
|
| 2079 |
+
>>> TP = TensorProduct
|
| 2080 |
+
|
| 2081 |
+
>>> metric_to_Christoffel_1st(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
| 2082 |
+
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
|
| 2083 |
+
>>> metric_to_Christoffel_1st(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
| 2084 |
+
[[[1/2, 0], [0, 0]], [[0, 0], [0, 0]]]
|
| 2085 |
+
|
| 2086 |
+
"""
|
| 2087 |
+
matrix = twoform_to_matrix(expr)
|
| 2088 |
+
if not matrix.is_symmetric():
|
| 2089 |
+
raise ValueError(
|
| 2090 |
+
'The two-form representing the metric is not symmetric.')
|
| 2091 |
+
coord_sys = _find_coords(expr).pop()
|
| 2092 |
+
deriv_matrices = [matrix.applyfunc(d) for d in coord_sys.base_vectors()]
|
| 2093 |
+
indices = list(range(coord_sys.dim))
|
| 2094 |
+
christoffel = [[[(deriv_matrices[k][i, j] + deriv_matrices[j][i, k] - deriv_matrices[i][j, k])/2
|
| 2095 |
+
for k in indices]
|
| 2096 |
+
for j in indices]
|
| 2097 |
+
for i in indices]
|
| 2098 |
+
return ImmutableDenseNDimArray(christoffel)
|
| 2099 |
+
|
| 2100 |
+
|
| 2101 |
+
def metric_to_Christoffel_2nd(expr):
|
| 2102 |
+
"""Return the nested list of Christoffel symbols for the given metric.
|
| 2103 |
+
This returns the Christoffel symbol of second kind that represents the
|
| 2104 |
+
Levi-Civita connection for the given metric.
|
| 2105 |
+
|
| 2106 |
+
Examples
|
| 2107 |
+
========
|
| 2108 |
+
|
| 2109 |
+
>>> from sympy.diffgeom.rn import R2
|
| 2110 |
+
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
|
| 2111 |
+
>>> TP = TensorProduct
|
| 2112 |
+
|
| 2113 |
+
>>> metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
| 2114 |
+
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
|
| 2115 |
+
>>> metric_to_Christoffel_2nd(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
| 2116 |
+
[[[1/(2*x), 0], [0, 0]], [[0, 0], [0, 0]]]
|
| 2117 |
+
|
| 2118 |
+
"""
|
| 2119 |
+
ch_1st = metric_to_Christoffel_1st(expr)
|
| 2120 |
+
coord_sys = _find_coords(expr).pop()
|
| 2121 |
+
indices = list(range(coord_sys.dim))
|
| 2122 |
+
# XXX workaround, inverting a matrix does not work if it contains non
|
| 2123 |
+
# symbols
|
| 2124 |
+
#matrix = twoform_to_matrix(expr).inv()
|
| 2125 |
+
matrix = twoform_to_matrix(expr)
|
| 2126 |
+
s_fields = set()
|
| 2127 |
+
for e in matrix:
|
| 2128 |
+
s_fields.update(e.atoms(BaseScalarField))
|
| 2129 |
+
s_fields = list(s_fields)
|
| 2130 |
+
dums = coord_sys.symbols
|
| 2131 |
+
matrix = matrix.subs(list(zip(s_fields, dums))).inv().subs(list(zip(dums, s_fields)))
|
| 2132 |
+
# XXX end of workaround
|
| 2133 |
+
christoffel = [[[Add(*[matrix[i, l]*ch_1st[l, j, k] for l in indices])
|
| 2134 |
+
for k in indices]
|
| 2135 |
+
for j in indices]
|
| 2136 |
+
for i in indices]
|
| 2137 |
+
return ImmutableDenseNDimArray(christoffel)
|
| 2138 |
+
|
| 2139 |
+
|
| 2140 |
+
def metric_to_Riemann_components(expr):
|
| 2141 |
+
"""Return the components of the Riemann tensor expressed in a given basis.
|
| 2142 |
+
|
| 2143 |
+
Given a metric it calculates the components of the Riemann tensor in the
|
| 2144 |
+
canonical basis of the coordinate system in which the metric expression is
|
| 2145 |
+
given.
|
| 2146 |
+
|
| 2147 |
+
Examples
|
| 2148 |
+
========
|
| 2149 |
+
|
| 2150 |
+
>>> from sympy import exp
|
| 2151 |
+
>>> from sympy.diffgeom.rn import R2
|
| 2152 |
+
>>> from sympy.diffgeom import metric_to_Riemann_components, TensorProduct
|
| 2153 |
+
>>> TP = TensorProduct
|
| 2154 |
+
|
| 2155 |
+
>>> metric_to_Riemann_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
| 2156 |
+
[[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]
|
| 2157 |
+
>>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
|
| 2158 |
+
R2.r**2*TP(R2.dtheta, R2.dtheta)
|
| 2159 |
+
>>> non_trivial_metric
|
| 2160 |
+
exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta)
|
| 2161 |
+
>>> riemann = metric_to_Riemann_components(non_trivial_metric)
|
| 2162 |
+
>>> riemann[0, :, :, :]
|
| 2163 |
+
[[[0, 0], [0, 0]], [[0, exp(-2*rho)*rho], [-exp(-2*rho)*rho, 0]]]
|
| 2164 |
+
>>> riemann[1, :, :, :]
|
| 2165 |
+
[[[0, -1/rho], [1/rho, 0]], [[0, 0], [0, 0]]]
|
| 2166 |
+
|
| 2167 |
+
"""
|
| 2168 |
+
ch_2nd = metric_to_Christoffel_2nd(expr)
|
| 2169 |
+
coord_sys = _find_coords(expr).pop()
|
| 2170 |
+
indices = list(range(coord_sys.dim))
|
| 2171 |
+
deriv_ch = [[[[d(ch_2nd[i, j, k])
|
| 2172 |
+
for d in coord_sys.base_vectors()]
|
| 2173 |
+
for k in indices]
|
| 2174 |
+
for j in indices]
|
| 2175 |
+
for i in indices]
|
| 2176 |
+
riemann_a = [[[[deriv_ch[rho][sig][nu][mu] - deriv_ch[rho][sig][mu][nu]
|
| 2177 |
+
for nu in indices]
|
| 2178 |
+
for mu in indices]
|
| 2179 |
+
for sig in indices]
|
| 2180 |
+
for rho in indices]
|
| 2181 |
+
riemann_b = [[[[Add(*[ch_2nd[rho, l, mu]*ch_2nd[l, sig, nu] - ch_2nd[rho, l, nu]*ch_2nd[l, sig, mu] for l in indices])
|
| 2182 |
+
for nu in indices]
|
| 2183 |
+
for mu in indices]
|
| 2184 |
+
for sig in indices]
|
| 2185 |
+
for rho in indices]
|
| 2186 |
+
riemann = [[[[riemann_a[rho][sig][mu][nu] + riemann_b[rho][sig][mu][nu]
|
| 2187 |
+
for nu in indices]
|
| 2188 |
+
for mu in indices]
|
| 2189 |
+
for sig in indices]
|
| 2190 |
+
for rho in indices]
|
| 2191 |
+
return ImmutableDenseNDimArray(riemann)
|
| 2192 |
+
|
| 2193 |
+
|
| 2194 |
+
def metric_to_Ricci_components(expr):
|
| 2195 |
+
|
| 2196 |
+
"""Return the components of the Ricci tensor expressed in a given basis.
|
| 2197 |
+
|
| 2198 |
+
Given a metric it calculates the components of the Ricci tensor in the
|
| 2199 |
+
canonical basis of the coordinate system in which the metric expression is
|
| 2200 |
+
given.
|
| 2201 |
+
|
| 2202 |
+
Examples
|
| 2203 |
+
========
|
| 2204 |
+
|
| 2205 |
+
>>> from sympy import exp
|
| 2206 |
+
>>> from sympy.diffgeom.rn import R2
|
| 2207 |
+
>>> from sympy.diffgeom import metric_to_Ricci_components, TensorProduct
|
| 2208 |
+
>>> TP = TensorProduct
|
| 2209 |
+
|
| 2210 |
+
>>> metric_to_Ricci_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
| 2211 |
+
[[0, 0], [0, 0]]
|
| 2212 |
+
>>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
|
| 2213 |
+
R2.r**2*TP(R2.dtheta, R2.dtheta)
|
| 2214 |
+
>>> non_trivial_metric
|
| 2215 |
+
exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta)
|
| 2216 |
+
>>> metric_to_Ricci_components(non_trivial_metric)
|
| 2217 |
+
[[1/rho, 0], [0, exp(-2*rho)*rho]]
|
| 2218 |
+
|
| 2219 |
+
"""
|
| 2220 |
+
riemann = metric_to_Riemann_components(expr)
|
| 2221 |
+
coord_sys = _find_coords(expr).pop()
|
| 2222 |
+
indices = list(range(coord_sys.dim))
|
| 2223 |
+
ricci = [[Add(*[riemann[k, i, k, j] for k in indices])
|
| 2224 |
+
for j in indices]
|
| 2225 |
+
for i in indices]
|
| 2226 |
+
return ImmutableDenseNDimArray(ricci)
|
| 2227 |
+
|
| 2228 |
+
###############################################################################
|
| 2229 |
+
# Classes for deprecation
|
| 2230 |
+
###############################################################################
|
| 2231 |
+
|
| 2232 |
+
class _deprecated_container:
|
| 2233 |
+
# This class gives deprecation warning.
|
| 2234 |
+
# When deprecated features are completely deleted, this should be removed as well.
|
| 2235 |
+
# See https://github.com/sympy/sympy/pull/19368
|
| 2236 |
+
def __init__(self, message, data):
|
| 2237 |
+
super().__init__(data)
|
| 2238 |
+
self.message = message
|
| 2239 |
+
|
| 2240 |
+
def warn(self):
|
| 2241 |
+
sympy_deprecation_warning(
|
| 2242 |
+
self.message,
|
| 2243 |
+
deprecated_since_version="1.7",
|
| 2244 |
+
active_deprecations_target="deprecated-diffgeom-mutable",
|
| 2245 |
+
stacklevel=4
|
| 2246 |
+
)
|
| 2247 |
+
|
| 2248 |
+
def __iter__(self):
|
| 2249 |
+
self.warn()
|
| 2250 |
+
return super().__iter__()
|
| 2251 |
+
|
| 2252 |
+
def __getitem__(self, key):
|
| 2253 |
+
self.warn()
|
| 2254 |
+
return super().__getitem__(key)
|
| 2255 |
+
|
| 2256 |
+
def __contains__(self, key):
|
| 2257 |
+
self.warn()
|
| 2258 |
+
return super().__contains__(key)
|
| 2259 |
+
|
| 2260 |
+
|
| 2261 |
+
class _deprecated_list(_deprecated_container, list):
|
| 2262 |
+
pass
|
| 2263 |
+
|
| 2264 |
+
|
| 2265 |
+
class _deprecated_dict(_deprecated_container, dict):
|
| 2266 |
+
pass
|
| 2267 |
+
|
| 2268 |
+
|
| 2269 |
+
# Import at end to avoid cyclic imports
|
| 2270 |
+
from sympy.simplify.simplify import simplify
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/rn.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Predefined R^n manifolds together with common coord. systems.
|
| 2 |
+
|
| 3 |
+
Coordinate systems are predefined as well as the transformation laws between
|
| 4 |
+
them.
|
| 5 |
+
|
| 6 |
+
Coordinate functions can be accessed as attributes of the manifold (eg `R2.x`),
|
| 7 |
+
as attributes of the coordinate systems (eg `R2_r.x` and `R2_p.theta`), or by
|
| 8 |
+
using the usual `coord_sys.coord_function(index, name)` interface.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from typing import Any
|
| 12 |
+
import warnings
|
| 13 |
+
|
| 14 |
+
from sympy.core.symbol import (Dummy, symbols)
|
| 15 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 16 |
+
from sympy.functions.elementary.trigonometric import (acos, atan2, cos, sin)
|
| 17 |
+
from .diffgeom import Manifold, Patch, CoordSystem
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
'R2', 'R2_origin', 'relations_2d', 'R2_r', 'R2_p',
|
| 21 |
+
'R3', 'R3_origin', 'relations_3d', 'R3_r', 'R3_c', 'R3_s'
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
###############################################################################
|
| 25 |
+
# R2
|
| 26 |
+
###############################################################################
|
| 27 |
+
R2: Any = Manifold('R^2', 2)
|
| 28 |
+
|
| 29 |
+
R2_origin: Any = Patch('origin', R2)
|
| 30 |
+
|
| 31 |
+
x, y = symbols('x y', real=True)
|
| 32 |
+
r, theta = symbols('rho theta', nonnegative=True)
|
| 33 |
+
|
| 34 |
+
relations_2d = {
|
| 35 |
+
('rectangular', 'polar'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))],
|
| 36 |
+
('polar', 'rectangular'): [(r, theta), (r*cos(theta), r*sin(theta))],
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
R2_r: Any = CoordSystem('rectangular', R2_origin, (x, y), relations_2d)
|
| 40 |
+
R2_p: Any = CoordSystem('polar', R2_origin, (r, theta), relations_2d)
|
| 41 |
+
|
| 42 |
+
# support deprecated feature
|
| 43 |
+
with warnings.catch_warnings():
|
| 44 |
+
warnings.simplefilter("ignore")
|
| 45 |
+
x, y, r, theta = symbols('x y r theta', cls=Dummy)
|
| 46 |
+
R2_r.connect_to(R2_p, [x, y],
|
| 47 |
+
[sqrt(x**2 + y**2), atan2(y, x)],
|
| 48 |
+
inverse=False, fill_in_gaps=False)
|
| 49 |
+
R2_p.connect_to(R2_r, [r, theta],
|
| 50 |
+
[r*cos(theta), r*sin(theta)],
|
| 51 |
+
inverse=False, fill_in_gaps=False)
|
| 52 |
+
|
| 53 |
+
# Defining the basis coordinate functions and adding shortcuts for them to the
|
| 54 |
+
# manifold and the patch.
|
| 55 |
+
R2.x, R2.y = R2_origin.x, R2_origin.y = R2_r.x, R2_r.y = R2_r.coord_functions()
|
| 56 |
+
R2.r, R2.theta = R2_origin.r, R2_origin.theta = R2_p.r, R2_p.theta = R2_p.coord_functions()
|
| 57 |
+
|
| 58 |
+
# Defining the basis vector fields and adding shortcuts for them to the
|
| 59 |
+
# manifold and the patch.
|
| 60 |
+
R2.e_x, R2.e_y = R2_origin.e_x, R2_origin.e_y = R2_r.e_x, R2_r.e_y = R2_r.base_vectors()
|
| 61 |
+
R2.e_r, R2.e_theta = R2_origin.e_r, R2_origin.e_theta = R2_p.e_r, R2_p.e_theta = R2_p.base_vectors()
|
| 62 |
+
|
| 63 |
+
# Defining the basis oneform fields and adding shortcuts for them to the
|
| 64 |
+
# manifold and the patch.
|
| 65 |
+
R2.dx, R2.dy = R2_origin.dx, R2_origin.dy = R2_r.dx, R2_r.dy = R2_r.base_oneforms()
|
| 66 |
+
R2.dr, R2.dtheta = R2_origin.dr, R2_origin.dtheta = R2_p.dr, R2_p.dtheta = R2_p.base_oneforms()
|
| 67 |
+
|
| 68 |
+
###############################################################################
|
| 69 |
+
# R3
|
| 70 |
+
###############################################################################
|
| 71 |
+
R3: Any = Manifold('R^3', 3)
|
| 72 |
+
|
| 73 |
+
R3_origin: Any = Patch('origin', R3)
|
| 74 |
+
|
| 75 |
+
x, y, z = symbols('x y z', real=True)
|
| 76 |
+
rho, psi, r, theta, phi = symbols('rho psi r theta phi', nonnegative=True)
|
| 77 |
+
|
| 78 |
+
relations_3d = {
|
| 79 |
+
('rectangular', 'cylindrical'): [(x, y, z),
|
| 80 |
+
(sqrt(x**2 + y**2), atan2(y, x), z)],
|
| 81 |
+
('cylindrical', 'rectangular'): [(rho, psi, z),
|
| 82 |
+
(rho*cos(psi), rho*sin(psi), z)],
|
| 83 |
+
('rectangular', 'spherical'): [(x, y, z),
|
| 84 |
+
(sqrt(x**2 + y**2 + z**2),
|
| 85 |
+
acos(z/sqrt(x**2 + y**2 + z**2)),
|
| 86 |
+
atan2(y, x))],
|
| 87 |
+
('spherical', 'rectangular'): [(r, theta, phi),
|
| 88 |
+
(r*sin(theta)*cos(phi),
|
| 89 |
+
r*sin(theta)*sin(phi),
|
| 90 |
+
r*cos(theta))],
|
| 91 |
+
('cylindrical', 'spherical'): [(rho, psi, z),
|
| 92 |
+
(sqrt(rho**2 + z**2),
|
| 93 |
+
acos(z/sqrt(rho**2 + z**2)),
|
| 94 |
+
psi)],
|
| 95 |
+
('spherical', 'cylindrical'): [(r, theta, phi),
|
| 96 |
+
(r*sin(theta), phi, r*cos(theta))],
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
R3_r: Any = CoordSystem('rectangular', R3_origin, (x, y, z), relations_3d)
|
| 100 |
+
R3_c: Any = CoordSystem('cylindrical', R3_origin, (rho, psi, z), relations_3d)
|
| 101 |
+
R3_s: Any = CoordSystem('spherical', R3_origin, (r, theta, phi), relations_3d)
|
| 102 |
+
|
| 103 |
+
# support deprecated feature
|
| 104 |
+
with warnings.catch_warnings():
|
| 105 |
+
warnings.simplefilter("ignore")
|
| 106 |
+
x, y, z, rho, psi, r, theta, phi = symbols('x y z rho psi r theta phi', cls=Dummy)
|
| 107 |
+
R3_r.connect_to(R3_c, [x, y, z],
|
| 108 |
+
[sqrt(x**2 + y**2), atan2(y, x), z],
|
| 109 |
+
inverse=False, fill_in_gaps=False)
|
| 110 |
+
R3_c.connect_to(R3_r, [rho, psi, z],
|
| 111 |
+
[rho*cos(psi), rho*sin(psi), z],
|
| 112 |
+
inverse=False, fill_in_gaps=False)
|
| 113 |
+
## rectangular <-> spherical
|
| 114 |
+
R3_r.connect_to(R3_s, [x, y, z],
|
| 115 |
+
[sqrt(x**2 + y**2 + z**2), acos(z/
|
| 116 |
+
sqrt(x**2 + y**2 + z**2)), atan2(y, x)],
|
| 117 |
+
inverse=False, fill_in_gaps=False)
|
| 118 |
+
R3_s.connect_to(R3_r, [r, theta, phi],
|
| 119 |
+
[r*sin(theta)*cos(phi), r*sin(
|
| 120 |
+
theta)*sin(phi), r*cos(theta)],
|
| 121 |
+
inverse=False, fill_in_gaps=False)
|
| 122 |
+
## cylindrical <-> spherical
|
| 123 |
+
R3_c.connect_to(R3_s, [rho, psi, z],
|
| 124 |
+
[sqrt(rho**2 + z**2), acos(z/sqrt(rho**2 + z**2)), psi],
|
| 125 |
+
inverse=False, fill_in_gaps=False)
|
| 126 |
+
R3_s.connect_to(R3_c, [r, theta, phi],
|
| 127 |
+
[r*sin(theta), phi, r*cos(theta)],
|
| 128 |
+
inverse=False, fill_in_gaps=False)
|
| 129 |
+
|
| 130 |
+
# Defining the basis coordinate functions.
|
| 131 |
+
R3_r.x, R3_r.y, R3_r.z = R3_r.coord_functions()
|
| 132 |
+
R3_c.rho, R3_c.psi, R3_c.z = R3_c.coord_functions()
|
| 133 |
+
R3_s.r, R3_s.theta, R3_s.phi = R3_s.coord_functions()
|
| 134 |
+
|
| 135 |
+
# Defining the basis vector fields.
|
| 136 |
+
R3_r.e_x, R3_r.e_y, R3_r.e_z = R3_r.base_vectors()
|
| 137 |
+
R3_c.e_rho, R3_c.e_psi, R3_c.e_z = R3_c.base_vectors()
|
| 138 |
+
R3_s.e_r, R3_s.e_theta, R3_s.e_phi = R3_s.base_vectors()
|
| 139 |
+
|
| 140 |
+
# Defining the basis oneform fields.
|
| 141 |
+
R3_r.dx, R3_r.dy, R3_r.dz = R3_r.base_oneforms()
|
| 142 |
+
R3_c.drho, R3_c.dpsi, R3_c.dz = R3_c.base_oneforms()
|
| 143 |
+
R3_s.dr, R3_s.dtheta, R3_s.dphi = R3_s.base_oneforms()
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__init__.py
ADDED
|
File without changes
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (172 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_class_structure.cpython-310.pyc
ADDED
|
Binary file (1.46 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_diffgeom.cpython-310.pyc
ADDED
|
Binary file (13.4 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_function_diffgeom_book.cpython-310.pyc
ADDED
|
Binary file (4.96 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_hyperbolic_space.cpython-310.pyc
ADDED
|
Binary file (2.73 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/test_class_structure.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.diffgeom import Manifold, Patch, CoordSystem, Point
|
| 2 |
+
from sympy.core.function import Function
|
| 3 |
+
from sympy.core.symbol import symbols
|
| 4 |
+
from sympy.testing.pytest import warns_deprecated_sympy
|
| 5 |
+
|
| 6 |
+
m = Manifold('m', 2)
|
| 7 |
+
p = Patch('p', m)
|
| 8 |
+
a, b = symbols('a b')
|
| 9 |
+
cs = CoordSystem('cs', p, [a, b])
|
| 10 |
+
x, y = symbols('x y')
|
| 11 |
+
f = Function('f')
|
| 12 |
+
s1, s2 = cs.coord_functions()
|
| 13 |
+
v1, v2 = cs.base_vectors()
|
| 14 |
+
f1, f2 = cs.base_oneforms()
|
| 15 |
+
|
| 16 |
+
def test_point():
|
| 17 |
+
point = Point(cs, [x, y])
|
| 18 |
+
assert point != Point(cs, [2, y])
|
| 19 |
+
#TODO assert point.subs(x, 2) == Point(cs, [2, y])
|
| 20 |
+
#TODO assert point.free_symbols == set([x, y])
|
| 21 |
+
|
| 22 |
+
def test_subs():
|
| 23 |
+
assert s1.subs(s1, s2) == s2
|
| 24 |
+
assert v1.subs(v1, v2) == v2
|
| 25 |
+
assert f1.subs(f1, f2) == f2
|
| 26 |
+
assert (x*f(s1) + y).subs(s1, s2) == x*f(s2) + y
|
| 27 |
+
assert (f(s1)*v1).subs(v1, v2) == f(s1)*v2
|
| 28 |
+
assert (y*f(s1)*f1).subs(f1, f2) == y*f(s1)*f2
|
| 29 |
+
|
| 30 |
+
def test_deprecated():
|
| 31 |
+
with warns_deprecated_sympy():
|
| 32 |
+
cs_wname = CoordSystem('cs', p, ['a', 'b'])
|
| 33 |
+
assert cs_wname == cs_wname.func(*cs_wname.args)
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/test_diffgeom.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import Lambda, Symbol, symbols
|
| 2 |
+
from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r, R3_c, R3_s, R2_origin
|
| 3 |
+
from sympy.diffgeom import (Manifold, Patch, CoordSystem, Commutator, Differential, TensorProduct,
|
| 4 |
+
WedgeProduct, BaseCovarDerivativeOp, CovarDerivativeOp, LieDerivative,
|
| 5 |
+
covariant_order, contravariant_order, twoform_to_matrix, metric_to_Christoffel_1st,
|
| 6 |
+
metric_to_Christoffel_2nd, metric_to_Riemann_components,
|
| 7 |
+
metric_to_Ricci_components, intcurve_diffequ, intcurve_series)
|
| 8 |
+
from sympy.simplify import trigsimp, simplify
|
| 9 |
+
from sympy.functions import sqrt, atan2, sin
|
| 10 |
+
from sympy.matrices import Matrix
|
| 11 |
+
from sympy.testing.pytest import raises, nocache_fail
|
| 12 |
+
from sympy.testing.pytest import warns_deprecated_sympy
|
| 13 |
+
|
| 14 |
+
TP = TensorProduct
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_coordsys_transform():
|
| 18 |
+
# test inverse transforms
|
| 19 |
+
p, q, r, s = symbols('p q r s')
|
| 20 |
+
rel = {('first', 'second'): [(p, q), (q, -p)]}
|
| 21 |
+
R2_pq = CoordSystem('first', R2_origin, [p, q], rel)
|
| 22 |
+
R2_rs = CoordSystem('second', R2_origin, [r, s], rel)
|
| 23 |
+
r, s = R2_rs.symbols
|
| 24 |
+
assert R2_rs.transform(R2_pq) == Matrix([[-s], [r]])
|
| 25 |
+
|
| 26 |
+
# inverse transform impossible case
|
| 27 |
+
a, b = symbols('a b', positive=True)
|
| 28 |
+
rel = {('first', 'second'): [(a,), (-a,)]}
|
| 29 |
+
R2_a = CoordSystem('first', R2_origin, [a], rel)
|
| 30 |
+
R2_b = CoordSystem('second', R2_origin, [b], rel)
|
| 31 |
+
# This transformation is uninvertible because there is no positive a, b satisfying a = -b
|
| 32 |
+
with raises(NotImplementedError):
|
| 33 |
+
R2_b.transform(R2_a)
|
| 34 |
+
|
| 35 |
+
# inverse transform ambiguous case
|
| 36 |
+
c, d = symbols('c d')
|
| 37 |
+
rel = {('first', 'second'): [(c,), (c**2,)]}
|
| 38 |
+
R2_c = CoordSystem('first', R2_origin, [c], rel)
|
| 39 |
+
R2_d = CoordSystem('second', R2_origin, [d], rel)
|
| 40 |
+
# The transform method should throw if it finds multiple inverses for a coordinate transformation.
|
| 41 |
+
with raises(ValueError):
|
| 42 |
+
R2_d.transform(R2_c)
|
| 43 |
+
|
| 44 |
+
# test indirect transformation
|
| 45 |
+
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
|
| 46 |
+
rel = {('C1', 'C2'): [(a, b), (2*a, 3*b)],
|
| 47 |
+
('C2', 'C3'): [(c, d), (3*c, 2*d)]}
|
| 48 |
+
C1 = CoordSystem('C1', R2_origin, (a, b), rel)
|
| 49 |
+
C2 = CoordSystem('C2', R2_origin, (c, d), rel)
|
| 50 |
+
C3 = CoordSystem('C3', R2_origin, (e, f), rel)
|
| 51 |
+
a, b = C1.symbols
|
| 52 |
+
c, d = C2.symbols
|
| 53 |
+
e, f = C3.symbols
|
| 54 |
+
assert C2.transform(C1) == Matrix([c/2, d/3])
|
| 55 |
+
assert C1.transform(C3) == Matrix([6*a, 6*b])
|
| 56 |
+
assert C3.transform(C1) == Matrix([e/6, f/6])
|
| 57 |
+
assert C3.transform(C2) == Matrix([e/3, f/2])
|
| 58 |
+
|
| 59 |
+
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
|
| 60 |
+
rel = {('C1', 'C2'): [(a, b), (2*a, 3*b + 1)],
|
| 61 |
+
('C3', 'C2'): [(e, f), (-e - 2, 2*f)]}
|
| 62 |
+
C1 = CoordSystem('C1', R2_origin, (a, b), rel)
|
| 63 |
+
C2 = CoordSystem('C2', R2_origin, (c, d), rel)
|
| 64 |
+
C3 = CoordSystem('C3', R2_origin, (e, f), rel)
|
| 65 |
+
a, b = C1.symbols
|
| 66 |
+
c, d = C2.symbols
|
| 67 |
+
e, f = C3.symbols
|
| 68 |
+
assert C2.transform(C1) == Matrix([c/2, (d - 1)/3])
|
| 69 |
+
assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2])
|
| 70 |
+
assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3])
|
| 71 |
+
assert C3.transform(C2) == Matrix([-e - 2, 2*f])
|
| 72 |
+
|
| 73 |
+
# old signature uses Lambda
|
| 74 |
+
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
|
| 75 |
+
rel = {('C1', 'C2'): Lambda((a, b), (2*a, 3*b + 1)),
|
| 76 |
+
('C3', 'C2'): Lambda((e, f), (-e - 2, 2*f))}
|
| 77 |
+
C1 = CoordSystem('C1', R2_origin, (a, b), rel)
|
| 78 |
+
C2 = CoordSystem('C2', R2_origin, (c, d), rel)
|
| 79 |
+
C3 = CoordSystem('C3', R2_origin, (e, f), rel)
|
| 80 |
+
a, b = C1.symbols
|
| 81 |
+
c, d = C2.symbols
|
| 82 |
+
e, f = C3.symbols
|
| 83 |
+
assert C2.transform(C1) == Matrix([c/2, (d - 1)/3])
|
| 84 |
+
assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2])
|
| 85 |
+
assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3])
|
| 86 |
+
assert C3.transform(C2) == Matrix([-e - 2, 2*f])
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_R2():
|
| 90 |
+
x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True)
|
| 91 |
+
point_r = R2_r.point([x0, y0])
|
| 92 |
+
point_p = R2_p.point([r0, theta0])
|
| 93 |
+
|
| 94 |
+
# r**2 = x**2 + y**2
|
| 95 |
+
assert (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_r) == 0
|
| 96 |
+
assert trigsimp( (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_p) ) == 0
|
| 97 |
+
assert trigsimp(R2.e_r(R2.x**2 + R2.y**2).rcall(point_p).doit()) == 2*r0
|
| 98 |
+
|
| 99 |
+
# polar->rect->polar == Id
|
| 100 |
+
a, b = symbols('a b', positive=True)
|
| 101 |
+
m = Matrix([[a], [b]])
|
| 102 |
+
|
| 103 |
+
#TODO assert m == R2_r.transform(R2_p, R2_p.transform(R2_r, [a, b])).applyfunc(simplify)
|
| 104 |
+
assert m == R2_p.transform(R2_r, R2_r.transform(R2_p, m)).applyfunc(simplify)
|
| 105 |
+
|
| 106 |
+
# deprecated method
|
| 107 |
+
with warns_deprecated_sympy():
|
| 108 |
+
assert m == R2_p.coord_tuple_transform_to(
|
| 109 |
+
R2_r, R2_r.coord_tuple_transform_to(R2_p, m)).applyfunc(simplify)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_R3():
|
| 113 |
+
a, b, c = symbols('a b c', positive=True)
|
| 114 |
+
m = Matrix([[a], [b], [c]])
|
| 115 |
+
|
| 116 |
+
assert m == R3_c.transform(R3_r, R3_r.transform(R3_c, m)).applyfunc(simplify)
|
| 117 |
+
#TODO assert m == R3_r.transform(R3_c, R3_c.transform(R3_r, m)).applyfunc(simplify)
|
| 118 |
+
assert m == R3_s.transform(
|
| 119 |
+
R3_r, R3_r.transform(R3_s, m)).applyfunc(simplify)
|
| 120 |
+
#TODO assert m == R3_r.transform(R3_s, R3_s.transform(R3_r, m)).applyfunc(simplify)
|
| 121 |
+
assert m == R3_s.transform(
|
| 122 |
+
R3_c, R3_c.transform(R3_s, m)).applyfunc(simplify)
|
| 123 |
+
#TODO assert m == R3_c.transform(R3_s, R3_s.transform(R3_c, m)).applyfunc(simplify)
|
| 124 |
+
|
| 125 |
+
with warns_deprecated_sympy():
|
| 126 |
+
assert m == R3_c.coord_tuple_transform_to(
|
| 127 |
+
R3_r, R3_r.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify)
|
| 128 |
+
#TODO assert m == R3_r.coord_tuple_transform_to(R3_c, R3_c.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify)
|
| 129 |
+
assert m == R3_s.coord_tuple_transform_to(
|
| 130 |
+
R3_r, R3_r.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify)
|
| 131 |
+
#TODO assert m == R3_r.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify)
|
| 132 |
+
assert m == R3_s.coord_tuple_transform_to(
|
| 133 |
+
R3_c, R3_c.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify)
|
| 134 |
+
#TODO assert m == R3_c.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def test_CoordinateSymbol():
|
| 138 |
+
x, y = R2_r.symbols
|
| 139 |
+
r, theta = R2_p.symbols
|
| 140 |
+
assert y.rewrite(R2_p) == r*sin(theta)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_point():
|
| 144 |
+
x, y = symbols('x, y')
|
| 145 |
+
p = R2_r.point([x, y])
|
| 146 |
+
assert p.free_symbols == {x, y}
|
| 147 |
+
assert p.coords(R2_r) == p.coords() == Matrix([x, y])
|
| 148 |
+
assert p.coords(R2_p) == Matrix([sqrt(x**2 + y**2), atan2(y, x)])
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_commutator():
|
| 152 |
+
assert Commutator(R2.e_x, R2.e_y) == 0
|
| 153 |
+
assert Commutator(R2.x*R2.e_x, R2.x*R2.e_x) == 0
|
| 154 |
+
assert Commutator(R2.x*R2.e_x, R2.x*R2.e_y) == R2.x*R2.e_y
|
| 155 |
+
c = Commutator(R2.e_x, R2.e_r)
|
| 156 |
+
assert c(R2.x) == R2.y*(R2.x**2 + R2.y**2)**(-1)*sin(R2.theta)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def test_differential():
|
| 160 |
+
xdy = R2.x*R2.dy
|
| 161 |
+
dxdy = Differential(xdy)
|
| 162 |
+
assert xdy.rcall(None) == xdy
|
| 163 |
+
assert dxdy(R2.e_x, R2.e_y) == 1
|
| 164 |
+
assert dxdy(R2.e_x, R2.x*R2.e_y) == R2.x
|
| 165 |
+
assert Differential(dxdy) == 0
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_products():
|
| 169 |
+
assert TensorProduct(
|
| 170 |
+
R2.dx, R2.dy)(R2.e_x, R2.e_y) == R2.dx(R2.e_x)*R2.dy(R2.e_y) == 1
|
| 171 |
+
assert TensorProduct(R2.dx, R2.dy)(None, R2.e_y) == R2.dx
|
| 172 |
+
assert TensorProduct(R2.dx, R2.dy)(R2.e_x, None) == R2.dy
|
| 173 |
+
assert TensorProduct(R2.dx, R2.dy)(R2.e_x) == R2.dy
|
| 174 |
+
assert TensorProduct(R2.x, R2.dx) == R2.x*R2.dx
|
| 175 |
+
assert TensorProduct(
|
| 176 |
+
R2.e_x, R2.e_y)(R2.x, R2.y) == R2.e_x(R2.x) * R2.e_y(R2.y) == 1
|
| 177 |
+
assert TensorProduct(R2.e_x, R2.e_y)(None, R2.y) == R2.e_x
|
| 178 |
+
assert TensorProduct(R2.e_x, R2.e_y)(R2.x, None) == R2.e_y
|
| 179 |
+
assert TensorProduct(R2.e_x, R2.e_y)(R2.x) == R2.e_y
|
| 180 |
+
assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x
|
| 181 |
+
assert TensorProduct(
|
| 182 |
+
R2.dx, R2.e_y)(R2.e_x, R2.y) == R2.dx(R2.e_x) * R2.e_y(R2.y) == 1
|
| 183 |
+
assert TensorProduct(R2.dx, R2.e_y)(None, R2.y) == R2.dx
|
| 184 |
+
assert TensorProduct(R2.dx, R2.e_y)(R2.e_x, None) == R2.e_y
|
| 185 |
+
assert TensorProduct(R2.dx, R2.e_y)(R2.e_x) == R2.e_y
|
| 186 |
+
assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x
|
| 187 |
+
assert TensorProduct(
|
| 188 |
+
R2.e_x, R2.dy)(R2.x, R2.e_y) == R2.e_x(R2.x) * R2.dy(R2.e_y) == 1
|
| 189 |
+
assert TensorProduct(R2.e_x, R2.dy)(None, R2.e_y) == R2.e_x
|
| 190 |
+
assert TensorProduct(R2.e_x, R2.dy)(R2.x, None) == R2.dy
|
| 191 |
+
assert TensorProduct(R2.e_x, R2.dy)(R2.x) == R2.dy
|
| 192 |
+
assert TensorProduct(R2.e_y,R2.e_x)(R2.x**2 + R2.y**2,R2.x**2 + R2.y**2) == 4*R2.x*R2.y
|
| 193 |
+
|
| 194 |
+
assert WedgeProduct(R2.dx, R2.dy)(R2.e_x, R2.e_y) == 1
|
| 195 |
+
assert WedgeProduct(R2.e_x, R2.e_y)(R2.x, R2.y) == 1
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def test_lie_derivative():
|
| 199 |
+
assert LieDerivative(R2.e_x, R2.y) == R2.e_x(R2.y) == 0
|
| 200 |
+
assert LieDerivative(R2.e_x, R2.x) == R2.e_x(R2.x) == 1
|
| 201 |
+
assert LieDerivative(R2.e_x, R2.e_x) == Commutator(R2.e_x, R2.e_x) == 0
|
| 202 |
+
assert LieDerivative(R2.e_x, R2.e_r) == Commutator(R2.e_x, R2.e_r)
|
| 203 |
+
assert LieDerivative(R2.e_x + R2.e_y, R2.x) == 1
|
| 204 |
+
assert LieDerivative(
|
| 205 |
+
R2.e_x, TensorProduct(R2.dx, R2.dy))(R2.e_x, R2.e_y) == 0
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@nocache_fail
|
| 209 |
+
def test_covar_deriv():
|
| 210 |
+
ch = metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
| 211 |
+
cvd = BaseCovarDerivativeOp(R2_r, 0, ch)
|
| 212 |
+
assert cvd(R2.x) == 1
|
| 213 |
+
# This line fails if the cache is disabled:
|
| 214 |
+
assert cvd(R2.x*R2.e_x) == R2.e_x
|
| 215 |
+
cvd = CovarDerivativeOp(R2.x*R2.e_x, ch)
|
| 216 |
+
assert cvd(R2.x) == R2.x
|
| 217 |
+
assert cvd(R2.x*R2.e_x) == R2.x*R2.e_x
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def test_intcurve_diffequ():
|
| 221 |
+
t = symbols('t')
|
| 222 |
+
start_point = R2_r.point([1, 0])
|
| 223 |
+
vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
|
| 224 |
+
equations, init_cond = intcurve_diffequ(vector_field, t, start_point)
|
| 225 |
+
assert str(equations) == '[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]'
|
| 226 |
+
assert str(init_cond) == '[f_0(0) - 1, f_1(0)]'
|
| 227 |
+
equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p)
|
| 228 |
+
assert str(
|
| 229 |
+
equations) == '[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]'
|
| 230 |
+
assert str(init_cond) == '[f_0(0) - 1, f_1(0)]'
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def test_helpers_and_coordinate_dependent():
|
| 234 |
+
one_form = R2.dr + R2.dx
|
| 235 |
+
two_form = Differential(R2.x*R2.dr + R2.r*R2.dx)
|
| 236 |
+
three_form = Differential(
|
| 237 |
+
R2.y*two_form) + Differential(R2.x*Differential(R2.r*R2.dr))
|
| 238 |
+
metric = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dy, R2.dy)
|
| 239 |
+
metric_ambig = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dr, R2.dr)
|
| 240 |
+
misform_a = TensorProduct(R2.dr, R2.dr) + R2.dr
|
| 241 |
+
misform_b = R2.dr**4
|
| 242 |
+
misform_c = R2.dx*R2.dy
|
| 243 |
+
twoform_not_sym = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dx, R2.dy)
|
| 244 |
+
twoform_not_TP = WedgeProduct(R2.dx, R2.dy)
|
| 245 |
+
|
| 246 |
+
one_vector = R2.e_x + R2.e_y
|
| 247 |
+
two_vector = TensorProduct(R2.e_x, R2.e_y)
|
| 248 |
+
three_vector = TensorProduct(R2.e_x, R2.e_y, R2.e_x)
|
| 249 |
+
two_wp = WedgeProduct(R2.e_x,R2.e_y)
|
| 250 |
+
|
| 251 |
+
assert covariant_order(one_form) == 1
|
| 252 |
+
assert covariant_order(two_form) == 2
|
| 253 |
+
assert covariant_order(three_form) == 3
|
| 254 |
+
assert covariant_order(two_form + metric) == 2
|
| 255 |
+
assert covariant_order(two_form + metric_ambig) == 2
|
| 256 |
+
assert covariant_order(two_form + twoform_not_sym) == 2
|
| 257 |
+
assert covariant_order(two_form + twoform_not_TP) == 2
|
| 258 |
+
|
| 259 |
+
assert contravariant_order(one_vector) == 1
|
| 260 |
+
assert contravariant_order(two_vector) == 2
|
| 261 |
+
assert contravariant_order(three_vector) == 3
|
| 262 |
+
assert contravariant_order(two_vector + two_wp) == 2
|
| 263 |
+
|
| 264 |
+
raises(ValueError, lambda: covariant_order(misform_a))
|
| 265 |
+
raises(ValueError, lambda: covariant_order(misform_b))
|
| 266 |
+
raises(ValueError, lambda: covariant_order(misform_c))
|
| 267 |
+
|
| 268 |
+
assert twoform_to_matrix(metric) == Matrix([[1, 0], [0, 1]])
|
| 269 |
+
assert twoform_to_matrix(twoform_not_sym) == Matrix([[1, 0], [1, 0]])
|
| 270 |
+
assert twoform_to_matrix(twoform_not_TP) == Matrix([[0, -1], [1, 0]])
|
| 271 |
+
|
| 272 |
+
raises(ValueError, lambda: twoform_to_matrix(one_form))
|
| 273 |
+
raises(ValueError, lambda: twoform_to_matrix(three_form))
|
| 274 |
+
raises(ValueError, lambda: twoform_to_matrix(metric_ambig))
|
| 275 |
+
|
| 276 |
+
raises(ValueError, lambda: metric_to_Christoffel_1st(twoform_not_sym))
|
| 277 |
+
raises(ValueError, lambda: metric_to_Christoffel_2nd(twoform_not_sym))
|
| 278 |
+
raises(ValueError, lambda: metric_to_Riemann_components(twoform_not_sym))
|
| 279 |
+
raises(ValueError, lambda: metric_to_Ricci_components(twoform_not_sym))
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def test_correct_arguments():
|
| 283 |
+
raises(ValueError, lambda: R2.e_x(R2.e_x))
|
| 284 |
+
raises(ValueError, lambda: R2.e_x(R2.dx))
|
| 285 |
+
|
| 286 |
+
raises(ValueError, lambda: Commutator(R2.e_x, R2.x))
|
| 287 |
+
raises(ValueError, lambda: Commutator(R2.dx, R2.e_x))
|
| 288 |
+
|
| 289 |
+
raises(ValueError, lambda: Differential(Differential(R2.e_x)))
|
| 290 |
+
|
| 291 |
+
raises(ValueError, lambda: R2.dx(R2.x))
|
| 292 |
+
|
| 293 |
+
raises(ValueError, lambda: LieDerivative(R2.dx, R2.dx))
|
| 294 |
+
raises(ValueError, lambda: LieDerivative(R2.x, R2.dx))
|
| 295 |
+
|
| 296 |
+
raises(ValueError, lambda: CovarDerivativeOp(R2.dx, []))
|
| 297 |
+
raises(ValueError, lambda: CovarDerivativeOp(R2.x, []))
|
| 298 |
+
|
| 299 |
+
a = Symbol('a')
|
| 300 |
+
raises(ValueError, lambda: intcurve_series(R2.dx, a, R2_r.point([1, 2])))
|
| 301 |
+
raises(ValueError, lambda: intcurve_series(R2.x, a, R2_r.point([1, 2])))
|
| 302 |
+
|
| 303 |
+
raises(ValueError, lambda: intcurve_diffequ(R2.dx, a, R2_r.point([1, 2])))
|
| 304 |
+
raises(ValueError, lambda: intcurve_diffequ(R2.x, a, R2_r.point([1, 2])))
|
| 305 |
+
|
| 306 |
+
raises(ValueError, lambda: contravariant_order(R2.e_x + R2.dx))
|
| 307 |
+
raises(ValueError, lambda: covariant_order(R2.e_x + R2.dx))
|
| 308 |
+
|
| 309 |
+
raises(ValueError, lambda: contravariant_order(R2.e_x*R2.e_y))
|
| 310 |
+
raises(ValueError, lambda: covariant_order(R2.dx*R2.dy))
|
| 311 |
+
|
| 312 |
+
def test_simplify():
|
| 313 |
+
x, y = R2_r.coord_functions()
|
| 314 |
+
dx, dy = R2_r.base_oneforms()
|
| 315 |
+
ex, ey = R2_r.base_vectors()
|
| 316 |
+
assert simplify(x) == x
|
| 317 |
+
assert simplify(x*y) == x*y
|
| 318 |
+
assert simplify(dx*dy) == dx*dy
|
| 319 |
+
assert simplify(ex*ey) == ex*ey
|
| 320 |
+
assert ((1-x)*dx)/(1-x)**2 == dx/(1-x)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def test_issue_17917():
|
| 324 |
+
X = R2.x*R2.e_x - R2.y*R2.e_y
|
| 325 |
+
Y = (R2.x**2 + R2.y**2)*R2.e_x - R2.x*R2.y*R2.e_y
|
| 326 |
+
assert LieDerivative(X, Y).expand() == (
|
| 327 |
+
R2.x**2*R2.e_x - 3*R2.y**2*R2.e_x - R2.x*R2.y*R2.e_y)
|
| 328 |
+
|
| 329 |
+
def test_deprecations():
|
| 330 |
+
m = Manifold('M', 2)
|
| 331 |
+
p = Patch('P', m)
|
| 332 |
+
with warns_deprecated_sympy():
|
| 333 |
+
CoordSystem('Car2d', p, names=['x', 'y'])
|
| 334 |
+
|
| 335 |
+
with warns_deprecated_sympy():
|
| 336 |
+
c = CoordSystem('Car2d', p, ['x', 'y'])
|
| 337 |
+
|
| 338 |
+
with warns_deprecated_sympy():
|
| 339 |
+
list(m.patches)
|
| 340 |
+
|
| 341 |
+
with warns_deprecated_sympy():
|
| 342 |
+
list(c.transforms)
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/test_function_diffgeom_book.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r
|
| 2 |
+
from sympy.diffgeom import intcurve_series, Differential, WedgeProduct
|
| 3 |
+
from sympy.core import symbols, Function, Derivative
|
| 4 |
+
from sympy.simplify import trigsimp, simplify
|
| 5 |
+
from sympy.functions import sqrt, atan2, sin, cos
|
| 6 |
+
from sympy.matrices import Matrix
|
| 7 |
+
|
| 8 |
+
# Most of the functionality is covered in the
|
| 9 |
+
# test_functional_diffgeom_ch* tests which are based on the
|
| 10 |
+
# example from the paper of Sussman and Wisdom.
|
| 11 |
+
# If they do not cover something, additional tests are added in other test
|
| 12 |
+
# functions.
|
| 13 |
+
|
| 14 |
+
# From "Functional Differential Geometry" as of 2011
|
| 15 |
+
# by Sussman and Wisdom.
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_functional_diffgeom_ch2():
|
| 19 |
+
x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True)
|
| 20 |
+
x, y = symbols('x, y', real=True)
|
| 21 |
+
f = Function('f')
|
| 22 |
+
|
| 23 |
+
assert (R2_p.point_to_coords(R2_r.point([x0, y0])) ==
|
| 24 |
+
Matrix([sqrt(x0**2 + y0**2), atan2(y0, x0)]))
|
| 25 |
+
assert (R2_r.point_to_coords(R2_p.point([r0, theta0])) ==
|
| 26 |
+
Matrix([r0*cos(theta0), r0*sin(theta0)]))
|
| 27 |
+
|
| 28 |
+
assert R2_p.jacobian(R2_r, [r0, theta0]) == Matrix(
|
| 29 |
+
[[cos(theta0), -r0*sin(theta0)], [sin(theta0), r0*cos(theta0)]])
|
| 30 |
+
|
| 31 |
+
field = f(R2.x, R2.y)
|
| 32 |
+
p1_in_rect = R2_r.point([x0, y0])
|
| 33 |
+
p1_in_polar = R2_p.point([sqrt(x0**2 + y0**2), atan2(y0, x0)])
|
| 34 |
+
assert field.rcall(p1_in_rect) == f(x0, y0)
|
| 35 |
+
assert field.rcall(p1_in_polar) == f(x0, y0)
|
| 36 |
+
|
| 37 |
+
p_r = R2_r.point([x0, y0])
|
| 38 |
+
p_p = R2_p.point([r0, theta0])
|
| 39 |
+
assert R2.x(p_r) == x0
|
| 40 |
+
assert R2.x(p_p) == r0*cos(theta0)
|
| 41 |
+
assert R2.r(p_p) == r0
|
| 42 |
+
assert R2.r(p_r) == sqrt(x0**2 + y0**2)
|
| 43 |
+
assert R2.theta(p_r) == atan2(y0, x0)
|
| 44 |
+
|
| 45 |
+
h = R2.x*R2.r**2 + R2.y**3
|
| 46 |
+
assert h.rcall(p_r) == x0*(x0**2 + y0**2) + y0**3
|
| 47 |
+
assert h.rcall(p_p) == r0**3*sin(theta0)**3 + r0**3*cos(theta0)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_functional_diffgeom_ch3():
|
| 51 |
+
x0, y0 = symbols('x0, y0', real=True)
|
| 52 |
+
x, y, t = symbols('x, y, t', real=True)
|
| 53 |
+
f = Function('f')
|
| 54 |
+
b1 = Function('b1')
|
| 55 |
+
b2 = Function('b2')
|
| 56 |
+
p_r = R2_r.point([x0, y0])
|
| 57 |
+
|
| 58 |
+
s_field = f(R2.x, R2.y)
|
| 59 |
+
v_field = b1(R2.x)*R2.e_x + b2(R2.y)*R2.e_y
|
| 60 |
+
assert v_field.rcall(s_field).rcall(p_r).doit() == b1(
|
| 61 |
+
x0)*Derivative(f(x0, y0), x0) + b2(y0)*Derivative(f(x0, y0), y0)
|
| 62 |
+
|
| 63 |
+
assert R2.e_x(R2.r**2).rcall(p_r) == 2*x0
|
| 64 |
+
v = R2.e_x + 2*R2.e_y
|
| 65 |
+
s = R2.r**2 + 3*R2.x
|
| 66 |
+
assert v.rcall(s).rcall(p_r).doit() == 2*x0 + 4*y0 + 3
|
| 67 |
+
|
| 68 |
+
circ = -R2.y*R2.e_x + R2.x*R2.e_y
|
| 69 |
+
series = intcurve_series(circ, t, R2_r.point([1, 0]), coeffs=True)
|
| 70 |
+
series_x, series_y = zip(*series)
|
| 71 |
+
assert all(
|
| 72 |
+
term == cos(t).taylor_term(i, t) for i, term in enumerate(series_x))
|
| 73 |
+
assert all(
|
| 74 |
+
term == sin(t).taylor_term(i, t) for i, term in enumerate(series_y))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_functional_diffgeom_ch4():
|
| 78 |
+
x0, y0, theta0 = symbols('x0, y0, theta0', real=True)
|
| 79 |
+
x, y, r, theta = symbols('x, y, r, theta', real=True)
|
| 80 |
+
r0 = symbols('r0', positive=True)
|
| 81 |
+
f = Function('f')
|
| 82 |
+
b1 = Function('b1')
|
| 83 |
+
b2 = Function('b2')
|
| 84 |
+
p_r = R2_r.point([x0, y0])
|
| 85 |
+
p_p = R2_p.point([r0, theta0])
|
| 86 |
+
|
| 87 |
+
f_field = b1(R2.x, R2.y)*R2.dx + b2(R2.x, R2.y)*R2.dy
|
| 88 |
+
assert f_field.rcall(R2.e_x).rcall(p_r) == b1(x0, y0)
|
| 89 |
+
assert f_field.rcall(R2.e_y).rcall(p_r) == b2(x0, y0)
|
| 90 |
+
|
| 91 |
+
s_field_r = f(R2.x, R2.y)
|
| 92 |
+
df = Differential(s_field_r)
|
| 93 |
+
assert df(R2.e_x).rcall(p_r).doit() == Derivative(f(x0, y0), x0)
|
| 94 |
+
assert df(R2.e_y).rcall(p_r).doit() == Derivative(f(x0, y0), y0)
|
| 95 |
+
|
| 96 |
+
s_field_p = f(R2.r, R2.theta)
|
| 97 |
+
df = Differential(s_field_p)
|
| 98 |
+
assert trigsimp(df(R2.e_x).rcall(p_p).doit()) == (
|
| 99 |
+
cos(theta0)*Derivative(f(r0, theta0), r0) -
|
| 100 |
+
sin(theta0)*Derivative(f(r0, theta0), theta0)/r0)
|
| 101 |
+
assert trigsimp(df(R2.e_y).rcall(p_p).doit()) == (
|
| 102 |
+
sin(theta0)*Derivative(f(r0, theta0), r0) +
|
| 103 |
+
cos(theta0)*Derivative(f(r0, theta0), theta0)/r0)
|
| 104 |
+
|
| 105 |
+
assert R2.dx(R2.e_x).rcall(p_r) == 1
|
| 106 |
+
assert R2.dx(R2.e_x) == 1
|
| 107 |
+
assert R2.dx(R2.e_y).rcall(p_r) == 0
|
| 108 |
+
assert R2.dx(R2.e_y) == 0
|
| 109 |
+
|
| 110 |
+
circ = -R2.y*R2.e_x + R2.x*R2.e_y
|
| 111 |
+
assert R2.dx(circ).rcall(p_r).doit() == -y0
|
| 112 |
+
assert R2.dy(circ).rcall(p_r) == x0
|
| 113 |
+
assert R2.dr(circ).rcall(p_r) == 0
|
| 114 |
+
assert simplify(R2.dtheta(circ).rcall(p_r)) == 1
|
| 115 |
+
|
| 116 |
+
assert (circ - R2.e_theta).rcall(s_field_r).rcall(p_r) == 0
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_functional_diffgeom_ch6():
|
| 120 |
+
u0, u1, u2, v0, v1, v2, w0, w1, w2 = symbols('u0:3, v0:3, w0:3', real=True)
|
| 121 |
+
|
| 122 |
+
u = u0*R2.e_x + u1*R2.e_y
|
| 123 |
+
v = v0*R2.e_x + v1*R2.e_y
|
| 124 |
+
wp = WedgeProduct(R2.dx, R2.dy)
|
| 125 |
+
assert wp(u, v) == u0*v1 - u1*v0
|
| 126 |
+
|
| 127 |
+
u = u0*R3_r.e_x + u1*R3_r.e_y + u2*R3_r.e_z
|
| 128 |
+
v = v0*R3_r.e_x + v1*R3_r.e_y + v2*R3_r.e_z
|
| 129 |
+
w = w0*R3_r.e_x + w1*R3_r.e_y + w2*R3_r.e_z
|
| 130 |
+
wp = WedgeProduct(R3_r.dx, R3_r.dy, R3_r.dz)
|
| 131 |
+
assert wp(
|
| 132 |
+
u, v, w) == Matrix(3, 3, [u0, u1, u2, v0, v1, v2, w0, w1, w2]).det()
|
| 133 |
+
|
| 134 |
+
a, b, c = symbols('a, b, c', cls=Function)
|
| 135 |
+
a_f = a(R3_r.x, R3_r.y, R3_r.z)
|
| 136 |
+
b_f = b(R3_r.x, R3_r.y, R3_r.z)
|
| 137 |
+
c_f = c(R3_r.x, R3_r.y, R3_r.z)
|
| 138 |
+
theta = a_f*R3_r.dx + b_f*R3_r.dy + c_f*R3_r.dz
|
| 139 |
+
dtheta = Differential(theta)
|
| 140 |
+
da = Differential(a_f)
|
| 141 |
+
db = Differential(b_f)
|
| 142 |
+
dc = Differential(c_f)
|
| 143 |
+
expr = dtheta - WedgeProduct(
|
| 144 |
+
da, R3_r.dx) - WedgeProduct(db, R3_r.dy) - WedgeProduct(dc, R3_r.dz)
|
| 145 |
+
assert expr.rcall(R3_r.e_x, R3_r.e_y) == 0
|
pllava/lib/python3.10/site-packages/sympy/diffgeom/tests/test_hyperbolic_space.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r'''
|
| 2 |
+
unit test describing the hyperbolic half-plane with the Poincare metric. This
|
| 3 |
+
is a basic model of hyperbolic geometry on the (positive) half-space
|
| 4 |
+
|
| 5 |
+
{(x,y) \in R^2 | y > 0}
|
| 6 |
+
|
| 7 |
+
with the Riemannian metric
|
| 8 |
+
|
| 9 |
+
ds^2 = (dx^2 + dy^2)/y^2
|
| 10 |
+
|
| 11 |
+
It has constant negative scalar curvature = -2
|
| 12 |
+
|
| 13 |
+
https://en.wikipedia.org/wiki/Poincare_half-plane_model
|
| 14 |
+
'''
|
| 15 |
+
from sympy.matrices.dense import diag
|
| 16 |
+
from sympy.diffgeom import (twoform_to_matrix,
|
| 17 |
+
metric_to_Christoffel_1st, metric_to_Christoffel_2nd,
|
| 18 |
+
metric_to_Riemann_components, metric_to_Ricci_components)
|
| 19 |
+
import sympy.diffgeom.rn
|
| 20 |
+
from sympy.tensor.array import ImmutableDenseNDimArray
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_H2():
|
| 24 |
+
TP = sympy.diffgeom.TensorProduct
|
| 25 |
+
R2 = sympy.diffgeom.rn.R2
|
| 26 |
+
y = R2.y
|
| 27 |
+
dy = R2.dy
|
| 28 |
+
dx = R2.dx
|
| 29 |
+
g = (TP(dx, dx) + TP(dy, dy))*y**(-2)
|
| 30 |
+
automat = twoform_to_matrix(g)
|
| 31 |
+
mat = diag(y**(-2), y**(-2))
|
| 32 |
+
assert mat == automat
|
| 33 |
+
|
| 34 |
+
gamma1 = metric_to_Christoffel_1st(g)
|
| 35 |
+
assert gamma1[0, 0, 0] == 0
|
| 36 |
+
assert gamma1[0, 0, 1] == -y**(-3)
|
| 37 |
+
assert gamma1[0, 1, 0] == -y**(-3)
|
| 38 |
+
assert gamma1[0, 1, 1] == 0
|
| 39 |
+
|
| 40 |
+
assert gamma1[1, 1, 1] == -y**(-3)
|
| 41 |
+
assert gamma1[1, 1, 0] == 0
|
| 42 |
+
assert gamma1[1, 0, 1] == 0
|
| 43 |
+
assert gamma1[1, 0, 0] == y**(-3)
|
| 44 |
+
|
| 45 |
+
gamma2 = metric_to_Christoffel_2nd(g)
|
| 46 |
+
assert gamma2[0, 0, 0] == 0
|
| 47 |
+
assert gamma2[0, 0, 1] == -y**(-1)
|
| 48 |
+
assert gamma2[0, 1, 0] == -y**(-1)
|
| 49 |
+
assert gamma2[0, 1, 1] == 0
|
| 50 |
+
|
| 51 |
+
assert gamma2[1, 1, 1] == -y**(-1)
|
| 52 |
+
assert gamma2[1, 1, 0] == 0
|
| 53 |
+
assert gamma2[1, 0, 1] == 0
|
| 54 |
+
assert gamma2[1, 0, 0] == y**(-1)
|
| 55 |
+
|
| 56 |
+
Rm = metric_to_Riemann_components(g)
|
| 57 |
+
assert Rm[0, 0, 0, 0] == 0
|
| 58 |
+
assert Rm[0, 0, 0, 1] == 0
|
| 59 |
+
assert Rm[0, 0, 1, 0] == 0
|
| 60 |
+
assert Rm[0, 0, 1, 1] == 0
|
| 61 |
+
|
| 62 |
+
assert Rm[0, 1, 0, 0] == 0
|
| 63 |
+
assert Rm[0, 1, 0, 1] == -y**(-2)
|
| 64 |
+
assert Rm[0, 1, 1, 0] == y**(-2)
|
| 65 |
+
assert Rm[0, 1, 1, 1] == 0
|
| 66 |
+
|
| 67 |
+
assert Rm[1, 0, 0, 0] == 0
|
| 68 |
+
assert Rm[1, 0, 0, 1] == y**(-2)
|
| 69 |
+
assert Rm[1, 0, 1, 0] == -y**(-2)
|
| 70 |
+
assert Rm[1, 0, 1, 1] == 0
|
| 71 |
+
|
| 72 |
+
assert Rm[1, 1, 0, 0] == 0
|
| 73 |
+
assert Rm[1, 1, 0, 1] == 0
|
| 74 |
+
assert Rm[1, 1, 1, 0] == 0
|
| 75 |
+
assert Rm[1, 1, 1, 1] == 0
|
| 76 |
+
|
| 77 |
+
Ric = metric_to_Ricci_components(g)
|
| 78 |
+
assert Ric[0, 0] == -y**(-2)
|
| 79 |
+
assert Ric[0, 1] == 0
|
| 80 |
+
assert Ric[1, 0] == 0
|
| 81 |
+
assert Ric[0, 0] == -y**(-2)
|
| 82 |
+
|
| 83 |
+
assert Ric == ImmutableDenseNDimArray([-y**(-2), 0, 0, -y**(-2)], (2, 2))
|
| 84 |
+
|
| 85 |
+
## scalar curvature is -2
|
| 86 |
+
#TODO - it would be nice to have index contraction built-in
|
| 87 |
+
R = (Ric[0, 0] + Ric[1, 1])*y**2
|
| 88 |
+
assert R == -2
|
| 89 |
+
|
| 90 |
+
## Gauss curvature is -1
|
| 91 |
+
assert R/2 == -1
|
pllava/lib/python3.10/site-packages/sympy/polys/__pycache__/polytools.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5e190ab6d918a9035f73d1463ba8efa7d42f1f0174bce577ac0e32153d1a80cf
|
| 3 |
+
size 186792
|
pllava/lib/python3.10/site-packages/sympy/polys/tests/__pycache__/test_polytools.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5c150eaf47b23d11ece2b8f4fdcaae77a0f30d570cd09c7aa3a18b844277f441
|
| 3 |
+
size 141252
|
pllava/lib/python3.10/site-packages/sympy/tensor/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A module to manipulate symbolic objects with indices including tensors
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
from .indexed import IndexedBase, Idx, Indexed
|
| 5 |
+
from .index_methods import get_contraction_structure, get_indices
|
| 6 |
+
from .functions import shape
|
| 7 |
+
from .array import (MutableDenseNDimArray, ImmutableDenseNDimArray,
|
| 8 |
+
MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct,
|
| 9 |
+
tensorcontraction, tensordiagonal, derive_by_array, permutedims, Array,
|
| 10 |
+
DenseNDimArray, SparseNDimArray,)
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
'IndexedBase', 'Idx', 'Indexed',
|
| 14 |
+
|
| 15 |
+
'get_contraction_structure', 'get_indices',
|
| 16 |
+
|
| 17 |
+
'shape',
|
| 18 |
+
|
| 19 |
+
'MutableDenseNDimArray', 'ImmutableDenseNDimArray',
|
| 20 |
+
'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray',
|
| 21 |
+
'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', 'permutedims',
|
| 22 |
+
'Array', 'DenseNDimArray', 'SparseNDimArray',
|
| 23 |
+
]
|
pllava/lib/python3.10/site-packages/sympy/tensor/array/__init__.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
N-dim array module for SymPy.
|
| 3 |
+
|
| 4 |
+
Four classes are provided to handle N-dim arrays, given by the combinations
|
| 5 |
+
dense/sparse (i.e. whether to store all elements or only the non-zero ones in
|
| 6 |
+
memory) and mutable/immutable (immutable classes are SymPy objects, but cannot
|
| 7 |
+
change after they have been created).
|
| 8 |
+
|
| 9 |
+
Examples
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
The following examples show the usage of ``Array``. This is an abbreviation for
|
| 13 |
+
``ImmutableDenseNDimArray``, that is an immutable and dense N-dim array, the
|
| 14 |
+
other classes are analogous. For mutable classes it is also possible to change
|
| 15 |
+
element values after the object has been constructed.
|
| 16 |
+
|
| 17 |
+
Array construction can detect the shape of nested lists and tuples:
|
| 18 |
+
|
| 19 |
+
>>> from sympy import Array
|
| 20 |
+
>>> a1 = Array([[1, 2], [3, 4], [5, 6]])
|
| 21 |
+
>>> a1
|
| 22 |
+
[[1, 2], [3, 4], [5, 6]]
|
| 23 |
+
>>> a1.shape
|
| 24 |
+
(3, 2)
|
| 25 |
+
>>> a1.rank()
|
| 26 |
+
2
|
| 27 |
+
>>> from sympy.abc import x, y, z
|
| 28 |
+
>>> a2 = Array([[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]])
|
| 29 |
+
>>> a2
|
| 30 |
+
[[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]]
|
| 31 |
+
>>> a2.shape
|
| 32 |
+
(2, 2, 2)
|
| 33 |
+
>>> a2.rank()
|
| 34 |
+
3
|
| 35 |
+
|
| 36 |
+
Otherwise one could pass a 1-dim array followed by a shape tuple:
|
| 37 |
+
|
| 38 |
+
>>> m1 = Array(range(12), (3, 4))
|
| 39 |
+
>>> m1
|
| 40 |
+
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
|
| 41 |
+
>>> m2 = Array(range(12), (3, 2, 2))
|
| 42 |
+
>>> m2
|
| 43 |
+
[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
|
| 44 |
+
>>> m2[1,1,1]
|
| 45 |
+
7
|
| 46 |
+
>>> m2.reshape(4, 3)
|
| 47 |
+
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
|
| 48 |
+
|
| 49 |
+
Slice support:
|
| 50 |
+
|
| 51 |
+
>>> m2[:, 1, 1]
|
| 52 |
+
[3, 7, 11]
|
| 53 |
+
|
| 54 |
+
Elementwise derivative:
|
| 55 |
+
|
| 56 |
+
>>> from sympy.abc import x, y, z
|
| 57 |
+
>>> m3 = Array([x**3, x*y, z])
|
| 58 |
+
>>> m3.diff(x)
|
| 59 |
+
[3*x**2, y, 0]
|
| 60 |
+
>>> m3.diff(z)
|
| 61 |
+
[0, 0, 1]
|
| 62 |
+
|
| 63 |
+
Multiplication with other SymPy expressions is applied elementwisely:
|
| 64 |
+
|
| 65 |
+
>>> (1+x)*m3
|
| 66 |
+
[x**3*(x + 1), x*y*(x + 1), z*(x + 1)]
|
| 67 |
+
|
| 68 |
+
To apply a function to each element of the N-dim array, use ``applyfunc``:
|
| 69 |
+
|
| 70 |
+
>>> m3.applyfunc(lambda x: x/2)
|
| 71 |
+
[x**3/2, x*y/2, z/2]
|
| 72 |
+
|
| 73 |
+
N-dim arrays can be converted to nested lists by the ``tolist()`` method:
|
| 74 |
+
|
| 75 |
+
>>> m2.tolist()
|
| 76 |
+
[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
|
| 77 |
+
>>> isinstance(m2.tolist(), list)
|
| 78 |
+
True
|
| 79 |
+
|
| 80 |
+
If the rank is 2, it is possible to convert them to matrices with ``tomatrix()``:
|
| 81 |
+
|
| 82 |
+
>>> m1.tomatrix()
|
| 83 |
+
Matrix([
|
| 84 |
+
[0, 1, 2, 3],
|
| 85 |
+
[4, 5, 6, 7],
|
| 86 |
+
[8, 9, 10, 11]])
|
| 87 |
+
|
| 88 |
+
Products and contractions
|
| 89 |
+
-------------------------
|
| 90 |
+
|
| 91 |
+
Tensor product between arrays `A_{i_1,\ldots,i_n}` and `B_{j_1,\ldots,j_m}`
|
| 92 |
+
creates the combined array `P = A \otimes B` defined as
|
| 93 |
+
|
| 94 |
+
`P_{i_1,\ldots,i_n,j_1,\ldots,j_m} := A_{i_1,\ldots,i_n}\cdot B_{j_1,\ldots,j_m}.`
|
| 95 |
+
|
| 96 |
+
It is available through ``tensorproduct(...)``:
|
| 97 |
+
|
| 98 |
+
>>> from sympy import Array, tensorproduct
|
| 99 |
+
>>> from sympy.abc import x,y,z,t
|
| 100 |
+
>>> A = Array([x, y, z, t])
|
| 101 |
+
>>> B = Array([1, 2, 3, 4])
|
| 102 |
+
>>> tensorproduct(A, B)
|
| 103 |
+
[[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]]
|
| 104 |
+
|
| 105 |
+
In case you don't want to evaluate the tensor product immediately, you can use
|
| 106 |
+
``ArrayTensorProduct``, which creates an unevaluated tensor product expression:
|
| 107 |
+
|
| 108 |
+
>>> from sympy.tensor.array.expressions import ArrayTensorProduct
|
| 109 |
+
>>> ArrayTensorProduct(A, B)
|
| 110 |
+
ArrayTensorProduct([x, y, z, t], [1, 2, 3, 4])
|
| 111 |
+
|
| 112 |
+
Calling ``.as_explicit()`` on ``ArrayTensorProduct`` is equivalent to just calling
|
| 113 |
+
``tensorproduct(...)``:
|
| 114 |
+
|
| 115 |
+
>>> ArrayTensorProduct(A, B).as_explicit()
|
| 116 |
+
[[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]]
|
| 117 |
+
|
| 118 |
+
Tensor product between a rank-1 array and a matrix creates a rank-3 array:
|
| 119 |
+
|
| 120 |
+
>>> from sympy import eye
|
| 121 |
+
>>> p1 = tensorproduct(A, eye(4))
|
| 122 |
+
>>> p1
|
| 123 |
+
[[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]], [[y, 0, 0, 0], [0, y, 0, 0], [0, 0, y, 0], [0, 0, 0, y]], [[z, 0, 0, 0], [0, z, 0, 0], [0, 0, z, 0], [0, 0, 0, z]], [[t, 0, 0, 0], [0, t, 0, 0], [0, 0, t, 0], [0, 0, 0, t]]]
|
| 124 |
+
|
| 125 |
+
Now, to get back `A_0 \otimes \mathbf{1}` one can access `p_{0,m,n}` by slicing:
|
| 126 |
+
|
| 127 |
+
>>> p1[0,:,:]
|
| 128 |
+
[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]]
|
| 129 |
+
|
| 130 |
+
Tensor contraction sums over the specified axes, for example contracting
|
| 131 |
+
positions `a` and `b` means
|
| 132 |
+
|
| 133 |
+
`A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies \sum_k A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}`
|
| 134 |
+
|
| 135 |
+
Remember that Python indexing is zero starting, to contract the a-th and b-th
|
| 136 |
+
axes it is therefore necessary to specify `a-1` and `b-1`
|
| 137 |
+
|
| 138 |
+
>>> from sympy import tensorcontraction
|
| 139 |
+
>>> C = Array([[x, y], [z, t]])
|
| 140 |
+
|
| 141 |
+
The matrix trace is equivalent to the contraction of a rank-2 array:
|
| 142 |
+
|
| 143 |
+
`A_{m,n} \implies \sum_k A_{k,k}`
|
| 144 |
+
|
| 145 |
+
>>> tensorcontraction(C, (0, 1))
|
| 146 |
+
t + x
|
| 147 |
+
|
| 148 |
+
To create an expression representing a tensor contraction that does not get
|
| 149 |
+
evaluated immediately, use ``ArrayContraction``, which is equivalent to
|
| 150 |
+
``tensorcontraction(...)`` if it is followed by ``.as_explicit()``:
|
| 151 |
+
|
| 152 |
+
>>> from sympy.tensor.array.expressions import ArrayContraction
|
| 153 |
+
>>> ArrayContraction(C, (0, 1))
|
| 154 |
+
ArrayContraction([[x, y], [z, t]], (0, 1))
|
| 155 |
+
>>> ArrayContraction(C, (0, 1)).as_explicit()
|
| 156 |
+
t + x
|
| 157 |
+
|
| 158 |
+
Matrix product is equivalent to a tensor product of two rank-2 arrays, followed
|
| 159 |
+
by a contraction of the 2nd and 3rd axes (in Python indexing axes number 1, 2).
|
| 160 |
+
|
| 161 |
+
`A_{m,n}\cdot B_{i,j} \implies \sum_k A_{m, k}\cdot B_{k, j}`
|
| 162 |
+
|
| 163 |
+
>>> D = Array([[2, 1], [0, -1]])
|
| 164 |
+
>>> tensorcontraction(tensorproduct(C, D), (1, 2))
|
| 165 |
+
[[2*x, x - y], [2*z, -t + z]]
|
| 166 |
+
|
| 167 |
+
One may verify that the matrix product is equivalent:
|
| 168 |
+
|
| 169 |
+
>>> from sympy import Matrix
|
| 170 |
+
>>> Matrix([[x, y], [z, t]])*Matrix([[2, 1], [0, -1]])
|
| 171 |
+
Matrix([
|
| 172 |
+
[2*x, x - y],
|
| 173 |
+
[2*z, -t + z]])
|
| 174 |
+
|
| 175 |
+
or equivalently
|
| 176 |
+
|
| 177 |
+
>>> C.tomatrix()*D.tomatrix()
|
| 178 |
+
Matrix([
|
| 179 |
+
[2*x, x - y],
|
| 180 |
+
[2*z, -t + z]])
|
| 181 |
+
|
| 182 |
+
Diagonal operator
|
| 183 |
+
-----------------
|
| 184 |
+
|
| 185 |
+
The ``tensordiagonal`` function acts in a similar manner as ``tensorcontraction``,
|
| 186 |
+
but the joined indices are not summed over, for example diagonalizing
|
| 187 |
+
positions `a` and `b` means
|
| 188 |
+
|
| 189 |
+
`A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}
|
| 190 |
+
\implies \tilde{A}_{i_1,\ldots,i_{a-1},i_{a+1},\ldots,i_{b-1},i_{b+1},\ldots,i_n,k}`
|
| 191 |
+
|
| 192 |
+
where `\tilde{A}` is the array equivalent to the diagonal of `A` at positions
|
| 193 |
+
`a` and `b` moved to the last index slot.
|
| 194 |
+
|
| 195 |
+
Compare the difference between contraction and diagonal operators:
|
| 196 |
+
|
| 197 |
+
>>> from sympy import tensordiagonal
|
| 198 |
+
>>> from sympy.abc import a, b, c, d
|
| 199 |
+
>>> m = Matrix([[a, b], [c, d]])
|
| 200 |
+
>>> tensorcontraction(m, [0, 1])
|
| 201 |
+
a + d
|
| 202 |
+
>>> tensordiagonal(m, [0, 1])
|
| 203 |
+
[a, d]
|
| 204 |
+
|
| 205 |
+
In short, no summation occurs with ``tensordiagonal``.
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
Derivatives by array
|
| 209 |
+
--------------------
|
| 210 |
+
|
| 211 |
+
The usual derivative operation may be extended to support derivation with
|
| 212 |
+
respect to arrays, provided that all elements in the that array are symbols or
|
| 213 |
+
expressions suitable for derivations.
|
| 214 |
+
|
| 215 |
+
The definition of a derivative by an array is as follows: given the array
|
| 216 |
+
`A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
|
| 217 |
+
the derivative of arrays will return a new array `B` defined by
|
| 218 |
+
|
| 219 |
+
`B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
|
| 220 |
+
|
| 221 |
+
The function ``derive_by_array`` performs such an operation:
|
| 222 |
+
|
| 223 |
+
>>> from sympy import derive_by_array
|
| 224 |
+
>>> from sympy.abc import x, y, z, t
|
| 225 |
+
>>> from sympy import sin, exp
|
| 226 |
+
|
| 227 |
+
With scalars, it behaves exactly as the ordinary derivative:
|
| 228 |
+
|
| 229 |
+
>>> derive_by_array(sin(x*y), x)
|
| 230 |
+
y*cos(x*y)
|
| 231 |
+
|
| 232 |
+
Scalar derived by an array basis:
|
| 233 |
+
|
| 234 |
+
>>> derive_by_array(sin(x*y), [x, y, z])
|
| 235 |
+
[y*cos(x*y), x*cos(x*y), 0]
|
| 236 |
+
|
| 237 |
+
Deriving array by an array basis: `B^{nm} := \frac{\partial A^m}{\partial x^n}`
|
| 238 |
+
|
| 239 |
+
>>> basis = [x, y, z]
|
| 240 |
+
>>> ax = derive_by_array([exp(x), sin(y*z), t], basis)
|
| 241 |
+
>>> ax
|
| 242 |
+
[[exp(x), 0, 0], [0, z*cos(y*z), 0], [0, y*cos(y*z), 0]]
|
| 243 |
+
|
| 244 |
+
Contraction of the resulting array: `\sum_m \frac{\partial A^m}{\partial x^m}`
|
| 245 |
+
|
| 246 |
+
>>> tensorcontraction(ax, (0, 1))
|
| 247 |
+
z*cos(y*z) + exp(x)
|
| 248 |
+
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
from .dense_ndim_array import MutableDenseNDimArray, ImmutableDenseNDimArray, DenseNDimArray
|
| 252 |
+
from .sparse_ndim_array import MutableSparseNDimArray, ImmutableSparseNDimArray, SparseNDimArray
|
| 253 |
+
from .ndim_array import NDimArray, ArrayKind
|
| 254 |
+
from .arrayop import tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, permutedims
|
| 255 |
+
from .array_comprehension import ArrayComprehension, ArrayComprehensionMap
|
| 256 |
+
|
| 257 |
+
Array = ImmutableDenseNDimArray
|
| 258 |
+
|
| 259 |
+
__all__ = [
|
| 260 |
+
'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'DenseNDimArray',
|
| 261 |
+
|
| 262 |
+
'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'SparseNDimArray',
|
| 263 |
+
|
| 264 |
+
'NDimArray', 'ArrayKind',
|
| 265 |
+
|
| 266 |
+
'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array',
|
| 267 |
+
|
| 268 |
+
'permutedims', 'ArrayComprehension', 'ArrayComprehensionMap',
|
| 269 |
+
|
| 270 |
+
'Array',
|
| 271 |
+
]
|
pllava/lib/python3.10/site-packages/sympy/tensor/array/array_derivatives.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from sympy.core.expr import Expr
|
| 4 |
+
from sympy.core.function import Derivative
|
| 5 |
+
from sympy.core.numbers import Integer
|
| 6 |
+
from sympy.matrices.matrixbase import MatrixBase
|
| 7 |
+
from .ndim_array import NDimArray
|
| 8 |
+
from .arrayop import derive_by_array
|
| 9 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
| 10 |
+
from sympy.matrices.expressions.special import ZeroMatrix
|
| 11 |
+
from sympy.matrices.expressions.matexpr import _matrix_derivative
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ArrayDerivative(Derivative):
|
| 15 |
+
|
| 16 |
+
is_scalar = False
|
| 17 |
+
|
| 18 |
+
def __new__(cls, expr, *variables, **kwargs):
|
| 19 |
+
obj = super().__new__(cls, expr, *variables, **kwargs)
|
| 20 |
+
if isinstance(obj, ArrayDerivative):
|
| 21 |
+
obj._shape = obj._get_shape()
|
| 22 |
+
return obj
|
| 23 |
+
|
| 24 |
+
def _get_shape(self):
|
| 25 |
+
shape = ()
|
| 26 |
+
for v, count in self.variable_count:
|
| 27 |
+
if hasattr(v, "shape"):
|
| 28 |
+
for i in range(count):
|
| 29 |
+
shape += v.shape
|
| 30 |
+
if hasattr(self.expr, "shape"):
|
| 31 |
+
shape += self.expr.shape
|
| 32 |
+
return shape
|
| 33 |
+
|
| 34 |
+
@property
|
| 35 |
+
def shape(self):
|
| 36 |
+
return self._shape
|
| 37 |
+
|
| 38 |
+
@classmethod
|
| 39 |
+
def _get_zero_with_shape_like(cls, expr):
|
| 40 |
+
if isinstance(expr, (MatrixBase, NDimArray)):
|
| 41 |
+
return expr.zeros(*expr.shape)
|
| 42 |
+
elif isinstance(expr, MatrixExpr):
|
| 43 |
+
return ZeroMatrix(*expr.shape)
|
| 44 |
+
else:
|
| 45 |
+
raise RuntimeError("Unable to determine shape of array-derivative.")
|
| 46 |
+
|
| 47 |
+
@staticmethod
|
| 48 |
+
def _call_derive_scalar_by_matrix(expr: Expr, v: MatrixBase) -> Expr:
|
| 49 |
+
return v.applyfunc(lambda x: expr.diff(x))
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def _call_derive_scalar_by_matexpr(expr: Expr, v: MatrixExpr) -> Expr:
|
| 53 |
+
if expr.has(v):
|
| 54 |
+
return _matrix_derivative(expr, v)
|
| 55 |
+
else:
|
| 56 |
+
return ZeroMatrix(*v.shape)
|
| 57 |
+
|
| 58 |
+
@staticmethod
|
| 59 |
+
def _call_derive_scalar_by_array(expr: Expr, v: NDimArray) -> Expr:
|
| 60 |
+
return v.applyfunc(lambda x: expr.diff(x))
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def _call_derive_matrix_by_scalar(expr: MatrixBase, v: Expr) -> Expr:
|
| 64 |
+
return _matrix_derivative(expr, v)
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def _call_derive_matexpr_by_scalar(expr: MatrixExpr, v: Expr) -> Expr:
|
| 68 |
+
return expr._eval_derivative(v)
|
| 69 |
+
|
| 70 |
+
@staticmethod
|
| 71 |
+
def _call_derive_array_by_scalar(expr: NDimArray, v: Expr) -> Expr:
|
| 72 |
+
return expr.applyfunc(lambda x: x.diff(v))
|
| 73 |
+
|
| 74 |
+
@staticmethod
|
| 75 |
+
def _call_derive_default(expr: Expr, v: Expr) -> Expr | None:
|
| 76 |
+
if expr.has(v):
|
| 77 |
+
return _matrix_derivative(expr, v)
|
| 78 |
+
else:
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
@classmethod
|
| 82 |
+
def _dispatch_eval_derivative_n_times(cls, expr, v, count):
|
| 83 |
+
# Evaluate the derivative `n` times. If
|
| 84 |
+
# `_eval_derivative_n_times` is not overridden by the current
|
| 85 |
+
# object, the default in `Basic` will call a loop over
|
| 86 |
+
# `_eval_derivative`:
|
| 87 |
+
|
| 88 |
+
if not isinstance(count, (int, Integer)) or ((count <= 0) == True):
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
# TODO: this could be done with multiple-dispatching:
|
| 92 |
+
if expr.is_scalar:
|
| 93 |
+
if isinstance(v, MatrixBase):
|
| 94 |
+
result = cls._call_derive_scalar_by_matrix(expr, v)
|
| 95 |
+
elif isinstance(v, MatrixExpr):
|
| 96 |
+
result = cls._call_derive_scalar_by_matexpr(expr, v)
|
| 97 |
+
elif isinstance(v, NDimArray):
|
| 98 |
+
result = cls._call_derive_scalar_by_array(expr, v)
|
| 99 |
+
elif v.is_scalar:
|
| 100 |
+
# scalar by scalar has a special
|
| 101 |
+
return super()._dispatch_eval_derivative_n_times(expr, v, count)
|
| 102 |
+
else:
|
| 103 |
+
return None
|
| 104 |
+
elif v.is_scalar:
|
| 105 |
+
if isinstance(expr, MatrixBase):
|
| 106 |
+
result = cls._call_derive_matrix_by_scalar(expr, v)
|
| 107 |
+
elif isinstance(expr, MatrixExpr):
|
| 108 |
+
result = cls._call_derive_matexpr_by_scalar(expr, v)
|
| 109 |
+
elif isinstance(expr, NDimArray):
|
| 110 |
+
result = cls._call_derive_array_by_scalar(expr, v)
|
| 111 |
+
else:
|
| 112 |
+
return None
|
| 113 |
+
else:
|
| 114 |
+
# Both `expr` and `v` are some array/matrix type:
|
| 115 |
+
if isinstance(expr, MatrixBase) or isinstance(v, MatrixBase):
|
| 116 |
+
result = derive_by_array(expr, v)
|
| 117 |
+
elif isinstance(expr, MatrixExpr) and isinstance(v, MatrixExpr):
|
| 118 |
+
result = cls._call_derive_default(expr, v)
|
| 119 |
+
elif isinstance(expr, MatrixExpr) or isinstance(v, MatrixExpr):
|
| 120 |
+
# if one expression is a symbolic matrix expression while the other isn't, don't evaluate:
|
| 121 |
+
return None
|
| 122 |
+
else:
|
| 123 |
+
result = derive_by_array(expr, v)
|
| 124 |
+
if result is None:
|
| 125 |
+
return None
|
| 126 |
+
if count == 1:
|
| 127 |
+
return result
|
| 128 |
+
else:
|
| 129 |
+
return cls._dispatch_eval_derivative_n_times(result, v, count - 1)
|
pllava/lib/python3.10/site-packages/sympy/tensor/array/dense_ndim_array.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
from sympy.core.basic import Basic
|
| 5 |
+
from sympy.core.containers import Tuple
|
| 6 |
+
from sympy.core.singleton import S
|
| 7 |
+
from sympy.core.sympify import _sympify
|
| 8 |
+
from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
|
| 9 |
+
from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray, ArrayKind
|
| 10 |
+
from sympy.utilities.iterables import flatten
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class DenseNDimArray(NDimArray):
|
| 14 |
+
|
| 15 |
+
_array: List[Basic]
|
| 16 |
+
|
| 17 |
+
def __new__(self, *args, **kwargs):
|
| 18 |
+
return ImmutableDenseNDimArray(*args, **kwargs)
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def kind(self) -> ArrayKind:
|
| 22 |
+
return ArrayKind._union(self._array)
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, index):
|
| 25 |
+
"""
|
| 26 |
+
Allows to get items from N-dim array.
|
| 27 |
+
|
| 28 |
+
Examples
|
| 29 |
+
========
|
| 30 |
+
|
| 31 |
+
>>> from sympy import MutableDenseNDimArray
|
| 32 |
+
>>> a = MutableDenseNDimArray([0, 1, 2, 3], (2, 2))
|
| 33 |
+
>>> a
|
| 34 |
+
[[0, 1], [2, 3]]
|
| 35 |
+
>>> a[0, 0]
|
| 36 |
+
0
|
| 37 |
+
>>> a[1, 1]
|
| 38 |
+
3
|
| 39 |
+
>>> a[0]
|
| 40 |
+
[0, 1]
|
| 41 |
+
>>> a[1]
|
| 42 |
+
[2, 3]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
Symbolic index:
|
| 46 |
+
|
| 47 |
+
>>> from sympy.abc import i, j
|
| 48 |
+
>>> a[i, j]
|
| 49 |
+
[[0, 1], [2, 3]][i, j]
|
| 50 |
+
|
| 51 |
+
Replace `i` and `j` to get element `(1, 1)`:
|
| 52 |
+
|
| 53 |
+
>>> a[i, j].subs({i: 1, j: 1})
|
| 54 |
+
3
|
| 55 |
+
|
| 56 |
+
"""
|
| 57 |
+
syindex = self._check_symbolic_index(index)
|
| 58 |
+
if syindex is not None:
|
| 59 |
+
return syindex
|
| 60 |
+
|
| 61 |
+
index = self._check_index_for_getitem(index)
|
| 62 |
+
|
| 63 |
+
if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
|
| 64 |
+
sl_factors, eindices = self._get_slice_data_for_array_access(index)
|
| 65 |
+
array = [self._array[self._parse_index(i)] for i in eindices]
|
| 66 |
+
nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
|
| 67 |
+
return type(self)(array, nshape)
|
| 68 |
+
else:
|
| 69 |
+
index = self._parse_index(index)
|
| 70 |
+
return self._array[index]
|
| 71 |
+
|
| 72 |
+
@classmethod
|
| 73 |
+
def zeros(cls, *shape):
|
| 74 |
+
list_length = functools.reduce(lambda x, y: x*y, shape, S.One)
|
| 75 |
+
return cls._new(([0]*list_length,), shape)
|
| 76 |
+
|
| 77 |
+
def tomatrix(self):
|
| 78 |
+
"""
|
| 79 |
+
Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error.
|
| 80 |
+
|
| 81 |
+
Examples
|
| 82 |
+
========
|
| 83 |
+
|
| 84 |
+
>>> from sympy import MutableDenseNDimArray
|
| 85 |
+
>>> a = MutableDenseNDimArray([1 for i in range(9)], (3, 3))
|
| 86 |
+
>>> b = a.tomatrix()
|
| 87 |
+
>>> b
|
| 88 |
+
Matrix([
|
| 89 |
+
[1, 1, 1],
|
| 90 |
+
[1, 1, 1],
|
| 91 |
+
[1, 1, 1]])
|
| 92 |
+
|
| 93 |
+
"""
|
| 94 |
+
from sympy.matrices import Matrix
|
| 95 |
+
|
| 96 |
+
if self.rank() != 2:
|
| 97 |
+
raise ValueError('Dimensions must be of size of 2')
|
| 98 |
+
|
| 99 |
+
return Matrix(self.shape[0], self.shape[1], self._array)
|
| 100 |
+
|
| 101 |
+
def reshape(self, *newshape):
|
| 102 |
+
"""
|
| 103 |
+
Returns MutableDenseNDimArray instance with new shape. Elements number
|
| 104 |
+
must be suitable to new shape. The only argument of method sets
|
| 105 |
+
new shape.
|
| 106 |
+
|
| 107 |
+
Examples
|
| 108 |
+
========
|
| 109 |
+
|
| 110 |
+
>>> from sympy import MutableDenseNDimArray
|
| 111 |
+
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
|
| 112 |
+
>>> a.shape
|
| 113 |
+
(2, 3)
|
| 114 |
+
>>> a
|
| 115 |
+
[[1, 2, 3], [4, 5, 6]]
|
| 116 |
+
>>> b = a.reshape(3, 2)
|
| 117 |
+
>>> b.shape
|
| 118 |
+
(3, 2)
|
| 119 |
+
>>> b
|
| 120 |
+
[[1, 2], [3, 4], [5, 6]]
|
| 121 |
+
|
| 122 |
+
"""
|
| 123 |
+
new_total_size = functools.reduce(lambda x,y: x*y, newshape)
|
| 124 |
+
if new_total_size != self._loop_size:
|
| 125 |
+
raise ValueError('Expecting reshape size to %d but got prod(%s) = %d' % (
|
| 126 |
+
self._loop_size, str(newshape), new_total_size))
|
| 127 |
+
|
| 128 |
+
# there is no `.func` as this class does not subtype `Basic`:
|
| 129 |
+
return type(self)(self._array, newshape)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class ImmutableDenseNDimArray(DenseNDimArray, ImmutableNDimArray): # type: ignore
|
| 133 |
+
def __new__(cls, iterable, shape=None, **kwargs):
|
| 134 |
+
return cls._new(iterable, shape, **kwargs)
|
| 135 |
+
|
| 136 |
+
@classmethod
|
| 137 |
+
def _new(cls, iterable, shape, **kwargs):
|
| 138 |
+
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
|
| 139 |
+
shape = Tuple(*map(_sympify, shape))
|
| 140 |
+
cls._check_special_bounds(flat_list, shape)
|
| 141 |
+
flat_list = flatten(flat_list)
|
| 142 |
+
flat_list = Tuple(*flat_list)
|
| 143 |
+
self = Basic.__new__(cls, flat_list, shape, **kwargs)
|
| 144 |
+
self._shape = shape
|
| 145 |
+
self._array = list(flat_list)
|
| 146 |
+
self._rank = len(shape)
|
| 147 |
+
self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1)
|
| 148 |
+
return self
|
| 149 |
+
|
| 150 |
+
def __setitem__(self, index, value):
|
| 151 |
+
raise TypeError('immutable N-dim array')
|
| 152 |
+
|
| 153 |
+
def as_mutable(self):
|
| 154 |
+
return MutableDenseNDimArray(self)
|
| 155 |
+
|
| 156 |
+
def _eval_simplify(self, **kwargs):
|
| 157 |
+
from sympy.simplify.simplify import simplify
|
| 158 |
+
return self.applyfunc(simplify)
|
| 159 |
+
|
| 160 |
+
class MutableDenseNDimArray(DenseNDimArray, MutableNDimArray):
|
| 161 |
+
|
| 162 |
+
def __new__(cls, iterable=None, shape=None, **kwargs):
|
| 163 |
+
return cls._new(iterable, shape, **kwargs)
|
| 164 |
+
|
| 165 |
+
@classmethod
|
| 166 |
+
def _new(cls, iterable, shape, **kwargs):
|
| 167 |
+
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
|
| 168 |
+
flat_list = flatten(flat_list)
|
| 169 |
+
self = object.__new__(cls)
|
| 170 |
+
self._shape = shape
|
| 171 |
+
self._array = list(flat_list)
|
| 172 |
+
self._rank = len(shape)
|
| 173 |
+
self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
|
| 174 |
+
return self
|
| 175 |
+
|
| 176 |
+
def __setitem__(self, index, value):
|
| 177 |
+
"""Allows to set items to MutableDenseNDimArray.
|
| 178 |
+
|
| 179 |
+
Examples
|
| 180 |
+
========
|
| 181 |
+
|
| 182 |
+
>>> from sympy import MutableDenseNDimArray
|
| 183 |
+
>>> a = MutableDenseNDimArray.zeros(2, 2)
|
| 184 |
+
>>> a[0,0] = 1
|
| 185 |
+
>>> a[1,1] = 1
|
| 186 |
+
>>> a
|
| 187 |
+
[[1, 0], [0, 1]]
|
| 188 |
+
|
| 189 |
+
"""
|
| 190 |
+
if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
|
| 191 |
+
value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
|
| 192 |
+
for i in eindices:
|
| 193 |
+
other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
|
| 194 |
+
self._array[self._parse_index(i)] = value[other_i]
|
| 195 |
+
else:
|
| 196 |
+
index = self._parse_index(index)
|
| 197 |
+
self._setter_iterable_check(value)
|
| 198 |
+
value = _sympify(value)
|
| 199 |
+
self._array[index] = value
|
| 200 |
+
|
| 201 |
+
def as_immutable(self):
|
| 202 |
+
return ImmutableDenseNDimArray(self)
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def free_symbols(self):
|
| 206 |
+
return {i for j in self._array for i in j.free_symbols}
|