Upload folder using huggingface_hub (part 17)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +35 -0
- .venv/lib/python3.12/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/categories/baseclasses.py +978 -0
- .venv/lib/python3.12/site-packages/sympy/categories/diagram_drawing.py +2580 -0
- .venv/lib/python3.12/site-packages/sympy/categories/tests/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/categories/tests/test_baseclasses.py +209 -0
- .venv/lib/python3.12/site-packages/sympy/categories/tests/test_drawing.py +919 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__init__.py +24 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/abstract_nodes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/algorithms.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/approximations.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/ast.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/cnodes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/cutils.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/cxxnodes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/fnodes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/futils.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/matrix_nodes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/pynodes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/pyutils.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/rewriting.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/scipy_nodes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/abstract_nodes.py +18 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/algorithms.py +180 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/approximations.py +187 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/ast.py +1906 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/cfunctions.py +558 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/cnodes.py +156 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/cutils.py +8 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/cxxnodes.py +14 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/fnodes.py +658 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/futils.py +40 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/matrix_nodes.py +71 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/numpy_nodes.py +177 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/pynodes.py +11 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/pyutils.py +24 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/rewriting.py +357 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/scipy_nodes.py +79 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/tests/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/tests/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/tests/__pycache__/test_abstract_nodes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/tests/__pycache__/test_algorithms.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/tests/__pycache__/test_applications.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/codegen/tests/__pycache__/test_approximations.cpython-312.pyc +0 -0
.gitattributes
CHANGED
|
@@ -408,3 +408,38 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 408 |
.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 409 |
.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 410 |
.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_query.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
.venv/lib/python3.12/site-packages/supervision/annotators/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 409 |
.venv/lib/python3.12/site-packages/supervision/detection/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 410 |
.venv/lib/python3.12/site-packages/sympy/assumptions/tests/__pycache__/test_query.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 411 |
+
.venv/lib/python3.12/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 412 |
+
.venv/lib/python3.12/site-packages/sympy/combinatorics/__pycache__/permutations.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 413 |
+
.venv/lib/python3.12/site-packages/sympy/concrete/tests/__pycache__/test_sums_products.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 414 |
+
.venv/lib/python3.12/site-packages/sympy/core/__pycache__/expr.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 415 |
+
.venv/lib/python3.12/site-packages/sympy/core/__pycache__/function.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 416 |
+
.venv/lib/python3.12/site-packages/sympy/core/__pycache__/numbers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 417 |
+
.venv/lib/python3.12/site-packages/sympy/core/tests/__pycache__/test_args.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 418 |
+
.venv/lib/python3.12/site-packages/sympy/core/tests/__pycache__/test_arit.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 419 |
+
.venv/lib/python3.12/site-packages/sympy/core/tests/__pycache__/test_expr.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 420 |
+
.venv/lib/python3.12/site-packages/sympy/core/tests/__pycache__/test_function.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 421 |
+
.venv/lib/python3.12/site-packages/sympy/core/tests/__pycache__/test_numbers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 422 |
+
.venv/lib/python3.12/site-packages/sympy/core/tests/__pycache__/test_relational.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 423 |
+
.venv/lib/python3.12/site-packages/sympy/crypto/__pycache__/crypto.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 424 |
+
.venv/lib/python3.12/site-packages/sympy/functions/combinatorial/__pycache__/numbers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 425 |
+
.venv/lib/python3.12/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_numbers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 426 |
+
.venv/lib/python3.12/site-packages/sympy/functions/elementary/__pycache__/hyperbolic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 427 |
+
.venv/lib/python3.12/site-packages/sympy/functions/elementary/__pycache__/trigonometric.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 428 |
+
.venv/lib/python3.12/site-packages/sympy/functions/elementary/tests/__pycache__/test_hyperbolic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 429 |
+
.venv/lib/python3.12/site-packages/sympy/functions/elementary/tests/__pycache__/test_piecewise.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 430 |
+
.venv/lib/python3.12/site-packages/sympy/functions/elementary/tests/__pycache__/test_trigonometric.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 431 |
+
.venv/lib/python3.12/site-packages/sympy/functions/special/__pycache__/bessel.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 432 |
+
.venv/lib/python3.12/site-packages/sympy/functions/special/__pycache__/error_functions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 433 |
+
.venv/lib/python3.12/site-packages/sympy/functions/special/tests/__pycache__/test_error_functions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 434 |
+
.venv/lib/python3.12/site-packages/sympy/geometry/__pycache__/polygon.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 435 |
+
.venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 436 |
+
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/laplace.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 437 |
+
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/manualintegrate.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 438 |
+
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/meijerint.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 439 |
+
.venv/lib/python3.12/site-packages/sympy/integrals/tests/__pycache__/test_integrals.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 440 |
+
.venv/lib/python3.12/site-packages/sympy/logic/__pycache__/boolalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 441 |
+
.venv/lib/python3.12/site-packages/sympy/logic/tests/__pycache__/test_boolalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 442 |
+
.venv/lib/python3.12/site-packages/sympy/matrices/__pycache__/common.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 443 |
+
.venv/lib/python3.12/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 444 |
+
.venv/lib/python3.12/site-packages/sympy/matrices/tests/__pycache__/test_matrices.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 445 |
+
.venv/lib/python3.12/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.12/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-312.pyc
ADDED
|
Binary file (85.7 kB). View file
|
|
|
.venv/lib/python3.12/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)
|
.venv/lib/python3.12/site-packages/sympy/categories/diagram_drawing.py
ADDED
|
@@ -0,0 +1,2580 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 = {obj: [] for obj in objects}
|
| 1032 |
+
|
| 1033 |
+
for morphism in merged_morphisms:
|
| 1034 |
+
adjlists[morphism.domain].append(morphism.codomain)
|
| 1035 |
+
adjlists[morphism.codomain].append(morphism.domain)
|
| 1036 |
+
|
| 1037 |
+
# Assure that the objects in the adjacency list are always in
|
| 1038 |
+
# the same order.
|
| 1039 |
+
for obj in adjlists.keys():
|
| 1040 |
+
adjlists[obj].sort(key=default_sort_key)
|
| 1041 |
+
|
| 1042 |
+
return adjlists
|
| 1043 |
+
|
| 1044 |
+
@staticmethod
|
| 1045 |
+
def _sequential_layout(diagram, merged_morphisms):
|
| 1046 |
+
r"""
|
| 1047 |
+
Lays out the diagram in "sequential" layout. This method
|
| 1048 |
+
will attempt to produce a result as close to a line as
|
| 1049 |
+
possible. For linear diagrams, the result will actually be a
|
| 1050 |
+
line.
|
| 1051 |
+
"""
|
| 1052 |
+
objects = diagram.objects
|
| 1053 |
+
sorted_objects = sorted(objects, key=default_sort_key)
|
| 1054 |
+
|
| 1055 |
+
# Set up the adjacency lists of the underlying undirected
|
| 1056 |
+
# graph of ``merged_morphisms``.
|
| 1057 |
+
adjlists = DiagramGrid._get_undirected_graph(objects, merged_morphisms)
|
| 1058 |
+
|
| 1059 |
+
root = min(sorted_objects, key=lambda x: len(adjlists[x]))
|
| 1060 |
+
grid = _GrowableGrid(1, 1)
|
| 1061 |
+
grid[0, 0] = root
|
| 1062 |
+
|
| 1063 |
+
placed_objects = {root}
|
| 1064 |
+
|
| 1065 |
+
def place_objects(pt, placed_objects):
|
| 1066 |
+
"""
|
| 1067 |
+
Does depth-first search in the underlying graph of the
|
| 1068 |
+
diagram and places the objects en route.
|
| 1069 |
+
"""
|
| 1070 |
+
# We will start placing new objects from here.
|
| 1071 |
+
new_pt = (pt[0], pt[1] + 1)
|
| 1072 |
+
|
| 1073 |
+
for adjacent_obj in adjlists[grid[pt]]:
|
| 1074 |
+
if adjacent_obj in placed_objects:
|
| 1075 |
+
# This object has already been placed.
|
| 1076 |
+
continue
|
| 1077 |
+
|
| 1078 |
+
DiagramGrid._put_object(new_pt, adjacent_obj, grid, [])
|
| 1079 |
+
placed_objects.add(adjacent_obj)
|
| 1080 |
+
placed_objects.update(place_objects(new_pt, placed_objects))
|
| 1081 |
+
|
| 1082 |
+
new_pt = (new_pt[0] + 1, new_pt[1])
|
| 1083 |
+
|
| 1084 |
+
return placed_objects
|
| 1085 |
+
|
| 1086 |
+
place_objects((0, 0), placed_objects)
|
| 1087 |
+
|
| 1088 |
+
return grid
|
| 1089 |
+
|
| 1090 |
+
@staticmethod
|
| 1091 |
+
def _drop_inessential_morphisms(merged_morphisms):
|
| 1092 |
+
r"""
|
| 1093 |
+
Removes those morphisms which should appear in the diagram,
|
| 1094 |
+
but which have no relevance to object layout.
|
| 1095 |
+
|
| 1096 |
+
Currently this removes "loop" morphisms: the non-identity
|
| 1097 |
+
morphisms with the same domains and codomains.
|
| 1098 |
+
"""
|
| 1099 |
+
morphisms = [m for m in merged_morphisms if m.domain != m.codomain]
|
| 1100 |
+
return morphisms
|
| 1101 |
+
|
| 1102 |
+
@staticmethod
|
| 1103 |
+
def _get_connected_components(objects, merged_morphisms):
|
| 1104 |
+
"""
|
| 1105 |
+
Given a container of morphisms, returns a list of connected
|
| 1106 |
+
components formed by these morphisms. A connected component
|
| 1107 |
+
is represented by a diagram consisting of the corresponding
|
| 1108 |
+
morphisms.
|
| 1109 |
+
"""
|
| 1110 |
+
component_index = {}
|
| 1111 |
+
for o in objects:
|
| 1112 |
+
component_index[o] = None
|
| 1113 |
+
|
| 1114 |
+
# Get the underlying undirected graph of the diagram.
|
| 1115 |
+
adjlist = DiagramGrid._get_undirected_graph(objects, merged_morphisms)
|
| 1116 |
+
|
| 1117 |
+
def traverse_component(object, current_index):
|
| 1118 |
+
"""
|
| 1119 |
+
Does a depth-first search traversal of the component
|
| 1120 |
+
containing ``object``.
|
| 1121 |
+
"""
|
| 1122 |
+
component_index[object] = current_index
|
| 1123 |
+
for o in adjlist[object]:
|
| 1124 |
+
if component_index[o] is None:
|
| 1125 |
+
traverse_component(o, current_index)
|
| 1126 |
+
|
| 1127 |
+
# Traverse all components.
|
| 1128 |
+
current_index = 0
|
| 1129 |
+
for o in adjlist:
|
| 1130 |
+
if component_index[o] is None:
|
| 1131 |
+
traverse_component(o, current_index)
|
| 1132 |
+
current_index += 1
|
| 1133 |
+
|
| 1134 |
+
# List the objects of the components.
|
| 1135 |
+
component_objects = [[] for i in range(current_index)]
|
| 1136 |
+
for o, idx in component_index.items():
|
| 1137 |
+
component_objects[idx].append(o)
|
| 1138 |
+
|
| 1139 |
+
# Finally, list the morphisms belonging to each component.
|
| 1140 |
+
#
|
| 1141 |
+
# Note: If some objects are isolated, they will not get any
|
| 1142 |
+
# morphisms at this stage, and since the layout algorithm
|
| 1143 |
+
# relies, we are essentially going to lose this object.
|
| 1144 |
+
# Therefore, check if there are isolated objects and, for each
|
| 1145 |
+
# of them, provide the trivial identity morphism. It will get
|
| 1146 |
+
# discarded later, but the object will be there.
|
| 1147 |
+
|
| 1148 |
+
component_morphisms = []
|
| 1149 |
+
for component in component_objects:
|
| 1150 |
+
current_morphisms = {}
|
| 1151 |
+
for m in merged_morphisms:
|
| 1152 |
+
if (m.domain in component) and (m.codomain in component):
|
| 1153 |
+
current_morphisms[m] = merged_morphisms[m]
|
| 1154 |
+
|
| 1155 |
+
if len(component) == 1:
|
| 1156 |
+
# Let's add an identity morphism, for the sake of
|
| 1157 |
+
# surely having morphisms in this component.
|
| 1158 |
+
current_morphisms[IdentityMorphism(component[0])] = FiniteSet()
|
| 1159 |
+
|
| 1160 |
+
component_morphisms.append(Diagram(current_morphisms))
|
| 1161 |
+
|
| 1162 |
+
return component_morphisms
|
| 1163 |
+
|
| 1164 |
+
def __init__(self, diagram, groups=None, **hints):
|
| 1165 |
+
premises = DiagramGrid._simplify_morphisms(diagram.premises)
|
| 1166 |
+
conclusions = DiagramGrid._simplify_morphisms(diagram.conclusions)
|
| 1167 |
+
all_merged_morphisms = DiagramGrid._merge_premises_conclusions(
|
| 1168 |
+
premises, conclusions)
|
| 1169 |
+
merged_morphisms = DiagramGrid._drop_inessential_morphisms(
|
| 1170 |
+
all_merged_morphisms)
|
| 1171 |
+
|
| 1172 |
+
# Store the merged morphisms for later use.
|
| 1173 |
+
self._morphisms = all_merged_morphisms
|
| 1174 |
+
|
| 1175 |
+
components = DiagramGrid._get_connected_components(
|
| 1176 |
+
diagram.objects, all_merged_morphisms)
|
| 1177 |
+
|
| 1178 |
+
if groups and (groups != diagram.objects):
|
| 1179 |
+
# Lay out the diagram according to the groups.
|
| 1180 |
+
self._grid = DiagramGrid._handle_groups(
|
| 1181 |
+
diagram, groups, merged_morphisms, hints)
|
| 1182 |
+
elif len(components) > 1:
|
| 1183 |
+
# Note that we check for connectedness _before_ checking
|
| 1184 |
+
# the layout hints because the layout strategies don't
|
| 1185 |
+
# know how to deal with disconnected diagrams.
|
| 1186 |
+
|
| 1187 |
+
# The diagram is disconnected. Lay out the components
|
| 1188 |
+
# independently.
|
| 1189 |
+
grids = []
|
| 1190 |
+
|
| 1191 |
+
# Sort the components to eventually get the grids arranged
|
| 1192 |
+
# in a fixed, hash-independent order.
|
| 1193 |
+
components = sorted(components, key=default_sort_key)
|
| 1194 |
+
|
| 1195 |
+
for component in components:
|
| 1196 |
+
grid = DiagramGrid(component, **hints)
|
| 1197 |
+
grids.append(grid)
|
| 1198 |
+
|
| 1199 |
+
# Throw the grids together, in a line.
|
| 1200 |
+
total_width = sum(g.width for g in grids)
|
| 1201 |
+
total_height = max(g.height for g in grids)
|
| 1202 |
+
|
| 1203 |
+
grid = _GrowableGrid(total_width, total_height)
|
| 1204 |
+
start_j = 0
|
| 1205 |
+
for g in grids:
|
| 1206 |
+
for i in range(g.height):
|
| 1207 |
+
for j in range(g.width):
|
| 1208 |
+
grid[i, start_j + j] = g[i, j]
|
| 1209 |
+
|
| 1210 |
+
start_j += g.width
|
| 1211 |
+
|
| 1212 |
+
self._grid = grid
|
| 1213 |
+
elif "layout" in hints:
|
| 1214 |
+
if hints["layout"] == "sequential":
|
| 1215 |
+
self._grid = DiagramGrid._sequential_layout(
|
| 1216 |
+
diagram, merged_morphisms)
|
| 1217 |
+
else:
|
| 1218 |
+
self._grid = DiagramGrid._generic_layout(diagram, merged_morphisms)
|
| 1219 |
+
|
| 1220 |
+
if hints.get("transpose"):
|
| 1221 |
+
# Transpose the resulting grid.
|
| 1222 |
+
grid = _GrowableGrid(self._grid.height, self._grid.width)
|
| 1223 |
+
for i in range(self._grid.height):
|
| 1224 |
+
for j in range(self._grid.width):
|
| 1225 |
+
grid[j, i] = self._grid[i, j]
|
| 1226 |
+
self._grid = grid
|
| 1227 |
+
|
| 1228 |
+
@property
|
| 1229 |
+
def width(self):
|
| 1230 |
+
"""
|
| 1231 |
+
Returns the number of columns in this diagram layout.
|
| 1232 |
+
|
| 1233 |
+
Examples
|
| 1234 |
+
========
|
| 1235 |
+
|
| 1236 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 1237 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 1238 |
+
>>> A = Object("A")
|
| 1239 |
+
>>> B = Object("B")
|
| 1240 |
+
>>> C = Object("C")
|
| 1241 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1242 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1243 |
+
>>> diagram = Diagram([f, g])
|
| 1244 |
+
>>> grid = DiagramGrid(diagram)
|
| 1245 |
+
>>> grid.width
|
| 1246 |
+
2
|
| 1247 |
+
|
| 1248 |
+
"""
|
| 1249 |
+
return self._grid.width
|
| 1250 |
+
|
| 1251 |
+
@property
|
| 1252 |
+
def height(self):
|
| 1253 |
+
"""
|
| 1254 |
+
Returns the number of rows in this diagram layout.
|
| 1255 |
+
|
| 1256 |
+
Examples
|
| 1257 |
+
========
|
| 1258 |
+
|
| 1259 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 1260 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 1261 |
+
>>> A = Object("A")
|
| 1262 |
+
>>> B = Object("B")
|
| 1263 |
+
>>> C = Object("C")
|
| 1264 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1265 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1266 |
+
>>> diagram = Diagram([f, g])
|
| 1267 |
+
>>> grid = DiagramGrid(diagram)
|
| 1268 |
+
>>> grid.height
|
| 1269 |
+
2
|
| 1270 |
+
|
| 1271 |
+
"""
|
| 1272 |
+
return self._grid.height
|
| 1273 |
+
|
| 1274 |
+
def __getitem__(self, i_j):
|
| 1275 |
+
"""
|
| 1276 |
+
Returns the object placed in the row ``i`` and column ``j``.
|
| 1277 |
+
The indices are 0-based.
|
| 1278 |
+
|
| 1279 |
+
Examples
|
| 1280 |
+
========
|
| 1281 |
+
|
| 1282 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 1283 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 1284 |
+
>>> A = Object("A")
|
| 1285 |
+
>>> B = Object("B")
|
| 1286 |
+
>>> C = Object("C")
|
| 1287 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1288 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1289 |
+
>>> diagram = Diagram([f, g])
|
| 1290 |
+
>>> grid = DiagramGrid(diagram)
|
| 1291 |
+
>>> (grid[0, 0], grid[0, 1])
|
| 1292 |
+
(Object("A"), Object("B"))
|
| 1293 |
+
>>> (grid[1, 0], grid[1, 1])
|
| 1294 |
+
(None, Object("C"))
|
| 1295 |
+
|
| 1296 |
+
"""
|
| 1297 |
+
i, j = i_j
|
| 1298 |
+
return self._grid[i, j]
|
| 1299 |
+
|
| 1300 |
+
@property
|
| 1301 |
+
def morphisms(self):
|
| 1302 |
+
"""
|
| 1303 |
+
Returns those morphisms (and their properties) which are
|
| 1304 |
+
sufficiently meaningful to be drawn.
|
| 1305 |
+
|
| 1306 |
+
Examples
|
| 1307 |
+
========
|
| 1308 |
+
|
| 1309 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 1310 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 1311 |
+
>>> A = Object("A")
|
| 1312 |
+
>>> B = Object("B")
|
| 1313 |
+
>>> C = Object("C")
|
| 1314 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1315 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1316 |
+
>>> diagram = Diagram([f, g])
|
| 1317 |
+
>>> grid = DiagramGrid(diagram)
|
| 1318 |
+
>>> grid.morphisms
|
| 1319 |
+
{NamedMorphism(Object("A"), Object("B"), "f"): EmptySet,
|
| 1320 |
+
NamedMorphism(Object("B"), Object("C"), "g"): EmptySet}
|
| 1321 |
+
|
| 1322 |
+
"""
|
| 1323 |
+
return self._morphisms
|
| 1324 |
+
|
| 1325 |
+
def __str__(self):
|
| 1326 |
+
"""
|
| 1327 |
+
Produces a string representation of this class.
|
| 1328 |
+
|
| 1329 |
+
This method returns a string representation of the underlying
|
| 1330 |
+
list of lists of objects.
|
| 1331 |
+
|
| 1332 |
+
Examples
|
| 1333 |
+
========
|
| 1334 |
+
|
| 1335 |
+
>>> from sympy.categories import Object, NamedMorphism
|
| 1336 |
+
>>> from sympy.categories import Diagram, DiagramGrid
|
| 1337 |
+
>>> A = Object("A")
|
| 1338 |
+
>>> B = Object("B")
|
| 1339 |
+
>>> C = Object("C")
|
| 1340 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1341 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1342 |
+
>>> diagram = Diagram([f, g])
|
| 1343 |
+
>>> grid = DiagramGrid(diagram)
|
| 1344 |
+
>>> print(grid)
|
| 1345 |
+
[[Object("A"), Object("B")],
|
| 1346 |
+
[None, Object("C")]]
|
| 1347 |
+
|
| 1348 |
+
"""
|
| 1349 |
+
return repr(self._grid._array)
|
| 1350 |
+
|
| 1351 |
+
|
| 1352 |
+
class ArrowStringDescription:
|
| 1353 |
+
r"""
|
| 1354 |
+
Stores the information necessary for producing an Xy-pic
|
| 1355 |
+
description of an arrow.
|
| 1356 |
+
|
| 1357 |
+
The principal goal of this class is to abstract away the string
|
| 1358 |
+
representation of an arrow and to also provide the functionality
|
| 1359 |
+
to produce the actual Xy-pic string.
|
| 1360 |
+
|
| 1361 |
+
``unit`` sets the unit which will be used to specify the amount of
|
| 1362 |
+
curving and other distances. ``horizontal_direction`` should be a
|
| 1363 |
+
string of ``"r"`` or ``"l"`` specifying the horizontal offset of the
|
| 1364 |
+
target cell of the arrow relatively to the current one.
|
| 1365 |
+
``vertical_direction`` should specify the vertical offset using a
|
| 1366 |
+
series of either ``"d"`` or ``"u"``. ``label_position`` should be
|
| 1367 |
+
either ``"^"``, ``"_"``, or ``"|"`` to specify that the label should
|
| 1368 |
+
be positioned above the arrow, below the arrow or just over the arrow,
|
| 1369 |
+
in a break. Note that the notions "above" and "below" are relative
|
| 1370 |
+
to arrow direction. ``label`` stores the morphism label.
|
| 1371 |
+
|
| 1372 |
+
This works as follows (disregard the yet unexplained arguments):
|
| 1373 |
+
|
| 1374 |
+
>>> from sympy.categories.diagram_drawing import ArrowStringDescription
|
| 1375 |
+
>>> astr = ArrowStringDescription(
|
| 1376 |
+
... unit="mm", curving=None, curving_amount=None,
|
| 1377 |
+
... looping_start=None, looping_end=None, horizontal_direction="d",
|
| 1378 |
+
... vertical_direction="r", label_position="_", label="f")
|
| 1379 |
+
>>> print(str(astr))
|
| 1380 |
+
\ar[dr]_{f}
|
| 1381 |
+
|
| 1382 |
+
``curving`` should be one of ``"^"``, ``"_"`` to specify in which
|
| 1383 |
+
direction the arrow is going to curve. ``curving_amount`` is a number
|
| 1384 |
+
describing how many ``unit``'s the morphism is going to curve:
|
| 1385 |
+
|
| 1386 |
+
>>> astr = ArrowStringDescription(
|
| 1387 |
+
... unit="mm", curving="^", curving_amount=12,
|
| 1388 |
+
... looping_start=None, looping_end=None, horizontal_direction="d",
|
| 1389 |
+
... vertical_direction="r", label_position="_", label="f")
|
| 1390 |
+
>>> print(str(astr))
|
| 1391 |
+
\ar@/^12mm/[dr]_{f}
|
| 1392 |
+
|
| 1393 |
+
``looping_start`` and ``looping_end`` are currently only used for
|
| 1394 |
+
loop morphisms, those which have the same domain and codomain.
|
| 1395 |
+
These two attributes should store a valid Xy-pic direction and
|
| 1396 |
+
specify, correspondingly, the direction the arrow gets out into
|
| 1397 |
+
and the direction the arrow gets back from:
|
| 1398 |
+
|
| 1399 |
+
>>> astr = ArrowStringDescription(
|
| 1400 |
+
... unit="mm", curving=None, curving_amount=None,
|
| 1401 |
+
... looping_start="u", looping_end="l", horizontal_direction="",
|
| 1402 |
+
... vertical_direction="", label_position="_", label="f")
|
| 1403 |
+
>>> print(str(astr))
|
| 1404 |
+
\ar@(u,l)[]_{f}
|
| 1405 |
+
|
| 1406 |
+
``label_displacement`` controls how far the arrow label is from
|
| 1407 |
+
the ends of the arrow. For example, to position the arrow label
|
| 1408 |
+
near the arrow head, use ">":
|
| 1409 |
+
|
| 1410 |
+
>>> astr = ArrowStringDescription(
|
| 1411 |
+
... unit="mm", curving="^", curving_amount=12,
|
| 1412 |
+
... looping_start=None, looping_end=None, horizontal_direction="d",
|
| 1413 |
+
... vertical_direction="r", label_position="_", label="f")
|
| 1414 |
+
>>> astr.label_displacement = ">"
|
| 1415 |
+
>>> print(str(astr))
|
| 1416 |
+
\ar@/^12mm/[dr]_>{f}
|
| 1417 |
+
|
| 1418 |
+
Finally, ``arrow_style`` is used to specify the arrow style. To
|
| 1419 |
+
get a dashed arrow, for example, use "{-->}" as arrow style:
|
| 1420 |
+
|
| 1421 |
+
>>> astr = ArrowStringDescription(
|
| 1422 |
+
... unit="mm", curving="^", curving_amount=12,
|
| 1423 |
+
... looping_start=None, looping_end=None, horizontal_direction="d",
|
| 1424 |
+
... vertical_direction="r", label_position="_", label="f")
|
| 1425 |
+
>>> astr.arrow_style = "{-->}"
|
| 1426 |
+
>>> print(str(astr))
|
| 1427 |
+
\ar@/^12mm/@{-->}[dr]_{f}
|
| 1428 |
+
|
| 1429 |
+
Notes
|
| 1430 |
+
=====
|
| 1431 |
+
|
| 1432 |
+
Instances of :class:`ArrowStringDescription` will be constructed
|
| 1433 |
+
by :class:`XypicDiagramDrawer` and provided for further use in
|
| 1434 |
+
formatters. The user is not expected to construct instances of
|
| 1435 |
+
:class:`ArrowStringDescription` themselves.
|
| 1436 |
+
|
| 1437 |
+
To be able to properly utilise this class, the reader is encouraged
|
| 1438 |
+
to checkout the Xy-pic user guide, available at [Xypic].
|
| 1439 |
+
|
| 1440 |
+
See Also
|
| 1441 |
+
========
|
| 1442 |
+
|
| 1443 |
+
XypicDiagramDrawer
|
| 1444 |
+
|
| 1445 |
+
References
|
| 1446 |
+
==========
|
| 1447 |
+
|
| 1448 |
+
.. [Xypic] https://xy-pic.sourceforge.net/
|
| 1449 |
+
"""
|
| 1450 |
+
def __init__(self, unit, curving, curving_amount, looping_start,
|
| 1451 |
+
looping_end, horizontal_direction, vertical_direction,
|
| 1452 |
+
label_position, label):
|
| 1453 |
+
self.unit = unit
|
| 1454 |
+
self.curving = curving
|
| 1455 |
+
self.curving_amount = curving_amount
|
| 1456 |
+
self.looping_start = looping_start
|
| 1457 |
+
self.looping_end = looping_end
|
| 1458 |
+
self.horizontal_direction = horizontal_direction
|
| 1459 |
+
self.vertical_direction = vertical_direction
|
| 1460 |
+
self.label_position = label_position
|
| 1461 |
+
self.label = label
|
| 1462 |
+
|
| 1463 |
+
self.label_displacement = ""
|
| 1464 |
+
self.arrow_style = ""
|
| 1465 |
+
|
| 1466 |
+
# This flag shows that the position of the label of this
|
| 1467 |
+
# morphism was set while typesetting a curved morphism and
|
| 1468 |
+
# should not be modified later.
|
| 1469 |
+
self.forced_label_position = False
|
| 1470 |
+
|
| 1471 |
+
def __str__(self):
|
| 1472 |
+
if self.curving:
|
| 1473 |
+
curving_str = "@/%s%d%s/" % (self.curving, self.curving_amount,
|
| 1474 |
+
self.unit)
|
| 1475 |
+
else:
|
| 1476 |
+
curving_str = ""
|
| 1477 |
+
|
| 1478 |
+
if self.looping_start and self.looping_end:
|
| 1479 |
+
looping_str = "@(%s,%s)" % (self.looping_start, self.looping_end)
|
| 1480 |
+
else:
|
| 1481 |
+
looping_str = ""
|
| 1482 |
+
|
| 1483 |
+
if self.arrow_style:
|
| 1484 |
+
|
| 1485 |
+
style_str = "@" + self.arrow_style
|
| 1486 |
+
else:
|
| 1487 |
+
style_str = ""
|
| 1488 |
+
|
| 1489 |
+
return "\\ar%s%s%s[%s%s]%s%s{%s}" % \
|
| 1490 |
+
(curving_str, looping_str, style_str, self.horizontal_direction,
|
| 1491 |
+
self.vertical_direction, self.label_position,
|
| 1492 |
+
self.label_displacement, self.label)
|
| 1493 |
+
|
| 1494 |
+
|
| 1495 |
+
class XypicDiagramDrawer:
|
| 1496 |
+
r"""
|
| 1497 |
+
Given a :class:`~.Diagram` and the corresponding
|
| 1498 |
+
:class:`DiagramGrid`, produces the Xy-pic representation of the
|
| 1499 |
+
diagram.
|
| 1500 |
+
|
| 1501 |
+
The most important method in this class is ``draw``. Consider the
|
| 1502 |
+
following triangle diagram:
|
| 1503 |
+
|
| 1504 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 1505 |
+
>>> from sympy.categories import DiagramGrid, XypicDiagramDrawer
|
| 1506 |
+
>>> A = Object("A")
|
| 1507 |
+
>>> B = Object("B")
|
| 1508 |
+
>>> C = Object("C")
|
| 1509 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 1510 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 1511 |
+
>>> diagram = Diagram([f, g], {g * f: "unique"})
|
| 1512 |
+
|
| 1513 |
+
To draw this diagram, its objects need to be laid out with a
|
| 1514 |
+
:class:`DiagramGrid`::
|
| 1515 |
+
|
| 1516 |
+
>>> grid = DiagramGrid(diagram)
|
| 1517 |
+
|
| 1518 |
+
Finally, the drawing:
|
| 1519 |
+
|
| 1520 |
+
>>> drawer = XypicDiagramDrawer()
|
| 1521 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1522 |
+
\xymatrix{
|
| 1523 |
+
A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 1524 |
+
C &
|
| 1525 |
+
}
|
| 1526 |
+
|
| 1527 |
+
For further details see the docstring of this method.
|
| 1528 |
+
|
| 1529 |
+
To control the appearance of the arrows, formatters are used. The
|
| 1530 |
+
dictionary ``arrow_formatters`` maps morphisms to formatter
|
| 1531 |
+
functions. A formatter is accepts an
|
| 1532 |
+
:class:`ArrowStringDescription` and is allowed to modify any of
|
| 1533 |
+
the arrow properties exposed thereby. For example, to have all
|
| 1534 |
+
morphisms with the property ``unique`` appear as dashed arrows,
|
| 1535 |
+
and to have their names prepended with `\exists !`, the following
|
| 1536 |
+
should be done:
|
| 1537 |
+
|
| 1538 |
+
>>> def formatter(astr):
|
| 1539 |
+
... astr.label = r"\exists !" + astr.label
|
| 1540 |
+
... astr.arrow_style = "{-->}"
|
| 1541 |
+
>>> drawer.arrow_formatters["unique"] = formatter
|
| 1542 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1543 |
+
\xymatrix{
|
| 1544 |
+
A \ar@{-->}[d]_{\exists !g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 1545 |
+
C &
|
| 1546 |
+
}
|
| 1547 |
+
|
| 1548 |
+
To modify the appearance of all arrows in the diagram, set
|
| 1549 |
+
``default_arrow_formatter``. For example, to place all morphism
|
| 1550 |
+
labels a little bit farther from the arrow head so that they look
|
| 1551 |
+
more centred, do as follows:
|
| 1552 |
+
|
| 1553 |
+
>>> def default_formatter(astr):
|
| 1554 |
+
... astr.label_displacement = "(0.45)"
|
| 1555 |
+
>>> drawer.default_arrow_formatter = default_formatter
|
| 1556 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1557 |
+
\xymatrix{
|
| 1558 |
+
A \ar@{-->}[d]_(0.45){\exists !g\circ f} \ar[r]^(0.45){f} & B \ar[ld]^(0.45){g} \\
|
| 1559 |
+
C &
|
| 1560 |
+
}
|
| 1561 |
+
|
| 1562 |
+
In some diagrams some morphisms are drawn as curved arrows.
|
| 1563 |
+
Consider the following diagram:
|
| 1564 |
+
|
| 1565 |
+
>>> D = Object("D")
|
| 1566 |
+
>>> E = Object("E")
|
| 1567 |
+
>>> h = NamedMorphism(D, A, "h")
|
| 1568 |
+
>>> k = NamedMorphism(D, B, "k")
|
| 1569 |
+
>>> diagram = Diagram([f, g, h, k])
|
| 1570 |
+
>>> grid = DiagramGrid(diagram)
|
| 1571 |
+
>>> drawer = XypicDiagramDrawer()
|
| 1572 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1573 |
+
\xymatrix{
|
| 1574 |
+
A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_3mm/[ll]_{h} \\
|
| 1575 |
+
& C &
|
| 1576 |
+
}
|
| 1577 |
+
|
| 1578 |
+
To control how far the morphisms are curved by default, one can
|
| 1579 |
+
use the ``unit`` and ``default_curving_amount`` attributes:
|
| 1580 |
+
|
| 1581 |
+
>>> drawer.unit = "cm"
|
| 1582 |
+
>>> drawer.default_curving_amount = 1
|
| 1583 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1584 |
+
\xymatrix{
|
| 1585 |
+
A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_1cm/[ll]_{h} \\
|
| 1586 |
+
& C &
|
| 1587 |
+
}
|
| 1588 |
+
|
| 1589 |
+
In some diagrams, there are multiple curved morphisms between the
|
| 1590 |
+
same two objects. To control by how much the curving changes
|
| 1591 |
+
between two such successive morphisms, use
|
| 1592 |
+
``default_curving_step``:
|
| 1593 |
+
|
| 1594 |
+
>>> drawer.default_curving_step = 1
|
| 1595 |
+
>>> h1 = NamedMorphism(A, D, "h1")
|
| 1596 |
+
>>> diagram = Diagram([f, g, h, k, h1])
|
| 1597 |
+
>>> grid = DiagramGrid(diagram)
|
| 1598 |
+
>>> print(drawer.draw(diagram, grid))
|
| 1599 |
+
\xymatrix{
|
| 1600 |
+
A \ar[r]_{f} \ar@/^1cm/[rr]^{h_{1}} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_2cm/[ll]_{h} \\
|
| 1601 |
+
& C &
|
| 1602 |
+
}
|
| 1603 |
+
|
| 1604 |
+
The default value of ``default_curving_step`` is 4 units.
|
| 1605 |
+
|
| 1606 |
+
See Also
|
| 1607 |
+
========
|
| 1608 |
+
|
| 1609 |
+
draw, ArrowStringDescription
|
| 1610 |
+
"""
|
| 1611 |
+
def __init__(self):
|
| 1612 |
+
self.unit = "mm"
|
| 1613 |
+
self.default_curving_amount = 3
|
| 1614 |
+
self.default_curving_step = 4
|
| 1615 |
+
|
| 1616 |
+
# This dictionary maps properties to the corresponding arrow
|
| 1617 |
+
# formatters.
|
| 1618 |
+
self.arrow_formatters = {}
|
| 1619 |
+
|
| 1620 |
+
# This is the default arrow formatter which will be applied to
|
| 1621 |
+
# each arrow independently of its properties.
|
| 1622 |
+
self.default_arrow_formatter = None
|
| 1623 |
+
|
| 1624 |
+
@staticmethod
|
| 1625 |
+
def _process_loop_morphism(i, j, grid, morphisms_str_info, object_coords):
|
| 1626 |
+
"""
|
| 1627 |
+
Produces the information required for constructing the string
|
| 1628 |
+
representation of a loop morphism. This function is invoked
|
| 1629 |
+
from ``_process_morphism``.
|
| 1630 |
+
|
| 1631 |
+
See Also
|
| 1632 |
+
========
|
| 1633 |
+
|
| 1634 |
+
_process_morphism
|
| 1635 |
+
"""
|
| 1636 |
+
curving = ""
|
| 1637 |
+
label_pos = "^"
|
| 1638 |
+
looping_start = ""
|
| 1639 |
+
looping_end = ""
|
| 1640 |
+
|
| 1641 |
+
# This is a loop morphism. Count how many morphisms stick
|
| 1642 |
+
# in each of the four quadrants. Note that straight
|
| 1643 |
+
# vertical and horizontal morphisms count in two quadrants
|
| 1644 |
+
# at the same time (i.e., a morphism going up counts both
|
| 1645 |
+
# in the first and the second quadrants).
|
| 1646 |
+
|
| 1647 |
+
# The usual numbering (counterclockwise) of quadrants
|
| 1648 |
+
# applies.
|
| 1649 |
+
quadrant = [0, 0, 0, 0]
|
| 1650 |
+
|
| 1651 |
+
obj = grid[i, j]
|
| 1652 |
+
|
| 1653 |
+
for m, m_str_info in morphisms_str_info.items():
|
| 1654 |
+
if (m.domain == obj) and (m.codomain == obj):
|
| 1655 |
+
# That's another loop morphism. Check how it
|
| 1656 |
+
# loops and mark the corresponding quadrants as
|
| 1657 |
+
# busy.
|
| 1658 |
+
(l_s, l_e) = (m_str_info.looping_start, m_str_info.looping_end)
|
| 1659 |
+
|
| 1660 |
+
if (l_s, l_e) == ("r", "u"):
|
| 1661 |
+
quadrant[0] += 1
|
| 1662 |
+
elif (l_s, l_e) == ("u", "l"):
|
| 1663 |
+
quadrant[1] += 1
|
| 1664 |
+
elif (l_s, l_e) == ("l", "d"):
|
| 1665 |
+
quadrant[2] += 1
|
| 1666 |
+
elif (l_s, l_e) == ("d", "r"):
|
| 1667 |
+
quadrant[3] += 1
|
| 1668 |
+
|
| 1669 |
+
continue
|
| 1670 |
+
if m.domain == obj:
|
| 1671 |
+
(end_i, end_j) = object_coords[m.codomain]
|
| 1672 |
+
goes_out = True
|
| 1673 |
+
elif m.codomain == obj:
|
| 1674 |
+
(end_i, end_j) = object_coords[m.domain]
|
| 1675 |
+
goes_out = False
|
| 1676 |
+
else:
|
| 1677 |
+
continue
|
| 1678 |
+
|
| 1679 |
+
d_i = end_i - i
|
| 1680 |
+
d_j = end_j - j
|
| 1681 |
+
m_curving = m_str_info.curving
|
| 1682 |
+
|
| 1683 |
+
if (d_i != 0) and (d_j != 0):
|
| 1684 |
+
# This is really a diagonal morphism. Detect the
|
| 1685 |
+
# quadrant.
|
| 1686 |
+
if (d_i > 0) and (d_j > 0):
|
| 1687 |
+
quadrant[0] += 1
|
| 1688 |
+
elif (d_i > 0) and (d_j < 0):
|
| 1689 |
+
quadrant[1] += 1
|
| 1690 |
+
elif (d_i < 0) and (d_j < 0):
|
| 1691 |
+
quadrant[2] += 1
|
| 1692 |
+
elif (d_i < 0) and (d_j > 0):
|
| 1693 |
+
quadrant[3] += 1
|
| 1694 |
+
elif d_i == 0:
|
| 1695 |
+
# Knowing where the other end of the morphism is
|
| 1696 |
+
# and which way it goes, we now have to decide
|
| 1697 |
+
# which quadrant is now the upper one and which is
|
| 1698 |
+
# the lower one.
|
| 1699 |
+
if d_j > 0:
|
| 1700 |
+
if goes_out:
|
| 1701 |
+
upper_quadrant = 0
|
| 1702 |
+
lower_quadrant = 3
|
| 1703 |
+
else:
|
| 1704 |
+
upper_quadrant = 3
|
| 1705 |
+
lower_quadrant = 0
|
| 1706 |
+
else:
|
| 1707 |
+
if goes_out:
|
| 1708 |
+
upper_quadrant = 2
|
| 1709 |
+
lower_quadrant = 1
|
| 1710 |
+
else:
|
| 1711 |
+
upper_quadrant = 1
|
| 1712 |
+
lower_quadrant = 2
|
| 1713 |
+
|
| 1714 |
+
if m_curving:
|
| 1715 |
+
if m_curving == "^":
|
| 1716 |
+
quadrant[upper_quadrant] += 1
|
| 1717 |
+
elif m_curving == "_":
|
| 1718 |
+
quadrant[lower_quadrant] += 1
|
| 1719 |
+
else:
|
| 1720 |
+
# This morphism counts in both upper and lower
|
| 1721 |
+
# quadrants.
|
| 1722 |
+
quadrant[upper_quadrant] += 1
|
| 1723 |
+
quadrant[lower_quadrant] += 1
|
| 1724 |
+
elif d_j == 0:
|
| 1725 |
+
# Knowing where the other end of the morphism is
|
| 1726 |
+
# and which way it goes, we now have to decide
|
| 1727 |
+
# which quadrant is now the left one and which is
|
| 1728 |
+
# the right one.
|
| 1729 |
+
if d_i < 0:
|
| 1730 |
+
if goes_out:
|
| 1731 |
+
left_quadrant = 1
|
| 1732 |
+
right_quadrant = 0
|
| 1733 |
+
else:
|
| 1734 |
+
left_quadrant = 0
|
| 1735 |
+
right_quadrant = 1
|
| 1736 |
+
else:
|
| 1737 |
+
if goes_out:
|
| 1738 |
+
left_quadrant = 3
|
| 1739 |
+
right_quadrant = 2
|
| 1740 |
+
else:
|
| 1741 |
+
left_quadrant = 2
|
| 1742 |
+
right_quadrant = 3
|
| 1743 |
+
|
| 1744 |
+
if m_curving:
|
| 1745 |
+
if m_curving == "^":
|
| 1746 |
+
quadrant[left_quadrant] += 1
|
| 1747 |
+
elif m_curving == "_":
|
| 1748 |
+
quadrant[right_quadrant] += 1
|
| 1749 |
+
else:
|
| 1750 |
+
# This morphism counts in both upper and lower
|
| 1751 |
+
# quadrants.
|
| 1752 |
+
quadrant[left_quadrant] += 1
|
| 1753 |
+
quadrant[right_quadrant] += 1
|
| 1754 |
+
|
| 1755 |
+
# Pick the freest quadrant to curve our morphism into.
|
| 1756 |
+
freest_quadrant = 0
|
| 1757 |
+
for i in range(4):
|
| 1758 |
+
if quadrant[i] < quadrant[freest_quadrant]:
|
| 1759 |
+
freest_quadrant = i
|
| 1760 |
+
|
| 1761 |
+
# Now set up proper looping.
|
| 1762 |
+
(looping_start, looping_end) = [("r", "u"), ("u", "l"), ("l", "d"),
|
| 1763 |
+
("d", "r")][freest_quadrant]
|
| 1764 |
+
|
| 1765 |
+
return (curving, label_pos, looping_start, looping_end)
|
| 1766 |
+
|
| 1767 |
+
@staticmethod
|
| 1768 |
+
def _process_horizontal_morphism(i, j, target_j, grid, morphisms_str_info,
|
| 1769 |
+
object_coords):
|
| 1770 |
+
"""
|
| 1771 |
+
Produces the information required for constructing the string
|
| 1772 |
+
representation of a horizontal morphism. This function is
|
| 1773 |
+
invoked from ``_process_morphism``.
|
| 1774 |
+
|
| 1775 |
+
See Also
|
| 1776 |
+
========
|
| 1777 |
+
|
| 1778 |
+
_process_morphism
|
| 1779 |
+
"""
|
| 1780 |
+
# The arrow is horizontal. Check if it goes from left to
|
| 1781 |
+
# right (``backwards == False``) or from right to left
|
| 1782 |
+
# (``backwards == True``).
|
| 1783 |
+
backwards = False
|
| 1784 |
+
start = j
|
| 1785 |
+
end = target_j
|
| 1786 |
+
if end < start:
|
| 1787 |
+
(start, end) = (end, start)
|
| 1788 |
+
backwards = True
|
| 1789 |
+
|
| 1790 |
+
# Let's see which objects are there between ``start`` and
|
| 1791 |
+
# ``end``, and then count how many morphisms stick out
|
| 1792 |
+
# upwards, and how many stick out downwards.
|
| 1793 |
+
#
|
| 1794 |
+
# For example, consider the situation:
|
| 1795 |
+
#
|
| 1796 |
+
# B1 C1
|
| 1797 |
+
# | |
|
| 1798 |
+
# A--B--C--D
|
| 1799 |
+
# |
|
| 1800 |
+
# B2
|
| 1801 |
+
#
|
| 1802 |
+
# Between the objects `A` and `D` there are two objects:
|
| 1803 |
+
# `B` and `C`. Further, there are two morphisms which
|
| 1804 |
+
# stick out upward (the ones between `B1` and `B` and
|
| 1805 |
+
# between `C` and `C1`) and one morphism which sticks out
|
| 1806 |
+
# downward (the one between `B and `B2`).
|
| 1807 |
+
#
|
| 1808 |
+
# We need this information to decide how to curve the
|
| 1809 |
+
# arrow between `A` and `D`. First of all, since there
|
| 1810 |
+
# are two objects between `A` and `D``, we must curve the
|
| 1811 |
+
# arrow. Then, we will have it curve downward, because
|
| 1812 |
+
# there is more space (less morphisms stick out downward
|
| 1813 |
+
# than upward).
|
| 1814 |
+
up = []
|
| 1815 |
+
down = []
|
| 1816 |
+
straight_horizontal = []
|
| 1817 |
+
for k in range(start + 1, end):
|
| 1818 |
+
obj = grid[i, k]
|
| 1819 |
+
if not obj:
|
| 1820 |
+
continue
|
| 1821 |
+
|
| 1822 |
+
for m in morphisms_str_info:
|
| 1823 |
+
if m.domain == obj:
|
| 1824 |
+
(end_i, end_j) = object_coords[m.codomain]
|
| 1825 |
+
elif m.codomain == obj:
|
| 1826 |
+
(end_i, end_j) = object_coords[m.domain]
|
| 1827 |
+
else:
|
| 1828 |
+
continue
|
| 1829 |
+
|
| 1830 |
+
if end_i > i:
|
| 1831 |
+
down.append(m)
|
| 1832 |
+
elif end_i < i:
|
| 1833 |
+
up.append(m)
|
| 1834 |
+
elif not morphisms_str_info[m].curving:
|
| 1835 |
+
# This is a straight horizontal morphism,
|
| 1836 |
+
# because it has no curving.
|
| 1837 |
+
straight_horizontal.append(m)
|
| 1838 |
+
|
| 1839 |
+
if len(up) < len(down):
|
| 1840 |
+
# More morphisms stick out downward than upward, let's
|
| 1841 |
+
# curve the morphism up.
|
| 1842 |
+
if backwards:
|
| 1843 |
+
curving = "_"
|
| 1844 |
+
label_pos = "_"
|
| 1845 |
+
else:
|
| 1846 |
+
curving = "^"
|
| 1847 |
+
label_pos = "^"
|
| 1848 |
+
|
| 1849 |
+
# Assure that the straight horizontal morphisms have
|
| 1850 |
+
# their labels on the lower side of the arrow.
|
| 1851 |
+
for m in straight_horizontal:
|
| 1852 |
+
(i1, j1) = object_coords[m.domain]
|
| 1853 |
+
(i2, j2) = object_coords[m.codomain]
|
| 1854 |
+
|
| 1855 |
+
m_str_info = morphisms_str_info[m]
|
| 1856 |
+
if j1 < j2:
|
| 1857 |
+
m_str_info.label_position = "_"
|
| 1858 |
+
else:
|
| 1859 |
+
m_str_info.label_position = "^"
|
| 1860 |
+
|
| 1861 |
+
# Don't allow any further modifications of the
|
| 1862 |
+
# position of this label.
|
| 1863 |
+
m_str_info.forced_label_position = True
|
| 1864 |
+
else:
|
| 1865 |
+
# More morphisms stick out downward than upward, let's
|
| 1866 |
+
# curve the morphism up.
|
| 1867 |
+
if backwards:
|
| 1868 |
+
curving = "^"
|
| 1869 |
+
label_pos = "^"
|
| 1870 |
+
else:
|
| 1871 |
+
curving = "_"
|
| 1872 |
+
label_pos = "_"
|
| 1873 |
+
|
| 1874 |
+
# Assure that the straight horizontal morphisms have
|
| 1875 |
+
# their labels on the upper side of the arrow.
|
| 1876 |
+
for m in straight_horizontal:
|
| 1877 |
+
(i1, j1) = object_coords[m.domain]
|
| 1878 |
+
(i2, j2) = object_coords[m.codomain]
|
| 1879 |
+
|
| 1880 |
+
m_str_info = morphisms_str_info[m]
|
| 1881 |
+
if j1 < j2:
|
| 1882 |
+
m_str_info.label_position = "^"
|
| 1883 |
+
else:
|
| 1884 |
+
m_str_info.label_position = "_"
|
| 1885 |
+
|
| 1886 |
+
# Don't allow any further modifications of the
|
| 1887 |
+
# position of this label.
|
| 1888 |
+
m_str_info.forced_label_position = True
|
| 1889 |
+
|
| 1890 |
+
return (curving, label_pos)
|
| 1891 |
+
|
| 1892 |
+
@staticmethod
|
| 1893 |
+
def _process_vertical_morphism(i, j, target_i, grid, morphisms_str_info,
|
| 1894 |
+
object_coords):
|
| 1895 |
+
"""
|
| 1896 |
+
Produces the information required for constructing the string
|
| 1897 |
+
representation of a vertical morphism. This function is
|
| 1898 |
+
invoked from ``_process_morphism``.
|
| 1899 |
+
|
| 1900 |
+
See Also
|
| 1901 |
+
========
|
| 1902 |
+
|
| 1903 |
+
_process_morphism
|
| 1904 |
+
"""
|
| 1905 |
+
# This arrow is vertical. Check if it goes from top to
|
| 1906 |
+
# bottom (``backwards == False``) or from bottom to top
|
| 1907 |
+
# (``backwards == True``).
|
| 1908 |
+
backwards = False
|
| 1909 |
+
start = i
|
| 1910 |
+
end = target_i
|
| 1911 |
+
if end < start:
|
| 1912 |
+
(start, end) = (end, start)
|
| 1913 |
+
backwards = True
|
| 1914 |
+
|
| 1915 |
+
# Let's see which objects are there between ``start`` and
|
| 1916 |
+
# ``end``, and then count how many morphisms stick out to
|
| 1917 |
+
# the left, and how many stick out to the right.
|
| 1918 |
+
#
|
| 1919 |
+
# See the corresponding comment in the previous branch of
|
| 1920 |
+
# this if-statement for more details.
|
| 1921 |
+
left = []
|
| 1922 |
+
right = []
|
| 1923 |
+
straight_vertical = []
|
| 1924 |
+
for k in range(start + 1, end):
|
| 1925 |
+
obj = grid[k, j]
|
| 1926 |
+
if not obj:
|
| 1927 |
+
continue
|
| 1928 |
+
|
| 1929 |
+
for m in morphisms_str_info:
|
| 1930 |
+
if m.domain == obj:
|
| 1931 |
+
(end_i, end_j) = object_coords[m.codomain]
|
| 1932 |
+
elif m.codomain == obj:
|
| 1933 |
+
(end_i, end_j) = object_coords[m.domain]
|
| 1934 |
+
else:
|
| 1935 |
+
continue
|
| 1936 |
+
|
| 1937 |
+
if end_j > j:
|
| 1938 |
+
right.append(m)
|
| 1939 |
+
elif end_j < j:
|
| 1940 |
+
left.append(m)
|
| 1941 |
+
elif not morphisms_str_info[m].curving:
|
| 1942 |
+
# This is a straight vertical morphism,
|
| 1943 |
+
# because it has no curving.
|
| 1944 |
+
straight_vertical.append(m)
|
| 1945 |
+
|
| 1946 |
+
if len(left) < len(right):
|
| 1947 |
+
# More morphisms stick out to the left than to the
|
| 1948 |
+
# right, let's curve the morphism to the right.
|
| 1949 |
+
if backwards:
|
| 1950 |
+
curving = "^"
|
| 1951 |
+
label_pos = "^"
|
| 1952 |
+
else:
|
| 1953 |
+
curving = "_"
|
| 1954 |
+
label_pos = "_"
|
| 1955 |
+
|
| 1956 |
+
# Assure that the straight vertical morphisms have
|
| 1957 |
+
# their labels on the left side of the arrow.
|
| 1958 |
+
for m in straight_vertical:
|
| 1959 |
+
(i1, j1) = object_coords[m.domain]
|
| 1960 |
+
(i2, j2) = object_coords[m.codomain]
|
| 1961 |
+
|
| 1962 |
+
m_str_info = morphisms_str_info[m]
|
| 1963 |
+
if i1 < i2:
|
| 1964 |
+
m_str_info.label_position = "^"
|
| 1965 |
+
else:
|
| 1966 |
+
m_str_info.label_position = "_"
|
| 1967 |
+
|
| 1968 |
+
# Don't allow any further modifications of the
|
| 1969 |
+
# position of this label.
|
| 1970 |
+
m_str_info.forced_label_position = True
|
| 1971 |
+
else:
|
| 1972 |
+
# More morphisms stick out to the right than to the
|
| 1973 |
+
# left, let's curve the morphism to the left.
|
| 1974 |
+
if backwards:
|
| 1975 |
+
curving = "_"
|
| 1976 |
+
label_pos = "_"
|
| 1977 |
+
else:
|
| 1978 |
+
curving = "^"
|
| 1979 |
+
label_pos = "^"
|
| 1980 |
+
|
| 1981 |
+
# Assure that the straight vertical morphisms have
|
| 1982 |
+
# their labels on the right side of the arrow.
|
| 1983 |
+
for m in straight_vertical:
|
| 1984 |
+
(i1, j1) = object_coords[m.domain]
|
| 1985 |
+
(i2, j2) = object_coords[m.codomain]
|
| 1986 |
+
|
| 1987 |
+
m_str_info = morphisms_str_info[m]
|
| 1988 |
+
if i1 < i2:
|
| 1989 |
+
m_str_info.label_position = "_"
|
| 1990 |
+
else:
|
| 1991 |
+
m_str_info.label_position = "^"
|
| 1992 |
+
|
| 1993 |
+
# Don't allow any further modifications of the
|
| 1994 |
+
# position of this label.
|
| 1995 |
+
m_str_info.forced_label_position = True
|
| 1996 |
+
|
| 1997 |
+
return (curving, label_pos)
|
| 1998 |
+
|
| 1999 |
+
def _process_morphism(self, diagram, grid, morphism, object_coords,
|
| 2000 |
+
morphisms, morphisms_str_info):
|
| 2001 |
+
"""
|
| 2002 |
+
Given the required information, produces the string
|
| 2003 |
+
representation of ``morphism``.
|
| 2004 |
+
"""
|
| 2005 |
+
def repeat_string_cond(times, str_gt, str_lt):
|
| 2006 |
+
"""
|
| 2007 |
+
If ``times > 0``, repeats ``str_gt`` ``times`` times.
|
| 2008 |
+
Otherwise, repeats ``str_lt`` ``-times`` times.
|
| 2009 |
+
"""
|
| 2010 |
+
if times > 0:
|
| 2011 |
+
return str_gt * times
|
| 2012 |
+
else:
|
| 2013 |
+
return str_lt * (-times)
|
| 2014 |
+
|
| 2015 |
+
def count_morphisms_undirected(A, B):
|
| 2016 |
+
"""
|
| 2017 |
+
Counts how many processed morphisms there are between the
|
| 2018 |
+
two supplied objects.
|
| 2019 |
+
"""
|
| 2020 |
+
return len([m for m in morphisms_str_info
|
| 2021 |
+
if {m.domain, m.codomain} == {A, B}])
|
| 2022 |
+
|
| 2023 |
+
def count_morphisms_filtered(dom, cod, curving):
|
| 2024 |
+
"""
|
| 2025 |
+
Counts the processed morphisms which go out of ``dom``
|
| 2026 |
+
into ``cod`` with curving ``curving``.
|
| 2027 |
+
"""
|
| 2028 |
+
return len([m for m, m_str_info in morphisms_str_info.items()
|
| 2029 |
+
if (m.domain, m.codomain) == (dom, cod) and
|
| 2030 |
+
(m_str_info.curving == curving)])
|
| 2031 |
+
|
| 2032 |
+
(i, j) = object_coords[morphism.domain]
|
| 2033 |
+
(target_i, target_j) = object_coords[morphism.codomain]
|
| 2034 |
+
|
| 2035 |
+
# We now need to determine the direction of
|
| 2036 |
+
# the arrow.
|
| 2037 |
+
delta_i = target_i - i
|
| 2038 |
+
delta_j = target_j - j
|
| 2039 |
+
vertical_direction = repeat_string_cond(delta_i,
|
| 2040 |
+
"d", "u")
|
| 2041 |
+
horizontal_direction = repeat_string_cond(delta_j,
|
| 2042 |
+
"r", "l")
|
| 2043 |
+
|
| 2044 |
+
curving = ""
|
| 2045 |
+
label_pos = "^"
|
| 2046 |
+
looping_start = ""
|
| 2047 |
+
looping_end = ""
|
| 2048 |
+
|
| 2049 |
+
if (delta_i == 0) and (delta_j == 0):
|
| 2050 |
+
# This is a loop morphism.
|
| 2051 |
+
(curving, label_pos, looping_start,
|
| 2052 |
+
looping_end) = XypicDiagramDrawer._process_loop_morphism(
|
| 2053 |
+
i, j, grid, morphisms_str_info, object_coords)
|
| 2054 |
+
elif (delta_i == 0) and (abs(j - target_j) > 1):
|
| 2055 |
+
# This is a horizontal morphism.
|
| 2056 |
+
(curving, label_pos) = XypicDiagramDrawer._process_horizontal_morphism(
|
| 2057 |
+
i, j, target_j, grid, morphisms_str_info, object_coords)
|
| 2058 |
+
elif (delta_j == 0) and (abs(i - target_i) > 1):
|
| 2059 |
+
# This is a vertical morphism.
|
| 2060 |
+
(curving, label_pos) = XypicDiagramDrawer._process_vertical_morphism(
|
| 2061 |
+
i, j, target_i, grid, morphisms_str_info, object_coords)
|
| 2062 |
+
|
| 2063 |
+
count = count_morphisms_undirected(morphism.domain, morphism.codomain)
|
| 2064 |
+
curving_amount = ""
|
| 2065 |
+
if curving:
|
| 2066 |
+
# This morphisms should be curved anyway.
|
| 2067 |
+
curving_amount = self.default_curving_amount + count * \
|
| 2068 |
+
self.default_curving_step
|
| 2069 |
+
elif count:
|
| 2070 |
+
# There are no objects between the domain and codomain of
|
| 2071 |
+
# the current morphism, but this is not there already are
|
| 2072 |
+
# some morphisms with the same domain and codomain, so we
|
| 2073 |
+
# have to curve this one.
|
| 2074 |
+
curving = "^"
|
| 2075 |
+
filtered_morphisms = count_morphisms_filtered(
|
| 2076 |
+
morphism.domain, morphism.codomain, curving)
|
| 2077 |
+
curving_amount = self.default_curving_amount + \
|
| 2078 |
+
filtered_morphisms * \
|
| 2079 |
+
self.default_curving_step
|
| 2080 |
+
|
| 2081 |
+
# Let's now get the name of the morphism.
|
| 2082 |
+
morphism_name = ""
|
| 2083 |
+
if isinstance(morphism, IdentityMorphism):
|
| 2084 |
+
morphism_name = "id_{%s}" + latex(grid[i, j])
|
| 2085 |
+
elif isinstance(morphism, CompositeMorphism):
|
| 2086 |
+
component_names = [latex(Symbol(component.name)) for
|
| 2087 |
+
component in morphism.components]
|
| 2088 |
+
component_names.reverse()
|
| 2089 |
+
morphism_name = "\\circ ".join(component_names)
|
| 2090 |
+
elif isinstance(morphism, NamedMorphism):
|
| 2091 |
+
morphism_name = latex(Symbol(morphism.name))
|
| 2092 |
+
|
| 2093 |
+
return ArrowStringDescription(
|
| 2094 |
+
self.unit, curving, curving_amount, looping_start,
|
| 2095 |
+
looping_end, horizontal_direction, vertical_direction,
|
| 2096 |
+
label_pos, morphism_name)
|
| 2097 |
+
|
| 2098 |
+
@staticmethod
|
| 2099 |
+
def _check_free_space_horizontal(dom_i, dom_j, cod_j, grid):
|
| 2100 |
+
"""
|
| 2101 |
+
For a horizontal morphism, checks whether there is free space
|
| 2102 |
+
(i.e., space not occupied by any objects) above the morphism
|
| 2103 |
+
or below it.
|
| 2104 |
+
"""
|
| 2105 |
+
if dom_j < cod_j:
|
| 2106 |
+
(start, end) = (dom_j, cod_j)
|
| 2107 |
+
backwards = False
|
| 2108 |
+
else:
|
| 2109 |
+
(start, end) = (cod_j, dom_j)
|
| 2110 |
+
backwards = True
|
| 2111 |
+
|
| 2112 |
+
# Check for free space above.
|
| 2113 |
+
if dom_i == 0:
|
| 2114 |
+
free_up = True
|
| 2115 |
+
else:
|
| 2116 |
+
free_up = all(grid[dom_i - 1, j] for j in
|
| 2117 |
+
range(start, end + 1))
|
| 2118 |
+
|
| 2119 |
+
# Check for free space below.
|
| 2120 |
+
if dom_i == grid.height - 1:
|
| 2121 |
+
free_down = True
|
| 2122 |
+
else:
|
| 2123 |
+
free_down = not any(grid[dom_i + 1, j] for j in
|
| 2124 |
+
range(start, end + 1))
|
| 2125 |
+
|
| 2126 |
+
return (free_up, free_down, backwards)
|
| 2127 |
+
|
| 2128 |
+
@staticmethod
|
| 2129 |
+
def _check_free_space_vertical(dom_i, cod_i, dom_j, grid):
|
| 2130 |
+
"""
|
| 2131 |
+
For a vertical morphism, checks whether there is free space
|
| 2132 |
+
(i.e., space not occupied by any objects) to the left of the
|
| 2133 |
+
morphism or to the right of it.
|
| 2134 |
+
"""
|
| 2135 |
+
if dom_i < cod_i:
|
| 2136 |
+
(start, end) = (dom_i, cod_i)
|
| 2137 |
+
backwards = False
|
| 2138 |
+
else:
|
| 2139 |
+
(start, end) = (cod_i, dom_i)
|
| 2140 |
+
backwards = True
|
| 2141 |
+
|
| 2142 |
+
# Check if there's space to the left.
|
| 2143 |
+
if dom_j == 0:
|
| 2144 |
+
free_left = True
|
| 2145 |
+
else:
|
| 2146 |
+
free_left = not any(grid[i, dom_j - 1] for i in
|
| 2147 |
+
range(start, end + 1))
|
| 2148 |
+
|
| 2149 |
+
if dom_j == grid.width - 1:
|
| 2150 |
+
free_right = True
|
| 2151 |
+
else:
|
| 2152 |
+
free_right = not any(grid[i, dom_j + 1] for i in
|
| 2153 |
+
range(start, end + 1))
|
| 2154 |
+
|
| 2155 |
+
return (free_left, free_right, backwards)
|
| 2156 |
+
|
| 2157 |
+
@staticmethod
|
| 2158 |
+
def _check_free_space_diagonal(dom_i, cod_i, dom_j, cod_j, grid):
|
| 2159 |
+
"""
|
| 2160 |
+
For a diagonal morphism, checks whether there is free space
|
| 2161 |
+
(i.e., space not occupied by any objects) above the morphism
|
| 2162 |
+
or below it.
|
| 2163 |
+
"""
|
| 2164 |
+
def abs_xrange(start, end):
|
| 2165 |
+
if start < end:
|
| 2166 |
+
return range(start, end + 1)
|
| 2167 |
+
else:
|
| 2168 |
+
return range(end, start + 1)
|
| 2169 |
+
|
| 2170 |
+
if dom_i < cod_i and dom_j < cod_j:
|
| 2171 |
+
# This morphism goes from top-left to
|
| 2172 |
+
# bottom-right.
|
| 2173 |
+
(start_i, start_j) = (dom_i, dom_j)
|
| 2174 |
+
(end_i, end_j) = (cod_i, cod_j)
|
| 2175 |
+
backwards = False
|
| 2176 |
+
elif dom_i > cod_i and dom_j > cod_j:
|
| 2177 |
+
# This morphism goes from bottom-right to
|
| 2178 |
+
# top-left.
|
| 2179 |
+
(start_i, start_j) = (cod_i, cod_j)
|
| 2180 |
+
(end_i, end_j) = (dom_i, dom_j)
|
| 2181 |
+
backwards = True
|
| 2182 |
+
if dom_i < cod_i and dom_j > cod_j:
|
| 2183 |
+
# This morphism goes from top-right to
|
| 2184 |
+
# bottom-left.
|
| 2185 |
+
(start_i, start_j) = (dom_i, dom_j)
|
| 2186 |
+
(end_i, end_j) = (cod_i, cod_j)
|
| 2187 |
+
backwards = True
|
| 2188 |
+
elif dom_i > cod_i and dom_j < cod_j:
|
| 2189 |
+
# This morphism goes from bottom-left to
|
| 2190 |
+
# top-right.
|
| 2191 |
+
(start_i, start_j) = (cod_i, cod_j)
|
| 2192 |
+
(end_i, end_j) = (dom_i, dom_j)
|
| 2193 |
+
backwards = False
|
| 2194 |
+
|
| 2195 |
+
# This is an attempt at a fast and furious strategy to
|
| 2196 |
+
# decide where there is free space on the two sides of
|
| 2197 |
+
# a diagonal morphism. For a diagonal morphism
|
| 2198 |
+
# starting at ``(start_i, start_j)`` and ending at
|
| 2199 |
+
# ``(end_i, end_j)`` the rectangle defined by these
|
| 2200 |
+
# two points is considered. The slope of the diagonal
|
| 2201 |
+
# ``alpha`` is then computed. Then, for every cell
|
| 2202 |
+
# ``(i, j)`` within the rectangle, the slope
|
| 2203 |
+
# ``alpha1`` of the line through ``(start_i,
|
| 2204 |
+
# start_j)`` and ``(i, j)`` is considered. If
|
| 2205 |
+
# ``alpha1`` is between 0 and ``alpha``, the point
|
| 2206 |
+
# ``(i, j)`` is above the diagonal, if ``alpha1`` is
|
| 2207 |
+
# between ``alpha`` and infinity, the point is below
|
| 2208 |
+
# the diagonal. Also note that, with some beforehand
|
| 2209 |
+
# precautions, this trick works for both the main and
|
| 2210 |
+
# the secondary diagonals of the rectangle.
|
| 2211 |
+
|
| 2212 |
+
# I have considered the possibility to only follow the
|
| 2213 |
+
# shorter diagonals immediately above and below the
|
| 2214 |
+
# main (or secondary) diagonal. This, however,
|
| 2215 |
+
# wouldn't have resulted in much performance gain or
|
| 2216 |
+
# better detection of outer edges, because of
|
| 2217 |
+
# relatively small sizes of diagram grids, while the
|
| 2218 |
+
# code would have become harder to understand.
|
| 2219 |
+
|
| 2220 |
+
alpha = float(end_i - start_i)/(end_j - start_j)
|
| 2221 |
+
free_up = True
|
| 2222 |
+
free_down = True
|
| 2223 |
+
for i in abs_xrange(start_i, end_i):
|
| 2224 |
+
if not free_up and not free_down:
|
| 2225 |
+
break
|
| 2226 |
+
|
| 2227 |
+
for j in abs_xrange(start_j, end_j):
|
| 2228 |
+
if not free_up and not free_down:
|
| 2229 |
+
break
|
| 2230 |
+
|
| 2231 |
+
if (i, j) == (start_i, start_j):
|
| 2232 |
+
continue
|
| 2233 |
+
|
| 2234 |
+
if j == start_j:
|
| 2235 |
+
alpha1 = "inf"
|
| 2236 |
+
else:
|
| 2237 |
+
alpha1 = float(i - start_i)/(j - start_j)
|
| 2238 |
+
|
| 2239 |
+
if grid[i, j]:
|
| 2240 |
+
if (alpha1 == "inf") or (abs(alpha1) > abs(alpha)):
|
| 2241 |
+
free_down = False
|
| 2242 |
+
elif abs(alpha1) < abs(alpha):
|
| 2243 |
+
free_up = False
|
| 2244 |
+
|
| 2245 |
+
return (free_up, free_down, backwards)
|
| 2246 |
+
|
| 2247 |
+
def _push_labels_out(self, morphisms_str_info, grid, object_coords):
|
| 2248 |
+
"""
|
| 2249 |
+
For all straight morphisms which form the visual boundary of
|
| 2250 |
+
the laid out diagram, puts their labels on their outer sides.
|
| 2251 |
+
"""
|
| 2252 |
+
def set_label_position(free1, free2, pos1, pos2, backwards, m_str_info):
|
| 2253 |
+
"""
|
| 2254 |
+
Given the information about room available to one side and
|
| 2255 |
+
to the other side of a morphism (``free1`` and ``free2``),
|
| 2256 |
+
sets the position of the morphism label in such a way that
|
| 2257 |
+
it is on the freer side. This latter operations involves
|
| 2258 |
+
choice between ``pos1`` and ``pos2``, taking ``backwards``
|
| 2259 |
+
in consideration.
|
| 2260 |
+
|
| 2261 |
+
Thus this function will do nothing if either both ``free1
|
| 2262 |
+
== True`` and ``free2 == True`` or both ``free1 == False``
|
| 2263 |
+
and ``free2 == False``. In either case, choosing one side
|
| 2264 |
+
over the other presents no advantage.
|
| 2265 |
+
"""
|
| 2266 |
+
if backwards:
|
| 2267 |
+
(pos1, pos2) = (pos2, pos1)
|
| 2268 |
+
|
| 2269 |
+
if free1 and not free2:
|
| 2270 |
+
m_str_info.label_position = pos1
|
| 2271 |
+
elif free2 and not free1:
|
| 2272 |
+
m_str_info.label_position = pos2
|
| 2273 |
+
|
| 2274 |
+
for m, m_str_info in morphisms_str_info.items():
|
| 2275 |
+
if m_str_info.curving or m_str_info.forced_label_position:
|
| 2276 |
+
# This is either a curved morphism, and curved
|
| 2277 |
+
# morphisms have other magic, or the position of this
|
| 2278 |
+
# label has already been fixed.
|
| 2279 |
+
continue
|
| 2280 |
+
|
| 2281 |
+
if m.domain == m.codomain:
|
| 2282 |
+
# This is a loop morphism, their labels, again have a
|
| 2283 |
+
# different magic.
|
| 2284 |
+
continue
|
| 2285 |
+
|
| 2286 |
+
(dom_i, dom_j) = object_coords[m.domain]
|
| 2287 |
+
(cod_i, cod_j) = object_coords[m.codomain]
|
| 2288 |
+
|
| 2289 |
+
if dom_i == cod_i:
|
| 2290 |
+
# Horizontal morphism.
|
| 2291 |
+
(free_up, free_down,
|
| 2292 |
+
backwards) = XypicDiagramDrawer._check_free_space_horizontal(
|
| 2293 |
+
dom_i, dom_j, cod_j, grid)
|
| 2294 |
+
|
| 2295 |
+
set_label_position(free_up, free_down, "^", "_",
|
| 2296 |
+
backwards, m_str_info)
|
| 2297 |
+
elif dom_j == cod_j:
|
| 2298 |
+
# Vertical morphism.
|
| 2299 |
+
(free_left, free_right,
|
| 2300 |
+
backwards) = XypicDiagramDrawer._check_free_space_vertical(
|
| 2301 |
+
dom_i, cod_i, dom_j, grid)
|
| 2302 |
+
|
| 2303 |
+
set_label_position(free_left, free_right, "_", "^",
|
| 2304 |
+
backwards, m_str_info)
|
| 2305 |
+
else:
|
| 2306 |
+
# A diagonal morphism.
|
| 2307 |
+
(free_up, free_down,
|
| 2308 |
+
backwards) = XypicDiagramDrawer._check_free_space_diagonal(
|
| 2309 |
+
dom_i, cod_i, dom_j, cod_j, grid)
|
| 2310 |
+
|
| 2311 |
+
set_label_position(free_up, free_down, "^", "_",
|
| 2312 |
+
backwards, m_str_info)
|
| 2313 |
+
|
| 2314 |
+
@staticmethod
|
| 2315 |
+
def _morphism_sort_key(morphism, object_coords):
|
| 2316 |
+
"""
|
| 2317 |
+
Provides a morphism sorting key such that horizontal or
|
| 2318 |
+
vertical morphisms between neighbouring objects come
|
| 2319 |
+
first, then horizontal or vertical morphisms between more
|
| 2320 |
+
far away objects, and finally, all other morphisms.
|
| 2321 |
+
"""
|
| 2322 |
+
(i, j) = object_coords[morphism.domain]
|
| 2323 |
+
(target_i, target_j) = object_coords[morphism.codomain]
|
| 2324 |
+
|
| 2325 |
+
if morphism.domain == morphism.codomain:
|
| 2326 |
+
# Loop morphisms should get after diagonal morphisms
|
| 2327 |
+
# so that the proper direction in which to curve the
|
| 2328 |
+
# loop can be determined.
|
| 2329 |
+
return (3, 0, default_sort_key(morphism))
|
| 2330 |
+
|
| 2331 |
+
if target_i == i:
|
| 2332 |
+
return (1, abs(target_j - j), default_sort_key(morphism))
|
| 2333 |
+
|
| 2334 |
+
if target_j == j:
|
| 2335 |
+
return (1, abs(target_i - i), default_sort_key(morphism))
|
| 2336 |
+
|
| 2337 |
+
# Diagonal morphism.
|
| 2338 |
+
return (2, 0, default_sort_key(morphism))
|
| 2339 |
+
|
| 2340 |
+
@staticmethod
|
| 2341 |
+
def _build_xypic_string(diagram, grid, morphisms,
|
| 2342 |
+
morphisms_str_info, diagram_format):
|
| 2343 |
+
"""
|
| 2344 |
+
Given a collection of :class:`ArrowStringDescription`
|
| 2345 |
+
describing the morphisms of a diagram and the object layout
|
| 2346 |
+
information of a diagram, produces the final Xy-pic picture.
|
| 2347 |
+
"""
|
| 2348 |
+
# Build the mapping between objects and morphisms which have
|
| 2349 |
+
# them as domains.
|
| 2350 |
+
object_morphisms = {}
|
| 2351 |
+
for obj in diagram.objects:
|
| 2352 |
+
object_morphisms[obj] = []
|
| 2353 |
+
for morphism in morphisms:
|
| 2354 |
+
object_morphisms[morphism.domain].append(morphism)
|
| 2355 |
+
|
| 2356 |
+
result = "\\xymatrix%s{\n" % diagram_format
|
| 2357 |
+
|
| 2358 |
+
for i in range(grid.height):
|
| 2359 |
+
for j in range(grid.width):
|
| 2360 |
+
obj = grid[i, j]
|
| 2361 |
+
if obj:
|
| 2362 |
+
result += latex(obj) + " "
|
| 2363 |
+
|
| 2364 |
+
morphisms_to_draw = object_morphisms[obj]
|
| 2365 |
+
for morphism in morphisms_to_draw:
|
| 2366 |
+
result += str(morphisms_str_info[morphism]) + " "
|
| 2367 |
+
|
| 2368 |
+
# Don't put the & after the last column.
|
| 2369 |
+
if j < grid.width - 1:
|
| 2370 |
+
result += "& "
|
| 2371 |
+
|
| 2372 |
+
# Don't put the line break after the last row.
|
| 2373 |
+
if i < grid.height - 1:
|
| 2374 |
+
result += "\\\\"
|
| 2375 |
+
result += "\n"
|
| 2376 |
+
|
| 2377 |
+
result += "}\n"
|
| 2378 |
+
|
| 2379 |
+
return result
|
| 2380 |
+
|
| 2381 |
+
def draw(self, diagram, grid, masked=None, diagram_format=""):
|
| 2382 |
+
r"""
|
| 2383 |
+
Returns the Xy-pic representation of ``diagram`` laid out in
|
| 2384 |
+
``grid``.
|
| 2385 |
+
|
| 2386 |
+
Consider the following simple triangle diagram.
|
| 2387 |
+
|
| 2388 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 2389 |
+
>>> from sympy.categories import DiagramGrid, XypicDiagramDrawer
|
| 2390 |
+
>>> A = Object("A")
|
| 2391 |
+
>>> B = Object("B")
|
| 2392 |
+
>>> C = Object("C")
|
| 2393 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 2394 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 2395 |
+
>>> diagram = Diagram([f, g], {g * f: "unique"})
|
| 2396 |
+
|
| 2397 |
+
To draw this diagram, its objects need to be laid out with a
|
| 2398 |
+
:class:`DiagramGrid`::
|
| 2399 |
+
|
| 2400 |
+
>>> grid = DiagramGrid(diagram)
|
| 2401 |
+
|
| 2402 |
+
Finally, the drawing:
|
| 2403 |
+
|
| 2404 |
+
>>> drawer = XypicDiagramDrawer()
|
| 2405 |
+
>>> print(drawer.draw(diagram, grid))
|
| 2406 |
+
\xymatrix{
|
| 2407 |
+
A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 2408 |
+
C &
|
| 2409 |
+
}
|
| 2410 |
+
|
| 2411 |
+
The argument ``masked`` can be used to skip morphisms in the
|
| 2412 |
+
presentation of the diagram:
|
| 2413 |
+
|
| 2414 |
+
>>> print(drawer.draw(diagram, grid, masked=[g * f]))
|
| 2415 |
+
\xymatrix{
|
| 2416 |
+
A \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 2417 |
+
C &
|
| 2418 |
+
}
|
| 2419 |
+
|
| 2420 |
+
Finally, the ``diagram_format`` argument can be used to
|
| 2421 |
+
specify the format string of the diagram. For example, to
|
| 2422 |
+
increase the spacing by 1 cm, proceeding as follows:
|
| 2423 |
+
|
| 2424 |
+
>>> print(drawer.draw(diagram, grid, diagram_format="@+1cm"))
|
| 2425 |
+
\xymatrix@+1cm{
|
| 2426 |
+
A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 2427 |
+
C &
|
| 2428 |
+
}
|
| 2429 |
+
|
| 2430 |
+
"""
|
| 2431 |
+
# This method works in several steps. It starts by removing
|
| 2432 |
+
# the masked morphisms, if necessary, and then maps objects to
|
| 2433 |
+
# their positions in the grid (coordinate tuples). Remember
|
| 2434 |
+
# that objects are unique in ``Diagram`` and in the layout
|
| 2435 |
+
# produced by ``DiagramGrid``, so every object is mapped to a
|
| 2436 |
+
# single coordinate pair.
|
| 2437 |
+
#
|
| 2438 |
+
# The next step is the central step and is concerned with
|
| 2439 |
+
# analysing the morphisms of the diagram and deciding how to
|
| 2440 |
+
# draw them. For example, how to curve the arrows is decided
|
| 2441 |
+
# at this step. The bulk of the analysis is implemented in
|
| 2442 |
+
# ``_process_morphism``, to the result of which the
|
| 2443 |
+
# appropriate formatters are applied.
|
| 2444 |
+
#
|
| 2445 |
+
# The result of the previous step is a list of
|
| 2446 |
+
# ``ArrowStringDescription``. After the analysis and
|
| 2447 |
+
# application of formatters, some extra logic tries to assure
|
| 2448 |
+
# better positioning of morphism labels (for example, an
|
| 2449 |
+
# attempt is made to avoid the situations when arrows cross
|
| 2450 |
+
# labels). This functionality constitutes the next step and
|
| 2451 |
+
# is implemented in ``_push_labels_out``. Note that label
|
| 2452 |
+
# positions which have been set via a formatter are not
|
| 2453 |
+
# affected in this step.
|
| 2454 |
+
#
|
| 2455 |
+
# Finally, at the closing step, the array of
|
| 2456 |
+
# ``ArrowStringDescription`` and the layout information
|
| 2457 |
+
# incorporated in ``DiagramGrid`` are combined to produce the
|
| 2458 |
+
# resulting Xy-pic picture. This part of code lies in
|
| 2459 |
+
# ``_build_xypic_string``.
|
| 2460 |
+
|
| 2461 |
+
if not masked:
|
| 2462 |
+
morphisms_props = grid.morphisms
|
| 2463 |
+
else:
|
| 2464 |
+
morphisms_props = {}
|
| 2465 |
+
for m, props in grid.morphisms.items():
|
| 2466 |
+
if m in masked:
|
| 2467 |
+
continue
|
| 2468 |
+
morphisms_props[m] = props
|
| 2469 |
+
|
| 2470 |
+
# Build the mapping between objects and their position in the
|
| 2471 |
+
# grid.
|
| 2472 |
+
object_coords = {}
|
| 2473 |
+
for i in range(grid.height):
|
| 2474 |
+
for j in range(grid.width):
|
| 2475 |
+
if grid[i, j]:
|
| 2476 |
+
object_coords[grid[i, j]] = (i, j)
|
| 2477 |
+
|
| 2478 |
+
morphisms = sorted(morphisms_props,
|
| 2479 |
+
key=lambda m: XypicDiagramDrawer._morphism_sort_key(
|
| 2480 |
+
m, object_coords))
|
| 2481 |
+
|
| 2482 |
+
# Build the tuples defining the string representations of
|
| 2483 |
+
# morphisms.
|
| 2484 |
+
morphisms_str_info = {}
|
| 2485 |
+
for morphism in morphisms:
|
| 2486 |
+
string_description = self._process_morphism(
|
| 2487 |
+
diagram, grid, morphism, object_coords, morphisms,
|
| 2488 |
+
morphisms_str_info)
|
| 2489 |
+
|
| 2490 |
+
if self.default_arrow_formatter:
|
| 2491 |
+
self.default_arrow_formatter(string_description)
|
| 2492 |
+
|
| 2493 |
+
for prop in morphisms_props[morphism]:
|
| 2494 |
+
# prop is a Symbol. TODO: Find out why.
|
| 2495 |
+
if prop.name in self.arrow_formatters:
|
| 2496 |
+
formatter = self.arrow_formatters[prop.name]
|
| 2497 |
+
formatter(string_description)
|
| 2498 |
+
|
| 2499 |
+
morphisms_str_info[morphism] = string_description
|
| 2500 |
+
|
| 2501 |
+
# Reposition the labels a bit.
|
| 2502 |
+
self._push_labels_out(morphisms_str_info, grid, object_coords)
|
| 2503 |
+
|
| 2504 |
+
return XypicDiagramDrawer._build_xypic_string(
|
| 2505 |
+
diagram, grid, morphisms, morphisms_str_info, diagram_format)
|
| 2506 |
+
|
| 2507 |
+
|
| 2508 |
+
def xypic_draw_diagram(diagram, masked=None, diagram_format="",
|
| 2509 |
+
groups=None, **hints):
|
| 2510 |
+
r"""
|
| 2511 |
+
Provides a shortcut combining :class:`DiagramGrid` and
|
| 2512 |
+
:class:`XypicDiagramDrawer`. Returns an Xy-pic presentation of
|
| 2513 |
+
``diagram``. The argument ``masked`` is a list of morphisms which
|
| 2514 |
+
will be not be drawn. The argument ``diagram_format`` is the
|
| 2515 |
+
format string inserted after "\xymatrix". ``groups`` should be a
|
| 2516 |
+
set of logical groups. The ``hints`` will be passed directly to
|
| 2517 |
+
the constructor of :class:`DiagramGrid`.
|
| 2518 |
+
|
| 2519 |
+
For more information about the arguments, see the docstrings of
|
| 2520 |
+
:class:`DiagramGrid` and ``XypicDiagramDrawer.draw``.
|
| 2521 |
+
|
| 2522 |
+
Examples
|
| 2523 |
+
========
|
| 2524 |
+
|
| 2525 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 2526 |
+
>>> from sympy.categories import xypic_draw_diagram
|
| 2527 |
+
>>> A = Object("A")
|
| 2528 |
+
>>> B = Object("B")
|
| 2529 |
+
>>> C = Object("C")
|
| 2530 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 2531 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 2532 |
+
>>> diagram = Diagram([f, g], {g * f: "unique"})
|
| 2533 |
+
>>> print(xypic_draw_diagram(diagram))
|
| 2534 |
+
\xymatrix{
|
| 2535 |
+
A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
|
| 2536 |
+
C &
|
| 2537 |
+
}
|
| 2538 |
+
|
| 2539 |
+
See Also
|
| 2540 |
+
========
|
| 2541 |
+
|
| 2542 |
+
XypicDiagramDrawer, DiagramGrid
|
| 2543 |
+
"""
|
| 2544 |
+
grid = DiagramGrid(diagram, groups, **hints)
|
| 2545 |
+
drawer = XypicDiagramDrawer()
|
| 2546 |
+
return drawer.draw(diagram, grid, masked, diagram_format)
|
| 2547 |
+
|
| 2548 |
+
|
| 2549 |
+
@doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',))
|
| 2550 |
+
def preview_diagram(diagram, masked=None, diagram_format="", groups=None,
|
| 2551 |
+
output='png', viewer=None, euler=True, **hints):
|
| 2552 |
+
"""
|
| 2553 |
+
Combines the functionality of ``xypic_draw_diagram`` and
|
| 2554 |
+
``sympy.printing.preview``. The arguments ``masked``,
|
| 2555 |
+
``diagram_format``, ``groups``, and ``hints`` are passed to
|
| 2556 |
+
``xypic_draw_diagram``, while ``output``, ``viewer, and ``euler``
|
| 2557 |
+
are passed to ``preview``.
|
| 2558 |
+
|
| 2559 |
+
Examples
|
| 2560 |
+
========
|
| 2561 |
+
|
| 2562 |
+
>>> from sympy.categories import Object, NamedMorphism, Diagram
|
| 2563 |
+
>>> from sympy.categories import preview_diagram
|
| 2564 |
+
>>> A = Object("A")
|
| 2565 |
+
>>> B = Object("B")
|
| 2566 |
+
>>> C = Object("C")
|
| 2567 |
+
>>> f = NamedMorphism(A, B, "f")
|
| 2568 |
+
>>> g = NamedMorphism(B, C, "g")
|
| 2569 |
+
>>> d = Diagram([f, g], {g * f: "unique"})
|
| 2570 |
+
>>> preview_diagram(d)
|
| 2571 |
+
|
| 2572 |
+
See Also
|
| 2573 |
+
========
|
| 2574 |
+
|
| 2575 |
+
XypicDiagramDrawer
|
| 2576 |
+
"""
|
| 2577 |
+
from sympy.printing import preview
|
| 2578 |
+
latex_output = xypic_draw_diagram(diagram, masked, diagram_format,
|
| 2579 |
+
groups, **hints)
|
| 2580 |
+
preview(latex_output, output, viewer, euler, ("xypic",))
|
.venv/lib/python3.12/site-packages/sympy/categories/tests/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (197 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-312.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-312.pyc
ADDED
|
Binary file (33.5 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/categories/tests/test_baseclasses.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(""))
|
.venv/lib/python3.12/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")
|
.venv/lib/python3.12/site-packages/sympy/codegen/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" The ``sympy.codegen`` module contains classes and functions for building
|
| 2 |
+
abstract syntax trees of algorithms. These trees may then be printed by the
|
| 3 |
+
code-printers in ``sympy.printing``.
|
| 4 |
+
|
| 5 |
+
There are several submodules available:
|
| 6 |
+
- ``sympy.codegen.ast``: AST nodes useful across multiple languages.
|
| 7 |
+
- ``sympy.codegen.cnodes``: AST nodes useful for the C family of languages.
|
| 8 |
+
- ``sympy.codegen.fnodes``: AST nodes useful for Fortran.
|
| 9 |
+
- ``sympy.codegen.cfunctions``: functions specific to C (C99 math functions)
|
| 10 |
+
- ``sympy.codegen.ffunctions``: functions specific to Fortran (e.g. ``kind``).
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
"""
|
| 15 |
+
from .ast import (
|
| 16 |
+
Assignment, aug_assign, CodeBlock, For, Attribute, Variable, Declaration,
|
| 17 |
+
While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
'Assignment', 'aug_assign', 'CodeBlock', 'For', 'Attribute', 'Variable',
|
| 22 |
+
'Declaration', 'While', 'Scope', 'Print', 'FunctionPrototype',
|
| 23 |
+
'FunctionDefinition', 'FunctionCall',
|
| 24 |
+
]
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.13 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/abstract_nodes.cpython-312.pyc
ADDED
|
Binary file (1.13 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/algorithms.cpython-312.pyc
ADDED
|
Binary file (8.63 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/approximations.cpython-312.pyc
ADDED
|
Binary file (9.02 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/ast.cpython-312.pyc
ADDED
|
Binary file (74 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-312.pyc
ADDED
|
Binary file (19 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/cnodes.cpython-312.pyc
ADDED
|
Binary file (5.61 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/cutils.cpython-312.pyc
ADDED
|
Binary file (796 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/cxxnodes.cpython-312.pyc
ADDED
|
Binary file (781 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/fnodes.cpython-312.pyc
ADDED
|
Binary file (26.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/futils.cpython-312.pyc
ADDED
|
Binary file (2.5 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/matrix_nodes.cpython-312.pyc
ADDED
|
Binary file (3.1 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-312.pyc
ADDED
|
Binary file (7.91 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/pynodes.cpython-312.pyc
ADDED
|
Binary file (727 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/pyutils.cpython-312.pyc
ADDED
|
Binary file (1.47 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/rewriting.cpython-312.pyc
ADDED
|
Binary file (18.4 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/__pycache__/scipy_nodes.cpython-312.pyc
ADDED
|
Binary file (4.42 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/abstract_nodes.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module provides containers for python objects that are valid
|
| 2 |
+
printing targets but are not a subclass of SymPy's Printable.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from sympy.core.containers import Tuple
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class List(Tuple):
|
| 10 |
+
"""Represents a (frozen) (Python) list (for code printing purposes)."""
|
| 11 |
+
def __eq__(self, other):
|
| 12 |
+
if isinstance(other, list):
|
| 13 |
+
return self == List(*other)
|
| 14 |
+
else:
|
| 15 |
+
return self.args == other
|
| 16 |
+
|
| 17 |
+
def __hash__(self):
|
| 18 |
+
return super().__hash__()
|
.venv/lib/python3.12/site-packages/sympy/codegen/algorithms.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.containers import Tuple
|
| 2 |
+
from sympy.core.numbers import oo
|
| 3 |
+
from sympy.core.relational import (Gt, Lt)
|
| 4 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
| 5 |
+
from sympy.functions.elementary.complexes import Abs
|
| 6 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
| 7 |
+
from sympy.logic.boolalg import And
|
| 8 |
+
from sympy.codegen.ast import (
|
| 9 |
+
Assignment, AddAugmentedAssignment, break_, CodeBlock, Declaration, FunctionDefinition,
|
| 10 |
+
Print, Return, Scope, While, Variable, Pointer, real
|
| 11 |
+
)
|
| 12 |
+
from sympy.codegen.cfunctions import isnan
|
| 13 |
+
|
| 14 |
+
""" This module collects functions for constructing ASTs representing algorithms. """
|
| 15 |
+
|
| 16 |
+
def newtons_method(expr, wrt, atol=1e-12, delta=None, *, rtol=4e-16, debug=False,
|
| 17 |
+
itermax=None, counter=None, delta_fn=lambda e, x: -e/e.diff(x),
|
| 18 |
+
cse=False, handle_nan=None,
|
| 19 |
+
bounds=None):
|
| 20 |
+
""" Generates an AST for Newton-Raphson method (a root-finding algorithm).
|
| 21 |
+
|
| 22 |
+
Explanation
|
| 23 |
+
===========
|
| 24 |
+
|
| 25 |
+
Returns an abstract syntax tree (AST) based on ``sympy.codegen.ast`` for Netwon's
|
| 26 |
+
method of root-finding.
|
| 27 |
+
|
| 28 |
+
Parameters
|
| 29 |
+
==========
|
| 30 |
+
|
| 31 |
+
expr : expression
|
| 32 |
+
wrt : Symbol
|
| 33 |
+
With respect to, i.e. what is the variable.
|
| 34 |
+
atol : number or expression
|
| 35 |
+
Absolute tolerance (stopping criterion)
|
| 36 |
+
rtol : number or expression
|
| 37 |
+
Relative tolerance (stopping criterion)
|
| 38 |
+
delta : Symbol
|
| 39 |
+
Will be a ``Dummy`` if ``None``.
|
| 40 |
+
debug : bool
|
| 41 |
+
Whether to print convergence information during iterations
|
| 42 |
+
itermax : number or expr
|
| 43 |
+
Maximum number of iterations.
|
| 44 |
+
counter : Symbol
|
| 45 |
+
Will be a ``Dummy`` if ``None``.
|
| 46 |
+
delta_fn: Callable[[Expr, Symbol], Expr]
|
| 47 |
+
computes the step, default is newtons method. For e.g. Halley's method
|
| 48 |
+
use delta_fn=lambda e, x: -2*e*e.diff(x)/(2*e.diff(x)**2 - e*e.diff(x, 2))
|
| 49 |
+
cse: bool
|
| 50 |
+
Perform common sub-expression elimination on delta expression
|
| 51 |
+
handle_nan: Token
|
| 52 |
+
How to handle occurrence of not-a-number (NaN).
|
| 53 |
+
bounds: Optional[tuple[Expr, Expr]]
|
| 54 |
+
Perform optimization within bounds
|
| 55 |
+
|
| 56 |
+
Examples
|
| 57 |
+
========
|
| 58 |
+
|
| 59 |
+
>>> from sympy import symbols, cos
|
| 60 |
+
>>> from sympy.codegen.ast import Assignment
|
| 61 |
+
>>> from sympy.codegen.algorithms import newtons_method
|
| 62 |
+
>>> x, dx, atol = symbols('x dx atol')
|
| 63 |
+
>>> expr = cos(x) - x**3
|
| 64 |
+
>>> algo = newtons_method(expr, x, atol=atol, delta=dx)
|
| 65 |
+
>>> algo.has(Assignment(dx, -expr/expr.diff(x)))
|
| 66 |
+
True
|
| 67 |
+
|
| 68 |
+
References
|
| 69 |
+
==========
|
| 70 |
+
|
| 71 |
+
.. [1] https://en.wikipedia.org/wiki/Newton%27s_method
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
if delta is None:
|
| 76 |
+
delta = Dummy()
|
| 77 |
+
Wrapper = Scope
|
| 78 |
+
name_d = 'delta'
|
| 79 |
+
else:
|
| 80 |
+
Wrapper = lambda x: x
|
| 81 |
+
name_d = delta.name
|
| 82 |
+
|
| 83 |
+
delta_expr = delta_fn(expr, wrt)
|
| 84 |
+
if cse:
|
| 85 |
+
from sympy.simplify.cse_main import cse
|
| 86 |
+
cses, (red,) = cse([delta_expr.factor()])
|
| 87 |
+
whl_bdy = [Assignment(dum, sub_e) for dum, sub_e in cses]
|
| 88 |
+
whl_bdy += [Assignment(delta, red)]
|
| 89 |
+
else:
|
| 90 |
+
whl_bdy = [Assignment(delta, delta_expr)]
|
| 91 |
+
if handle_nan is not None:
|
| 92 |
+
whl_bdy += [While(isnan(delta), CodeBlock(handle_nan, break_))]
|
| 93 |
+
whl_bdy += [AddAugmentedAssignment(wrt, delta)]
|
| 94 |
+
if bounds is not None:
|
| 95 |
+
whl_bdy += [Assignment(wrt, Min(Max(wrt, bounds[0]), bounds[1]))]
|
| 96 |
+
if debug:
|
| 97 |
+
prnt = Print([wrt, delta], r"{}=%12.5g {}=%12.5g\n".format(wrt.name, name_d))
|
| 98 |
+
whl_bdy += [prnt]
|
| 99 |
+
req = Gt(Abs(delta), atol + rtol*Abs(wrt))
|
| 100 |
+
declars = [Declaration(Variable(delta, type=real, value=oo))]
|
| 101 |
+
if itermax is not None:
|
| 102 |
+
counter = counter or Dummy(integer=True)
|
| 103 |
+
v_counter = Variable.deduced(counter, 0)
|
| 104 |
+
declars.append(Declaration(v_counter))
|
| 105 |
+
whl_bdy.append(AddAugmentedAssignment(counter, 1))
|
| 106 |
+
req = And(req, Lt(counter, itermax))
|
| 107 |
+
whl = While(req, CodeBlock(*whl_bdy))
|
| 108 |
+
blck = declars
|
| 109 |
+
if debug:
|
| 110 |
+
blck.append(Print([wrt], r"{}=%12.5g\n".format(wrt.name)))
|
| 111 |
+
blck += [whl]
|
| 112 |
+
return Wrapper(CodeBlock(*blck))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _symbol_of(arg):
|
| 116 |
+
if isinstance(arg, Declaration):
|
| 117 |
+
arg = arg.variable.symbol
|
| 118 |
+
elif isinstance(arg, Variable):
|
| 119 |
+
arg = arg.symbol
|
| 120 |
+
return arg
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def newtons_method_function(expr, wrt, params=None, func_name="newton", attrs=Tuple(), *, delta=None, **kwargs):
|
| 124 |
+
""" Generates an AST for a function implementing the Newton-Raphson method.
|
| 125 |
+
|
| 126 |
+
Parameters
|
| 127 |
+
==========
|
| 128 |
+
|
| 129 |
+
expr : expression
|
| 130 |
+
wrt : Symbol
|
| 131 |
+
With respect to, i.e. what is the variable
|
| 132 |
+
params : iterable of symbols
|
| 133 |
+
Symbols appearing in expr that are taken as constants during the iterations
|
| 134 |
+
(these will be accepted as parameters to the generated function).
|
| 135 |
+
func_name : str
|
| 136 |
+
Name of the generated function.
|
| 137 |
+
attrs : Tuple
|
| 138 |
+
Attribute instances passed as ``attrs`` to ``FunctionDefinition``.
|
| 139 |
+
\\*\\*kwargs :
|
| 140 |
+
Keyword arguments passed to :func:`sympy.codegen.algorithms.newtons_method`.
|
| 141 |
+
|
| 142 |
+
Examples
|
| 143 |
+
========
|
| 144 |
+
|
| 145 |
+
>>> from sympy import symbols, cos
|
| 146 |
+
>>> from sympy.codegen.algorithms import newtons_method_function
|
| 147 |
+
>>> from sympy.codegen.pyutils import render_as_module
|
| 148 |
+
>>> x = symbols('x')
|
| 149 |
+
>>> expr = cos(x) - x**3
|
| 150 |
+
>>> func = newtons_method_function(expr, x)
|
| 151 |
+
>>> py_mod = render_as_module(func) # source code as string
|
| 152 |
+
>>> namespace = {}
|
| 153 |
+
>>> exec(py_mod, namespace, namespace)
|
| 154 |
+
>>> res = eval('newton(0.5)', namespace)
|
| 155 |
+
>>> abs(res - 0.865474033102) < 1e-12
|
| 156 |
+
True
|
| 157 |
+
|
| 158 |
+
See Also
|
| 159 |
+
========
|
| 160 |
+
|
| 161 |
+
sympy.codegen.algorithms.newtons_method
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
if params is None:
|
| 165 |
+
params = (wrt,)
|
| 166 |
+
pointer_subs = {p.symbol: Symbol('(*%s)' % p.symbol.name)
|
| 167 |
+
for p in params if isinstance(p, Pointer)}
|
| 168 |
+
if delta is None:
|
| 169 |
+
delta = Symbol('d_' + wrt.name)
|
| 170 |
+
if expr.has(delta):
|
| 171 |
+
delta = None # will use Dummy
|
| 172 |
+
algo = newtons_method(expr, wrt, delta=delta, **kwargs).xreplace(pointer_subs)
|
| 173 |
+
if isinstance(algo, Scope):
|
| 174 |
+
algo = algo.body
|
| 175 |
+
not_in_params = expr.free_symbols.difference({_symbol_of(p) for p in params})
|
| 176 |
+
if not_in_params:
|
| 177 |
+
raise ValueError("Missing symbols in params: %s" % ', '.join(map(str, not_in_params)))
|
| 178 |
+
declars = tuple(Variable(p, real) for p in params)
|
| 179 |
+
body = CodeBlock(algo, Return(wrt))
|
| 180 |
+
return FunctionDefinition(real, func_name, declars, body, attrs=attrs)
|
.venv/lib/python3.12/site-packages/sympy/codegen/approximations.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from sympy.sets.sets import Interval
|
| 3 |
+
from sympy.calculus.singularities import is_increasing, is_decreasing
|
| 4 |
+
from sympy.codegen.rewriting import Optimization
|
| 5 |
+
from sympy.core.function import UndefinedFunction
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
This module collects classes useful for approximate rewriting of expressions.
|
| 9 |
+
This can be beneficial when generating numeric code for which performance is
|
| 10 |
+
of greater importance than precision (e.g. for preconditioners used in iterative
|
| 11 |
+
methods).
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
class SumApprox(Optimization):
|
| 15 |
+
"""
|
| 16 |
+
Approximates sum by neglecting small terms.
|
| 17 |
+
|
| 18 |
+
Explanation
|
| 19 |
+
===========
|
| 20 |
+
|
| 21 |
+
If terms are expressions which can be determined to be monotonic, then
|
| 22 |
+
bounds for those expressions are added.
|
| 23 |
+
|
| 24 |
+
Parameters
|
| 25 |
+
==========
|
| 26 |
+
|
| 27 |
+
bounds : dict
|
| 28 |
+
Mapping expressions to length 2 tuple of bounds (low, high).
|
| 29 |
+
reltol : number
|
| 30 |
+
Threshold for when to ignore a term. Taken relative to the largest
|
| 31 |
+
lower bound among bounds.
|
| 32 |
+
|
| 33 |
+
Examples
|
| 34 |
+
========
|
| 35 |
+
|
| 36 |
+
>>> from sympy import exp
|
| 37 |
+
>>> from sympy.abc import x, y, z
|
| 38 |
+
>>> from sympy.codegen.rewriting import optimize
|
| 39 |
+
>>> from sympy.codegen.approximations import SumApprox
|
| 40 |
+
>>> bounds = {x: (-1, 1), y: (1000, 2000), z: (-10, 3)}
|
| 41 |
+
>>> sum_approx3 = SumApprox(bounds, reltol=1e-3)
|
| 42 |
+
>>> sum_approx2 = SumApprox(bounds, reltol=1e-2)
|
| 43 |
+
>>> sum_approx1 = SumApprox(bounds, reltol=1e-1)
|
| 44 |
+
>>> expr = 3*(x + y + exp(z))
|
| 45 |
+
>>> optimize(expr, [sum_approx3])
|
| 46 |
+
3*(x + y + exp(z))
|
| 47 |
+
>>> optimize(expr, [sum_approx2])
|
| 48 |
+
3*y + 3*exp(z)
|
| 49 |
+
>>> optimize(expr, [sum_approx1])
|
| 50 |
+
3*y
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, bounds, reltol, **kwargs):
|
| 55 |
+
super().__init__(**kwargs)
|
| 56 |
+
self.bounds = bounds
|
| 57 |
+
self.reltol = reltol
|
| 58 |
+
|
| 59 |
+
def __call__(self, expr):
|
| 60 |
+
return expr.factor().replace(self.query, lambda arg: self.value(arg))
|
| 61 |
+
|
| 62 |
+
def query(self, expr):
|
| 63 |
+
return expr.is_Add
|
| 64 |
+
|
| 65 |
+
def value(self, add):
|
| 66 |
+
for term in add.args:
|
| 67 |
+
if term.is_number or term in self.bounds or len(term.free_symbols) != 1:
|
| 68 |
+
continue
|
| 69 |
+
fs, = term.free_symbols
|
| 70 |
+
if fs not in self.bounds:
|
| 71 |
+
continue
|
| 72 |
+
intrvl = Interval(*self.bounds[fs])
|
| 73 |
+
if is_increasing(term, intrvl, fs):
|
| 74 |
+
self.bounds[term] = (
|
| 75 |
+
term.subs({fs: self.bounds[fs][0]}),
|
| 76 |
+
term.subs({fs: self.bounds[fs][1]})
|
| 77 |
+
)
|
| 78 |
+
elif is_decreasing(term, intrvl, fs):
|
| 79 |
+
self.bounds[term] = (
|
| 80 |
+
term.subs({fs: self.bounds[fs][1]}),
|
| 81 |
+
term.subs({fs: self.bounds[fs][0]})
|
| 82 |
+
)
|
| 83 |
+
else:
|
| 84 |
+
return add
|
| 85 |
+
|
| 86 |
+
if all(term.is_number or term in self.bounds for term in add.args):
|
| 87 |
+
bounds = [(term, term) if term.is_number else self.bounds[term] for term in add.args]
|
| 88 |
+
largest_abs_guarantee = 0
|
| 89 |
+
for lo, hi in bounds:
|
| 90 |
+
if lo <= 0 <= hi:
|
| 91 |
+
continue
|
| 92 |
+
largest_abs_guarantee = max(largest_abs_guarantee,
|
| 93 |
+
min(abs(lo), abs(hi)))
|
| 94 |
+
new_terms = []
|
| 95 |
+
for term, (lo, hi) in zip(add.args, bounds):
|
| 96 |
+
if max(abs(lo), abs(hi)) >= largest_abs_guarantee*self.reltol:
|
| 97 |
+
new_terms.append(term)
|
| 98 |
+
return add.func(*new_terms)
|
| 99 |
+
else:
|
| 100 |
+
return add
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class SeriesApprox(Optimization):
|
| 104 |
+
""" Approximates functions by expanding them as a series.
|
| 105 |
+
|
| 106 |
+
Parameters
|
| 107 |
+
==========
|
| 108 |
+
|
| 109 |
+
bounds : dict
|
| 110 |
+
Mapping expressions to length 2 tuple of bounds (low, high).
|
| 111 |
+
reltol : number
|
| 112 |
+
Threshold for when to ignore a term. Taken relative to the largest
|
| 113 |
+
lower bound among bounds.
|
| 114 |
+
max_order : int
|
| 115 |
+
Largest order to include in series expansion
|
| 116 |
+
n_point_checks : int (even)
|
| 117 |
+
The validity of an expansion (with respect to reltol) is checked at
|
| 118 |
+
discrete points (linearly spaced over the bounds of the variable). The
|
| 119 |
+
number of points used in this numerical check is given by this number.
|
| 120 |
+
|
| 121 |
+
Examples
|
| 122 |
+
========
|
| 123 |
+
|
| 124 |
+
>>> from sympy import sin, pi
|
| 125 |
+
>>> from sympy.abc import x, y
|
| 126 |
+
>>> from sympy.codegen.rewriting import optimize
|
| 127 |
+
>>> from sympy.codegen.approximations import SeriesApprox
|
| 128 |
+
>>> bounds = {x: (-.1, .1), y: (pi-1, pi+1)}
|
| 129 |
+
>>> series_approx2 = SeriesApprox(bounds, reltol=1e-2)
|
| 130 |
+
>>> series_approx3 = SeriesApprox(bounds, reltol=1e-3)
|
| 131 |
+
>>> series_approx8 = SeriesApprox(bounds, reltol=1e-8)
|
| 132 |
+
>>> expr = sin(x)*sin(y)
|
| 133 |
+
>>> optimize(expr, [series_approx2])
|
| 134 |
+
x*(-y + (y - pi)**3/6 + pi)
|
| 135 |
+
>>> optimize(expr, [series_approx3])
|
| 136 |
+
(-x**3/6 + x)*sin(y)
|
| 137 |
+
>>> optimize(expr, [series_approx8])
|
| 138 |
+
sin(x)*sin(y)
|
| 139 |
+
|
| 140 |
+
"""
|
| 141 |
+
def __init__(self, bounds, reltol, max_order=4, n_point_checks=4, **kwargs):
|
| 142 |
+
super().__init__(**kwargs)
|
| 143 |
+
self.bounds = bounds
|
| 144 |
+
self.reltol = reltol
|
| 145 |
+
self.max_order = max_order
|
| 146 |
+
if n_point_checks % 2 == 1:
|
| 147 |
+
raise ValueError("Checking the solution at expansion point is not helpful")
|
| 148 |
+
self.n_point_checks = n_point_checks
|
| 149 |
+
self._prec = math.ceil(-math.log10(self.reltol))
|
| 150 |
+
|
| 151 |
+
def __call__(self, expr):
|
| 152 |
+
return expr.factor().replace(self.query, lambda arg: self.value(arg))
|
| 153 |
+
|
| 154 |
+
def query(self, expr):
|
| 155 |
+
return (expr.is_Function and not isinstance(expr, UndefinedFunction)
|
| 156 |
+
and len(expr.args) == 1)
|
| 157 |
+
|
| 158 |
+
def value(self, fexpr):
|
| 159 |
+
free_symbols = fexpr.free_symbols
|
| 160 |
+
if len(free_symbols) != 1:
|
| 161 |
+
return fexpr
|
| 162 |
+
symb, = free_symbols
|
| 163 |
+
if symb not in self.bounds:
|
| 164 |
+
return fexpr
|
| 165 |
+
lo, hi = self.bounds[symb]
|
| 166 |
+
x0 = (lo + hi)/2
|
| 167 |
+
cheapest = None
|
| 168 |
+
for n in range(self.max_order+1, 0, -1):
|
| 169 |
+
fseri = fexpr.series(symb, x0=x0, n=n).removeO()
|
| 170 |
+
n_ok = True
|
| 171 |
+
for idx in range(self.n_point_checks):
|
| 172 |
+
x = lo + idx*(hi - lo)/(self.n_point_checks - 1)
|
| 173 |
+
val = fseri.xreplace({symb: x})
|
| 174 |
+
ref = fexpr.xreplace({symb: x})
|
| 175 |
+
if abs((1 - val/ref).evalf(self._prec)) > self.reltol:
|
| 176 |
+
n_ok = False
|
| 177 |
+
break
|
| 178 |
+
|
| 179 |
+
if n_ok:
|
| 180 |
+
cheapest = fseri
|
| 181 |
+
else:
|
| 182 |
+
break
|
| 183 |
+
|
| 184 |
+
if cheapest is None:
|
| 185 |
+
return fexpr
|
| 186 |
+
else:
|
| 187 |
+
return cheapest
|
.venv/lib/python3.12/site-packages/sympy/codegen/ast.py
ADDED
|
@@ -0,0 +1,1906 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Types used to represent a full function/module as an Abstract Syntax Tree.
|
| 3 |
+
|
| 4 |
+
Most types are small, and are merely used as tokens in the AST. A tree diagram
|
| 5 |
+
has been included below to illustrate the relationships between the AST types.
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
AST Type Tree
|
| 9 |
+
-------------
|
| 10 |
+
::
|
| 11 |
+
|
| 12 |
+
*Basic*
|
| 13 |
+
|
|
| 14 |
+
|
|
| 15 |
+
CodegenAST
|
| 16 |
+
|
|
| 17 |
+
|--->AssignmentBase
|
| 18 |
+
| |--->Assignment
|
| 19 |
+
| |--->AugmentedAssignment
|
| 20 |
+
| |--->AddAugmentedAssignment
|
| 21 |
+
| |--->SubAugmentedAssignment
|
| 22 |
+
| |--->MulAugmentedAssignment
|
| 23 |
+
| |--->DivAugmentedAssignment
|
| 24 |
+
| |--->ModAugmentedAssignment
|
| 25 |
+
|
|
| 26 |
+
|--->CodeBlock
|
| 27 |
+
|
|
| 28 |
+
|
|
| 29 |
+
|--->Token
|
| 30 |
+
|--->Attribute
|
| 31 |
+
|--->For
|
| 32 |
+
|--->String
|
| 33 |
+
| |--->QuotedString
|
| 34 |
+
| |--->Comment
|
| 35 |
+
|--->Type
|
| 36 |
+
| |--->IntBaseType
|
| 37 |
+
| | |--->_SizedIntType
|
| 38 |
+
| | |--->SignedIntType
|
| 39 |
+
| | |--->UnsignedIntType
|
| 40 |
+
| |--->FloatBaseType
|
| 41 |
+
| |--->FloatType
|
| 42 |
+
| |--->ComplexBaseType
|
| 43 |
+
| |--->ComplexType
|
| 44 |
+
|--->Node
|
| 45 |
+
| |--->Variable
|
| 46 |
+
| | |---> Pointer
|
| 47 |
+
| |--->FunctionPrototype
|
| 48 |
+
| |--->FunctionDefinition
|
| 49 |
+
|--->Element
|
| 50 |
+
|--->Declaration
|
| 51 |
+
|--->While
|
| 52 |
+
|--->Scope
|
| 53 |
+
|--->Stream
|
| 54 |
+
|--->Print
|
| 55 |
+
|--->FunctionCall
|
| 56 |
+
|--->BreakToken
|
| 57 |
+
|--->ContinueToken
|
| 58 |
+
|--->NoneToken
|
| 59 |
+
|--->Return
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
Predefined types
|
| 63 |
+
----------------
|
| 64 |
+
|
| 65 |
+
A number of ``Type`` instances are provided in the ``sympy.codegen.ast`` module
|
| 66 |
+
for convenience. Perhaps the two most common ones for code-generation (of numeric
|
| 67 |
+
codes) are ``float32`` and ``float64`` (known as single and double precision respectively).
|
| 68 |
+
There are also precision generic versions of Types (for which the codeprinters selects the
|
| 69 |
+
underlying data type at time of printing): ``real``, ``integer``, ``complex_``, ``bool_``.
|
| 70 |
+
|
| 71 |
+
The other ``Type`` instances defined are:
|
| 72 |
+
|
| 73 |
+
- ``intc``: Integer type used by C's "int".
|
| 74 |
+
- ``intp``: Integer type used by C's "unsigned".
|
| 75 |
+
- ``int8``, ``int16``, ``int32``, ``int64``: n-bit integers.
|
| 76 |
+
- ``uint8``, ``uint16``, ``uint32``, ``uint64``: n-bit unsigned integers.
|
| 77 |
+
- ``float80``: known as "extended precision" on modern x86/amd64 hardware.
|
| 78 |
+
- ``complex64``: Complex number represented by two ``float32`` numbers
|
| 79 |
+
- ``complex128``: Complex number represented by two ``float64`` numbers
|
| 80 |
+
|
| 81 |
+
Using the nodes
|
| 82 |
+
---------------
|
| 83 |
+
|
| 84 |
+
It is possible to construct simple algorithms using the AST nodes. Let's construct a loop applying
|
| 85 |
+
Newton's method::
|
| 86 |
+
|
| 87 |
+
>>> from sympy import symbols, cos
|
| 88 |
+
>>> from sympy.codegen.ast import While, Assignment, aug_assign, Print, QuotedString
|
| 89 |
+
>>> t, dx, x = symbols('tol delta val')
|
| 90 |
+
>>> expr = cos(x) - x**3
|
| 91 |
+
>>> whl = While(abs(dx) > t, [
|
| 92 |
+
... Assignment(dx, -expr/expr.diff(x)),
|
| 93 |
+
... aug_assign(x, '+', dx),
|
| 94 |
+
... Print([x])
|
| 95 |
+
... ])
|
| 96 |
+
>>> from sympy import pycode
|
| 97 |
+
>>> py_str = pycode(whl)
|
| 98 |
+
>>> print(py_str)
|
| 99 |
+
while (abs(delta) > tol):
|
| 100 |
+
delta = (val**3 - math.cos(val))/(-3*val**2 - math.sin(val))
|
| 101 |
+
val += delta
|
| 102 |
+
print(val)
|
| 103 |
+
>>> import math
|
| 104 |
+
>>> tol, val, delta = 1e-5, 0.5, float('inf')
|
| 105 |
+
>>> exec(py_str)
|
| 106 |
+
1.1121416371
|
| 107 |
+
0.909672693737
|
| 108 |
+
0.867263818209
|
| 109 |
+
0.865477135298
|
| 110 |
+
0.865474033111
|
| 111 |
+
>>> print('%3.1g' % (math.cos(val) - val**3))
|
| 112 |
+
-3e-11
|
| 113 |
+
|
| 114 |
+
If we want to generate Fortran code for the same while loop we simple call ``fcode``::
|
| 115 |
+
|
| 116 |
+
>>> from sympy import fcode
|
| 117 |
+
>>> print(fcode(whl, standard=2003, source_format='free'))
|
| 118 |
+
do while (abs(delta) > tol)
|
| 119 |
+
delta = (val**3 - cos(val))/(-3*val**2 - sin(val))
|
| 120 |
+
val = val + delta
|
| 121 |
+
print *, val
|
| 122 |
+
end do
|
| 123 |
+
|
| 124 |
+
There is a function constructing a loop (or a complete function) like this in
|
| 125 |
+
:mod:`sympy.codegen.algorithms`.
|
| 126 |
+
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
from __future__ import annotations
|
| 130 |
+
from typing import Any
|
| 131 |
+
|
| 132 |
+
from collections import defaultdict
|
| 133 |
+
|
| 134 |
+
from sympy.core.relational import (Ge, Gt, Le, Lt)
|
| 135 |
+
from sympy.core import Symbol, Tuple, Dummy
|
| 136 |
+
from sympy.core.basic import Basic
|
| 137 |
+
from sympy.core.expr import Expr, Atom
|
| 138 |
+
from sympy.core.numbers import Float, Integer, oo
|
| 139 |
+
from sympy.core.sympify import _sympify, sympify, SympifyError
|
| 140 |
+
from sympy.utilities.iterables import (iterable, topological_sort,
|
| 141 |
+
numbered_symbols, filter_symbols)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _mk_Tuple(args):
|
| 145 |
+
"""
|
| 146 |
+
Create a SymPy Tuple object from an iterable, converting Python strings to
|
| 147 |
+
AST strings.
|
| 148 |
+
|
| 149 |
+
Parameters
|
| 150 |
+
==========
|
| 151 |
+
|
| 152 |
+
args: iterable
|
| 153 |
+
Arguments to :class:`sympy.Tuple`.
|
| 154 |
+
|
| 155 |
+
Returns
|
| 156 |
+
=======
|
| 157 |
+
|
| 158 |
+
sympy.Tuple
|
| 159 |
+
"""
|
| 160 |
+
args = [String(arg) if isinstance(arg, str) else arg for arg in args]
|
| 161 |
+
return Tuple(*args)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class CodegenAST(Basic):
|
| 165 |
+
__slots__ = ()
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class Token(CodegenAST):
|
| 169 |
+
""" Base class for the AST types.
|
| 170 |
+
|
| 171 |
+
Explanation
|
| 172 |
+
===========
|
| 173 |
+
|
| 174 |
+
Defining fields are set in ``_fields``. Attributes (defined in _fields)
|
| 175 |
+
are only allowed to contain instances of Basic (unless atomic, see
|
| 176 |
+
``String``). The arguments to ``__new__()`` correspond to the attributes in
|
| 177 |
+
the order defined in ``_fields`. The ``defaults`` class attribute is a
|
| 178 |
+
dictionary mapping attribute names to their default values.
|
| 179 |
+
|
| 180 |
+
Subclasses should not need to override the ``__new__()`` method. They may
|
| 181 |
+
define a class or static method named ``_construct_<attr>`` for each
|
| 182 |
+
attribute to process the value passed to ``__new__()``. Attributes listed
|
| 183 |
+
in the class attribute ``not_in_args`` are not passed to :class:`~.Basic`.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
__slots__: tuple[str, ...] = ()
|
| 187 |
+
_fields = __slots__
|
| 188 |
+
defaults: dict[str, Any] = {}
|
| 189 |
+
not_in_args: list[str] = []
|
| 190 |
+
indented_args = ['body']
|
| 191 |
+
|
| 192 |
+
@property
|
| 193 |
+
def is_Atom(self):
|
| 194 |
+
return len(self._fields) == 0
|
| 195 |
+
|
| 196 |
+
@classmethod
|
| 197 |
+
def _get_constructor(cls, attr):
|
| 198 |
+
""" Get the constructor function for an attribute by name. """
|
| 199 |
+
return getattr(cls, '_construct_%s' % attr, lambda x: x)
|
| 200 |
+
|
| 201 |
+
@classmethod
|
| 202 |
+
def _construct(cls, attr, arg):
|
| 203 |
+
""" Construct an attribute value from argument passed to ``__new__()``. """
|
| 204 |
+
# arg may be ``NoneToken()``, so comparison is done using == instead of ``is`` operator
|
| 205 |
+
if arg == None:
|
| 206 |
+
return cls.defaults.get(attr, none)
|
| 207 |
+
else:
|
| 208 |
+
if isinstance(arg, Dummy): # SymPy's replace uses Dummy instances
|
| 209 |
+
return arg
|
| 210 |
+
else:
|
| 211 |
+
return cls._get_constructor(attr)(arg)
|
| 212 |
+
|
| 213 |
+
def __new__(cls, *args, **kwargs):
|
| 214 |
+
# Pass through existing instances when given as sole argument
|
| 215 |
+
if len(args) == 1 and not kwargs and isinstance(args[0], cls):
|
| 216 |
+
return args[0]
|
| 217 |
+
|
| 218 |
+
if len(args) > len(cls._fields):
|
| 219 |
+
raise ValueError("Too many arguments (%d), expected at most %d" % (len(args), len(cls._fields)))
|
| 220 |
+
|
| 221 |
+
attrvals = []
|
| 222 |
+
|
| 223 |
+
# Process positional arguments
|
| 224 |
+
for attrname, argval in zip(cls._fields, args):
|
| 225 |
+
if attrname in kwargs:
|
| 226 |
+
raise TypeError('Got multiple values for attribute %r' % attrname)
|
| 227 |
+
|
| 228 |
+
attrvals.append(cls._construct(attrname, argval))
|
| 229 |
+
|
| 230 |
+
# Process keyword arguments
|
| 231 |
+
for attrname in cls._fields[len(args):]:
|
| 232 |
+
if attrname in kwargs:
|
| 233 |
+
argval = kwargs.pop(attrname)
|
| 234 |
+
|
| 235 |
+
elif attrname in cls.defaults:
|
| 236 |
+
argval = cls.defaults[attrname]
|
| 237 |
+
|
| 238 |
+
else:
|
| 239 |
+
raise TypeError('No value for %r given and attribute has no default' % attrname)
|
| 240 |
+
|
| 241 |
+
attrvals.append(cls._construct(attrname, argval))
|
| 242 |
+
|
| 243 |
+
if kwargs:
|
| 244 |
+
raise ValueError("Unknown keyword arguments: %s" % ' '.join(kwargs))
|
| 245 |
+
|
| 246 |
+
# Parent constructor
|
| 247 |
+
basic_args = [
|
| 248 |
+
val for attr, val in zip(cls._fields, attrvals)
|
| 249 |
+
if attr not in cls.not_in_args
|
| 250 |
+
]
|
| 251 |
+
obj = CodegenAST.__new__(cls, *basic_args)
|
| 252 |
+
|
| 253 |
+
# Set attributes
|
| 254 |
+
for attr, arg in zip(cls._fields, attrvals):
|
| 255 |
+
setattr(obj, attr, arg)
|
| 256 |
+
|
| 257 |
+
return obj
|
| 258 |
+
|
| 259 |
+
def __eq__(self, other):
|
| 260 |
+
if not isinstance(other, self.__class__):
|
| 261 |
+
return False
|
| 262 |
+
for attr in self._fields:
|
| 263 |
+
if getattr(self, attr) != getattr(other, attr):
|
| 264 |
+
return False
|
| 265 |
+
return True
|
| 266 |
+
|
| 267 |
+
def _hashable_content(self):
|
| 268 |
+
return tuple([getattr(self, attr) for attr in self._fields])
|
| 269 |
+
|
| 270 |
+
def __hash__(self):
|
| 271 |
+
return super().__hash__()
|
| 272 |
+
|
| 273 |
+
def _joiner(self, k, indent_level):
|
| 274 |
+
return (',\n' + ' '*indent_level) if k in self.indented_args else ', '
|
| 275 |
+
|
| 276 |
+
def _indented(self, printer, k, v, *args, **kwargs):
|
| 277 |
+
il = printer._context['indent_level']
|
| 278 |
+
def _print(arg):
|
| 279 |
+
if isinstance(arg, Token):
|
| 280 |
+
return printer._print(arg, *args, joiner=self._joiner(k, il), **kwargs)
|
| 281 |
+
else:
|
| 282 |
+
return printer._print(arg, *args, **kwargs)
|
| 283 |
+
|
| 284 |
+
if isinstance(v, Tuple):
|
| 285 |
+
joined = self._joiner(k, il).join([_print(arg) for arg in v.args])
|
| 286 |
+
if k in self.indented_args:
|
| 287 |
+
return '(\n' + ' '*il + joined + ',\n' + ' '*(il - 4) + ')'
|
| 288 |
+
else:
|
| 289 |
+
return ('({0},)' if len(v.args) == 1 else '({0})').format(joined)
|
| 290 |
+
else:
|
| 291 |
+
return _print(v)
|
| 292 |
+
|
| 293 |
+
def _sympyrepr(self, printer, *args, joiner=', ', **kwargs):
|
| 294 |
+
from sympy.printing.printer import printer_context
|
| 295 |
+
exclude = kwargs.get('exclude', ())
|
| 296 |
+
values = [getattr(self, k) for k in self._fields]
|
| 297 |
+
indent_level = printer._context.get('indent_level', 0)
|
| 298 |
+
|
| 299 |
+
arg_reprs = []
|
| 300 |
+
|
| 301 |
+
for i, (attr, value) in enumerate(zip(self._fields, values)):
|
| 302 |
+
if attr in exclude:
|
| 303 |
+
continue
|
| 304 |
+
|
| 305 |
+
# Skip attributes which have the default value
|
| 306 |
+
if attr in self.defaults and value == self.defaults[attr]:
|
| 307 |
+
continue
|
| 308 |
+
|
| 309 |
+
ilvl = indent_level + 4 if attr in self.indented_args else 0
|
| 310 |
+
with printer_context(printer, indent_level=ilvl):
|
| 311 |
+
indented = self._indented(printer, attr, value, *args, **kwargs)
|
| 312 |
+
arg_reprs.append(('{1}' if i == 0 else '{0}={1}').format(attr, indented.lstrip()))
|
| 313 |
+
|
| 314 |
+
return "{}({})".format(self.__class__.__name__, joiner.join(arg_reprs))
|
| 315 |
+
|
| 316 |
+
_sympystr = _sympyrepr
|
| 317 |
+
|
| 318 |
+
def __repr__(self): # sympy.core.Basic.__repr__ uses sstr
|
| 319 |
+
from sympy.printing import srepr
|
| 320 |
+
return srepr(self)
|
| 321 |
+
|
| 322 |
+
def kwargs(self, exclude=(), apply=None):
|
| 323 |
+
""" Get instance's attributes as dict of keyword arguments.
|
| 324 |
+
|
| 325 |
+
Parameters
|
| 326 |
+
==========
|
| 327 |
+
|
| 328 |
+
exclude : collection of str
|
| 329 |
+
Collection of keywords to exclude.
|
| 330 |
+
|
| 331 |
+
apply : callable, optional
|
| 332 |
+
Function to apply to all values.
|
| 333 |
+
"""
|
| 334 |
+
kwargs = {k: getattr(self, k) for k in self._fields if k not in exclude}
|
| 335 |
+
if apply is not None:
|
| 336 |
+
return {k: apply(v) for k, v in kwargs.items()}
|
| 337 |
+
else:
|
| 338 |
+
return kwargs
|
| 339 |
+
|
| 340 |
+
class BreakToken(Token):
|
| 341 |
+
""" Represents 'break' in C/Python ('exit' in Fortran).
|
| 342 |
+
|
| 343 |
+
Use the premade instance ``break_`` or instantiate manually.
|
| 344 |
+
|
| 345 |
+
Examples
|
| 346 |
+
========
|
| 347 |
+
|
| 348 |
+
>>> from sympy import ccode, fcode
|
| 349 |
+
>>> from sympy.codegen.ast import break_
|
| 350 |
+
>>> ccode(break_)
|
| 351 |
+
'break'
|
| 352 |
+
>>> fcode(break_, source_format='free')
|
| 353 |
+
'exit'
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
break_ = BreakToken()
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class ContinueToken(Token):
|
| 360 |
+
""" Represents 'continue' in C/Python ('cycle' in Fortran)
|
| 361 |
+
|
| 362 |
+
Use the premade instance ``continue_`` or instantiate manually.
|
| 363 |
+
|
| 364 |
+
Examples
|
| 365 |
+
========
|
| 366 |
+
|
| 367 |
+
>>> from sympy import ccode, fcode
|
| 368 |
+
>>> from sympy.codegen.ast import continue_
|
| 369 |
+
>>> ccode(continue_)
|
| 370 |
+
'continue'
|
| 371 |
+
>>> fcode(continue_, source_format='free')
|
| 372 |
+
'cycle'
|
| 373 |
+
"""
|
| 374 |
+
|
| 375 |
+
continue_ = ContinueToken()
|
| 376 |
+
|
| 377 |
+
class NoneToken(Token):
|
| 378 |
+
""" The AST equivalence of Python's NoneType
|
| 379 |
+
|
| 380 |
+
The corresponding instance of Python's ``None`` is ``none``.
|
| 381 |
+
|
| 382 |
+
Examples
|
| 383 |
+
========
|
| 384 |
+
|
| 385 |
+
>>> from sympy.codegen.ast import none, Variable
|
| 386 |
+
>>> from sympy import pycode
|
| 387 |
+
>>> print(pycode(Variable('x').as_Declaration(value=none)))
|
| 388 |
+
x = None
|
| 389 |
+
|
| 390 |
+
"""
|
| 391 |
+
def __eq__(self, other):
|
| 392 |
+
return other is None or isinstance(other, NoneToken)
|
| 393 |
+
|
| 394 |
+
def _hashable_content(self):
|
| 395 |
+
return ()
|
| 396 |
+
|
| 397 |
+
def __hash__(self):
|
| 398 |
+
return super().__hash__()
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
none = NoneToken()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class AssignmentBase(CodegenAST):
|
| 405 |
+
""" Abstract base class for Assignment and AugmentedAssignment.
|
| 406 |
+
|
| 407 |
+
Attributes:
|
| 408 |
+
===========
|
| 409 |
+
|
| 410 |
+
op : str
|
| 411 |
+
Symbol for assignment operator, e.g. "=", "+=", etc.
|
| 412 |
+
"""
|
| 413 |
+
|
| 414 |
+
def __new__(cls, lhs, rhs):
|
| 415 |
+
lhs = _sympify(lhs)
|
| 416 |
+
rhs = _sympify(rhs)
|
| 417 |
+
|
| 418 |
+
cls._check_args(lhs, rhs)
|
| 419 |
+
|
| 420 |
+
return super().__new__(cls, lhs, rhs)
|
| 421 |
+
|
| 422 |
+
@property
|
| 423 |
+
def lhs(self):
|
| 424 |
+
return self.args[0]
|
| 425 |
+
|
| 426 |
+
@property
|
| 427 |
+
def rhs(self):
|
| 428 |
+
return self.args[1]
|
| 429 |
+
|
| 430 |
+
@classmethod
|
| 431 |
+
def _check_args(cls, lhs, rhs):
|
| 432 |
+
""" Check arguments to __new__ and raise exception if any problems found.
|
| 433 |
+
|
| 434 |
+
Derived classes may wish to override this.
|
| 435 |
+
"""
|
| 436 |
+
from sympy.matrices.expressions.matexpr import (
|
| 437 |
+
MatrixElement, MatrixSymbol)
|
| 438 |
+
from sympy.tensor.indexed import Indexed
|
| 439 |
+
from sympy.tensor.array.expressions import ArrayElement
|
| 440 |
+
|
| 441 |
+
# Tuple of things that can be on the lhs of an assignment
|
| 442 |
+
assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed, Element, Variable,
|
| 443 |
+
ArrayElement)
|
| 444 |
+
if not isinstance(lhs, assignable):
|
| 445 |
+
raise TypeError("Cannot assign to lhs of type %s." % type(lhs))
|
| 446 |
+
|
| 447 |
+
# Indexed types implement shape, but don't define it until later. This
|
| 448 |
+
# causes issues in assignment validation. For now, matrices are defined
|
| 449 |
+
# as anything with a shape that is not an Indexed
|
| 450 |
+
lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed)
|
| 451 |
+
rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed)
|
| 452 |
+
|
| 453 |
+
# If lhs and rhs have same structure, then this assignment is ok
|
| 454 |
+
if lhs_is_mat:
|
| 455 |
+
if not rhs_is_mat:
|
| 456 |
+
raise ValueError("Cannot assign a scalar to a matrix.")
|
| 457 |
+
elif lhs.shape != rhs.shape:
|
| 458 |
+
raise ValueError("Dimensions of lhs and rhs do not align.")
|
| 459 |
+
elif rhs_is_mat and not lhs_is_mat:
|
| 460 |
+
raise ValueError("Cannot assign a matrix to a scalar.")
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class Assignment(AssignmentBase):
|
| 464 |
+
"""
|
| 465 |
+
Represents variable assignment for code generation.
|
| 466 |
+
|
| 467 |
+
Parameters
|
| 468 |
+
==========
|
| 469 |
+
|
| 470 |
+
lhs : Expr
|
| 471 |
+
SymPy object representing the lhs of the expression. These should be
|
| 472 |
+
singular objects, such as one would use in writing code. Notable types
|
| 473 |
+
include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
|
| 474 |
+
subclass these types are also supported.
|
| 475 |
+
|
| 476 |
+
rhs : Expr
|
| 477 |
+
SymPy object representing the rhs of the expression. This can be any
|
| 478 |
+
type, provided its shape corresponds to that of the lhs. For example,
|
| 479 |
+
a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
|
| 480 |
+
the dimensions will not align.
|
| 481 |
+
|
| 482 |
+
Examples
|
| 483 |
+
========
|
| 484 |
+
|
| 485 |
+
>>> from sympy import symbols, MatrixSymbol, Matrix
|
| 486 |
+
>>> from sympy.codegen.ast import Assignment
|
| 487 |
+
>>> x, y, z = symbols('x, y, z')
|
| 488 |
+
>>> Assignment(x, y)
|
| 489 |
+
Assignment(x, y)
|
| 490 |
+
>>> Assignment(x, 0)
|
| 491 |
+
Assignment(x, 0)
|
| 492 |
+
>>> A = MatrixSymbol('A', 1, 3)
|
| 493 |
+
>>> mat = Matrix([x, y, z]).T
|
| 494 |
+
>>> Assignment(A, mat)
|
| 495 |
+
Assignment(A, Matrix([[x, y, z]]))
|
| 496 |
+
>>> Assignment(A[0, 1], x)
|
| 497 |
+
Assignment(A[0, 1], x)
|
| 498 |
+
"""
|
| 499 |
+
|
| 500 |
+
op = ':='
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class AugmentedAssignment(AssignmentBase):
|
| 504 |
+
"""
|
| 505 |
+
Base class for augmented assignments.
|
| 506 |
+
|
| 507 |
+
Attributes:
|
| 508 |
+
===========
|
| 509 |
+
|
| 510 |
+
binop : str
|
| 511 |
+
Symbol for binary operation being applied in the assignment, such as "+",
|
| 512 |
+
"*", etc.
|
| 513 |
+
"""
|
| 514 |
+
binop: str | None
|
| 515 |
+
|
| 516 |
+
@property
|
| 517 |
+
def op(self):
|
| 518 |
+
return self.binop + '='
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class AddAugmentedAssignment(AugmentedAssignment):
|
| 522 |
+
binop = '+'
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
class SubAugmentedAssignment(AugmentedAssignment):
|
| 526 |
+
binop = '-'
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
class MulAugmentedAssignment(AugmentedAssignment):
|
| 530 |
+
binop = '*'
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
class DivAugmentedAssignment(AugmentedAssignment):
|
| 534 |
+
binop = '/'
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
class ModAugmentedAssignment(AugmentedAssignment):
|
| 538 |
+
binop = '%'
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
# Mapping from binary op strings to AugmentedAssignment subclasses
|
| 542 |
+
augassign_classes = {
|
| 543 |
+
cls.binop: cls for cls in [
|
| 544 |
+
AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment,
|
| 545 |
+
DivAugmentedAssignment, ModAugmentedAssignment
|
| 546 |
+
]
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def aug_assign(lhs, op, rhs):
|
| 551 |
+
"""
|
| 552 |
+
Create 'lhs op= rhs'.
|
| 553 |
+
|
| 554 |
+
Explanation
|
| 555 |
+
===========
|
| 556 |
+
|
| 557 |
+
Represents augmented variable assignment for code generation. This is a
|
| 558 |
+
convenience function. You can also use the AugmentedAssignment classes
|
| 559 |
+
directly, like AddAugmentedAssignment(x, y).
|
| 560 |
+
|
| 561 |
+
Parameters
|
| 562 |
+
==========
|
| 563 |
+
|
| 564 |
+
lhs : Expr
|
| 565 |
+
SymPy object representing the lhs of the expression. These should be
|
| 566 |
+
singular objects, such as one would use in writing code. Notable types
|
| 567 |
+
include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
|
| 568 |
+
subclass these types are also supported.
|
| 569 |
+
|
| 570 |
+
op : str
|
| 571 |
+
Operator (+, -, /, \\*, %).
|
| 572 |
+
|
| 573 |
+
rhs : Expr
|
| 574 |
+
SymPy object representing the rhs of the expression. This can be any
|
| 575 |
+
type, provided its shape corresponds to that of the lhs. For example,
|
| 576 |
+
a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
|
| 577 |
+
the dimensions will not align.
|
| 578 |
+
|
| 579 |
+
Examples
|
| 580 |
+
========
|
| 581 |
+
|
| 582 |
+
>>> from sympy import symbols
|
| 583 |
+
>>> from sympy.codegen.ast import aug_assign
|
| 584 |
+
>>> x, y = symbols('x, y')
|
| 585 |
+
>>> aug_assign(x, '+', y)
|
| 586 |
+
AddAugmentedAssignment(x, y)
|
| 587 |
+
"""
|
| 588 |
+
if op not in augassign_classes:
|
| 589 |
+
raise ValueError("Unrecognized operator %s" % op)
|
| 590 |
+
return augassign_classes[op](lhs, rhs)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
class CodeBlock(CodegenAST):
|
| 594 |
+
"""
|
| 595 |
+
Represents a block of code.
|
| 596 |
+
|
| 597 |
+
Explanation
|
| 598 |
+
===========
|
| 599 |
+
|
| 600 |
+
For now only assignments are supported. This restriction will be lifted in
|
| 601 |
+
the future.
|
| 602 |
+
|
| 603 |
+
Useful attributes on this object are:
|
| 604 |
+
|
| 605 |
+
``left_hand_sides``:
|
| 606 |
+
Tuple of left-hand sides of assignments, in order.
|
| 607 |
+
``left_hand_sides``:
|
| 608 |
+
Tuple of right-hand sides of assignments, in order.
|
| 609 |
+
``free_symbols``: Free symbols of the expressions in the right-hand sides
|
| 610 |
+
which do not appear in the left-hand side of an assignment.
|
| 611 |
+
|
| 612 |
+
Useful methods on this object are:
|
| 613 |
+
|
| 614 |
+
``topological_sort``:
|
| 615 |
+
Class method. Return a CodeBlock with assignments
|
| 616 |
+
sorted so that variables are assigned before they
|
| 617 |
+
are used.
|
| 618 |
+
``cse``:
|
| 619 |
+
Return a new CodeBlock with common subexpressions eliminated and
|
| 620 |
+
pulled out as assignments.
|
| 621 |
+
|
| 622 |
+
Examples
|
| 623 |
+
========
|
| 624 |
+
|
| 625 |
+
>>> from sympy import symbols, ccode
|
| 626 |
+
>>> from sympy.codegen.ast import CodeBlock, Assignment
|
| 627 |
+
>>> x, y = symbols('x y')
|
| 628 |
+
>>> c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1))
|
| 629 |
+
>>> print(ccode(c))
|
| 630 |
+
x = 1;
|
| 631 |
+
y = x + 1;
|
| 632 |
+
|
| 633 |
+
"""
|
| 634 |
+
def __new__(cls, *args):
|
| 635 |
+
left_hand_sides = []
|
| 636 |
+
right_hand_sides = []
|
| 637 |
+
for i in args:
|
| 638 |
+
if isinstance(i, Assignment):
|
| 639 |
+
lhs, rhs = i.args
|
| 640 |
+
left_hand_sides.append(lhs)
|
| 641 |
+
right_hand_sides.append(rhs)
|
| 642 |
+
|
| 643 |
+
obj = CodegenAST.__new__(cls, *args)
|
| 644 |
+
|
| 645 |
+
obj.left_hand_sides = Tuple(*left_hand_sides)
|
| 646 |
+
obj.right_hand_sides = Tuple(*right_hand_sides)
|
| 647 |
+
return obj
|
| 648 |
+
|
| 649 |
+
def __iter__(self):
|
| 650 |
+
return iter(self.args)
|
| 651 |
+
|
| 652 |
+
def _sympyrepr(self, printer, *args, **kwargs):
|
| 653 |
+
il = printer._context.get('indent_level', 0)
|
| 654 |
+
joiner = ',\n' + ' '*il
|
| 655 |
+
joined = joiner.join(map(printer._print, self.args))
|
| 656 |
+
return ('{}(\n'.format(' '*(il-4) + self.__class__.__name__,) +
|
| 657 |
+
' '*il + joined + '\n' + ' '*(il - 4) + ')')
|
| 658 |
+
|
| 659 |
+
_sympystr = _sympyrepr
|
| 660 |
+
|
| 661 |
+
@property
|
| 662 |
+
def free_symbols(self):
|
| 663 |
+
return super().free_symbols - set(self.left_hand_sides)
|
| 664 |
+
|
| 665 |
+
@classmethod
|
| 666 |
+
def topological_sort(cls, assignments):
|
| 667 |
+
"""
|
| 668 |
+
Return a CodeBlock with topologically sorted assignments so that
|
| 669 |
+
variables are assigned before they are used.
|
| 670 |
+
|
| 671 |
+
Examples
|
| 672 |
+
========
|
| 673 |
+
|
| 674 |
+
The existing order of assignments is preserved as much as possible.
|
| 675 |
+
|
| 676 |
+
This function assumes that variables are assigned to only once.
|
| 677 |
+
|
| 678 |
+
This is a class constructor so that the default constructor for
|
| 679 |
+
CodeBlock can error when variables are used before they are assigned.
|
| 680 |
+
|
| 681 |
+
>>> from sympy import symbols
|
| 682 |
+
>>> from sympy.codegen.ast import CodeBlock, Assignment
|
| 683 |
+
>>> x, y, z = symbols('x y z')
|
| 684 |
+
|
| 685 |
+
>>> assignments = [
|
| 686 |
+
... Assignment(x, y + z),
|
| 687 |
+
... Assignment(y, z + 1),
|
| 688 |
+
... Assignment(z, 2),
|
| 689 |
+
... ]
|
| 690 |
+
>>> CodeBlock.topological_sort(assignments)
|
| 691 |
+
CodeBlock(
|
| 692 |
+
Assignment(z, 2),
|
| 693 |
+
Assignment(y, z + 1),
|
| 694 |
+
Assignment(x, y + z)
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
"""
|
| 698 |
+
|
| 699 |
+
if not all(isinstance(i, Assignment) for i in assignments):
|
| 700 |
+
# Will support more things later
|
| 701 |
+
raise NotImplementedError("CodeBlock.topological_sort only supports Assignments")
|
| 702 |
+
|
| 703 |
+
if any(isinstance(i, AugmentedAssignment) for i in assignments):
|
| 704 |
+
raise NotImplementedError("CodeBlock.topological_sort does not yet work with AugmentedAssignments")
|
| 705 |
+
|
| 706 |
+
# Create a graph where the nodes are assignments and there is a directed edge
|
| 707 |
+
# between nodes that use a variable and nodes that assign that
|
| 708 |
+
# variable, like
|
| 709 |
+
|
| 710 |
+
# [(x := 1, y := x + 1), (x := 1, z := y + z), (y := x + 1, z := y + z)]
|
| 711 |
+
|
| 712 |
+
# If we then topologically sort these nodes, they will be in
|
| 713 |
+
# assignment order, like
|
| 714 |
+
|
| 715 |
+
# x := 1
|
| 716 |
+
# y := x + 1
|
| 717 |
+
# z := y + z
|
| 718 |
+
|
| 719 |
+
# A = The nodes
|
| 720 |
+
#
|
| 721 |
+
# enumerate keeps nodes in the same order they are already in if
|
| 722 |
+
# possible. It will also allow us to handle duplicate assignments to
|
| 723 |
+
# the same variable when those are implemented.
|
| 724 |
+
A = list(enumerate(assignments))
|
| 725 |
+
|
| 726 |
+
# var_map = {variable: [nodes for which this variable is assigned to]}
|
| 727 |
+
# like {x: [(1, x := y + z), (4, x := 2 * w)], ...}
|
| 728 |
+
var_map = defaultdict(list)
|
| 729 |
+
for node in A:
|
| 730 |
+
i, a = node
|
| 731 |
+
var_map[a.lhs].append(node)
|
| 732 |
+
|
| 733 |
+
# E = Edges in the graph
|
| 734 |
+
E = []
|
| 735 |
+
for dst_node in A:
|
| 736 |
+
i, a = dst_node
|
| 737 |
+
for s in a.rhs.free_symbols:
|
| 738 |
+
for src_node in var_map[s]:
|
| 739 |
+
E.append((src_node, dst_node))
|
| 740 |
+
|
| 741 |
+
ordered_assignments = topological_sort([A, E])
|
| 742 |
+
|
| 743 |
+
# De-enumerate the result
|
| 744 |
+
return cls(*[a for i, a in ordered_assignments])
|
| 745 |
+
|
| 746 |
+
def cse(self, symbols=None, optimizations=None, postprocess=None,
|
| 747 |
+
order='canonical'):
|
| 748 |
+
"""
|
| 749 |
+
Return a new code block with common subexpressions eliminated.
|
| 750 |
+
|
| 751 |
+
Explanation
|
| 752 |
+
===========
|
| 753 |
+
|
| 754 |
+
See the docstring of :func:`sympy.simplify.cse_main.cse` for more
|
| 755 |
+
information.
|
| 756 |
+
|
| 757 |
+
Examples
|
| 758 |
+
========
|
| 759 |
+
|
| 760 |
+
>>> from sympy import symbols, sin
|
| 761 |
+
>>> from sympy.codegen.ast import CodeBlock, Assignment
|
| 762 |
+
>>> x, y, z = symbols('x y z')
|
| 763 |
+
|
| 764 |
+
>>> c = CodeBlock(
|
| 765 |
+
... Assignment(x, 1),
|
| 766 |
+
... Assignment(y, sin(x) + 1),
|
| 767 |
+
... Assignment(z, sin(x) - 1),
|
| 768 |
+
... )
|
| 769 |
+
...
|
| 770 |
+
>>> c.cse()
|
| 771 |
+
CodeBlock(
|
| 772 |
+
Assignment(x, 1),
|
| 773 |
+
Assignment(x0, sin(x)),
|
| 774 |
+
Assignment(y, x0 + 1),
|
| 775 |
+
Assignment(z, x0 - 1)
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
"""
|
| 779 |
+
from sympy.simplify.cse_main import cse
|
| 780 |
+
|
| 781 |
+
# Check that the CodeBlock only contains assignments to unique variables
|
| 782 |
+
if not all(isinstance(i, Assignment) for i in self.args):
|
| 783 |
+
# Will support more things later
|
| 784 |
+
raise NotImplementedError("CodeBlock.cse only supports Assignments")
|
| 785 |
+
|
| 786 |
+
if any(isinstance(i, AugmentedAssignment) for i in self.args):
|
| 787 |
+
raise NotImplementedError("CodeBlock.cse does not yet work with AugmentedAssignments")
|
| 788 |
+
|
| 789 |
+
for i, lhs in enumerate(self.left_hand_sides):
|
| 790 |
+
if lhs in self.left_hand_sides[:i]:
|
| 791 |
+
raise NotImplementedError("Duplicate assignments to the same "
|
| 792 |
+
"variable are not yet supported (%s)" % lhs)
|
| 793 |
+
|
| 794 |
+
# Ensure new symbols for subexpressions do not conflict with existing
|
| 795 |
+
existing_symbols = self.atoms(Symbol)
|
| 796 |
+
if symbols is None:
|
| 797 |
+
symbols = numbered_symbols()
|
| 798 |
+
symbols = filter_symbols(symbols, existing_symbols)
|
| 799 |
+
|
| 800 |
+
replacements, reduced_exprs = cse(list(self.right_hand_sides),
|
| 801 |
+
symbols=symbols, optimizations=optimizations, postprocess=postprocess,
|
| 802 |
+
order=order)
|
| 803 |
+
|
| 804 |
+
new_block = [Assignment(var, expr) for var, expr in
|
| 805 |
+
zip(self.left_hand_sides, reduced_exprs)]
|
| 806 |
+
new_assignments = [Assignment(var, expr) for var, expr in replacements]
|
| 807 |
+
return self.topological_sort(new_assignments + new_block)
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
class For(Token):
|
| 811 |
+
"""Represents a 'for-loop' in the code.
|
| 812 |
+
|
| 813 |
+
Expressions are of the form:
|
| 814 |
+
"for target in iter:
|
| 815 |
+
body..."
|
| 816 |
+
|
| 817 |
+
Parameters
|
| 818 |
+
==========
|
| 819 |
+
|
| 820 |
+
target : symbol
|
| 821 |
+
iter : iterable
|
| 822 |
+
body : CodeBlock or iterable
|
| 823 |
+
! When passed an iterable it is used to instantiate a CodeBlock.
|
| 824 |
+
|
| 825 |
+
Examples
|
| 826 |
+
========
|
| 827 |
+
|
| 828 |
+
>>> from sympy import symbols, Range
|
| 829 |
+
>>> from sympy.codegen.ast import aug_assign, For
|
| 830 |
+
>>> x, i, j, k = symbols('x i j k')
|
| 831 |
+
>>> for_i = For(i, Range(10), [aug_assign(x, '+', i*j*k)])
|
| 832 |
+
>>> for_i # doctest: -NORMALIZE_WHITESPACE
|
| 833 |
+
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
|
| 834 |
+
AddAugmentedAssignment(x, i*j*k)
|
| 835 |
+
))
|
| 836 |
+
>>> for_ji = For(j, Range(7), [for_i])
|
| 837 |
+
>>> for_ji # doctest: -NORMALIZE_WHITESPACE
|
| 838 |
+
For(j, iterable=Range(0, 7, 1), body=CodeBlock(
|
| 839 |
+
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
|
| 840 |
+
AddAugmentedAssignment(x, i*j*k)
|
| 841 |
+
))
|
| 842 |
+
))
|
| 843 |
+
>>> for_kji =For(k, Range(5), [for_ji])
|
| 844 |
+
>>> for_kji # doctest: -NORMALIZE_WHITESPACE
|
| 845 |
+
For(k, iterable=Range(0, 5, 1), body=CodeBlock(
|
| 846 |
+
For(j, iterable=Range(0, 7, 1), body=CodeBlock(
|
| 847 |
+
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
|
| 848 |
+
AddAugmentedAssignment(x, i*j*k)
|
| 849 |
+
))
|
| 850 |
+
))
|
| 851 |
+
))
|
| 852 |
+
"""
|
| 853 |
+
__slots__ = _fields = ('target', 'iterable', 'body')
|
| 854 |
+
_construct_target = staticmethod(_sympify)
|
| 855 |
+
|
| 856 |
+
@classmethod
|
| 857 |
+
def _construct_body(cls, itr):
|
| 858 |
+
if isinstance(itr, CodeBlock):
|
| 859 |
+
return itr
|
| 860 |
+
else:
|
| 861 |
+
return CodeBlock(*itr)
|
| 862 |
+
|
| 863 |
+
@classmethod
|
| 864 |
+
def _construct_iterable(cls, itr):
|
| 865 |
+
if not iterable(itr):
|
| 866 |
+
raise TypeError("iterable must be an iterable")
|
| 867 |
+
if isinstance(itr, list): # _sympify errors on lists because they are mutable
|
| 868 |
+
itr = tuple(itr)
|
| 869 |
+
return _sympify(itr)
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
class String(Atom, Token):
|
| 873 |
+
""" SymPy object representing a string.
|
| 874 |
+
|
| 875 |
+
Atomic object which is not an expression (as opposed to Symbol).
|
| 876 |
+
|
| 877 |
+
Parameters
|
| 878 |
+
==========
|
| 879 |
+
|
| 880 |
+
text : str
|
| 881 |
+
|
| 882 |
+
Examples
|
| 883 |
+
========
|
| 884 |
+
|
| 885 |
+
>>> from sympy.codegen.ast import String
|
| 886 |
+
>>> f = String('foo')
|
| 887 |
+
>>> f
|
| 888 |
+
foo
|
| 889 |
+
>>> str(f)
|
| 890 |
+
'foo'
|
| 891 |
+
>>> f.text
|
| 892 |
+
'foo'
|
| 893 |
+
>>> print(repr(f))
|
| 894 |
+
String('foo')
|
| 895 |
+
|
| 896 |
+
"""
|
| 897 |
+
__slots__ = _fields = ('text',)
|
| 898 |
+
not_in_args = ['text']
|
| 899 |
+
is_Atom = True
|
| 900 |
+
|
| 901 |
+
@classmethod
|
| 902 |
+
def _construct_text(cls, text):
|
| 903 |
+
if not isinstance(text, str):
|
| 904 |
+
raise TypeError("Argument text is not a string type.")
|
| 905 |
+
return text
|
| 906 |
+
|
| 907 |
+
def _sympystr(self, printer, *args, **kwargs):
|
| 908 |
+
return self.text
|
| 909 |
+
|
| 910 |
+
def kwargs(self, exclude = (), apply = None):
|
| 911 |
+
return {}
|
| 912 |
+
|
| 913 |
+
#to be removed when Atom is given a suitable func
|
| 914 |
+
@property
|
| 915 |
+
def func(self):
|
| 916 |
+
return lambda: self
|
| 917 |
+
|
| 918 |
+
def _latex(self, printer):
|
| 919 |
+
from sympy.printing.latex import latex_escape
|
| 920 |
+
return r'\texttt{{"{}"}}'.format(latex_escape(self.text))
|
| 921 |
+
|
| 922 |
+
class QuotedString(String):
|
| 923 |
+
""" Represents a string which should be printed with quotes. """
|
| 924 |
+
|
| 925 |
+
class Comment(String):
|
| 926 |
+
""" Represents a comment. """
|
| 927 |
+
|
| 928 |
+
class Node(Token):
|
| 929 |
+
""" Subclass of Token, carrying the attribute 'attrs' (Tuple)
|
| 930 |
+
|
| 931 |
+
Examples
|
| 932 |
+
========
|
| 933 |
+
|
| 934 |
+
>>> from sympy.codegen.ast import Node, value_const, pointer_const
|
| 935 |
+
>>> n1 = Node([value_const])
|
| 936 |
+
>>> n1.attr_params('value_const') # get the parameters of attribute (by name)
|
| 937 |
+
()
|
| 938 |
+
>>> from sympy.codegen.fnodes import dimension
|
| 939 |
+
>>> n2 = Node([value_const, dimension(5, 3)])
|
| 940 |
+
>>> n2.attr_params(value_const) # get the parameters of attribute (by Attribute instance)
|
| 941 |
+
()
|
| 942 |
+
>>> n2.attr_params('dimension') # get the parameters of attribute (by name)
|
| 943 |
+
(5, 3)
|
| 944 |
+
>>> n2.attr_params(pointer_const) is None
|
| 945 |
+
True
|
| 946 |
+
|
| 947 |
+
"""
|
| 948 |
+
|
| 949 |
+
__slots__: tuple[str, ...] = ('attrs',)
|
| 950 |
+
_fields = __slots__
|
| 951 |
+
|
| 952 |
+
defaults: dict[str, Any] = {'attrs': Tuple()}
|
| 953 |
+
|
| 954 |
+
_construct_attrs = staticmethod(_mk_Tuple)
|
| 955 |
+
|
| 956 |
+
def attr_params(self, looking_for):
|
| 957 |
+
""" Returns the parameters of the Attribute with name ``looking_for`` in self.attrs """
|
| 958 |
+
for attr in self.attrs:
|
| 959 |
+
if str(attr.name) == str(looking_for):
|
| 960 |
+
return attr.parameters
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
class Type(Token):
|
| 964 |
+
""" Represents a type.
|
| 965 |
+
|
| 966 |
+
Explanation
|
| 967 |
+
===========
|
| 968 |
+
|
| 969 |
+
The naming is a super-set of NumPy naming. Type has a classmethod
|
| 970 |
+
``from_expr`` which offer type deduction. It also has a method
|
| 971 |
+
``cast_check`` which casts the argument to its type, possibly raising an
|
| 972 |
+
exception if rounding error is not within tolerances, or if the value is not
|
| 973 |
+
representable by the underlying data type (e.g. unsigned integers).
|
| 974 |
+
|
| 975 |
+
Parameters
|
| 976 |
+
==========
|
| 977 |
+
|
| 978 |
+
name : str
|
| 979 |
+
Name of the type, e.g. ``object``, ``int16``, ``float16`` (where the latter two
|
| 980 |
+
would use the ``Type`` sub-classes ``IntType`` and ``FloatType`` respectively).
|
| 981 |
+
If a ``Type`` instance is given, the said instance is returned.
|
| 982 |
+
|
| 983 |
+
Examples
|
| 984 |
+
========
|
| 985 |
+
|
| 986 |
+
>>> from sympy.codegen.ast import Type
|
| 987 |
+
>>> t = Type.from_expr(42)
|
| 988 |
+
>>> t
|
| 989 |
+
integer
|
| 990 |
+
>>> print(repr(t))
|
| 991 |
+
IntBaseType(String('integer'))
|
| 992 |
+
>>> from sympy.codegen.ast import uint8
|
| 993 |
+
>>> uint8.cast_check(-1) # doctest: +ELLIPSIS
|
| 994 |
+
Traceback (most recent call last):
|
| 995 |
+
...
|
| 996 |
+
ValueError: Minimum value for data type bigger than new value.
|
| 997 |
+
>>> from sympy.codegen.ast import float32
|
| 998 |
+
>>> v6 = 0.123456
|
| 999 |
+
>>> float32.cast_check(v6)
|
| 1000 |
+
0.123456
|
| 1001 |
+
>>> v10 = 12345.67894
|
| 1002 |
+
>>> float32.cast_check(v10) # doctest: +ELLIPSIS
|
| 1003 |
+
Traceback (most recent call last):
|
| 1004 |
+
...
|
| 1005 |
+
ValueError: Casting gives a significantly different value.
|
| 1006 |
+
>>> boost_mp50 = Type('boost::multiprecision::cpp_dec_float_50')
|
| 1007 |
+
>>> from sympy import cxxcode
|
| 1008 |
+
>>> from sympy.codegen.ast import Declaration, Variable
|
| 1009 |
+
>>> cxxcode(Declaration(Variable('x', type=boost_mp50)))
|
| 1010 |
+
'boost::multiprecision::cpp_dec_float_50 x'
|
| 1011 |
+
|
| 1012 |
+
References
|
| 1013 |
+
==========
|
| 1014 |
+
|
| 1015 |
+
.. [1] https://numpy.org/doc/stable/user/basics.types.html
|
| 1016 |
+
|
| 1017 |
+
"""
|
| 1018 |
+
__slots__: tuple[str, ...] = ('name',)
|
| 1019 |
+
_fields = __slots__
|
| 1020 |
+
|
| 1021 |
+
_construct_name = String
|
| 1022 |
+
|
| 1023 |
+
def _sympystr(self, printer, *args, **kwargs):
|
| 1024 |
+
return str(self.name)
|
| 1025 |
+
|
| 1026 |
+
@classmethod
|
| 1027 |
+
def from_expr(cls, expr):
|
| 1028 |
+
""" Deduces type from an expression or a ``Symbol``.
|
| 1029 |
+
|
| 1030 |
+
Parameters
|
| 1031 |
+
==========
|
| 1032 |
+
|
| 1033 |
+
expr : number or SymPy object
|
| 1034 |
+
The type will be deduced from type or properties.
|
| 1035 |
+
|
| 1036 |
+
Examples
|
| 1037 |
+
========
|
| 1038 |
+
|
| 1039 |
+
>>> from sympy.codegen.ast import Type, integer, complex_
|
| 1040 |
+
>>> Type.from_expr(2) == integer
|
| 1041 |
+
True
|
| 1042 |
+
>>> from sympy import Symbol
|
| 1043 |
+
>>> Type.from_expr(Symbol('z', complex=True)) == complex_
|
| 1044 |
+
True
|
| 1045 |
+
>>> Type.from_expr(sum) # doctest: +ELLIPSIS
|
| 1046 |
+
Traceback (most recent call last):
|
| 1047 |
+
...
|
| 1048 |
+
ValueError: Could not deduce type from expr.
|
| 1049 |
+
|
| 1050 |
+
Raises
|
| 1051 |
+
======
|
| 1052 |
+
|
| 1053 |
+
ValueError when type deduction fails.
|
| 1054 |
+
|
| 1055 |
+
"""
|
| 1056 |
+
if isinstance(expr, (float, Float)):
|
| 1057 |
+
return real
|
| 1058 |
+
if isinstance(expr, (int, Integer)) or getattr(expr, 'is_integer', False):
|
| 1059 |
+
return integer
|
| 1060 |
+
if getattr(expr, 'is_real', False):
|
| 1061 |
+
return real
|
| 1062 |
+
if isinstance(expr, complex) or getattr(expr, 'is_complex', False):
|
| 1063 |
+
return complex_
|
| 1064 |
+
if isinstance(expr, bool) or getattr(expr, 'is_Relational', False):
|
| 1065 |
+
return bool_
|
| 1066 |
+
else:
|
| 1067 |
+
raise ValueError("Could not deduce type from expr.")
|
| 1068 |
+
|
| 1069 |
+
def _check(self, value):
|
| 1070 |
+
pass
|
| 1071 |
+
|
| 1072 |
+
def cast_check(self, value, rtol=None, atol=0, precision_targets=None):
|
| 1073 |
+
""" Casts a value to the data type of the instance.
|
| 1074 |
+
|
| 1075 |
+
Parameters
|
| 1076 |
+
==========
|
| 1077 |
+
|
| 1078 |
+
value : number
|
| 1079 |
+
rtol : floating point number
|
| 1080 |
+
Relative tolerance. (will be deduced if not given).
|
| 1081 |
+
atol : floating point number
|
| 1082 |
+
Absolute tolerance (in addition to ``rtol``).
|
| 1083 |
+
type_aliases : dict
|
| 1084 |
+
Maps substitutions for Type, e.g. {integer: int64, real: float32}
|
| 1085 |
+
|
| 1086 |
+
Examples
|
| 1087 |
+
========
|
| 1088 |
+
|
| 1089 |
+
>>> from sympy.codegen.ast import integer, float32, int8
|
| 1090 |
+
>>> integer.cast_check(3.0) == 3
|
| 1091 |
+
True
|
| 1092 |
+
>>> float32.cast_check(1e-40) # doctest: +ELLIPSIS
|
| 1093 |
+
Traceback (most recent call last):
|
| 1094 |
+
...
|
| 1095 |
+
ValueError: Minimum value for data type bigger than new value.
|
| 1096 |
+
>>> int8.cast_check(256) # doctest: +ELLIPSIS
|
| 1097 |
+
Traceback (most recent call last):
|
| 1098 |
+
...
|
| 1099 |
+
ValueError: Maximum value for data type smaller than new value.
|
| 1100 |
+
>>> v10 = 12345.67894
|
| 1101 |
+
>>> float32.cast_check(v10) # doctest: +ELLIPSIS
|
| 1102 |
+
Traceback (most recent call last):
|
| 1103 |
+
...
|
| 1104 |
+
ValueError: Casting gives a significantly different value.
|
| 1105 |
+
>>> from sympy.codegen.ast import float64
|
| 1106 |
+
>>> float64.cast_check(v10)
|
| 1107 |
+
12345.67894
|
| 1108 |
+
>>> from sympy import Float
|
| 1109 |
+
>>> v18 = Float('0.123456789012345646')
|
| 1110 |
+
>>> float64.cast_check(v18)
|
| 1111 |
+
Traceback (most recent call last):
|
| 1112 |
+
...
|
| 1113 |
+
ValueError: Casting gives a significantly different value.
|
| 1114 |
+
>>> from sympy.codegen.ast import float80
|
| 1115 |
+
>>> float80.cast_check(v18)
|
| 1116 |
+
0.123456789012345649
|
| 1117 |
+
|
| 1118 |
+
"""
|
| 1119 |
+
val = sympify(value)
|
| 1120 |
+
|
| 1121 |
+
ten = Integer(10)
|
| 1122 |
+
exp10 = getattr(self, 'decimal_dig', None)
|
| 1123 |
+
|
| 1124 |
+
if rtol is None:
|
| 1125 |
+
rtol = 1e-15 if exp10 is None else 2.0*ten**(-exp10)
|
| 1126 |
+
|
| 1127 |
+
def tol(num):
|
| 1128 |
+
return atol + rtol*abs(num)
|
| 1129 |
+
|
| 1130 |
+
new_val = self.cast_nocheck(value)
|
| 1131 |
+
self._check(new_val)
|
| 1132 |
+
|
| 1133 |
+
delta = new_val - val
|
| 1134 |
+
if abs(delta) > tol(val): # rounding, e.g. int(3.5) != 3.5
|
| 1135 |
+
raise ValueError("Casting gives a significantly different value.")
|
| 1136 |
+
|
| 1137 |
+
return new_val
|
| 1138 |
+
|
| 1139 |
+
def _latex(self, printer):
|
| 1140 |
+
from sympy.printing.latex import latex_escape
|
| 1141 |
+
type_name = latex_escape(self.__class__.__name__)
|
| 1142 |
+
name = latex_escape(self.name.text)
|
| 1143 |
+
return r"\text{{{}}}\left(\texttt{{{}}}\right)".format(type_name, name)
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
class IntBaseType(Type):
|
| 1147 |
+
""" Integer base type, contains no size information. """
|
| 1148 |
+
__slots__ = ()
|
| 1149 |
+
cast_nocheck = lambda self, i: Integer(int(i))
|
| 1150 |
+
|
| 1151 |
+
|
| 1152 |
+
class _SizedIntType(IntBaseType):
|
| 1153 |
+
__slots__ = ('nbits',)
|
| 1154 |
+
_fields = Type._fields + __slots__
|
| 1155 |
+
|
| 1156 |
+
_construct_nbits = Integer
|
| 1157 |
+
|
| 1158 |
+
def _check(self, value):
|
| 1159 |
+
if value < self.min:
|
| 1160 |
+
raise ValueError("Value is too small: %d < %d" % (value, self.min))
|
| 1161 |
+
if value > self.max:
|
| 1162 |
+
raise ValueError("Value is too big: %d > %d" % (value, self.max))
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
class SignedIntType(_SizedIntType):
|
| 1166 |
+
""" Represents a signed integer type. """
|
| 1167 |
+
__slots__ = ()
|
| 1168 |
+
@property
|
| 1169 |
+
def min(self):
|
| 1170 |
+
return -2**(self.nbits-1)
|
| 1171 |
+
|
| 1172 |
+
@property
|
| 1173 |
+
def max(self):
|
| 1174 |
+
return 2**(self.nbits-1) - 1
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
class UnsignedIntType(_SizedIntType):
|
| 1178 |
+
""" Represents an unsigned integer type. """
|
| 1179 |
+
__slots__ = ()
|
| 1180 |
+
@property
|
| 1181 |
+
def min(self):
|
| 1182 |
+
return 0
|
| 1183 |
+
|
| 1184 |
+
@property
|
| 1185 |
+
def max(self):
|
| 1186 |
+
return 2**self.nbits - 1
|
| 1187 |
+
|
| 1188 |
+
two = Integer(2)
|
| 1189 |
+
|
| 1190 |
+
class FloatBaseType(Type):
|
| 1191 |
+
""" Represents a floating point number type. """
|
| 1192 |
+
__slots__ = ()
|
| 1193 |
+
cast_nocheck = Float
|
| 1194 |
+
|
| 1195 |
+
class FloatType(FloatBaseType):
|
| 1196 |
+
""" Represents a floating point type with fixed bit width.
|
| 1197 |
+
|
| 1198 |
+
Base 2 & one sign bit is assumed.
|
| 1199 |
+
|
| 1200 |
+
Parameters
|
| 1201 |
+
==========
|
| 1202 |
+
|
| 1203 |
+
name : str
|
| 1204 |
+
Name of the type.
|
| 1205 |
+
nbits : integer
|
| 1206 |
+
Number of bits used (storage).
|
| 1207 |
+
nmant : integer
|
| 1208 |
+
Number of bits used to represent the mantissa.
|
| 1209 |
+
nexp : integer
|
| 1210 |
+
Number of bits used to represent the mantissa.
|
| 1211 |
+
|
| 1212 |
+
Examples
|
| 1213 |
+
========
|
| 1214 |
+
|
| 1215 |
+
>>> from sympy import S
|
| 1216 |
+
>>> from sympy.codegen.ast import FloatType
|
| 1217 |
+
>>> half_precision = FloatType('f16', nbits=16, nmant=10, nexp=5)
|
| 1218 |
+
>>> half_precision.max
|
| 1219 |
+
65504
|
| 1220 |
+
>>> half_precision.tiny == S(2)**-14
|
| 1221 |
+
True
|
| 1222 |
+
>>> half_precision.eps == S(2)**-10
|
| 1223 |
+
True
|
| 1224 |
+
>>> half_precision.dig == 3
|
| 1225 |
+
True
|
| 1226 |
+
>>> half_precision.decimal_dig == 5
|
| 1227 |
+
True
|
| 1228 |
+
>>> half_precision.cast_check(1.0)
|
| 1229 |
+
1.0
|
| 1230 |
+
>>> half_precision.cast_check(1e5) # doctest: +ELLIPSIS
|
| 1231 |
+
Traceback (most recent call last):
|
| 1232 |
+
...
|
| 1233 |
+
ValueError: Maximum value for data type smaller than new value.
|
| 1234 |
+
"""
|
| 1235 |
+
|
| 1236 |
+
__slots__ = ('nbits', 'nmant', 'nexp',)
|
| 1237 |
+
_fields = Type._fields + __slots__
|
| 1238 |
+
|
| 1239 |
+
_construct_nbits = _construct_nmant = _construct_nexp = Integer
|
| 1240 |
+
|
| 1241 |
+
|
| 1242 |
+
@property
|
| 1243 |
+
def max_exponent(self):
|
| 1244 |
+
""" The largest positive number n, such that 2**(n - 1) is a representable finite value. """
|
| 1245 |
+
# cf. C++'s ``std::numeric_limits::max_exponent``
|
| 1246 |
+
return two**(self.nexp - 1)
|
| 1247 |
+
|
| 1248 |
+
@property
|
| 1249 |
+
def min_exponent(self):
|
| 1250 |
+
""" The lowest negative number n, such that 2**(n - 1) is a valid normalized number. """
|
| 1251 |
+
# cf. C++'s ``std::numeric_limits::min_exponent``
|
| 1252 |
+
return 3 - self.max_exponent
|
| 1253 |
+
|
| 1254 |
+
@property
|
| 1255 |
+
def max(self):
|
| 1256 |
+
""" Maximum value representable. """
|
| 1257 |
+
return (1 - two**-(self.nmant+1))*two**self.max_exponent
|
| 1258 |
+
|
| 1259 |
+
@property
|
| 1260 |
+
def tiny(self):
|
| 1261 |
+
""" The minimum positive normalized value. """
|
| 1262 |
+
# See C macros: FLT_MIN, DBL_MIN, LDBL_MIN
|
| 1263 |
+
# or C++'s ``std::numeric_limits::min``
|
| 1264 |
+
# or numpy.finfo(dtype).tiny
|
| 1265 |
+
return two**(self.min_exponent - 1)
|
| 1266 |
+
|
| 1267 |
+
|
| 1268 |
+
@property
|
| 1269 |
+
def eps(self):
|
| 1270 |
+
""" Difference between 1.0 and the next representable value. """
|
| 1271 |
+
return two**(-self.nmant)
|
| 1272 |
+
|
| 1273 |
+
@property
|
| 1274 |
+
def dig(self):
|
| 1275 |
+
""" Number of decimal digits that are guaranteed to be preserved in text.
|
| 1276 |
+
|
| 1277 |
+
When converting text -> float -> text, you are guaranteed that at least ``dig``
|
| 1278 |
+
number of digits are preserved with respect to rounding or overflow.
|
| 1279 |
+
"""
|
| 1280 |
+
from sympy.functions import floor, log
|
| 1281 |
+
return floor(self.nmant * log(2)/log(10))
|
| 1282 |
+
|
| 1283 |
+
@property
|
| 1284 |
+
def decimal_dig(self):
|
| 1285 |
+
""" Number of digits needed to store & load without loss.
|
| 1286 |
+
|
| 1287 |
+
Explanation
|
| 1288 |
+
===========
|
| 1289 |
+
|
| 1290 |
+
Number of decimal digits needed to guarantee that two consecutive conversions
|
| 1291 |
+
(float -> text -> float) to be idempotent. This is useful when one do not want
|
| 1292 |
+
to loose precision due to rounding errors when storing a floating point value
|
| 1293 |
+
as text.
|
| 1294 |
+
"""
|
| 1295 |
+
from sympy.functions import ceiling, log
|
| 1296 |
+
return ceiling((self.nmant + 1) * log(2)/log(10) + 1)
|
| 1297 |
+
|
| 1298 |
+
def cast_nocheck(self, value):
|
| 1299 |
+
""" Casts without checking if out of bounds or subnormal. """
|
| 1300 |
+
if value == oo: # float(oo) or oo
|
| 1301 |
+
return float(oo)
|
| 1302 |
+
elif value == -oo: # float(-oo) or -oo
|
| 1303 |
+
return float(-oo)
|
| 1304 |
+
return Float(str(sympify(value).evalf(self.decimal_dig)), self.decimal_dig)
|
| 1305 |
+
|
| 1306 |
+
def _check(self, value):
|
| 1307 |
+
if value < -self.max:
|
| 1308 |
+
raise ValueError("Value is too small: %d < %d" % (value, -self.max))
|
| 1309 |
+
if value > self.max:
|
| 1310 |
+
raise ValueError("Value is too big: %d > %d" % (value, self.max))
|
| 1311 |
+
if abs(value) < self.tiny:
|
| 1312 |
+
raise ValueError("Smallest (absolute) value for data type bigger than new value.")
|
| 1313 |
+
|
| 1314 |
+
class ComplexBaseType(FloatBaseType):
|
| 1315 |
+
|
| 1316 |
+
__slots__ = ()
|
| 1317 |
+
|
| 1318 |
+
def cast_nocheck(self, value):
|
| 1319 |
+
""" Casts without checking if out of bounds or subnormal. """
|
| 1320 |
+
from sympy.functions import re, im
|
| 1321 |
+
return (
|
| 1322 |
+
super().cast_nocheck(re(value)) +
|
| 1323 |
+
super().cast_nocheck(im(value))*1j
|
| 1324 |
+
)
|
| 1325 |
+
|
| 1326 |
+
def _check(self, value):
|
| 1327 |
+
from sympy.functions import re, im
|
| 1328 |
+
super()._check(re(value))
|
| 1329 |
+
super()._check(im(value))
|
| 1330 |
+
|
| 1331 |
+
|
| 1332 |
+
class ComplexType(ComplexBaseType, FloatType):
|
| 1333 |
+
""" Represents a complex floating point number. """
|
| 1334 |
+
__slots__ = ()
|
| 1335 |
+
|
| 1336 |
+
|
| 1337 |
+
# NumPy types:
|
| 1338 |
+
intc = IntBaseType('intc')
|
| 1339 |
+
intp = IntBaseType('intp')
|
| 1340 |
+
int8 = SignedIntType('int8', 8)
|
| 1341 |
+
int16 = SignedIntType('int16', 16)
|
| 1342 |
+
int32 = SignedIntType('int32', 32)
|
| 1343 |
+
int64 = SignedIntType('int64', 64)
|
| 1344 |
+
uint8 = UnsignedIntType('uint8', 8)
|
| 1345 |
+
uint16 = UnsignedIntType('uint16', 16)
|
| 1346 |
+
uint32 = UnsignedIntType('uint32', 32)
|
| 1347 |
+
uint64 = UnsignedIntType('uint64', 64)
|
| 1348 |
+
float16 = FloatType('float16', 16, nexp=5, nmant=10) # IEEE 754 binary16, Half precision
|
| 1349 |
+
float32 = FloatType('float32', 32, nexp=8, nmant=23) # IEEE 754 binary32, Single precision
|
| 1350 |
+
float64 = FloatType('float64', 64, nexp=11, nmant=52) # IEEE 754 binary64, Double precision
|
| 1351 |
+
float80 = FloatType('float80', 80, nexp=15, nmant=63) # x86 extended precision (1 integer part bit), "long double"
|
| 1352 |
+
float128 = FloatType('float128', 128, nexp=15, nmant=112) # IEEE 754 binary128, Quadruple precision
|
| 1353 |
+
float256 = FloatType('float256', 256, nexp=19, nmant=236) # IEEE 754 binary256, Octuple precision
|
| 1354 |
+
|
| 1355 |
+
complex64 = ComplexType('complex64', nbits=64, **float32.kwargs(exclude=('name', 'nbits')))
|
| 1356 |
+
complex128 = ComplexType('complex128', nbits=128, **float64.kwargs(exclude=('name', 'nbits')))
|
| 1357 |
+
|
| 1358 |
+
# Generic types (precision may be chosen by code printers):
|
| 1359 |
+
untyped = Type('untyped')
|
| 1360 |
+
real = FloatBaseType('real')
|
| 1361 |
+
integer = IntBaseType('integer')
|
| 1362 |
+
complex_ = ComplexBaseType('complex')
|
| 1363 |
+
bool_ = Type('bool')
|
| 1364 |
+
|
| 1365 |
+
|
| 1366 |
+
class Attribute(Token):
|
| 1367 |
+
""" Attribute (possibly parametrized)
|
| 1368 |
+
|
| 1369 |
+
For use with :class:`sympy.codegen.ast.Node` (which takes instances of
|
| 1370 |
+
``Attribute`` as ``attrs``).
|
| 1371 |
+
|
| 1372 |
+
Parameters
|
| 1373 |
+
==========
|
| 1374 |
+
|
| 1375 |
+
name : str
|
| 1376 |
+
parameters : Tuple
|
| 1377 |
+
|
| 1378 |
+
Examples
|
| 1379 |
+
========
|
| 1380 |
+
|
| 1381 |
+
>>> from sympy.codegen.ast import Attribute
|
| 1382 |
+
>>> volatile = Attribute('volatile')
|
| 1383 |
+
>>> volatile
|
| 1384 |
+
volatile
|
| 1385 |
+
>>> print(repr(volatile))
|
| 1386 |
+
Attribute(String('volatile'))
|
| 1387 |
+
>>> a = Attribute('foo', [1, 2, 3])
|
| 1388 |
+
>>> a
|
| 1389 |
+
foo(1, 2, 3)
|
| 1390 |
+
>>> a.parameters == (1, 2, 3)
|
| 1391 |
+
True
|
| 1392 |
+
"""
|
| 1393 |
+
__slots__ = _fields = ('name', 'parameters')
|
| 1394 |
+
defaults = {'parameters': Tuple()}
|
| 1395 |
+
|
| 1396 |
+
_construct_name = String
|
| 1397 |
+
_construct_parameters = staticmethod(_mk_Tuple)
|
| 1398 |
+
|
| 1399 |
+
def _sympystr(self, printer, *args, **kwargs):
|
| 1400 |
+
result = str(self.name)
|
| 1401 |
+
if self.parameters:
|
| 1402 |
+
result += '(%s)' % ', '.join((printer._print(
|
| 1403 |
+
arg, *args, **kwargs) for arg in self.parameters))
|
| 1404 |
+
return result
|
| 1405 |
+
|
| 1406 |
+
value_const = Attribute('value_const')
|
| 1407 |
+
pointer_const = Attribute('pointer_const')
|
| 1408 |
+
|
| 1409 |
+
|
| 1410 |
+
class Variable(Node):
|
| 1411 |
+
""" Represents a variable.
|
| 1412 |
+
|
| 1413 |
+
Parameters
|
| 1414 |
+
==========
|
| 1415 |
+
|
| 1416 |
+
symbol : Symbol
|
| 1417 |
+
type : Type (optional)
|
| 1418 |
+
Type of the variable.
|
| 1419 |
+
attrs : iterable of Attribute instances
|
| 1420 |
+
Will be stored as a Tuple.
|
| 1421 |
+
|
| 1422 |
+
Examples
|
| 1423 |
+
========
|
| 1424 |
+
|
| 1425 |
+
>>> from sympy import Symbol
|
| 1426 |
+
>>> from sympy.codegen.ast import Variable, float32, integer
|
| 1427 |
+
>>> x = Symbol('x')
|
| 1428 |
+
>>> v = Variable(x, type=float32)
|
| 1429 |
+
>>> v.attrs
|
| 1430 |
+
()
|
| 1431 |
+
>>> v == Variable('x')
|
| 1432 |
+
False
|
| 1433 |
+
>>> v == Variable('x', type=float32)
|
| 1434 |
+
True
|
| 1435 |
+
>>> v
|
| 1436 |
+
Variable(x, type=float32)
|
| 1437 |
+
|
| 1438 |
+
One may also construct a ``Variable`` instance with the type deduced from
|
| 1439 |
+
assumptions about the symbol using the ``deduced`` classmethod:
|
| 1440 |
+
|
| 1441 |
+
>>> i = Symbol('i', integer=True)
|
| 1442 |
+
>>> v = Variable.deduced(i)
|
| 1443 |
+
>>> v.type == integer
|
| 1444 |
+
True
|
| 1445 |
+
>>> v == Variable('i')
|
| 1446 |
+
False
|
| 1447 |
+
>>> from sympy.codegen.ast import value_const
|
| 1448 |
+
>>> value_const in v.attrs
|
| 1449 |
+
False
|
| 1450 |
+
>>> w = Variable('w', attrs=[value_const])
|
| 1451 |
+
>>> w
|
| 1452 |
+
Variable(w, attrs=(value_const,))
|
| 1453 |
+
>>> value_const in w.attrs
|
| 1454 |
+
True
|
| 1455 |
+
>>> w.as_Declaration(value=42)
|
| 1456 |
+
Declaration(Variable(w, value=42, attrs=(value_const,)))
|
| 1457 |
+
|
| 1458 |
+
"""
|
| 1459 |
+
|
| 1460 |
+
__slots__ = ('symbol', 'type', 'value')
|
| 1461 |
+
_fields = __slots__ + Node._fields
|
| 1462 |
+
|
| 1463 |
+
defaults = Node.defaults.copy()
|
| 1464 |
+
defaults.update({'type': untyped, 'value': none})
|
| 1465 |
+
|
| 1466 |
+
_construct_symbol = staticmethod(sympify)
|
| 1467 |
+
_construct_value = staticmethod(sympify)
|
| 1468 |
+
|
| 1469 |
+
@classmethod
|
| 1470 |
+
def deduced(cls, symbol, value=None, attrs=Tuple(), cast_check=True):
|
| 1471 |
+
""" Alt. constructor with type deduction from ``Type.from_expr``.
|
| 1472 |
+
|
| 1473 |
+
Deduces type primarily from ``symbol``, secondarily from ``value``.
|
| 1474 |
+
|
| 1475 |
+
Parameters
|
| 1476 |
+
==========
|
| 1477 |
+
|
| 1478 |
+
symbol : Symbol
|
| 1479 |
+
value : expr
|
| 1480 |
+
(optional) value of the variable.
|
| 1481 |
+
attrs : iterable of Attribute instances
|
| 1482 |
+
cast_check : bool
|
| 1483 |
+
Whether to apply ``Type.cast_check`` on ``value``.
|
| 1484 |
+
|
| 1485 |
+
Examples
|
| 1486 |
+
========
|
| 1487 |
+
|
| 1488 |
+
>>> from sympy import Symbol
|
| 1489 |
+
>>> from sympy.codegen.ast import Variable, complex_
|
| 1490 |
+
>>> n = Symbol('n', integer=True)
|
| 1491 |
+
>>> str(Variable.deduced(n).type)
|
| 1492 |
+
'integer'
|
| 1493 |
+
>>> x = Symbol('x', real=True)
|
| 1494 |
+
>>> v = Variable.deduced(x)
|
| 1495 |
+
>>> v.type
|
| 1496 |
+
real
|
| 1497 |
+
>>> z = Symbol('z', complex=True)
|
| 1498 |
+
>>> Variable.deduced(z).type == complex_
|
| 1499 |
+
True
|
| 1500 |
+
|
| 1501 |
+
"""
|
| 1502 |
+
if isinstance(symbol, Variable):
|
| 1503 |
+
return symbol
|
| 1504 |
+
|
| 1505 |
+
try:
|
| 1506 |
+
type_ = Type.from_expr(symbol)
|
| 1507 |
+
except ValueError:
|
| 1508 |
+
type_ = Type.from_expr(value)
|
| 1509 |
+
|
| 1510 |
+
if value is not None and cast_check:
|
| 1511 |
+
value = type_.cast_check(value)
|
| 1512 |
+
return cls(symbol, type=type_, value=value, attrs=attrs)
|
| 1513 |
+
|
| 1514 |
+
def as_Declaration(self, **kwargs):
|
| 1515 |
+
""" Convenience method for creating a Declaration instance.
|
| 1516 |
+
|
| 1517 |
+
Explanation
|
| 1518 |
+
===========
|
| 1519 |
+
|
| 1520 |
+
If the variable of the Declaration need to wrap a modified
|
| 1521 |
+
variable keyword arguments may be passed (overriding e.g.
|
| 1522 |
+
the ``value`` of the Variable instance).
|
| 1523 |
+
|
| 1524 |
+
Examples
|
| 1525 |
+
========
|
| 1526 |
+
|
| 1527 |
+
>>> from sympy.codegen.ast import Variable, NoneToken
|
| 1528 |
+
>>> x = Variable('x')
|
| 1529 |
+
>>> decl1 = x.as_Declaration()
|
| 1530 |
+
>>> # value is special NoneToken() which must be tested with == operator
|
| 1531 |
+
>>> decl1.variable.value is None # won't work
|
| 1532 |
+
False
|
| 1533 |
+
>>> decl1.variable.value == None # not PEP-8 compliant
|
| 1534 |
+
True
|
| 1535 |
+
>>> decl1.variable.value == NoneToken() # OK
|
| 1536 |
+
True
|
| 1537 |
+
>>> decl2 = x.as_Declaration(value=42.0)
|
| 1538 |
+
>>> decl2.variable.value == 42.0
|
| 1539 |
+
True
|
| 1540 |
+
|
| 1541 |
+
"""
|
| 1542 |
+
kw = self.kwargs()
|
| 1543 |
+
kw.update(kwargs)
|
| 1544 |
+
return Declaration(self.func(**kw))
|
| 1545 |
+
|
| 1546 |
+
def _relation(self, rhs, op):
|
| 1547 |
+
try:
|
| 1548 |
+
rhs = _sympify(rhs)
|
| 1549 |
+
except SympifyError:
|
| 1550 |
+
raise TypeError("Invalid comparison %s < %s" % (self, rhs))
|
| 1551 |
+
return op(self, rhs, evaluate=False)
|
| 1552 |
+
|
| 1553 |
+
__lt__ = lambda self, other: self._relation(other, Lt)
|
| 1554 |
+
__le__ = lambda self, other: self._relation(other, Le)
|
| 1555 |
+
__ge__ = lambda self, other: self._relation(other, Ge)
|
| 1556 |
+
__gt__ = lambda self, other: self._relation(other, Gt)
|
| 1557 |
+
|
| 1558 |
+
class Pointer(Variable):
|
| 1559 |
+
""" Represents a pointer. See ``Variable``.
|
| 1560 |
+
|
| 1561 |
+
Examples
|
| 1562 |
+
========
|
| 1563 |
+
|
| 1564 |
+
Can create instances of ``Element``:
|
| 1565 |
+
|
| 1566 |
+
>>> from sympy import Symbol
|
| 1567 |
+
>>> from sympy.codegen.ast import Pointer
|
| 1568 |
+
>>> i = Symbol('i', integer=True)
|
| 1569 |
+
>>> p = Pointer('x')
|
| 1570 |
+
>>> p[i+1]
|
| 1571 |
+
Element(x, indices=(i + 1,))
|
| 1572 |
+
|
| 1573 |
+
"""
|
| 1574 |
+
__slots__ = ()
|
| 1575 |
+
|
| 1576 |
+
def __getitem__(self, key):
|
| 1577 |
+
try:
|
| 1578 |
+
return Element(self.symbol, key)
|
| 1579 |
+
except TypeError:
|
| 1580 |
+
return Element(self.symbol, (key,))
|
| 1581 |
+
|
| 1582 |
+
|
| 1583 |
+
class Element(Token):
|
| 1584 |
+
""" Element in (a possibly N-dimensional) array.
|
| 1585 |
+
|
| 1586 |
+
Examples
|
| 1587 |
+
========
|
| 1588 |
+
|
| 1589 |
+
>>> from sympy.codegen.ast import Element
|
| 1590 |
+
>>> elem = Element('x', 'ijk')
|
| 1591 |
+
>>> elem.symbol.name == 'x'
|
| 1592 |
+
True
|
| 1593 |
+
>>> elem.indices
|
| 1594 |
+
(i, j, k)
|
| 1595 |
+
>>> from sympy import ccode
|
| 1596 |
+
>>> ccode(elem)
|
| 1597 |
+
'x[i][j][k]'
|
| 1598 |
+
>>> ccode(Element('x', 'ijk', strides='lmn', offset='o'))
|
| 1599 |
+
'x[i*l + j*m + k*n + o]'
|
| 1600 |
+
|
| 1601 |
+
"""
|
| 1602 |
+
__slots__ = _fields = ('symbol', 'indices', 'strides', 'offset')
|
| 1603 |
+
defaults = {'strides': none, 'offset': none}
|
| 1604 |
+
_construct_symbol = staticmethod(sympify)
|
| 1605 |
+
_construct_indices = staticmethod(lambda arg: Tuple(*arg))
|
| 1606 |
+
_construct_strides = staticmethod(lambda arg: Tuple(*arg))
|
| 1607 |
+
_construct_offset = staticmethod(sympify)
|
| 1608 |
+
|
| 1609 |
+
|
| 1610 |
+
class Declaration(Token):
|
| 1611 |
+
""" Represents a variable declaration
|
| 1612 |
+
|
| 1613 |
+
Parameters
|
| 1614 |
+
==========
|
| 1615 |
+
|
| 1616 |
+
variable : Variable
|
| 1617 |
+
|
| 1618 |
+
Examples
|
| 1619 |
+
========
|
| 1620 |
+
|
| 1621 |
+
>>> from sympy.codegen.ast import Declaration, NoneToken, untyped
|
| 1622 |
+
>>> z = Declaration('z')
|
| 1623 |
+
>>> z.variable.type == untyped
|
| 1624 |
+
True
|
| 1625 |
+
>>> # value is special NoneToken() which must be tested with == operator
|
| 1626 |
+
>>> z.variable.value is None # won't work
|
| 1627 |
+
False
|
| 1628 |
+
>>> z.variable.value == None # not PEP-8 compliant
|
| 1629 |
+
True
|
| 1630 |
+
>>> z.variable.value == NoneToken() # OK
|
| 1631 |
+
True
|
| 1632 |
+
"""
|
| 1633 |
+
__slots__ = _fields = ('variable',)
|
| 1634 |
+
_construct_variable = Variable
|
| 1635 |
+
|
| 1636 |
+
|
| 1637 |
+
class While(Token):
|
| 1638 |
+
""" Represents a 'for-loop' in the code.
|
| 1639 |
+
|
| 1640 |
+
Expressions are of the form:
|
| 1641 |
+
"while condition:
|
| 1642 |
+
body..."
|
| 1643 |
+
|
| 1644 |
+
Parameters
|
| 1645 |
+
==========
|
| 1646 |
+
|
| 1647 |
+
condition : expression convertible to Boolean
|
| 1648 |
+
body : CodeBlock or iterable
|
| 1649 |
+
When passed an iterable it is used to instantiate a CodeBlock.
|
| 1650 |
+
|
| 1651 |
+
Examples
|
| 1652 |
+
========
|
| 1653 |
+
|
| 1654 |
+
>>> from sympy import symbols, Gt, Abs
|
| 1655 |
+
>>> from sympy.codegen import aug_assign, Assignment, While
|
| 1656 |
+
>>> x, dx = symbols('x dx')
|
| 1657 |
+
>>> expr = 1 - x**2
|
| 1658 |
+
>>> whl = While(Gt(Abs(dx), 1e-9), [
|
| 1659 |
+
... Assignment(dx, -expr/expr.diff(x)),
|
| 1660 |
+
... aug_assign(x, '+', dx)
|
| 1661 |
+
... ])
|
| 1662 |
+
|
| 1663 |
+
"""
|
| 1664 |
+
__slots__ = _fields = ('condition', 'body')
|
| 1665 |
+
_construct_condition = staticmethod(lambda cond: _sympify(cond))
|
| 1666 |
+
|
| 1667 |
+
@classmethod
|
| 1668 |
+
def _construct_body(cls, itr):
|
| 1669 |
+
if isinstance(itr, CodeBlock):
|
| 1670 |
+
return itr
|
| 1671 |
+
else:
|
| 1672 |
+
return CodeBlock(*itr)
|
| 1673 |
+
|
| 1674 |
+
|
| 1675 |
+
class Scope(Token):
|
| 1676 |
+
""" Represents a scope in the code.
|
| 1677 |
+
|
| 1678 |
+
Parameters
|
| 1679 |
+
==========
|
| 1680 |
+
|
| 1681 |
+
body : CodeBlock or iterable
|
| 1682 |
+
When passed an iterable it is used to instantiate a CodeBlock.
|
| 1683 |
+
|
| 1684 |
+
"""
|
| 1685 |
+
__slots__ = _fields = ('body',)
|
| 1686 |
+
|
| 1687 |
+
@classmethod
|
| 1688 |
+
def _construct_body(cls, itr):
|
| 1689 |
+
if isinstance(itr, CodeBlock):
|
| 1690 |
+
return itr
|
| 1691 |
+
else:
|
| 1692 |
+
return CodeBlock(*itr)
|
| 1693 |
+
|
| 1694 |
+
|
| 1695 |
+
class Stream(Token):
|
| 1696 |
+
""" Represents a stream.
|
| 1697 |
+
|
| 1698 |
+
There are two predefined Stream instances ``stdout`` & ``stderr``.
|
| 1699 |
+
|
| 1700 |
+
Parameters
|
| 1701 |
+
==========
|
| 1702 |
+
|
| 1703 |
+
name : str
|
| 1704 |
+
|
| 1705 |
+
Examples
|
| 1706 |
+
========
|
| 1707 |
+
|
| 1708 |
+
>>> from sympy import pycode, Symbol
|
| 1709 |
+
>>> from sympy.codegen.ast import Print, stderr, QuotedString
|
| 1710 |
+
>>> print(pycode(Print(['x'], file=stderr)))
|
| 1711 |
+
print(x, file=sys.stderr)
|
| 1712 |
+
>>> x = Symbol('x')
|
| 1713 |
+
>>> print(pycode(Print([QuotedString('x')], file=stderr))) # print literally "x"
|
| 1714 |
+
print("x", file=sys.stderr)
|
| 1715 |
+
|
| 1716 |
+
"""
|
| 1717 |
+
__slots__ = _fields = ('name',)
|
| 1718 |
+
_construct_name = String
|
| 1719 |
+
|
| 1720 |
+
stdout = Stream('stdout')
|
| 1721 |
+
stderr = Stream('stderr')
|
| 1722 |
+
|
| 1723 |
+
|
| 1724 |
+
class Print(Token):
|
| 1725 |
+
r""" Represents print command in the code.
|
| 1726 |
+
|
| 1727 |
+
Parameters
|
| 1728 |
+
==========
|
| 1729 |
+
|
| 1730 |
+
formatstring : str
|
| 1731 |
+
*args : Basic instances (or convertible to such through sympify)
|
| 1732 |
+
|
| 1733 |
+
Examples
|
| 1734 |
+
========
|
| 1735 |
+
|
| 1736 |
+
>>> from sympy.codegen.ast import Print
|
| 1737 |
+
>>> from sympy import pycode
|
| 1738 |
+
>>> print(pycode(Print('x y'.split(), "coordinate: %12.5g %12.5g\\n")))
|
| 1739 |
+
print("coordinate: %12.5g %12.5g\n" % (x, y), end="")
|
| 1740 |
+
|
| 1741 |
+
"""
|
| 1742 |
+
|
| 1743 |
+
__slots__ = _fields = ('print_args', 'format_string', 'file')
|
| 1744 |
+
defaults = {'format_string': none, 'file': none}
|
| 1745 |
+
|
| 1746 |
+
_construct_print_args = staticmethod(_mk_Tuple)
|
| 1747 |
+
_construct_format_string = QuotedString
|
| 1748 |
+
_construct_file = Stream
|
| 1749 |
+
|
| 1750 |
+
|
| 1751 |
+
class FunctionPrototype(Node):
|
| 1752 |
+
""" Represents a function prototype
|
| 1753 |
+
|
| 1754 |
+
Allows the user to generate forward declaration in e.g. C/C++.
|
| 1755 |
+
|
| 1756 |
+
Parameters
|
| 1757 |
+
==========
|
| 1758 |
+
|
| 1759 |
+
return_type : Type
|
| 1760 |
+
name : str
|
| 1761 |
+
parameters: iterable of Variable instances
|
| 1762 |
+
attrs : iterable of Attribute instances
|
| 1763 |
+
|
| 1764 |
+
Examples
|
| 1765 |
+
========
|
| 1766 |
+
|
| 1767 |
+
>>> from sympy import ccode, symbols
|
| 1768 |
+
>>> from sympy.codegen.ast import real, FunctionPrototype
|
| 1769 |
+
>>> x, y = symbols('x y', real=True)
|
| 1770 |
+
>>> fp = FunctionPrototype(real, 'foo', [x, y])
|
| 1771 |
+
>>> ccode(fp)
|
| 1772 |
+
'double foo(double x, double y)'
|
| 1773 |
+
|
| 1774 |
+
"""
|
| 1775 |
+
|
| 1776 |
+
__slots__ = ('return_type', 'name', 'parameters')
|
| 1777 |
+
_fields: tuple[str, ...] = __slots__ + Node._fields
|
| 1778 |
+
|
| 1779 |
+
_construct_return_type = Type
|
| 1780 |
+
_construct_name = String
|
| 1781 |
+
|
| 1782 |
+
@staticmethod
|
| 1783 |
+
def _construct_parameters(args):
|
| 1784 |
+
def _var(arg):
|
| 1785 |
+
if isinstance(arg, Declaration):
|
| 1786 |
+
return arg.variable
|
| 1787 |
+
elif isinstance(arg, Variable):
|
| 1788 |
+
return arg
|
| 1789 |
+
else:
|
| 1790 |
+
return Variable.deduced(arg)
|
| 1791 |
+
return Tuple(*map(_var, args))
|
| 1792 |
+
|
| 1793 |
+
@classmethod
|
| 1794 |
+
def from_FunctionDefinition(cls, func_def):
|
| 1795 |
+
if not isinstance(func_def, FunctionDefinition):
|
| 1796 |
+
raise TypeError("func_def is not an instance of FunctionDefinition")
|
| 1797 |
+
return cls(**func_def.kwargs(exclude=('body',)))
|
| 1798 |
+
|
| 1799 |
+
|
| 1800 |
+
class FunctionDefinition(FunctionPrototype):
|
| 1801 |
+
""" Represents a function definition in the code.
|
| 1802 |
+
|
| 1803 |
+
Parameters
|
| 1804 |
+
==========
|
| 1805 |
+
|
| 1806 |
+
return_type : Type
|
| 1807 |
+
name : str
|
| 1808 |
+
parameters: iterable of Variable instances
|
| 1809 |
+
body : CodeBlock or iterable
|
| 1810 |
+
attrs : iterable of Attribute instances
|
| 1811 |
+
|
| 1812 |
+
Examples
|
| 1813 |
+
========
|
| 1814 |
+
|
| 1815 |
+
>>> from sympy import ccode, symbols
|
| 1816 |
+
>>> from sympy.codegen.ast import real, FunctionPrototype
|
| 1817 |
+
>>> x, y = symbols('x y', real=True)
|
| 1818 |
+
>>> fp = FunctionPrototype(real, 'foo', [x, y])
|
| 1819 |
+
>>> ccode(fp)
|
| 1820 |
+
'double foo(double x, double y)'
|
| 1821 |
+
>>> from sympy.codegen.ast import FunctionDefinition, Return
|
| 1822 |
+
>>> body = [Return(x*y)]
|
| 1823 |
+
>>> fd = FunctionDefinition.from_FunctionPrototype(fp, body)
|
| 1824 |
+
>>> print(ccode(fd))
|
| 1825 |
+
double foo(double x, double y){
|
| 1826 |
+
return x*y;
|
| 1827 |
+
}
|
| 1828 |
+
"""
|
| 1829 |
+
|
| 1830 |
+
__slots__ = ('body', )
|
| 1831 |
+
_fields = FunctionPrototype._fields[:-1] + __slots__ + Node._fields
|
| 1832 |
+
|
| 1833 |
+
@classmethod
|
| 1834 |
+
def _construct_body(cls, itr):
|
| 1835 |
+
if isinstance(itr, CodeBlock):
|
| 1836 |
+
return itr
|
| 1837 |
+
else:
|
| 1838 |
+
return CodeBlock(*itr)
|
| 1839 |
+
|
| 1840 |
+
@classmethod
|
| 1841 |
+
def from_FunctionPrototype(cls, func_proto, body):
|
| 1842 |
+
if not isinstance(func_proto, FunctionPrototype):
|
| 1843 |
+
raise TypeError("func_proto is not an instance of FunctionPrototype")
|
| 1844 |
+
return cls(body=body, **func_proto.kwargs())
|
| 1845 |
+
|
| 1846 |
+
|
| 1847 |
+
class Return(Token):
|
| 1848 |
+
""" Represents a return command in the code.
|
| 1849 |
+
|
| 1850 |
+
Parameters
|
| 1851 |
+
==========
|
| 1852 |
+
|
| 1853 |
+
return : Basic
|
| 1854 |
+
|
| 1855 |
+
Examples
|
| 1856 |
+
========
|
| 1857 |
+
|
| 1858 |
+
>>> from sympy.codegen.ast import Return
|
| 1859 |
+
>>> from sympy.printing.pycode import pycode
|
| 1860 |
+
>>> from sympy import Symbol
|
| 1861 |
+
>>> x = Symbol('x')
|
| 1862 |
+
>>> print(pycode(Return(x)))
|
| 1863 |
+
return x
|
| 1864 |
+
|
| 1865 |
+
"""
|
| 1866 |
+
__slots__ = _fields = ('return',)
|
| 1867 |
+
_construct_return=staticmethod(_sympify)
|
| 1868 |
+
|
| 1869 |
+
|
| 1870 |
+
class FunctionCall(Token, Expr):
|
| 1871 |
+
""" Represents a call to a function in the code.
|
| 1872 |
+
|
| 1873 |
+
Parameters
|
| 1874 |
+
==========
|
| 1875 |
+
|
| 1876 |
+
name : str
|
| 1877 |
+
function_args : Tuple
|
| 1878 |
+
|
| 1879 |
+
Examples
|
| 1880 |
+
========
|
| 1881 |
+
|
| 1882 |
+
>>> from sympy.codegen.ast import FunctionCall
|
| 1883 |
+
>>> from sympy import pycode
|
| 1884 |
+
>>> fcall = FunctionCall('foo', 'bar baz'.split())
|
| 1885 |
+
>>> print(pycode(fcall))
|
| 1886 |
+
foo(bar, baz)
|
| 1887 |
+
|
| 1888 |
+
"""
|
| 1889 |
+
__slots__ = _fields = ('name', 'function_args')
|
| 1890 |
+
|
| 1891 |
+
_construct_name = String
|
| 1892 |
+
_construct_function_args = staticmethod(lambda args: Tuple(*args))
|
| 1893 |
+
|
| 1894 |
+
|
| 1895 |
+
class Raise(Token):
|
| 1896 |
+
""" Prints as 'raise ...' in Python, 'throw ...' in C++"""
|
| 1897 |
+
__slots__ = _fields = ('exception',)
|
| 1898 |
+
|
| 1899 |
+
|
| 1900 |
+
class RuntimeError_(Token):
|
| 1901 |
+
""" Represents 'std::runtime_error' in C++ and 'RuntimeError' in Python.
|
| 1902 |
+
|
| 1903 |
+
Note that the latter is uncommon, and you might want to use e.g. ValueError.
|
| 1904 |
+
"""
|
| 1905 |
+
__slots__ = _fields = ('message',)
|
| 1906 |
+
_construct_message = String
|
.venv/lib/python3.12/site-packages/sympy/codegen/cfunctions.py
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module contains SymPy functions mathcin corresponding to special math functions in the
|
| 3 |
+
C standard library (since C99, also available in C++11).
|
| 4 |
+
|
| 5 |
+
The functions defined in this module allows the user to express functions such as ``expm1``
|
| 6 |
+
as a SymPy function for symbolic manipulation.
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
from sympy.core.function import ArgumentIndexError, Function
|
| 10 |
+
from sympy.core.numbers import Rational
|
| 11 |
+
from sympy.core.power import Pow
|
| 12 |
+
from sympy.core.singleton import S
|
| 13 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 14 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 15 |
+
from sympy.logic.boolalg import BooleanFunction, true, false
|
| 16 |
+
|
| 17 |
+
def _expm1(x):
|
| 18 |
+
return exp(x) - S.One
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class expm1(Function):
|
| 22 |
+
"""
|
| 23 |
+
Represents the exponential function minus one.
|
| 24 |
+
|
| 25 |
+
Explanation
|
| 26 |
+
===========
|
| 27 |
+
|
| 28 |
+
The benefit of using ``expm1(x)`` over ``exp(x) - 1``
|
| 29 |
+
is that the latter is prone to cancellation under finite precision
|
| 30 |
+
arithmetic when x is close to zero.
|
| 31 |
+
|
| 32 |
+
Examples
|
| 33 |
+
========
|
| 34 |
+
|
| 35 |
+
>>> from sympy.abc import x
|
| 36 |
+
>>> from sympy.codegen.cfunctions import expm1
|
| 37 |
+
>>> '%.0e' % expm1(1e-99).evalf()
|
| 38 |
+
'1e-99'
|
| 39 |
+
>>> from math import exp
|
| 40 |
+
>>> exp(1e-99) - 1
|
| 41 |
+
0.0
|
| 42 |
+
>>> expm1(x).diff(x)
|
| 43 |
+
exp(x)
|
| 44 |
+
|
| 45 |
+
See Also
|
| 46 |
+
========
|
| 47 |
+
|
| 48 |
+
log1p
|
| 49 |
+
"""
|
| 50 |
+
nargs = 1
|
| 51 |
+
|
| 52 |
+
def fdiff(self, argindex=1):
|
| 53 |
+
"""
|
| 54 |
+
Returns the first derivative of this function.
|
| 55 |
+
"""
|
| 56 |
+
if argindex == 1:
|
| 57 |
+
return exp(*self.args)
|
| 58 |
+
else:
|
| 59 |
+
raise ArgumentIndexError(self, argindex)
|
| 60 |
+
|
| 61 |
+
def _eval_expand_func(self, **hints):
|
| 62 |
+
return _expm1(*self.args)
|
| 63 |
+
|
| 64 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
| 65 |
+
return exp(arg) - S.One
|
| 66 |
+
|
| 67 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_exp
|
| 68 |
+
|
| 69 |
+
@classmethod
|
| 70 |
+
def eval(cls, arg):
|
| 71 |
+
exp_arg = exp.eval(arg)
|
| 72 |
+
if exp_arg is not None:
|
| 73 |
+
return exp_arg - S.One
|
| 74 |
+
|
| 75 |
+
def _eval_is_real(self):
|
| 76 |
+
return self.args[0].is_real
|
| 77 |
+
|
| 78 |
+
def _eval_is_finite(self):
|
| 79 |
+
return self.args[0].is_finite
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _log1p(x):
|
| 83 |
+
return log(x + S.One)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class log1p(Function):
|
| 87 |
+
"""
|
| 88 |
+
Represents the natural logarithm of a number plus one.
|
| 89 |
+
|
| 90 |
+
Explanation
|
| 91 |
+
===========
|
| 92 |
+
|
| 93 |
+
The benefit of using ``log1p(x)`` over ``log(x + 1)``
|
| 94 |
+
is that the latter is prone to cancellation under finite precision
|
| 95 |
+
arithmetic when x is close to zero.
|
| 96 |
+
|
| 97 |
+
Examples
|
| 98 |
+
========
|
| 99 |
+
|
| 100 |
+
>>> from sympy.abc import x
|
| 101 |
+
>>> from sympy.codegen.cfunctions import log1p
|
| 102 |
+
>>> from sympy import expand_log
|
| 103 |
+
>>> '%.0e' % expand_log(log1p(1e-99)).evalf()
|
| 104 |
+
'1e-99'
|
| 105 |
+
>>> from math import log
|
| 106 |
+
>>> log(1 + 1e-99)
|
| 107 |
+
0.0
|
| 108 |
+
>>> log1p(x).diff(x)
|
| 109 |
+
1/(x + 1)
|
| 110 |
+
|
| 111 |
+
See Also
|
| 112 |
+
========
|
| 113 |
+
|
| 114 |
+
expm1
|
| 115 |
+
"""
|
| 116 |
+
nargs = 1
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def fdiff(self, argindex=1):
|
| 120 |
+
"""
|
| 121 |
+
Returns the first derivative of this function.
|
| 122 |
+
"""
|
| 123 |
+
if argindex == 1:
|
| 124 |
+
return S.One/(self.args[0] + S.One)
|
| 125 |
+
else:
|
| 126 |
+
raise ArgumentIndexError(self, argindex)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _eval_expand_func(self, **hints):
|
| 130 |
+
return _log1p(*self.args)
|
| 131 |
+
|
| 132 |
+
def _eval_rewrite_as_log(self, arg, **kwargs):
|
| 133 |
+
return _log1p(arg)
|
| 134 |
+
|
| 135 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 136 |
+
|
| 137 |
+
@classmethod
|
| 138 |
+
def eval(cls, arg):
|
| 139 |
+
if arg.is_Rational:
|
| 140 |
+
return log(arg + S.One)
|
| 141 |
+
elif not arg.is_Float: # not safe to add 1 to Float
|
| 142 |
+
return log.eval(arg + S.One)
|
| 143 |
+
elif arg.is_number:
|
| 144 |
+
return log(Rational(arg) + S.One)
|
| 145 |
+
|
| 146 |
+
def _eval_is_real(self):
|
| 147 |
+
return (self.args[0] + S.One).is_nonnegative
|
| 148 |
+
|
| 149 |
+
def _eval_is_finite(self):
|
| 150 |
+
if (self.args[0] + S.One).is_zero:
|
| 151 |
+
return False
|
| 152 |
+
return self.args[0].is_finite
|
| 153 |
+
|
| 154 |
+
def _eval_is_positive(self):
|
| 155 |
+
return self.args[0].is_positive
|
| 156 |
+
|
| 157 |
+
def _eval_is_zero(self):
|
| 158 |
+
return self.args[0].is_zero
|
| 159 |
+
|
| 160 |
+
def _eval_is_nonnegative(self):
|
| 161 |
+
return self.args[0].is_nonnegative
|
| 162 |
+
|
| 163 |
+
_Two = S(2)
|
| 164 |
+
|
| 165 |
+
def _exp2(x):
|
| 166 |
+
return Pow(_Two, x)
|
| 167 |
+
|
| 168 |
+
class exp2(Function):
|
| 169 |
+
"""
|
| 170 |
+
Represents the exponential function with base two.
|
| 171 |
+
|
| 172 |
+
Explanation
|
| 173 |
+
===========
|
| 174 |
+
|
| 175 |
+
The benefit of using ``exp2(x)`` over ``2**x``
|
| 176 |
+
is that the latter is not as efficient under finite precision
|
| 177 |
+
arithmetic.
|
| 178 |
+
|
| 179 |
+
Examples
|
| 180 |
+
========
|
| 181 |
+
|
| 182 |
+
>>> from sympy.abc import x
|
| 183 |
+
>>> from sympy.codegen.cfunctions import exp2
|
| 184 |
+
>>> exp2(2).evalf() == 4.0
|
| 185 |
+
True
|
| 186 |
+
>>> exp2(x).diff(x)
|
| 187 |
+
log(2)*exp2(x)
|
| 188 |
+
|
| 189 |
+
See Also
|
| 190 |
+
========
|
| 191 |
+
|
| 192 |
+
log2
|
| 193 |
+
"""
|
| 194 |
+
nargs = 1
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def fdiff(self, argindex=1):
|
| 198 |
+
"""
|
| 199 |
+
Returns the first derivative of this function.
|
| 200 |
+
"""
|
| 201 |
+
if argindex == 1:
|
| 202 |
+
return self*log(_Two)
|
| 203 |
+
else:
|
| 204 |
+
raise ArgumentIndexError(self, argindex)
|
| 205 |
+
|
| 206 |
+
def _eval_rewrite_as_Pow(self, arg, **kwargs):
|
| 207 |
+
return _exp2(arg)
|
| 208 |
+
|
| 209 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
|
| 210 |
+
|
| 211 |
+
def _eval_expand_func(self, **hints):
|
| 212 |
+
return _exp2(*self.args)
|
| 213 |
+
|
| 214 |
+
@classmethod
|
| 215 |
+
def eval(cls, arg):
|
| 216 |
+
if arg.is_number:
|
| 217 |
+
return _exp2(arg)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _log2(x):
|
| 221 |
+
return log(x)/log(_Two)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class log2(Function):
|
| 225 |
+
"""
|
| 226 |
+
Represents the logarithm function with base two.
|
| 227 |
+
|
| 228 |
+
Explanation
|
| 229 |
+
===========
|
| 230 |
+
|
| 231 |
+
The benefit of using ``log2(x)`` over ``log(x)/log(2)``
|
| 232 |
+
is that the latter is not as efficient under finite precision
|
| 233 |
+
arithmetic.
|
| 234 |
+
|
| 235 |
+
Examples
|
| 236 |
+
========
|
| 237 |
+
|
| 238 |
+
>>> from sympy.abc import x
|
| 239 |
+
>>> from sympy.codegen.cfunctions import log2
|
| 240 |
+
>>> log2(4).evalf() == 2.0
|
| 241 |
+
True
|
| 242 |
+
>>> log2(x).diff(x)
|
| 243 |
+
1/(x*log(2))
|
| 244 |
+
|
| 245 |
+
See Also
|
| 246 |
+
========
|
| 247 |
+
|
| 248 |
+
exp2
|
| 249 |
+
log10
|
| 250 |
+
"""
|
| 251 |
+
nargs = 1
|
| 252 |
+
|
| 253 |
+
def fdiff(self, argindex=1):
|
| 254 |
+
"""
|
| 255 |
+
Returns the first derivative of this function.
|
| 256 |
+
"""
|
| 257 |
+
if argindex == 1:
|
| 258 |
+
return S.One/(log(_Two)*self.args[0])
|
| 259 |
+
else:
|
| 260 |
+
raise ArgumentIndexError(self, argindex)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
@classmethod
|
| 264 |
+
def eval(cls, arg):
|
| 265 |
+
if arg.is_number:
|
| 266 |
+
result = log.eval(arg, base=_Two)
|
| 267 |
+
if result.is_Atom:
|
| 268 |
+
return result
|
| 269 |
+
elif arg.is_Pow and arg.base == _Two:
|
| 270 |
+
return arg.exp
|
| 271 |
+
|
| 272 |
+
def _eval_evalf(self, *args, **kwargs):
|
| 273 |
+
return self.rewrite(log).evalf(*args, **kwargs)
|
| 274 |
+
|
| 275 |
+
def _eval_expand_func(self, **hints):
|
| 276 |
+
return _log2(*self.args)
|
| 277 |
+
|
| 278 |
+
def _eval_rewrite_as_log(self, arg, **kwargs):
|
| 279 |
+
return _log2(arg)
|
| 280 |
+
|
| 281 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _fma(x, y, z):
|
| 285 |
+
return x*y + z
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class fma(Function):
|
| 289 |
+
"""
|
| 290 |
+
Represents "fused multiply add".
|
| 291 |
+
|
| 292 |
+
Explanation
|
| 293 |
+
===========
|
| 294 |
+
|
| 295 |
+
The benefit of using ``fma(x, y, z)`` over ``x*y + z``
|
| 296 |
+
is that, under finite precision arithmetic, the former is
|
| 297 |
+
supported by special instructions on some CPUs.
|
| 298 |
+
|
| 299 |
+
Examples
|
| 300 |
+
========
|
| 301 |
+
|
| 302 |
+
>>> from sympy.abc import x, y, z
|
| 303 |
+
>>> from sympy.codegen.cfunctions import fma
|
| 304 |
+
>>> fma(x, y, z).diff(x)
|
| 305 |
+
y
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
nargs = 3
|
| 309 |
+
|
| 310 |
+
def fdiff(self, argindex=1):
|
| 311 |
+
"""
|
| 312 |
+
Returns the first derivative of this function.
|
| 313 |
+
"""
|
| 314 |
+
if argindex in (1, 2):
|
| 315 |
+
return self.args[2 - argindex]
|
| 316 |
+
elif argindex == 3:
|
| 317 |
+
return S.One
|
| 318 |
+
else:
|
| 319 |
+
raise ArgumentIndexError(self, argindex)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _eval_expand_func(self, **hints):
|
| 323 |
+
return _fma(*self.args)
|
| 324 |
+
|
| 325 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
| 326 |
+
return _fma(arg)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
_Ten = S(10)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _log10(x):
|
| 333 |
+
return log(x)/log(_Ten)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
class log10(Function):
|
| 337 |
+
"""
|
| 338 |
+
Represents the logarithm function with base ten.
|
| 339 |
+
|
| 340 |
+
Examples
|
| 341 |
+
========
|
| 342 |
+
|
| 343 |
+
>>> from sympy.abc import x
|
| 344 |
+
>>> from sympy.codegen.cfunctions import log10
|
| 345 |
+
>>> log10(100).evalf() == 2.0
|
| 346 |
+
True
|
| 347 |
+
>>> log10(x).diff(x)
|
| 348 |
+
1/(x*log(10))
|
| 349 |
+
|
| 350 |
+
See Also
|
| 351 |
+
========
|
| 352 |
+
|
| 353 |
+
log2
|
| 354 |
+
"""
|
| 355 |
+
nargs = 1
|
| 356 |
+
|
| 357 |
+
def fdiff(self, argindex=1):
|
| 358 |
+
"""
|
| 359 |
+
Returns the first derivative of this function.
|
| 360 |
+
"""
|
| 361 |
+
if argindex == 1:
|
| 362 |
+
return S.One/(log(_Ten)*self.args[0])
|
| 363 |
+
else:
|
| 364 |
+
raise ArgumentIndexError(self, argindex)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@classmethod
|
| 368 |
+
def eval(cls, arg):
|
| 369 |
+
if arg.is_number:
|
| 370 |
+
result = log.eval(arg, base=_Ten)
|
| 371 |
+
if result.is_Atom:
|
| 372 |
+
return result
|
| 373 |
+
elif arg.is_Pow and arg.base == _Ten:
|
| 374 |
+
return arg.exp
|
| 375 |
+
|
| 376 |
+
def _eval_expand_func(self, **hints):
|
| 377 |
+
return _log10(*self.args)
|
| 378 |
+
|
| 379 |
+
def _eval_rewrite_as_log(self, arg, **kwargs):
|
| 380 |
+
return _log10(arg)
|
| 381 |
+
|
| 382 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def _Sqrt(x):
|
| 386 |
+
return Pow(x, S.Half)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class Sqrt(Function): # 'sqrt' already defined in sympy.functions.elementary.miscellaneous
|
| 390 |
+
"""
|
| 391 |
+
Represents the square root function.
|
| 392 |
+
|
| 393 |
+
Explanation
|
| 394 |
+
===========
|
| 395 |
+
|
| 396 |
+
The reason why one would use ``Sqrt(x)`` over ``sqrt(x)``
|
| 397 |
+
is that the latter is internally represented as ``Pow(x, S.Half)`` which
|
| 398 |
+
may not be what one wants when doing code-generation.
|
| 399 |
+
|
| 400 |
+
Examples
|
| 401 |
+
========
|
| 402 |
+
|
| 403 |
+
>>> from sympy.abc import x
|
| 404 |
+
>>> from sympy.codegen.cfunctions import Sqrt
|
| 405 |
+
>>> Sqrt(x)
|
| 406 |
+
Sqrt(x)
|
| 407 |
+
>>> Sqrt(x).diff(x)
|
| 408 |
+
1/(2*sqrt(x))
|
| 409 |
+
|
| 410 |
+
See Also
|
| 411 |
+
========
|
| 412 |
+
|
| 413 |
+
Cbrt
|
| 414 |
+
"""
|
| 415 |
+
nargs = 1
|
| 416 |
+
|
| 417 |
+
def fdiff(self, argindex=1):
|
| 418 |
+
"""
|
| 419 |
+
Returns the first derivative of this function.
|
| 420 |
+
"""
|
| 421 |
+
if argindex == 1:
|
| 422 |
+
return Pow(self.args[0], Rational(-1, 2))/_Two
|
| 423 |
+
else:
|
| 424 |
+
raise ArgumentIndexError(self, argindex)
|
| 425 |
+
|
| 426 |
+
def _eval_expand_func(self, **hints):
|
| 427 |
+
return _Sqrt(*self.args)
|
| 428 |
+
|
| 429 |
+
def _eval_rewrite_as_Pow(self, arg, **kwargs):
|
| 430 |
+
return _Sqrt(arg)
|
| 431 |
+
|
| 432 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def _Cbrt(x):
|
| 436 |
+
return Pow(x, Rational(1, 3))
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
class Cbrt(Function): # 'cbrt' already defined in sympy.functions.elementary.miscellaneous
|
| 440 |
+
"""
|
| 441 |
+
Represents the cube root function.
|
| 442 |
+
|
| 443 |
+
Explanation
|
| 444 |
+
===========
|
| 445 |
+
|
| 446 |
+
The reason why one would use ``Cbrt(x)`` over ``cbrt(x)``
|
| 447 |
+
is that the latter is internally represented as ``Pow(x, Rational(1, 3))`` which
|
| 448 |
+
may not be what one wants when doing code-generation.
|
| 449 |
+
|
| 450 |
+
Examples
|
| 451 |
+
========
|
| 452 |
+
|
| 453 |
+
>>> from sympy.abc import x
|
| 454 |
+
>>> from sympy.codegen.cfunctions import Cbrt
|
| 455 |
+
>>> Cbrt(x)
|
| 456 |
+
Cbrt(x)
|
| 457 |
+
>>> Cbrt(x).diff(x)
|
| 458 |
+
1/(3*x**(2/3))
|
| 459 |
+
|
| 460 |
+
See Also
|
| 461 |
+
========
|
| 462 |
+
|
| 463 |
+
Sqrt
|
| 464 |
+
"""
|
| 465 |
+
nargs = 1
|
| 466 |
+
|
| 467 |
+
def fdiff(self, argindex=1):
|
| 468 |
+
"""
|
| 469 |
+
Returns the first derivative of this function.
|
| 470 |
+
"""
|
| 471 |
+
if argindex == 1:
|
| 472 |
+
return Pow(self.args[0], Rational(-_Two/3))/3
|
| 473 |
+
else:
|
| 474 |
+
raise ArgumentIndexError(self, argindex)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def _eval_expand_func(self, **hints):
|
| 478 |
+
return _Cbrt(*self.args)
|
| 479 |
+
|
| 480 |
+
def _eval_rewrite_as_Pow(self, arg, **kwargs):
|
| 481 |
+
return _Cbrt(arg)
|
| 482 |
+
|
| 483 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def _hypot(x, y):
|
| 487 |
+
return sqrt(Pow(x, 2) + Pow(y, 2))
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
class hypot(Function):
|
| 491 |
+
"""
|
| 492 |
+
Represents the hypotenuse function.
|
| 493 |
+
|
| 494 |
+
Explanation
|
| 495 |
+
===========
|
| 496 |
+
|
| 497 |
+
The hypotenuse function is provided by e.g. the math library
|
| 498 |
+
in the C99 standard, hence one may want to represent the function
|
| 499 |
+
symbolically when doing code-generation.
|
| 500 |
+
|
| 501 |
+
Examples
|
| 502 |
+
========
|
| 503 |
+
|
| 504 |
+
>>> from sympy.abc import x, y
|
| 505 |
+
>>> from sympy.codegen.cfunctions import hypot
|
| 506 |
+
>>> hypot(3, 4).evalf() == 5.0
|
| 507 |
+
True
|
| 508 |
+
>>> hypot(x, y)
|
| 509 |
+
hypot(x, y)
|
| 510 |
+
>>> hypot(x, y).diff(x)
|
| 511 |
+
x/hypot(x, y)
|
| 512 |
+
|
| 513 |
+
"""
|
| 514 |
+
nargs = 2
|
| 515 |
+
|
| 516 |
+
def fdiff(self, argindex=1):
|
| 517 |
+
"""
|
| 518 |
+
Returns the first derivative of this function.
|
| 519 |
+
"""
|
| 520 |
+
if argindex in (1, 2):
|
| 521 |
+
return 2*self.args[argindex-1]/(_Two*self.func(*self.args))
|
| 522 |
+
else:
|
| 523 |
+
raise ArgumentIndexError(self, argindex)
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _eval_expand_func(self, **hints):
|
| 527 |
+
return _hypot(*self.args)
|
| 528 |
+
|
| 529 |
+
def _eval_rewrite_as_Pow(self, arg, **kwargs):
|
| 530 |
+
return _hypot(arg)
|
| 531 |
+
|
| 532 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class isnan(BooleanFunction):
|
| 536 |
+
nargs = 1
|
| 537 |
+
|
| 538 |
+
@classmethod
|
| 539 |
+
def eval(cls, arg):
|
| 540 |
+
if arg is S.NaN:
|
| 541 |
+
return true
|
| 542 |
+
elif arg.is_number:
|
| 543 |
+
return false
|
| 544 |
+
else:
|
| 545 |
+
return None
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
class isinf(BooleanFunction):
|
| 549 |
+
nargs = 1
|
| 550 |
+
|
| 551 |
+
@classmethod
|
| 552 |
+
def eval(cls, arg):
|
| 553 |
+
if arg.is_infinite:
|
| 554 |
+
return true
|
| 555 |
+
elif arg.is_finite:
|
| 556 |
+
return false
|
| 557 |
+
else:
|
| 558 |
+
return None
|
.venv/lib/python3.12/site-packages/sympy/codegen/cnodes.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AST nodes specific to the C family of languages
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from sympy.codegen.ast import (
|
| 6 |
+
Attribute, Declaration, Node, String, Token, Type, none,
|
| 7 |
+
FunctionCall, CodeBlock
|
| 8 |
+
)
|
| 9 |
+
from sympy.core.basic import Basic
|
| 10 |
+
from sympy.core.containers import Tuple
|
| 11 |
+
from sympy.core.sympify import sympify
|
| 12 |
+
|
| 13 |
+
void = Type('void')
|
| 14 |
+
|
| 15 |
+
restrict = Attribute('restrict') # guarantees no pointer aliasing
|
| 16 |
+
volatile = Attribute('volatile')
|
| 17 |
+
static = Attribute('static')
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def alignof(arg):
|
| 21 |
+
""" Generate of FunctionCall instance for calling 'alignof' """
|
| 22 |
+
return FunctionCall('alignof', [String(arg) if isinstance(arg, str) else arg])
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def sizeof(arg):
|
| 26 |
+
""" Generate of FunctionCall instance for calling 'sizeof'
|
| 27 |
+
|
| 28 |
+
Examples
|
| 29 |
+
========
|
| 30 |
+
|
| 31 |
+
>>> from sympy.codegen.ast import real
|
| 32 |
+
>>> from sympy.codegen.cnodes import sizeof
|
| 33 |
+
>>> from sympy import ccode
|
| 34 |
+
>>> ccode(sizeof(real))
|
| 35 |
+
'sizeof(double)'
|
| 36 |
+
"""
|
| 37 |
+
return FunctionCall('sizeof', [String(arg) if isinstance(arg, str) else arg])
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class CommaOperator(Basic):
|
| 41 |
+
""" Represents the comma operator in C """
|
| 42 |
+
def __new__(cls, *args):
|
| 43 |
+
return Basic.__new__(cls, *[sympify(arg) for arg in args])
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Label(Node):
|
| 47 |
+
""" Label for use with e.g. goto statement.
|
| 48 |
+
|
| 49 |
+
Examples
|
| 50 |
+
========
|
| 51 |
+
|
| 52 |
+
>>> from sympy import ccode, Symbol
|
| 53 |
+
>>> from sympy.codegen.cnodes import Label, PreIncrement
|
| 54 |
+
>>> print(ccode(Label('foo')))
|
| 55 |
+
foo:
|
| 56 |
+
>>> print(ccode(Label('bar', [PreIncrement(Symbol('a'))])))
|
| 57 |
+
bar:
|
| 58 |
+
++(a);
|
| 59 |
+
|
| 60 |
+
"""
|
| 61 |
+
__slots__ = _fields = ('name', 'body')
|
| 62 |
+
defaults = {'body': none}
|
| 63 |
+
_construct_name = String
|
| 64 |
+
|
| 65 |
+
@classmethod
|
| 66 |
+
def _construct_body(cls, itr):
|
| 67 |
+
if isinstance(itr, CodeBlock):
|
| 68 |
+
return itr
|
| 69 |
+
else:
|
| 70 |
+
return CodeBlock(*itr)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class goto(Token):
|
| 74 |
+
""" Represents goto in C """
|
| 75 |
+
__slots__ = _fields = ('label',)
|
| 76 |
+
_construct_label = Label
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class PreDecrement(Basic):
|
| 80 |
+
""" Represents the pre-decrement operator
|
| 81 |
+
|
| 82 |
+
Examples
|
| 83 |
+
========
|
| 84 |
+
|
| 85 |
+
>>> from sympy.abc import x
|
| 86 |
+
>>> from sympy.codegen.cnodes import PreDecrement
|
| 87 |
+
>>> from sympy import ccode
|
| 88 |
+
>>> ccode(PreDecrement(x))
|
| 89 |
+
'--(x)'
|
| 90 |
+
|
| 91 |
+
"""
|
| 92 |
+
nargs = 1
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class PostDecrement(Basic):
|
| 96 |
+
""" Represents the post-decrement operator
|
| 97 |
+
|
| 98 |
+
Examples
|
| 99 |
+
========
|
| 100 |
+
|
| 101 |
+
>>> from sympy.abc import x
|
| 102 |
+
>>> from sympy.codegen.cnodes import PostDecrement
|
| 103 |
+
>>> from sympy import ccode
|
| 104 |
+
>>> ccode(PostDecrement(x))
|
| 105 |
+
'(x)--'
|
| 106 |
+
|
| 107 |
+
"""
|
| 108 |
+
nargs = 1
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class PreIncrement(Basic):
|
| 112 |
+
""" Represents the pre-increment operator
|
| 113 |
+
|
| 114 |
+
Examples
|
| 115 |
+
========
|
| 116 |
+
|
| 117 |
+
>>> from sympy.abc import x
|
| 118 |
+
>>> from sympy.codegen.cnodes import PreIncrement
|
| 119 |
+
>>> from sympy import ccode
|
| 120 |
+
>>> ccode(PreIncrement(x))
|
| 121 |
+
'++(x)'
|
| 122 |
+
|
| 123 |
+
"""
|
| 124 |
+
nargs = 1
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class PostIncrement(Basic):
|
| 128 |
+
""" Represents the post-increment operator
|
| 129 |
+
|
| 130 |
+
Examples
|
| 131 |
+
========
|
| 132 |
+
|
| 133 |
+
>>> from sympy.abc import x
|
| 134 |
+
>>> from sympy.codegen.cnodes import PostIncrement
|
| 135 |
+
>>> from sympy import ccode
|
| 136 |
+
>>> ccode(PostIncrement(x))
|
| 137 |
+
'(x)++'
|
| 138 |
+
|
| 139 |
+
"""
|
| 140 |
+
nargs = 1
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class struct(Node):
|
| 144 |
+
""" Represents a struct in C """
|
| 145 |
+
__slots__ = _fields = ('name', 'declarations')
|
| 146 |
+
defaults = {'name': none}
|
| 147 |
+
_construct_name = String
|
| 148 |
+
|
| 149 |
+
@classmethod
|
| 150 |
+
def _construct_declarations(cls, args):
|
| 151 |
+
return Tuple(*[Declaration(arg) for arg in args])
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class union(struct):
|
| 155 |
+
""" Represents a union in C """
|
| 156 |
+
__slots__ = ()
|
.venv/lib/python3.12/site-packages/sympy/codegen/cutils.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.printing.c import C99CodePrinter
|
| 2 |
+
|
| 3 |
+
def render_as_source_file(content, Printer=C99CodePrinter, settings=None):
|
| 4 |
+
""" Renders a C source file (with required #include statements) """
|
| 5 |
+
printer = Printer(settings or {})
|
| 6 |
+
code_str = printer.doprint(content)
|
| 7 |
+
includes = '\n'.join(['#include <%s>' % h for h in printer.headers])
|
| 8 |
+
return includes + '\n\n' + code_str
|
.venv/lib/python3.12/site-packages/sympy/codegen/cxxnodes.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AST nodes specific to C++.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from sympy.codegen.ast import Attribute, String, Token, Type, none
|
| 6 |
+
|
| 7 |
+
class using(Token):
|
| 8 |
+
""" Represents a 'using' statement in C++ """
|
| 9 |
+
__slots__ = _fields = ('type', 'alias')
|
| 10 |
+
defaults = {'alias': none}
|
| 11 |
+
_construct_type = Type
|
| 12 |
+
_construct_alias = String
|
| 13 |
+
|
| 14 |
+
constexpr = Attribute('constexpr')
|
.venv/lib/python3.12/site-packages/sympy/codegen/fnodes.py
ADDED
|
@@ -0,0 +1,658 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AST nodes specific to Fortran.
|
| 3 |
+
|
| 4 |
+
The functions defined in this module allows the user to express functions such as ``dsign``
|
| 5 |
+
as a SymPy function for symbolic manipulation.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
from sympy.codegen.ast import (
|
| 10 |
+
Attribute, CodeBlock, FunctionCall, Node, none, String,
|
| 11 |
+
Token, _mk_Tuple, Variable
|
| 12 |
+
)
|
| 13 |
+
from sympy.core.basic import Basic
|
| 14 |
+
from sympy.core.containers import Tuple
|
| 15 |
+
from sympy.core.expr import Expr
|
| 16 |
+
from sympy.core.function import Function
|
| 17 |
+
from sympy.core.numbers import Float, Integer
|
| 18 |
+
from sympy.core.symbol import Str
|
| 19 |
+
from sympy.core.sympify import sympify
|
| 20 |
+
from sympy.logic import true, false
|
| 21 |
+
from sympy.utilities.iterables import iterable
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
pure = Attribute('pure')
|
| 26 |
+
elemental = Attribute('elemental') # (all elemental procedures are also pure)
|
| 27 |
+
|
| 28 |
+
intent_in = Attribute('intent_in')
|
| 29 |
+
intent_out = Attribute('intent_out')
|
| 30 |
+
intent_inout = Attribute('intent_inout')
|
| 31 |
+
|
| 32 |
+
allocatable = Attribute('allocatable')
|
| 33 |
+
|
| 34 |
+
class Program(Token):
|
| 35 |
+
""" Represents a 'program' block in Fortran.
|
| 36 |
+
|
| 37 |
+
Examples
|
| 38 |
+
========
|
| 39 |
+
|
| 40 |
+
>>> from sympy.codegen.ast import Print
|
| 41 |
+
>>> from sympy.codegen.fnodes import Program
|
| 42 |
+
>>> prog = Program('myprogram', [Print([42])])
|
| 43 |
+
>>> from sympy import fcode
|
| 44 |
+
>>> print(fcode(prog, source_format='free'))
|
| 45 |
+
program myprogram
|
| 46 |
+
print *, 42
|
| 47 |
+
end program
|
| 48 |
+
|
| 49 |
+
"""
|
| 50 |
+
__slots__ = _fields = ('name', 'body')
|
| 51 |
+
_construct_name = String
|
| 52 |
+
_construct_body = staticmethod(lambda body: CodeBlock(*body))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class use_rename(Token):
|
| 56 |
+
""" Represents a renaming in a use statement in Fortran.
|
| 57 |
+
|
| 58 |
+
Examples
|
| 59 |
+
========
|
| 60 |
+
|
| 61 |
+
>>> from sympy.codegen.fnodes import use_rename, use
|
| 62 |
+
>>> from sympy import fcode
|
| 63 |
+
>>> ren = use_rename("thingy", "convolution2d")
|
| 64 |
+
>>> print(fcode(ren, source_format='free'))
|
| 65 |
+
thingy => convolution2d
|
| 66 |
+
>>> full = use('signallib', only=['snr', ren])
|
| 67 |
+
>>> print(fcode(full, source_format='free'))
|
| 68 |
+
use signallib, only: snr, thingy => convolution2d
|
| 69 |
+
|
| 70 |
+
"""
|
| 71 |
+
__slots__ = _fields = ('local', 'original')
|
| 72 |
+
_construct_local = String
|
| 73 |
+
_construct_original = String
|
| 74 |
+
|
| 75 |
+
def _name(arg):
|
| 76 |
+
if hasattr(arg, 'name'):
|
| 77 |
+
return arg.name
|
| 78 |
+
else:
|
| 79 |
+
return String(arg)
|
| 80 |
+
|
| 81 |
+
class use(Token):
|
| 82 |
+
""" Represents a use statement in Fortran.
|
| 83 |
+
|
| 84 |
+
Examples
|
| 85 |
+
========
|
| 86 |
+
|
| 87 |
+
>>> from sympy.codegen.fnodes import use
|
| 88 |
+
>>> from sympy import fcode
|
| 89 |
+
>>> fcode(use('signallib'), source_format='free')
|
| 90 |
+
'use signallib'
|
| 91 |
+
>>> fcode(use('signallib', [('metric', 'snr')]), source_format='free')
|
| 92 |
+
'use signallib, metric => snr'
|
| 93 |
+
>>> fcode(use('signallib', only=['snr', 'convolution2d']), source_format='free')
|
| 94 |
+
'use signallib, only: snr, convolution2d'
|
| 95 |
+
|
| 96 |
+
"""
|
| 97 |
+
__slots__ = _fields = ('namespace', 'rename', 'only')
|
| 98 |
+
defaults = {'rename': none, 'only': none}
|
| 99 |
+
_construct_namespace = staticmethod(_name)
|
| 100 |
+
_construct_rename = staticmethod(lambda args: Tuple(*[arg if isinstance(arg, use_rename) else use_rename(*arg) for arg in args]))
|
| 101 |
+
_construct_only = staticmethod(lambda args: Tuple(*[arg if isinstance(arg, use_rename) else _name(arg) for arg in args]))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class Module(Token):
|
| 105 |
+
""" Represents a module in Fortran.
|
| 106 |
+
|
| 107 |
+
Examples
|
| 108 |
+
========
|
| 109 |
+
|
| 110 |
+
>>> from sympy.codegen.fnodes import Module
|
| 111 |
+
>>> from sympy import fcode
|
| 112 |
+
>>> print(fcode(Module('signallib', ['implicit none'], []), source_format='free'))
|
| 113 |
+
module signallib
|
| 114 |
+
implicit none
|
| 115 |
+
<BLANKLINE>
|
| 116 |
+
contains
|
| 117 |
+
<BLANKLINE>
|
| 118 |
+
<BLANKLINE>
|
| 119 |
+
end module
|
| 120 |
+
|
| 121 |
+
"""
|
| 122 |
+
__slots__ = _fields = ('name', 'declarations', 'definitions')
|
| 123 |
+
defaults = {'declarations': Tuple()}
|
| 124 |
+
_construct_name = String
|
| 125 |
+
|
| 126 |
+
@classmethod
|
| 127 |
+
def _construct_declarations(cls, args):
|
| 128 |
+
args = [Str(arg) if isinstance(arg, str) else arg for arg in args]
|
| 129 |
+
return CodeBlock(*args)
|
| 130 |
+
|
| 131 |
+
_construct_definitions = staticmethod(lambda arg: CodeBlock(*arg))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class Subroutine(Node):
|
| 135 |
+
""" Represents a subroutine in Fortran.
|
| 136 |
+
|
| 137 |
+
Examples
|
| 138 |
+
========
|
| 139 |
+
|
| 140 |
+
>>> from sympy import fcode, symbols
|
| 141 |
+
>>> from sympy.codegen.ast import Print
|
| 142 |
+
>>> from sympy.codegen.fnodes import Subroutine
|
| 143 |
+
>>> x, y = symbols('x y', real=True)
|
| 144 |
+
>>> sub = Subroutine('mysub', [x, y], [Print([x**2 + y**2, x*y])])
|
| 145 |
+
>>> print(fcode(sub, source_format='free', standard=2003))
|
| 146 |
+
subroutine mysub(x, y)
|
| 147 |
+
real*8 :: x
|
| 148 |
+
real*8 :: y
|
| 149 |
+
print *, x**2 + y**2, x*y
|
| 150 |
+
end subroutine
|
| 151 |
+
|
| 152 |
+
"""
|
| 153 |
+
__slots__ = ('name', 'parameters', 'body')
|
| 154 |
+
_fields = __slots__ + Node._fields
|
| 155 |
+
_construct_name = String
|
| 156 |
+
_construct_parameters = staticmethod(lambda params: Tuple(*map(Variable.deduced, params)))
|
| 157 |
+
|
| 158 |
+
@classmethod
|
| 159 |
+
def _construct_body(cls, itr):
|
| 160 |
+
if isinstance(itr, CodeBlock):
|
| 161 |
+
return itr
|
| 162 |
+
else:
|
| 163 |
+
return CodeBlock(*itr)
|
| 164 |
+
|
| 165 |
+
class SubroutineCall(Token):
|
| 166 |
+
""" Represents a call to a subroutine in Fortran.
|
| 167 |
+
|
| 168 |
+
Examples
|
| 169 |
+
========
|
| 170 |
+
|
| 171 |
+
>>> from sympy.codegen.fnodes import SubroutineCall
|
| 172 |
+
>>> from sympy import fcode
|
| 173 |
+
>>> fcode(SubroutineCall('mysub', 'x y'.split()))
|
| 174 |
+
' call mysub(x, y)'
|
| 175 |
+
|
| 176 |
+
"""
|
| 177 |
+
__slots__ = _fields = ('name', 'subroutine_args')
|
| 178 |
+
_construct_name = staticmethod(_name)
|
| 179 |
+
_construct_subroutine_args = staticmethod(_mk_Tuple)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class Do(Token):
|
| 183 |
+
""" Represents a Do loop in in Fortran.
|
| 184 |
+
|
| 185 |
+
Examples
|
| 186 |
+
========
|
| 187 |
+
|
| 188 |
+
>>> from sympy import fcode, symbols
|
| 189 |
+
>>> from sympy.codegen.ast import aug_assign, Print
|
| 190 |
+
>>> from sympy.codegen.fnodes import Do
|
| 191 |
+
>>> i, n = symbols('i n', integer=True)
|
| 192 |
+
>>> r = symbols('r', real=True)
|
| 193 |
+
>>> body = [aug_assign(r, '+', 1/i), Print([i, r])]
|
| 194 |
+
>>> do1 = Do(body, i, 1, n)
|
| 195 |
+
>>> print(fcode(do1, source_format='free'))
|
| 196 |
+
do i = 1, n
|
| 197 |
+
r = r + 1d0/i
|
| 198 |
+
print *, i, r
|
| 199 |
+
end do
|
| 200 |
+
>>> do2 = Do(body, i, 1, n, 2)
|
| 201 |
+
>>> print(fcode(do2, source_format='free'))
|
| 202 |
+
do i = 1, n, 2
|
| 203 |
+
r = r + 1d0/i
|
| 204 |
+
print *, i, r
|
| 205 |
+
end do
|
| 206 |
+
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
__slots__ = _fields = ('body', 'counter', 'first', 'last', 'step', 'concurrent')
|
| 210 |
+
defaults = {'step': Integer(1), 'concurrent': false}
|
| 211 |
+
_construct_body = staticmethod(lambda body: CodeBlock(*body))
|
| 212 |
+
_construct_counter = staticmethod(sympify)
|
| 213 |
+
_construct_first = staticmethod(sympify)
|
| 214 |
+
_construct_last = staticmethod(sympify)
|
| 215 |
+
_construct_step = staticmethod(sympify)
|
| 216 |
+
_construct_concurrent = staticmethod(lambda arg: true if arg else false)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class ArrayConstructor(Token):
|
| 220 |
+
""" Represents an array constructor.
|
| 221 |
+
|
| 222 |
+
Examples
|
| 223 |
+
========
|
| 224 |
+
|
| 225 |
+
>>> from sympy import fcode
|
| 226 |
+
>>> from sympy.codegen.fnodes import ArrayConstructor
|
| 227 |
+
>>> ac = ArrayConstructor([1, 2, 3])
|
| 228 |
+
>>> fcode(ac, standard=95, source_format='free')
|
| 229 |
+
'(/1, 2, 3/)'
|
| 230 |
+
>>> fcode(ac, standard=2003, source_format='free')
|
| 231 |
+
'[1, 2, 3]'
|
| 232 |
+
|
| 233 |
+
"""
|
| 234 |
+
__slots__ = _fields = ('elements',)
|
| 235 |
+
_construct_elements = staticmethod(_mk_Tuple)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class ImpliedDoLoop(Token):
|
| 239 |
+
""" Represents an implied do loop in Fortran.
|
| 240 |
+
|
| 241 |
+
Examples
|
| 242 |
+
========
|
| 243 |
+
|
| 244 |
+
>>> from sympy import Symbol, fcode
|
| 245 |
+
>>> from sympy.codegen.fnodes import ImpliedDoLoop, ArrayConstructor
|
| 246 |
+
>>> i = Symbol('i', integer=True)
|
| 247 |
+
>>> idl = ImpliedDoLoop(i**3, i, -3, 3, 2) # -27, -1, 1, 27
|
| 248 |
+
>>> ac = ArrayConstructor([-28, idl, 28]) # -28, -27, -1, 1, 27, 28
|
| 249 |
+
>>> fcode(ac, standard=2003, source_format='free')
|
| 250 |
+
'[-28, (i**3, i = -3, 3, 2), 28]'
|
| 251 |
+
|
| 252 |
+
"""
|
| 253 |
+
__slots__ = _fields = ('expr', 'counter', 'first', 'last', 'step')
|
| 254 |
+
defaults = {'step': Integer(1)}
|
| 255 |
+
_construct_expr = staticmethod(sympify)
|
| 256 |
+
_construct_counter = staticmethod(sympify)
|
| 257 |
+
_construct_first = staticmethod(sympify)
|
| 258 |
+
_construct_last = staticmethod(sympify)
|
| 259 |
+
_construct_step = staticmethod(sympify)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class Extent(Basic):
|
| 263 |
+
""" Represents a dimension extent.
|
| 264 |
+
|
| 265 |
+
Examples
|
| 266 |
+
========
|
| 267 |
+
|
| 268 |
+
>>> from sympy.codegen.fnodes import Extent
|
| 269 |
+
>>> e = Extent(-3, 3) # -3, -2, -1, 0, 1, 2, 3
|
| 270 |
+
>>> from sympy import fcode
|
| 271 |
+
>>> fcode(e, source_format='free')
|
| 272 |
+
'-3:3'
|
| 273 |
+
>>> from sympy.codegen.ast import Variable, real
|
| 274 |
+
>>> from sympy.codegen.fnodes import dimension, intent_out
|
| 275 |
+
>>> dim = dimension(e, e)
|
| 276 |
+
>>> arr = Variable('x', real, attrs=[dim, intent_out])
|
| 277 |
+
>>> fcode(arr.as_Declaration(), source_format='free', standard=2003)
|
| 278 |
+
'real*8, dimension(-3:3, -3:3), intent(out) :: x'
|
| 279 |
+
|
| 280 |
+
"""
|
| 281 |
+
def __new__(cls, *args):
|
| 282 |
+
if len(args) == 2:
|
| 283 |
+
low, high = args
|
| 284 |
+
return Basic.__new__(cls, sympify(low), sympify(high))
|
| 285 |
+
elif len(args) == 0 or (len(args) == 1 and args[0] in (':', None)):
|
| 286 |
+
return Basic.__new__(cls) # assumed shape
|
| 287 |
+
else:
|
| 288 |
+
raise ValueError("Expected 0 or 2 args (or one argument == None or ':')")
|
| 289 |
+
|
| 290 |
+
def _sympystr(self, printer):
|
| 291 |
+
if len(self.args) == 0:
|
| 292 |
+
return ':'
|
| 293 |
+
return ":".join(str(arg) for arg in self.args)
|
| 294 |
+
|
| 295 |
+
assumed_extent = Extent() # or Extent(':'), Extent(None)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def dimension(*args):
|
| 299 |
+
""" Creates a 'dimension' Attribute with (up to 7) extents.
|
| 300 |
+
|
| 301 |
+
Examples
|
| 302 |
+
========
|
| 303 |
+
|
| 304 |
+
>>> from sympy import fcode
|
| 305 |
+
>>> from sympy.codegen.fnodes import dimension, intent_in
|
| 306 |
+
>>> dim = dimension('2', ':') # 2 rows, runtime determined number of columns
|
| 307 |
+
>>> from sympy.codegen.ast import Variable, integer
|
| 308 |
+
>>> arr = Variable('a', integer, attrs=[dim, intent_in])
|
| 309 |
+
>>> fcode(arr.as_Declaration(), source_format='free', standard=2003)
|
| 310 |
+
'integer*4, dimension(2, :), intent(in) :: a'
|
| 311 |
+
|
| 312 |
+
"""
|
| 313 |
+
if len(args) > 7:
|
| 314 |
+
raise ValueError("Fortran only supports up to 7 dimensional arrays")
|
| 315 |
+
parameters = []
|
| 316 |
+
for arg in args:
|
| 317 |
+
if isinstance(arg, Extent):
|
| 318 |
+
parameters.append(arg)
|
| 319 |
+
elif isinstance(arg, str):
|
| 320 |
+
if arg == ':':
|
| 321 |
+
parameters.append(Extent())
|
| 322 |
+
else:
|
| 323 |
+
parameters.append(String(arg))
|
| 324 |
+
elif iterable(arg):
|
| 325 |
+
parameters.append(Extent(*arg))
|
| 326 |
+
else:
|
| 327 |
+
parameters.append(sympify(arg))
|
| 328 |
+
if len(args) == 0:
|
| 329 |
+
raise ValueError("Need at least one dimension")
|
| 330 |
+
return Attribute('dimension', parameters)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
assumed_size = dimension('*')
|
| 334 |
+
|
| 335 |
+
def array(symbol, dim, intent=None, *, attrs=(), value=None, type=None):
|
| 336 |
+
""" Convenience function for creating a Variable instance for a Fortran array.
|
| 337 |
+
|
| 338 |
+
Parameters
|
| 339 |
+
==========
|
| 340 |
+
|
| 341 |
+
symbol : symbol
|
| 342 |
+
dim : Attribute or iterable
|
| 343 |
+
If dim is an ``Attribute`` it need to have the name 'dimension'. If it is
|
| 344 |
+
not an ``Attribute``, then it is passed to :func:`dimension` as ``*dim``
|
| 345 |
+
intent : str
|
| 346 |
+
One of: 'in', 'out', 'inout' or None
|
| 347 |
+
\\*\\*kwargs:
|
| 348 |
+
Keyword arguments for ``Variable`` ('type' & 'value')
|
| 349 |
+
|
| 350 |
+
Examples
|
| 351 |
+
========
|
| 352 |
+
|
| 353 |
+
>>> from sympy import fcode
|
| 354 |
+
>>> from sympy.codegen.ast import integer, real
|
| 355 |
+
>>> from sympy.codegen.fnodes import array
|
| 356 |
+
>>> arr = array('a', '*', 'in', type=integer)
|
| 357 |
+
>>> print(fcode(arr.as_Declaration(), source_format='free', standard=2003))
|
| 358 |
+
integer*4, dimension(*), intent(in) :: a
|
| 359 |
+
>>> x = array('x', [3, ':', ':'], intent='out', type=real)
|
| 360 |
+
>>> print(fcode(x.as_Declaration(value=1), source_format='free', standard=2003))
|
| 361 |
+
real*8, dimension(3, :, :), intent(out) :: x = 1
|
| 362 |
+
|
| 363 |
+
"""
|
| 364 |
+
if isinstance(dim, Attribute):
|
| 365 |
+
if str(dim.name) != 'dimension':
|
| 366 |
+
raise ValueError("Got an unexpected Attribute argument as dim: %s" % str(dim))
|
| 367 |
+
else:
|
| 368 |
+
dim = dimension(*dim)
|
| 369 |
+
|
| 370 |
+
attrs = list(attrs) + [dim]
|
| 371 |
+
if intent is not None:
|
| 372 |
+
if intent not in (intent_in, intent_out, intent_inout):
|
| 373 |
+
intent = {'in': intent_in, 'out': intent_out, 'inout': intent_inout}[intent]
|
| 374 |
+
attrs.append(intent)
|
| 375 |
+
if type is None:
|
| 376 |
+
return Variable.deduced(symbol, value=value, attrs=attrs)
|
| 377 |
+
else:
|
| 378 |
+
return Variable(symbol, type, value=value, attrs=attrs)
|
| 379 |
+
|
| 380 |
+
def _printable(arg):
|
| 381 |
+
return String(arg) if isinstance(arg, str) else sympify(arg)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def allocated(array):
|
| 385 |
+
""" Creates an AST node for a function call to Fortran's "allocated(...)"
|
| 386 |
+
|
| 387 |
+
Examples
|
| 388 |
+
========
|
| 389 |
+
|
| 390 |
+
>>> from sympy import fcode
|
| 391 |
+
>>> from sympy.codegen.fnodes import allocated
|
| 392 |
+
>>> alloc = allocated('x')
|
| 393 |
+
>>> fcode(alloc, source_format='free')
|
| 394 |
+
'allocated(x)'
|
| 395 |
+
|
| 396 |
+
"""
|
| 397 |
+
return FunctionCall('allocated', [_printable(array)])
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def lbound(array, dim=None, kind=None):
|
| 401 |
+
""" Creates an AST node for a function call to Fortran's "lbound(...)"
|
| 402 |
+
|
| 403 |
+
Parameters
|
| 404 |
+
==========
|
| 405 |
+
|
| 406 |
+
array : Symbol or String
|
| 407 |
+
dim : expr
|
| 408 |
+
kind : expr
|
| 409 |
+
|
| 410 |
+
Examples
|
| 411 |
+
========
|
| 412 |
+
|
| 413 |
+
>>> from sympy import fcode
|
| 414 |
+
>>> from sympy.codegen.fnodes import lbound
|
| 415 |
+
>>> lb = lbound('arr', dim=2)
|
| 416 |
+
>>> fcode(lb, source_format='free')
|
| 417 |
+
'lbound(arr, 2)'
|
| 418 |
+
|
| 419 |
+
"""
|
| 420 |
+
return FunctionCall(
|
| 421 |
+
'lbound',
|
| 422 |
+
[_printable(array)] +
|
| 423 |
+
([_printable(dim)] if dim else []) +
|
| 424 |
+
([_printable(kind)] if kind else [])
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def ubound(array, dim=None, kind=None):
|
| 429 |
+
return FunctionCall(
|
| 430 |
+
'ubound',
|
| 431 |
+
[_printable(array)] +
|
| 432 |
+
([_printable(dim)] if dim else []) +
|
| 433 |
+
([_printable(kind)] if kind else [])
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def shape(source, kind=None):
|
| 438 |
+
""" Creates an AST node for a function call to Fortran's "shape(...)"
|
| 439 |
+
|
| 440 |
+
Parameters
|
| 441 |
+
==========
|
| 442 |
+
|
| 443 |
+
source : Symbol or String
|
| 444 |
+
kind : expr
|
| 445 |
+
|
| 446 |
+
Examples
|
| 447 |
+
========
|
| 448 |
+
|
| 449 |
+
>>> from sympy import fcode
|
| 450 |
+
>>> from sympy.codegen.fnodes import shape
|
| 451 |
+
>>> shp = shape('x')
|
| 452 |
+
>>> fcode(shp, source_format='free')
|
| 453 |
+
'shape(x)'
|
| 454 |
+
|
| 455 |
+
"""
|
| 456 |
+
return FunctionCall(
|
| 457 |
+
'shape',
|
| 458 |
+
[_printable(source)] +
|
| 459 |
+
([_printable(kind)] if kind else [])
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def size(array, dim=None, kind=None):
|
| 464 |
+
""" Creates an AST node for a function call to Fortran's "size(...)"
|
| 465 |
+
|
| 466 |
+
Examples
|
| 467 |
+
========
|
| 468 |
+
|
| 469 |
+
>>> from sympy import fcode, Symbol
|
| 470 |
+
>>> from sympy.codegen.ast import FunctionDefinition, real, Return
|
| 471 |
+
>>> from sympy.codegen.fnodes import array, sum_, size
|
| 472 |
+
>>> a = Symbol('a', real=True)
|
| 473 |
+
>>> body = [Return((sum_(a**2)/size(a))**.5)]
|
| 474 |
+
>>> arr = array(a, dim=[':'], intent='in')
|
| 475 |
+
>>> fd = FunctionDefinition(real, 'rms', [arr], body)
|
| 476 |
+
>>> print(fcode(fd, source_format='free', standard=2003))
|
| 477 |
+
real*8 function rms(a)
|
| 478 |
+
real*8, dimension(:), intent(in) :: a
|
| 479 |
+
rms = sqrt(sum(a**2)*1d0/size(a))
|
| 480 |
+
end function
|
| 481 |
+
|
| 482 |
+
"""
|
| 483 |
+
return FunctionCall(
|
| 484 |
+
'size',
|
| 485 |
+
[_printable(array)] +
|
| 486 |
+
([_printable(dim)] if dim else []) +
|
| 487 |
+
([_printable(kind)] if kind else [])
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def reshape(source, shape, pad=None, order=None):
|
| 492 |
+
""" Creates an AST node for a function call to Fortran's "reshape(...)"
|
| 493 |
+
|
| 494 |
+
Parameters
|
| 495 |
+
==========
|
| 496 |
+
|
| 497 |
+
source : Symbol or String
|
| 498 |
+
shape : ArrayExpr
|
| 499 |
+
|
| 500 |
+
"""
|
| 501 |
+
return FunctionCall(
|
| 502 |
+
'reshape',
|
| 503 |
+
[_printable(source), _printable(shape)] +
|
| 504 |
+
([_printable(pad)] if pad else []) +
|
| 505 |
+
([_printable(order)] if pad else [])
|
| 506 |
+
)
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def bind_C(name=None):
|
| 510 |
+
""" Creates an Attribute ``bind_C`` with a name.
|
| 511 |
+
|
| 512 |
+
Parameters
|
| 513 |
+
==========
|
| 514 |
+
|
| 515 |
+
name : str
|
| 516 |
+
|
| 517 |
+
Examples
|
| 518 |
+
========
|
| 519 |
+
|
| 520 |
+
>>> from sympy import fcode, Symbol
|
| 521 |
+
>>> from sympy.codegen.ast import FunctionDefinition, real, Return
|
| 522 |
+
>>> from sympy.codegen.fnodes import array, sum_, bind_C
|
| 523 |
+
>>> a = Symbol('a', real=True)
|
| 524 |
+
>>> s = Symbol('s', integer=True)
|
| 525 |
+
>>> arr = array(a, dim=[s], intent='in')
|
| 526 |
+
>>> body = [Return((sum_(a**2)/s)**.5)]
|
| 527 |
+
>>> fd = FunctionDefinition(real, 'rms', [arr, s], body, attrs=[bind_C('rms')])
|
| 528 |
+
>>> print(fcode(fd, source_format='free', standard=2003))
|
| 529 |
+
real*8 function rms(a, s) bind(C, name="rms")
|
| 530 |
+
real*8, dimension(s), intent(in) :: a
|
| 531 |
+
integer*4 :: s
|
| 532 |
+
rms = sqrt(sum(a**2)/s)
|
| 533 |
+
end function
|
| 534 |
+
|
| 535 |
+
"""
|
| 536 |
+
return Attribute('bind_C', [String(name)] if name else [])
|
| 537 |
+
|
| 538 |
+
class GoTo(Token):
|
| 539 |
+
""" Represents a goto statement in Fortran
|
| 540 |
+
|
| 541 |
+
Examples
|
| 542 |
+
========
|
| 543 |
+
|
| 544 |
+
>>> from sympy.codegen.fnodes import GoTo
|
| 545 |
+
>>> go = GoTo([10, 20, 30], 'i')
|
| 546 |
+
>>> from sympy import fcode
|
| 547 |
+
>>> fcode(go, source_format='free')
|
| 548 |
+
'go to (10, 20, 30), i'
|
| 549 |
+
|
| 550 |
+
"""
|
| 551 |
+
__slots__ = _fields = ('labels', 'expr')
|
| 552 |
+
defaults = {'expr': none}
|
| 553 |
+
_construct_labels = staticmethod(_mk_Tuple)
|
| 554 |
+
_construct_expr = staticmethod(sympify)
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
class FortranReturn(Token):
|
| 558 |
+
""" AST node explicitly mapped to a fortran "return".
|
| 559 |
+
|
| 560 |
+
Explanation
|
| 561 |
+
===========
|
| 562 |
+
|
| 563 |
+
Because a return statement in fortran is different from C, and
|
| 564 |
+
in order to aid reuse of our codegen ASTs the ordinary
|
| 565 |
+
``.codegen.ast.Return`` is interpreted as assignment to
|
| 566 |
+
the result variable of the function. If one for some reason needs
|
| 567 |
+
to generate a fortran RETURN statement, this node should be used.
|
| 568 |
+
|
| 569 |
+
Examples
|
| 570 |
+
========
|
| 571 |
+
|
| 572 |
+
>>> from sympy.codegen.fnodes import FortranReturn
|
| 573 |
+
>>> from sympy import fcode
|
| 574 |
+
>>> fcode(FortranReturn('x'))
|
| 575 |
+
' return x'
|
| 576 |
+
|
| 577 |
+
"""
|
| 578 |
+
__slots__ = _fields = ('return_value',)
|
| 579 |
+
defaults = {'return_value': none}
|
| 580 |
+
_construct_return_value = staticmethod(sympify)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
class FFunction(Function):
|
| 584 |
+
_required_standard = 77
|
| 585 |
+
|
| 586 |
+
def _fcode(self, printer):
|
| 587 |
+
name = self.__class__.__name__
|
| 588 |
+
if printer._settings['standard'] < self._required_standard:
|
| 589 |
+
raise NotImplementedError("%s requires Fortran %d or newer" %
|
| 590 |
+
(name, self._required_standard))
|
| 591 |
+
return '{}({})'.format(name, ', '.join(map(printer._print, self.args)))
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
class F95Function(FFunction):
|
| 595 |
+
_required_standard = 95
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
class isign(FFunction):
|
| 599 |
+
""" Fortran sign intrinsic for integer arguments. """
|
| 600 |
+
nargs = 2
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
class dsign(FFunction):
|
| 604 |
+
""" Fortran sign intrinsic for double precision arguments. """
|
| 605 |
+
nargs = 2
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
class cmplx(FFunction):
|
| 609 |
+
""" Fortran complex conversion function. """
|
| 610 |
+
nargs = 2 # may be extended to (2, 3) at a later point
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
class kind(FFunction):
|
| 614 |
+
""" Fortran kind function. """
|
| 615 |
+
nargs = 1
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
class merge(F95Function):
|
| 619 |
+
""" Fortran merge function """
|
| 620 |
+
nargs = 3
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
class _literal(Float):
|
| 624 |
+
_token: str
|
| 625 |
+
_decimals: int
|
| 626 |
+
|
| 627 |
+
def _fcode(self, printer, *args, **kwargs):
|
| 628 |
+
mantissa, sgnd_ex = ('%.{}e'.format(self._decimals) % self).split('e')
|
| 629 |
+
mantissa = mantissa.strip('0').rstrip('.')
|
| 630 |
+
ex_sgn, ex_num = sgnd_ex[0], sgnd_ex[1:].lstrip('0')
|
| 631 |
+
ex_sgn = '' if ex_sgn == '+' else ex_sgn
|
| 632 |
+
return (mantissa or '0') + self._token + ex_sgn + (ex_num or '0')
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
class literal_sp(_literal):
|
| 636 |
+
""" Fortran single precision real literal """
|
| 637 |
+
_token = 'e'
|
| 638 |
+
_decimals = 9
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
class literal_dp(_literal):
|
| 642 |
+
""" Fortran double precision real literal """
|
| 643 |
+
_token = 'd'
|
| 644 |
+
_decimals = 17
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
class sum_(Token, Expr):
|
| 648 |
+
__slots__ = _fields = ('array', 'dim', 'mask')
|
| 649 |
+
defaults = {'dim': none, 'mask': none}
|
| 650 |
+
_construct_array = staticmethod(sympify)
|
| 651 |
+
_construct_dim = staticmethod(sympify)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
class product_(Token, Expr):
|
| 655 |
+
__slots__ = _fields = ('array', 'dim', 'mask')
|
| 656 |
+
defaults = {'dim': none, 'mask': none}
|
| 657 |
+
_construct_array = staticmethod(sympify)
|
| 658 |
+
_construct_dim = staticmethod(sympify)
|
.venv/lib/python3.12/site-packages/sympy/codegen/futils.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import chain
|
| 2 |
+
from sympy.codegen.fnodes import Module
|
| 3 |
+
from sympy.core.symbol import Dummy
|
| 4 |
+
from sympy.printing.fortran import FCodePrinter
|
| 5 |
+
|
| 6 |
+
""" This module collects utilities for rendering Fortran code. """
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def render_as_module(definitions, name, declarations=(), printer_settings=None):
|
| 10 |
+
""" Creates a ``Module`` instance and renders it as a string.
|
| 11 |
+
|
| 12 |
+
This generates Fortran source code for a module with the correct ``use`` statements.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
==========
|
| 16 |
+
|
| 17 |
+
definitions : iterable
|
| 18 |
+
Passed to :class:`sympy.codegen.fnodes.Module`.
|
| 19 |
+
name : str
|
| 20 |
+
Passed to :class:`sympy.codegen.fnodes.Module`.
|
| 21 |
+
declarations : iterable
|
| 22 |
+
Passed to :class:`sympy.codegen.fnodes.Module`. It will be extended with
|
| 23 |
+
use statements, 'implicit none' and public list generated from ``definitions``.
|
| 24 |
+
printer_settings : dict
|
| 25 |
+
Passed to ``FCodePrinter`` (default: ``{'standard': 2003, 'source_format': 'free'}``).
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
printer_settings = printer_settings or {'standard': 2003, 'source_format': 'free'}
|
| 29 |
+
printer = FCodePrinter(printer_settings)
|
| 30 |
+
dummy = Dummy()
|
| 31 |
+
if isinstance(definitions, Module):
|
| 32 |
+
raise ValueError("This function expects to construct a module on its own.")
|
| 33 |
+
mod = Module(name, chain(declarations, [dummy]), definitions)
|
| 34 |
+
fstr = printer.doprint(mod)
|
| 35 |
+
module_use_str = ' %s\n' % ' \n'.join(['use %s, only: %s' % (k, ', '.join(v)) for
|
| 36 |
+
k, v in printer.module_uses.items()])
|
| 37 |
+
module_use_str += ' implicit none\n'
|
| 38 |
+
module_use_str += ' private\n'
|
| 39 |
+
module_use_str += ' public %s\n' % ', '.join([str(node.name) for node in definitions if getattr(node, 'name', None)])
|
| 40 |
+
return fstr.replace(printer.doprint(dummy), module_use_str)
|
.venv/lib/python3.12/site-packages/sympy/codegen/matrix_nodes.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Additional AST nodes for operations on matrices. The nodes in this module
|
| 3 |
+
are meant to represent optimization of matrix expressions within codegen's
|
| 4 |
+
target languages that cannot be represented by SymPy expressions.
|
| 5 |
+
|
| 6 |
+
As an example, we can use :meth:`sympy.codegen.rewriting.optimize` and the
|
| 7 |
+
``matin_opt`` optimization provided in :mod:`sympy.codegen.rewriting` to
|
| 8 |
+
transform matrix multiplication under certain assumptions:
|
| 9 |
+
|
| 10 |
+
>>> from sympy import symbols, MatrixSymbol
|
| 11 |
+
>>> n = symbols('n', integer=True)
|
| 12 |
+
>>> A = MatrixSymbol('A', n, n)
|
| 13 |
+
>>> x = MatrixSymbol('x', n, 1)
|
| 14 |
+
>>> expr = A**(-1) * x
|
| 15 |
+
>>> from sympy import assuming, Q
|
| 16 |
+
>>> from sympy.codegen.rewriting import matinv_opt, optimize
|
| 17 |
+
>>> with assuming(Q.fullrank(A)):
|
| 18 |
+
... optimize(expr, [matinv_opt])
|
| 19 |
+
MatrixSolve(A, vector=x)
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from .ast import Token
|
| 23 |
+
from sympy.matrices import MatrixExpr
|
| 24 |
+
from sympy.core.sympify import sympify
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class MatrixSolve(Token, MatrixExpr):
|
| 28 |
+
"""Represents an operation to solve a linear matrix equation.
|
| 29 |
+
|
| 30 |
+
Parameters
|
| 31 |
+
==========
|
| 32 |
+
|
| 33 |
+
matrix : MatrixSymbol
|
| 34 |
+
|
| 35 |
+
Matrix representing the coefficients of variables in the linear
|
| 36 |
+
equation. This matrix must be square and full-rank (i.e. all columns must
|
| 37 |
+
be linearly independent) for the solving operation to be valid.
|
| 38 |
+
|
| 39 |
+
vector : MatrixSymbol
|
| 40 |
+
|
| 41 |
+
One-column matrix representing the solutions to the equations
|
| 42 |
+
represented in ``matrix``.
|
| 43 |
+
|
| 44 |
+
Examples
|
| 45 |
+
========
|
| 46 |
+
|
| 47 |
+
>>> from sympy import symbols, MatrixSymbol
|
| 48 |
+
>>> from sympy.codegen.matrix_nodes import MatrixSolve
|
| 49 |
+
>>> n = symbols('n', integer=True)
|
| 50 |
+
>>> A = MatrixSymbol('A', n, n)
|
| 51 |
+
>>> x = MatrixSymbol('x', n, 1)
|
| 52 |
+
>>> from sympy.printing.numpy import NumPyPrinter
|
| 53 |
+
>>> NumPyPrinter().doprint(MatrixSolve(A, x))
|
| 54 |
+
'numpy.linalg.solve(A, x)'
|
| 55 |
+
>>> from sympy import octave_code
|
| 56 |
+
>>> octave_code(MatrixSolve(A, x))
|
| 57 |
+
'A \\\\ x'
|
| 58 |
+
|
| 59 |
+
"""
|
| 60 |
+
__slots__ = _fields = ('matrix', 'vector')
|
| 61 |
+
|
| 62 |
+
_construct_matrix = staticmethod(sympify)
|
| 63 |
+
_construct_vector = staticmethod(sympify)
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
def shape(self):
|
| 67 |
+
return self.vector.shape
|
| 68 |
+
|
| 69 |
+
def _eval_derivative(self, x):
|
| 70 |
+
A, b = self.matrix, self.vector
|
| 71 |
+
return MatrixSolve(A, b.diff(x) - A.diff(x) * MatrixSolve(A, b))
|
.venv/lib/python3.12/site-packages/sympy/codegen/numpy_nodes.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.function import Add, ArgumentIndexError, Function
|
| 2 |
+
from sympy.core.power import Pow
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.core.sorting import default_sort_key
|
| 5 |
+
from sympy.core.sympify import sympify
|
| 6 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 7 |
+
from sympy.functions.elementary.miscellaneous import Max, Min
|
| 8 |
+
from .ast import Token, none
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _logaddexp(x1, x2, *, evaluate=True):
|
| 12 |
+
return log(Add(exp(x1, evaluate=evaluate), exp(x2, evaluate=evaluate), evaluate=evaluate))
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
_two = S.One*2
|
| 16 |
+
_ln2 = log(_two)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _lb(x, *, evaluate=True):
|
| 20 |
+
return log(x, evaluate=evaluate)/_ln2
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _exp2(x, *, evaluate=True):
|
| 24 |
+
return Pow(_two, x, evaluate=evaluate)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _logaddexp2(x1, x2, *, evaluate=True):
|
| 28 |
+
return _lb(Add(_exp2(x1, evaluate=evaluate),
|
| 29 |
+
_exp2(x2, evaluate=evaluate), evaluate=evaluate))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class logaddexp(Function):
|
| 33 |
+
""" Logarithm of the sum of exponentiations of the inputs.
|
| 34 |
+
|
| 35 |
+
Helper class for use with e.g. numpy.logaddexp
|
| 36 |
+
|
| 37 |
+
See Also
|
| 38 |
+
========
|
| 39 |
+
|
| 40 |
+
https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html
|
| 41 |
+
"""
|
| 42 |
+
nargs = 2
|
| 43 |
+
|
| 44 |
+
def __new__(cls, *args):
|
| 45 |
+
return Function.__new__(cls, *sorted(args, key=default_sort_key))
|
| 46 |
+
|
| 47 |
+
def fdiff(self, argindex=1):
|
| 48 |
+
"""
|
| 49 |
+
Returns the first derivative of this function.
|
| 50 |
+
"""
|
| 51 |
+
if argindex == 1:
|
| 52 |
+
wrt, other = self.args
|
| 53 |
+
elif argindex == 2:
|
| 54 |
+
other, wrt = self.args
|
| 55 |
+
else:
|
| 56 |
+
raise ArgumentIndexError(self, argindex)
|
| 57 |
+
return S.One/(S.One + exp(other-wrt))
|
| 58 |
+
|
| 59 |
+
def _eval_rewrite_as_log(self, x1, x2, **kwargs):
|
| 60 |
+
return _logaddexp(x1, x2)
|
| 61 |
+
|
| 62 |
+
def _eval_evalf(self, *args, **kwargs):
|
| 63 |
+
return self.rewrite(log).evalf(*args, **kwargs)
|
| 64 |
+
|
| 65 |
+
def _eval_simplify(self, *args, **kwargs):
|
| 66 |
+
a, b = (x.simplify(**kwargs) for x in self.args)
|
| 67 |
+
candidate = _logaddexp(a, b)
|
| 68 |
+
if candidate != _logaddexp(a, b, evaluate=False):
|
| 69 |
+
return candidate
|
| 70 |
+
else:
|
| 71 |
+
return logaddexp(a, b)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class logaddexp2(Function):
|
| 75 |
+
""" Logarithm of the sum of exponentiations of the inputs in base-2.
|
| 76 |
+
|
| 77 |
+
Helper class for use with e.g. numpy.logaddexp2
|
| 78 |
+
|
| 79 |
+
See Also
|
| 80 |
+
========
|
| 81 |
+
|
| 82 |
+
https://numpy.org/doc/stable/reference/generated/numpy.logaddexp2.html
|
| 83 |
+
"""
|
| 84 |
+
nargs = 2
|
| 85 |
+
|
| 86 |
+
def __new__(cls, *args):
|
| 87 |
+
return Function.__new__(cls, *sorted(args, key=default_sort_key))
|
| 88 |
+
|
| 89 |
+
def fdiff(self, argindex=1):
|
| 90 |
+
"""
|
| 91 |
+
Returns the first derivative of this function.
|
| 92 |
+
"""
|
| 93 |
+
if argindex == 1:
|
| 94 |
+
wrt, other = self.args
|
| 95 |
+
elif argindex == 2:
|
| 96 |
+
other, wrt = self.args
|
| 97 |
+
else:
|
| 98 |
+
raise ArgumentIndexError(self, argindex)
|
| 99 |
+
return S.One/(S.One + _exp2(other-wrt))
|
| 100 |
+
|
| 101 |
+
def _eval_rewrite_as_log(self, x1, x2, **kwargs):
|
| 102 |
+
return _logaddexp2(x1, x2)
|
| 103 |
+
|
| 104 |
+
def _eval_evalf(self, *args, **kwargs):
|
| 105 |
+
return self.rewrite(log).evalf(*args, **kwargs)
|
| 106 |
+
|
| 107 |
+
def _eval_simplify(self, *args, **kwargs):
|
| 108 |
+
a, b = (x.simplify(**kwargs).factor() for x in self.args)
|
| 109 |
+
candidate = _logaddexp2(a, b)
|
| 110 |
+
if candidate != _logaddexp2(a, b, evaluate=False):
|
| 111 |
+
return candidate
|
| 112 |
+
else:
|
| 113 |
+
return logaddexp2(a, b)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class amin(Token):
|
| 117 |
+
""" Minimum value along an axis.
|
| 118 |
+
|
| 119 |
+
Helper class for use with e.g. numpy.amin
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
See Also
|
| 123 |
+
========
|
| 124 |
+
|
| 125 |
+
https://numpy.org/doc/stable/reference/generated/numpy.amin.html
|
| 126 |
+
"""
|
| 127 |
+
__slots__ = _fields = ('array', 'axis')
|
| 128 |
+
defaults = {'axis': none}
|
| 129 |
+
_construct_axis = staticmethod(sympify)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class amax(Token):
|
| 133 |
+
""" Maximum value along an axis.
|
| 134 |
+
|
| 135 |
+
Helper class for use with e.g. numpy.amax
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
See Also
|
| 139 |
+
========
|
| 140 |
+
|
| 141 |
+
https://numpy.org/doc/stable/reference/generated/numpy.amax.html
|
| 142 |
+
"""
|
| 143 |
+
__slots__ = _fields = ('array', 'axis')
|
| 144 |
+
defaults = {'axis': none}
|
| 145 |
+
_construct_axis = staticmethod(sympify)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class maximum(Function):
|
| 149 |
+
""" Element-wise maximum of array elements.
|
| 150 |
+
|
| 151 |
+
Helper class for use with e.g. numpy.maximum
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
See Also
|
| 155 |
+
========
|
| 156 |
+
|
| 157 |
+
https://numpy.org/doc/stable/reference/generated/numpy.maximum.html
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
def _eval_rewrite_as_Max(self, *args):
|
| 161 |
+
return Max(*self.args)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class minimum(Function):
|
| 165 |
+
""" Element-wise minimum of array elements.
|
| 166 |
+
|
| 167 |
+
Helper class for use with e.g. numpy.minimum
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
See Also
|
| 171 |
+
========
|
| 172 |
+
|
| 173 |
+
https://numpy.org/doc/stable/reference/generated/numpy.minimum.html
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
def _eval_rewrite_as_Min(self, *args):
|
| 177 |
+
return Min(*self.args)
|
.venv/lib/python3.12/site-packages/sympy/codegen/pynodes.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .abstract_nodes import List as AbstractList
|
| 2 |
+
from .ast import Token
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class List(AbstractList):
|
| 6 |
+
pass
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class NumExprEvaluate(Token):
|
| 10 |
+
"""represents a call to :class:`numexpr`s :func:`evaluate`"""
|
| 11 |
+
__slots__ = _fields = ('expr',)
|
.venv/lib/python3.12/site-packages/sympy/codegen/pyutils.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.printing.pycode import PythonCodePrinter
|
| 2 |
+
|
| 3 |
+
""" This module collects utilities for rendering Python code. """
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def render_as_module(content, standard='python3'):
|
| 7 |
+
"""Renders Python code as a module (with the required imports).
|
| 8 |
+
|
| 9 |
+
Parameters
|
| 10 |
+
==========
|
| 11 |
+
|
| 12 |
+
standard :
|
| 13 |
+
See the parameter ``standard`` in
|
| 14 |
+
:meth:`sympy.printing.pycode.pycode`
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
printer = PythonCodePrinter({'standard':standard})
|
| 18 |
+
pystr = printer.doprint(content)
|
| 19 |
+
if printer._settings['fully_qualified_modules']:
|
| 20 |
+
module_imports_str = '\n'.join('import %s' % k for k in printer.module_imports)
|
| 21 |
+
else:
|
| 22 |
+
module_imports_str = '\n'.join(['from %s import %s' % (k, ', '.join(v)) for
|
| 23 |
+
k, v in printer.module_imports.items()])
|
| 24 |
+
return module_imports_str + '\n\n' + pystr
|
.venv/lib/python3.12/site-packages/sympy/codegen/rewriting.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Classes and functions useful for rewriting expressions for optimized code
|
| 3 |
+
generation. Some languages (or standards thereof), e.g. C99, offer specialized
|
| 4 |
+
math functions for better performance and/or precision.
|
| 5 |
+
|
| 6 |
+
Using the ``optimize`` function in this module, together with a collection of
|
| 7 |
+
rules (represented as instances of ``Optimization``), one can rewrite the
|
| 8 |
+
expressions for this purpose::
|
| 9 |
+
|
| 10 |
+
>>> from sympy import Symbol, exp, log
|
| 11 |
+
>>> from sympy.codegen.rewriting import optimize, optims_c99
|
| 12 |
+
>>> x = Symbol('x')
|
| 13 |
+
>>> optimize(3*exp(2*x) - 3, optims_c99)
|
| 14 |
+
3*expm1(2*x)
|
| 15 |
+
>>> optimize(exp(2*x) - 1 - exp(-33), optims_c99)
|
| 16 |
+
expm1(2*x) - exp(-33)
|
| 17 |
+
>>> optimize(log(3*x + 3), optims_c99)
|
| 18 |
+
log1p(x) + log(3)
|
| 19 |
+
>>> optimize(log(2*x + 3), optims_c99)
|
| 20 |
+
log(2*x + 3)
|
| 21 |
+
|
| 22 |
+
The ``optims_c99`` imported above is tuple containing the following instances
|
| 23 |
+
(which may be imported from ``sympy.codegen.rewriting``):
|
| 24 |
+
|
| 25 |
+
- ``expm1_opt``
|
| 26 |
+
- ``log1p_opt``
|
| 27 |
+
- ``exp2_opt``
|
| 28 |
+
- ``log2_opt``
|
| 29 |
+
- ``log2const_opt``
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
from sympy.core.function import expand_log
|
| 34 |
+
from sympy.core.singleton import S
|
| 35 |
+
from sympy.core.symbol import Wild
|
| 36 |
+
from sympy.functions.elementary.complexes import sign
|
| 37 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 38 |
+
from sympy.functions.elementary.miscellaneous import (Max, Min)
|
| 39 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, sinc)
|
| 40 |
+
from sympy.assumptions import Q, ask
|
| 41 |
+
from sympy.codegen.cfunctions import log1p, log2, exp2, expm1
|
| 42 |
+
from sympy.codegen.matrix_nodes import MatrixSolve
|
| 43 |
+
from sympy.core.expr import UnevaluatedExpr
|
| 44 |
+
from sympy.core.power import Pow
|
| 45 |
+
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
|
| 46 |
+
from sympy.codegen.scipy_nodes import cosm1, powm1
|
| 47 |
+
from sympy.core.mul import Mul
|
| 48 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
| 49 |
+
from sympy.utilities.iterables import sift
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class Optimization:
|
| 53 |
+
""" Abstract base class for rewriting optimization.
|
| 54 |
+
|
| 55 |
+
Subclasses should implement ``__call__`` taking an expression
|
| 56 |
+
as argument.
|
| 57 |
+
|
| 58 |
+
Parameters
|
| 59 |
+
==========
|
| 60 |
+
cost_function : callable returning number
|
| 61 |
+
priority : number
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
def __init__(self, cost_function=None, priority=1):
|
| 65 |
+
self.cost_function = cost_function
|
| 66 |
+
self.priority=priority
|
| 67 |
+
|
| 68 |
+
def cheapest(self, *args):
|
| 69 |
+
return min(args, key=self.cost_function)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class ReplaceOptim(Optimization):
|
| 73 |
+
""" Rewriting optimization calling replace on expressions.
|
| 74 |
+
|
| 75 |
+
Explanation
|
| 76 |
+
===========
|
| 77 |
+
|
| 78 |
+
The instance can be used as a function on expressions for which
|
| 79 |
+
it will apply the ``replace`` method (see
|
| 80 |
+
:meth:`sympy.core.basic.Basic.replace`).
|
| 81 |
+
|
| 82 |
+
Parameters
|
| 83 |
+
==========
|
| 84 |
+
|
| 85 |
+
query :
|
| 86 |
+
First argument passed to replace.
|
| 87 |
+
value :
|
| 88 |
+
Second argument passed to replace.
|
| 89 |
+
|
| 90 |
+
Examples
|
| 91 |
+
========
|
| 92 |
+
|
| 93 |
+
>>> from sympy import Symbol
|
| 94 |
+
>>> from sympy.codegen.rewriting import ReplaceOptim
|
| 95 |
+
>>> from sympy.codegen.cfunctions import exp2
|
| 96 |
+
>>> x = Symbol('x')
|
| 97 |
+
>>> exp2_opt = ReplaceOptim(lambda p: p.is_Pow and p.base == 2,
|
| 98 |
+
... lambda p: exp2(p.exp))
|
| 99 |
+
>>> exp2_opt(2**x)
|
| 100 |
+
exp2(x)
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
def __init__(self, query, value, **kwargs):
|
| 105 |
+
super().__init__(**kwargs)
|
| 106 |
+
self.query = query
|
| 107 |
+
self.value = value
|
| 108 |
+
|
| 109 |
+
def __call__(self, expr):
|
| 110 |
+
return expr.replace(self.query, self.value)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def optimize(expr, optimizations):
|
| 114 |
+
""" Apply optimizations to an expression.
|
| 115 |
+
|
| 116 |
+
Parameters
|
| 117 |
+
==========
|
| 118 |
+
|
| 119 |
+
expr : expression
|
| 120 |
+
optimizations : iterable of ``Optimization`` instances
|
| 121 |
+
The optimizations will be sorted with respect to ``priority`` (highest first).
|
| 122 |
+
|
| 123 |
+
Examples
|
| 124 |
+
========
|
| 125 |
+
|
| 126 |
+
>>> from sympy import log, Symbol
|
| 127 |
+
>>> from sympy.codegen.rewriting import optims_c99, optimize
|
| 128 |
+
>>> x = Symbol('x')
|
| 129 |
+
>>> optimize(log(x+3)/log(2) + log(x**2 + 1), optims_c99)
|
| 130 |
+
log1p(x**2) + log2(x + 3)
|
| 131 |
+
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
for optim in sorted(optimizations, key=lambda opt: opt.priority, reverse=True):
|
| 135 |
+
new_expr = optim(expr)
|
| 136 |
+
if optim.cost_function is None:
|
| 137 |
+
expr = new_expr
|
| 138 |
+
else:
|
| 139 |
+
expr = optim.cheapest(expr, new_expr)
|
| 140 |
+
return expr
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
exp2_opt = ReplaceOptim(
|
| 144 |
+
lambda p: p.is_Pow and p.base == 2,
|
| 145 |
+
lambda p: exp2(p.exp)
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
_d = Wild('d', properties=[lambda x: x.is_Dummy])
|
| 150 |
+
_u = Wild('u', properties=[lambda x: not x.is_number and not x.is_Add])
|
| 151 |
+
_v = Wild('v')
|
| 152 |
+
_w = Wild('w')
|
| 153 |
+
_n = Wild('n', properties=[lambda x: x.is_number])
|
| 154 |
+
|
| 155 |
+
sinc_opt1 = ReplaceOptim(
|
| 156 |
+
sin(_w)/_w, sinc(_w)
|
| 157 |
+
)
|
| 158 |
+
sinc_opt2 = ReplaceOptim(
|
| 159 |
+
sin(_n*_w)/_w, _n*sinc(_n*_w)
|
| 160 |
+
)
|
| 161 |
+
sinc_opts = (sinc_opt1, sinc_opt2)
|
| 162 |
+
|
| 163 |
+
log2_opt = ReplaceOptim(_v*log(_w)/log(2), _v*log2(_w), cost_function=lambda expr: expr.count(
|
| 164 |
+
lambda e: ( # division & eval of transcendentals are expensive floating point operations...
|
| 165 |
+
e.is_Pow and e.exp.is_negative # division
|
| 166 |
+
or (isinstance(e, (log, log2)) and not e.args[0].is_number)) # transcendental
|
| 167 |
+
)
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
log2const_opt = ReplaceOptim(log(2)*log2(_w), log(_w))
|
| 171 |
+
|
| 172 |
+
logsumexp_2terms_opt = ReplaceOptim(
|
| 173 |
+
lambda l: (isinstance(l, log)
|
| 174 |
+
and l.args[0].is_Add
|
| 175 |
+
and len(l.args[0].args) == 2
|
| 176 |
+
and all(isinstance(t, exp) for t in l.args[0].args)),
|
| 177 |
+
lambda l: (
|
| 178 |
+
Max(*[e.args[0] for e in l.args[0].args]) +
|
| 179 |
+
log1p(exp(Min(*[e.args[0] for e in l.args[0].args])))
|
| 180 |
+
)
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class FuncMinusOneOptim(ReplaceOptim):
|
| 185 |
+
"""Specialization of ReplaceOptim for functions evaluating "f(x) - 1".
|
| 186 |
+
|
| 187 |
+
Explanation
|
| 188 |
+
===========
|
| 189 |
+
|
| 190 |
+
Numerical functions which go toward one as x go toward zero is often best
|
| 191 |
+
implemented by a dedicated function in order to avoid catastrophic
|
| 192 |
+
cancellation. One such example is ``expm1(x)`` in the C standard library
|
| 193 |
+
which evaluates ``exp(x) - 1``. Such functions preserves many more
|
| 194 |
+
significant digits when its argument is much smaller than one, compared
|
| 195 |
+
to subtracting one afterwards.
|
| 196 |
+
|
| 197 |
+
Parameters
|
| 198 |
+
==========
|
| 199 |
+
|
| 200 |
+
func :
|
| 201 |
+
The function which is subtracted by one.
|
| 202 |
+
func_m_1 :
|
| 203 |
+
The specialized function evaluating ``func(x) - 1``.
|
| 204 |
+
opportunistic : bool
|
| 205 |
+
When ``True``, apply the transformation as long as the magnitude of the
|
| 206 |
+
remaining number terms decreases. When ``False``, only apply the
|
| 207 |
+
transformation if it completely eliminates the number term.
|
| 208 |
+
|
| 209 |
+
Examples
|
| 210 |
+
========
|
| 211 |
+
|
| 212 |
+
>>> from sympy import symbols, exp
|
| 213 |
+
>>> from sympy.codegen.rewriting import FuncMinusOneOptim
|
| 214 |
+
>>> from sympy.codegen.cfunctions import expm1
|
| 215 |
+
>>> x, y = symbols('x y')
|
| 216 |
+
>>> expm1_opt = FuncMinusOneOptim(exp, expm1)
|
| 217 |
+
>>> expm1_opt(exp(x) + 2*exp(5*y) - 3)
|
| 218 |
+
expm1(x) + 2*expm1(5*y)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
def __init__(self, func, func_m_1, opportunistic=True):
|
| 224 |
+
weight = 10 # <-- this is an arbitrary number (heuristic)
|
| 225 |
+
super().__init__(lambda e: e.is_Add, self.replace_in_Add,
|
| 226 |
+
cost_function=lambda expr: expr.count_ops() - weight*expr.count(func_m_1))
|
| 227 |
+
self.func = func
|
| 228 |
+
self.func_m_1 = func_m_1
|
| 229 |
+
self.opportunistic = opportunistic
|
| 230 |
+
|
| 231 |
+
def _group_Add_terms(self, add):
|
| 232 |
+
numbers, non_num = sift(add.args, lambda arg: arg.is_number, binary=True)
|
| 233 |
+
numsum = sum(numbers)
|
| 234 |
+
terms_with_func, other = sift(non_num, lambda arg: arg.has(self.func), binary=True)
|
| 235 |
+
return numsum, terms_with_func, other
|
| 236 |
+
|
| 237 |
+
def replace_in_Add(self, e):
|
| 238 |
+
""" passed as second argument to Basic.replace(...) """
|
| 239 |
+
numsum, terms_with_func, other_non_num_terms = self._group_Add_terms(e)
|
| 240 |
+
if numsum == 0:
|
| 241 |
+
return e
|
| 242 |
+
substituted, untouched = [], []
|
| 243 |
+
for with_func in terms_with_func:
|
| 244 |
+
if with_func.is_Mul:
|
| 245 |
+
func, coeff = sift(with_func.args, lambda arg: arg.func == self.func, binary=True)
|
| 246 |
+
if len(func) == 1 and len(coeff) == 1:
|
| 247 |
+
func, coeff = func[0], coeff[0]
|
| 248 |
+
else:
|
| 249 |
+
coeff = None
|
| 250 |
+
elif with_func.func == self.func:
|
| 251 |
+
func, coeff = with_func, S.One
|
| 252 |
+
else:
|
| 253 |
+
coeff = None
|
| 254 |
+
|
| 255 |
+
if coeff is not None and coeff.is_number and sign(coeff) == -sign(numsum):
|
| 256 |
+
if self.opportunistic:
|
| 257 |
+
do_substitute = abs(coeff+numsum) < abs(numsum)
|
| 258 |
+
else:
|
| 259 |
+
do_substitute = coeff+numsum == 0
|
| 260 |
+
|
| 261 |
+
if do_substitute: # advantageous substitution
|
| 262 |
+
numsum += coeff
|
| 263 |
+
substituted.append(coeff*self.func_m_1(*func.args))
|
| 264 |
+
continue
|
| 265 |
+
untouched.append(with_func)
|
| 266 |
+
|
| 267 |
+
return e.func(numsum, *substituted, *untouched, *other_non_num_terms)
|
| 268 |
+
|
| 269 |
+
def __call__(self, expr):
|
| 270 |
+
alt1 = super().__call__(expr)
|
| 271 |
+
alt2 = super().__call__(expr.factor())
|
| 272 |
+
return self.cheapest(alt1, alt2)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
expm1_opt = FuncMinusOneOptim(exp, expm1)
|
| 276 |
+
cosm1_opt = FuncMinusOneOptim(cos, cosm1)
|
| 277 |
+
powm1_opt = FuncMinusOneOptim(Pow, powm1)
|
| 278 |
+
|
| 279 |
+
log1p_opt = ReplaceOptim(
|
| 280 |
+
lambda e: isinstance(e, log),
|
| 281 |
+
lambda l: expand_log(l.replace(
|
| 282 |
+
log, lambda arg: log(arg.factor())
|
| 283 |
+
)).replace(log(_u+1), log1p(_u))
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
def create_expand_pow_optimization(limit, *, base_req=lambda b: b.is_symbol):
|
| 287 |
+
""" Creates an instance of :class:`ReplaceOptim` for expanding ``Pow``.
|
| 288 |
+
|
| 289 |
+
Explanation
|
| 290 |
+
===========
|
| 291 |
+
|
| 292 |
+
The requirements for expansions are that the base needs to be a symbol
|
| 293 |
+
and the exponent needs to be an Integer (and be less than or equal to
|
| 294 |
+
``limit``).
|
| 295 |
+
|
| 296 |
+
Parameters
|
| 297 |
+
==========
|
| 298 |
+
|
| 299 |
+
limit : int
|
| 300 |
+
The highest power which is expanded into multiplication.
|
| 301 |
+
base_req : function returning bool
|
| 302 |
+
Requirement on base for expansion to happen, default is to return
|
| 303 |
+
the ``is_symbol`` attribute of the base.
|
| 304 |
+
|
| 305 |
+
Examples
|
| 306 |
+
========
|
| 307 |
+
|
| 308 |
+
>>> from sympy import Symbol, sin
|
| 309 |
+
>>> from sympy.codegen.rewriting import create_expand_pow_optimization
|
| 310 |
+
>>> x = Symbol('x')
|
| 311 |
+
>>> expand_opt = create_expand_pow_optimization(3)
|
| 312 |
+
>>> expand_opt(x**5 + x**3)
|
| 313 |
+
x**5 + x*x*x
|
| 314 |
+
>>> expand_opt(x**5 + x**3 + sin(x)**3)
|
| 315 |
+
x**5 + sin(x)**3 + x*x*x
|
| 316 |
+
>>> opt2 = create_expand_pow_optimization(3, base_req=lambda b: not b.is_Function)
|
| 317 |
+
>>> opt2((x+1)**2 + sin(x)**2)
|
| 318 |
+
sin(x)**2 + (x + 1)*(x + 1)
|
| 319 |
+
|
| 320 |
+
"""
|
| 321 |
+
return ReplaceOptim(
|
| 322 |
+
lambda e: e.is_Pow and base_req(e.base) and e.exp.is_Integer and abs(e.exp) <= limit,
|
| 323 |
+
lambda p: (
|
| 324 |
+
UnevaluatedExpr(Mul(*([p.base]*+p.exp), evaluate=False)) if p.exp > 0 else
|
| 325 |
+
1/UnevaluatedExpr(Mul(*([p.base]*-p.exp), evaluate=False))
|
| 326 |
+
))
|
| 327 |
+
|
| 328 |
+
# Optimization procedures for turning A**(-1) * x into MatrixSolve(A, x)
|
| 329 |
+
def _matinv_predicate(expr):
|
| 330 |
+
# TODO: We should be able to support more than 2 elements
|
| 331 |
+
if expr.is_MatMul and len(expr.args) == 2:
|
| 332 |
+
left, right = expr.args
|
| 333 |
+
if left.is_Inverse and right.shape[1] == 1:
|
| 334 |
+
inv_arg = left.arg
|
| 335 |
+
if isinstance(inv_arg, MatrixSymbol):
|
| 336 |
+
return bool(ask(Q.fullrank(left.arg)))
|
| 337 |
+
|
| 338 |
+
return False
|
| 339 |
+
|
| 340 |
+
def _matinv_transform(expr):
|
| 341 |
+
left, right = expr.args
|
| 342 |
+
inv_arg = left.arg
|
| 343 |
+
return MatrixSolve(inv_arg, right)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
matinv_opt = ReplaceOptim(_matinv_predicate, _matinv_transform)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
logaddexp_opt = ReplaceOptim(log(exp(_v)+exp(_w)), logaddexp(_v, _w))
|
| 350 |
+
logaddexp2_opt = ReplaceOptim(log(Pow(2, _v)+Pow(2, _w)), logaddexp2(_v, _w)*log(2))
|
| 351 |
+
|
| 352 |
+
# Collections of optimizations:
|
| 353 |
+
optims_c99 = (expm1_opt, log1p_opt, exp2_opt, log2_opt, log2const_opt)
|
| 354 |
+
|
| 355 |
+
optims_numpy = optims_c99 + (logaddexp_opt, logaddexp2_opt,) + sinc_opts
|
| 356 |
+
|
| 357 |
+
optims_scipy = (cosm1_opt, powm1_opt)
|
.venv/lib/python3.12/site-packages/sympy/codegen/scipy_nodes.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.function import Add, ArgumentIndexError, Function
|
| 2 |
+
from sympy.core.power import Pow
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.functions.elementary.exponential import log
|
| 5 |
+
from sympy.functions.elementary.trigonometric import cos, sin
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _cosm1(x, *, evaluate=True):
|
| 9 |
+
return Add(cos(x, evaluate=evaluate), -S.One, evaluate=evaluate)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class cosm1(Function):
|
| 13 |
+
""" Minus one plus cosine of x, i.e. cos(x) - 1. For use when x is close to zero.
|
| 14 |
+
|
| 15 |
+
Helper class for use with e.g. scipy.special.cosm1
|
| 16 |
+
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.cosm1.html
|
| 17 |
+
"""
|
| 18 |
+
nargs = 1
|
| 19 |
+
|
| 20 |
+
def fdiff(self, argindex=1):
|
| 21 |
+
"""
|
| 22 |
+
Returns the first derivative of this function.
|
| 23 |
+
"""
|
| 24 |
+
if argindex == 1:
|
| 25 |
+
return -sin(*self.args)
|
| 26 |
+
else:
|
| 27 |
+
raise ArgumentIndexError(self, argindex)
|
| 28 |
+
|
| 29 |
+
def _eval_rewrite_as_cos(self, x, **kwargs):
|
| 30 |
+
return _cosm1(x)
|
| 31 |
+
|
| 32 |
+
def _eval_evalf(self, *args, **kwargs):
|
| 33 |
+
return self.rewrite(cos).evalf(*args, **kwargs)
|
| 34 |
+
|
| 35 |
+
def _eval_simplify(self, **kwargs):
|
| 36 |
+
x, = self.args
|
| 37 |
+
candidate = _cosm1(x.simplify(**kwargs))
|
| 38 |
+
if candidate != _cosm1(x, evaluate=False):
|
| 39 |
+
return candidate
|
| 40 |
+
else:
|
| 41 |
+
return cosm1(x)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _powm1(x, y, *, evaluate=True):
|
| 45 |
+
return Add(Pow(x, y, evaluate=evaluate), -S.One, evaluate=evaluate)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class powm1(Function):
|
| 49 |
+
""" Minus one plus x to the power of y, i.e. x**y - 1. For use when x is close to one or y is close to zero.
|
| 50 |
+
|
| 51 |
+
Helper class for use with e.g. scipy.special.powm1
|
| 52 |
+
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.powm1.html
|
| 53 |
+
"""
|
| 54 |
+
nargs = 2
|
| 55 |
+
|
| 56 |
+
def fdiff(self, argindex=1):
|
| 57 |
+
"""
|
| 58 |
+
Returns the first derivative of this function.
|
| 59 |
+
"""
|
| 60 |
+
if argindex == 1:
|
| 61 |
+
return Pow(self.args[0], self.args[1])*self.args[1]/self.args[0]
|
| 62 |
+
elif argindex == 2:
|
| 63 |
+
return log(self.args[0])*Pow(*self.args)
|
| 64 |
+
else:
|
| 65 |
+
raise ArgumentIndexError(self, argindex)
|
| 66 |
+
|
| 67 |
+
def _eval_rewrite_as_Pow(self, x, y, **kwargs):
|
| 68 |
+
return _powm1(x, y)
|
| 69 |
+
|
| 70 |
+
def _eval_evalf(self, *args, **kwargs):
|
| 71 |
+
return self.rewrite(Pow).evalf(*args, **kwargs)
|
| 72 |
+
|
| 73 |
+
def _eval_simplify(self, **kwargs):
|
| 74 |
+
x, y = self.args
|
| 75 |
+
candidate = _powm1(x.simplify(**kwargs), y.simplify(**kwargs))
|
| 76 |
+
if candidate != _powm1(x, y, evaluate=False):
|
| 77 |
+
return candidate
|
| 78 |
+
else:
|
| 79 |
+
return powm1(x, y)
|
.venv/lib/python3.12/site-packages/sympy/codegen/tests/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/sympy/codegen/tests/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (194 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/tests/__pycache__/test_abstract_nodes.cpython-312.pyc
ADDED
|
Binary file (1.29 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/tests/__pycache__/test_algorithms.cpython-312.pyc
ADDED
|
Binary file (10.9 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/tests/__pycache__/test_applications.cpython-312.pyc
ADDED
|
Binary file (3.55 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/codegen/tests/__pycache__/test_approximations.cpython-312.pyc
ADDED
|
Binary file (3.52 kB). View file
|
|
|