applied-ai-018 commited on
Commit
1e44f68
·
verified ·
1 Parent(s): 1574eb8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/13.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step80/zero/13.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
  3. ckpts/universal/global_step80/zero/20.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
  4. ckpts/universal/global_step80/zero/20.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
  5. venv/lib/python3.10/site-packages/sympy/diffgeom/__init__.py +19 -0
  6. venv/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/__init__.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/diffgeom.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/rn.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/sympy/diffgeom/diffgeom.py +2273 -0
  10. venv/lib/python3.10/site-packages/sympy/diffgeom/rn.py +143 -0
  11. venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__init__.py +0 -0
  12. venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_class_structure.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_diffgeom.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_function_diffgeom_book.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_hyperbolic_space.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/sympy/diffgeom/tests/test_class_structure.py +33 -0
  18. venv/lib/python3.10/site-packages/sympy/diffgeom/tests/test_diffgeom.py +342 -0
  19. venv/lib/python3.10/site-packages/sympy/diffgeom/tests/test_function_diffgeom_book.py +145 -0
  20. venv/lib/python3.10/site-packages/sympy/diffgeom/tests/test_hyperbolic_space.py +91 -0
  21. venv/lib/python3.10/site-packages/sympy/logic/__pycache__/__init__.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/sympy/logic/__pycache__/boolalg.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/sympy/logic/__pycache__/inference.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/sympy/logic/algorithms/__init__.py +0 -0
  25. venv/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/__init__.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/dpll.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/dpll2.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/minisat22_wrapper.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/pycosat_wrapper.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll.py +308 -0
  31. venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll2.py +659 -0
  32. venv/lib/python3.10/site-packages/sympy/logic/algorithms/minisat22_wrapper.py +46 -0
  33. venv/lib/python3.10/site-packages/sympy/logic/algorithms/pycosat_wrapper.py +41 -0
  34. venv/lib/python3.10/site-packages/sympy/logic/tests/__init__.py +0 -0
  35. venv/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/test_boolalg.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/test_dimacs.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/test_inference.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/sympy/logic/tests/test_boolalg.py +1340 -0
  40. venv/lib/python3.10/site-packages/sympy/logic/tests/test_dimacs.py +234 -0
  41. venv/lib/python3.10/site-packages/sympy/logic/tests/test_inference.py +315 -0
  42. venv/lib/python3.10/site-packages/sympy/logic/utilities/__init__.py +3 -0
  43. venv/lib/python3.10/site-packages/sympy/logic/utilities/__pycache__/__init__.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/sympy/logic/utilities/__pycache__/dimacs.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/sympy/plotting/__init__.py +22 -0
  46. venv/lib/python3.10/site-packages/sympy/plotting/experimental_lambdify.py +643 -0
  47. venv/lib/python3.10/site-packages/sympy/plotting/plot.py +2637 -0
  48. venv/lib/python3.10/site-packages/sympy/plotting/plot_implicit.py +432 -0
  49. venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__init__.py +138 -0
  50. venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/__init__.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/13.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:785559081eb2828103a981407fbf5905cd526067bbd395412d0efb018602b891
3
+ size 33555612
ckpts/universal/global_step80/zero/13.mlp.dense_h_to_4h_swiglu.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d79c0316c53126b57df63fd5587d56c318d6a1e27a71ee40751cac93110a7da
3
+ size 33555533
ckpts/universal/global_step80/zero/20.mlp.dense_h_to_4h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f7fa65e5a53100f630453eca9a75ea41f58a021f60c5a95cfceddf09b584a02
3
+ size 33555627
ckpts/universal/global_step80/zero/20.mlp.dense_h_to_4h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34e9f6573a2fddcb5d8671b6ed96d08bf0e548aba706f1aabf5a0b3bbbf759e6
3
+ size 33555533
venv/lib/python3.10/site-packages/sympy/diffgeom/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .diffgeom import (
2
+ BaseCovarDerivativeOp, BaseScalarField, BaseVectorField, Commutator,
3
+ contravariant_order, CoordSystem, CoordinateSymbol,
4
+ CovarDerivativeOp, covariant_order, Differential, intcurve_diffequ,
5
+ intcurve_series, LieDerivative, Manifold, metric_to_Christoffel_1st,
6
+ metric_to_Christoffel_2nd, metric_to_Ricci_components,
7
+ metric_to_Riemann_components, Patch, Point, TensorProduct, twoform_to_matrix,
8
+ vectors_in_basis, WedgeProduct,
9
+ )
10
+
11
+ __all__ = [
12
+ 'BaseCovarDerivativeOp', 'BaseScalarField', 'BaseVectorField', 'Commutator',
13
+ 'contravariant_order', 'CoordSystem', 'CoordinateSymbol',
14
+ 'CovarDerivativeOp', 'covariant_order', 'Differential', 'intcurve_diffequ',
15
+ 'intcurve_series', 'LieDerivative', 'Manifold', 'metric_to_Christoffel_1st',
16
+ 'metric_to_Christoffel_2nd', 'metric_to_Ricci_components',
17
+ 'metric_to_Riemann_components', 'Patch', 'Point', 'TensorProduct',
18
+ 'twoform_to_matrix', 'vectors_in_basis', 'WedgeProduct',
19
+ ]
venv/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (862 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/diffgeom.cpython-310.pyc ADDED
Binary file (76.2 kB). View file
 
venv/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/rn.cpython-310.pyc ADDED
Binary file (3.65 kB). View file
 
venv/lib/python3.10/site-packages/sympy/diffgeom/diffgeom.py ADDED
@@ -0,0 +1,2273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Any
3
+
4
+ from functools import reduce
5
+ from itertools import permutations
6
+
7
+ from sympy.combinatorics import Permutation
8
+ from sympy.core import (
9
+ Basic, Expr, Function, diff,
10
+ Pow, Mul, Add, Lambda, S, Tuple, Dict
11
+ )
12
+ from sympy.core.cache import cacheit
13
+
14
+ from sympy.core.symbol import Symbol, Dummy
15
+ from sympy.core.symbol import Str
16
+ from sympy.core.sympify import _sympify
17
+ from sympy.functions import factorial
18
+ from sympy.matrices import ImmutableDenseMatrix as Matrix
19
+ from sympy.solvers import solve
20
+
21
+ from sympy.utilities.exceptions import (sympy_deprecation_warning,
22
+ SymPyDeprecationWarning,
23
+ ignore_warnings)
24
+
25
+
26
+ # TODO you are a bit excessive in the use of Dummies
27
+ # TODO dummy point, literal field
28
+ # TODO too often one needs to call doit or simplify on the output, check the
29
+ # tests and find out why
30
+ from sympy.tensor.array import ImmutableDenseNDimArray
31
+
32
+
33
+ class Manifold(Basic):
34
+ """
35
+ A mathematical manifold.
36
+
37
+ Explanation
38
+ ===========
39
+
40
+ A manifold is a topological space that locally resembles
41
+ Euclidean space near each point [1].
42
+ This class does not provide any means to study the topological
43
+ characteristics of the manifold that it represents, though.
44
+
45
+ Parameters
46
+ ==========
47
+
48
+ name : str
49
+ The name of the manifold.
50
+
51
+ dim : int
52
+ The dimension of the manifold.
53
+
54
+ Examples
55
+ ========
56
+
57
+ >>> from sympy.diffgeom import Manifold
58
+ >>> m = Manifold('M', 2)
59
+ >>> m
60
+ M
61
+ >>> m.dim
62
+ 2
63
+
64
+ References
65
+ ==========
66
+
67
+ .. [1] https://en.wikipedia.org/wiki/Manifold
68
+ """
69
+
70
+ def __new__(cls, name, dim, **kwargs):
71
+ if not isinstance(name, Str):
72
+ name = Str(name)
73
+ dim = _sympify(dim)
74
+ obj = super().__new__(cls, name, dim)
75
+
76
+ obj.patches = _deprecated_list(
77
+ """
78
+ Manifold.patches is deprecated. The Manifold object is now
79
+ immutable. Instead use a separate list to keep track of the
80
+ patches.
81
+ """, [])
82
+ return obj
83
+
84
+ @property
85
+ def name(self):
86
+ return self.args[0]
87
+
88
+ @property
89
+ def dim(self):
90
+ return self.args[1]
91
+
92
+
93
+ class Patch(Basic):
94
+ """
95
+ A patch on a manifold.
96
+
97
+ Explanation
98
+ ===========
99
+
100
+ Coordinate patch, or patch in short, is a simply-connected open set around
101
+ a point in the manifold [1]. On a manifold one can have many patches that
102
+ do not always include the whole manifold. On these patches coordinate
103
+ charts can be defined that permit the parameterization of any point on the
104
+ patch in terms of a tuple of real numbers (the coordinates).
105
+
106
+ This class does not provide any means to study the topological
107
+ characteristics of the patch that it represents.
108
+
109
+ Parameters
110
+ ==========
111
+
112
+ name : str
113
+ The name of the patch.
114
+
115
+ manifold : Manifold
116
+ The manifold on which the patch is defined.
117
+
118
+ Examples
119
+ ========
120
+
121
+ >>> from sympy.diffgeom import Manifold, Patch
122
+ >>> m = Manifold('M', 2)
123
+ >>> p = Patch('P', m)
124
+ >>> p
125
+ P
126
+ >>> p.dim
127
+ 2
128
+
129
+ References
130
+ ==========
131
+
132
+ .. [1] G. Sussman, J. Wisdom, W. Farr, Functional Differential Geometry
133
+ (2013)
134
+
135
+ """
136
+ def __new__(cls, name, manifold, **kwargs):
137
+ if not isinstance(name, Str):
138
+ name = Str(name)
139
+ obj = super().__new__(cls, name, manifold)
140
+
141
+ obj.manifold.patches.append(obj) # deprecated
142
+ obj.coord_systems = _deprecated_list(
143
+ """
144
+ Patch.coord_systms is deprecated. The Patch class is now
145
+ immutable. Instead use a separate list to keep track of coordinate
146
+ systems.
147
+ """, [])
148
+ return obj
149
+
150
+ @property
151
+ def name(self):
152
+ return self.args[0]
153
+
154
+ @property
155
+ def manifold(self):
156
+ return self.args[1]
157
+
158
+ @property
159
+ def dim(self):
160
+ return self.manifold.dim
161
+
162
+
163
+ class CoordSystem(Basic):
164
+ """
165
+ A coordinate system defined on the patch.
166
+
167
+ Explanation
168
+ ===========
169
+
170
+ Coordinate system is a system that uses one or more coordinates to uniquely
171
+ determine the position of the points or other geometric elements on a
172
+ manifold [1].
173
+
174
+ By passing ``Symbols`` to *symbols* parameter, user can define the name and
175
+ assumptions of coordinate symbols of the coordinate system. If not passed,
176
+ these symbols are generated automatically and are assumed to be real valued.
177
+
178
+ By passing *relations* parameter, user can define the transform relations of
179
+ coordinate systems. Inverse transformation and indirect transformation can
180
+ be found automatically. If this parameter is not passed, coordinate
181
+ transformation cannot be done.
182
+
183
+ Parameters
184
+ ==========
185
+
186
+ name : str
187
+ The name of the coordinate system.
188
+
189
+ patch : Patch
190
+ The patch where the coordinate system is defined.
191
+
192
+ symbols : list of Symbols, optional
193
+ Defines the names and assumptions of coordinate symbols.
194
+
195
+ relations : dict, optional
196
+ Key is a tuple of two strings, who are the names of the systems where
197
+ the coordinates transform from and transform to.
198
+ Value is a tuple of the symbols before transformation and a tuple of
199
+ the expressions after transformation.
200
+
201
+ Examples
202
+ ========
203
+
204
+ We define two-dimensional Cartesian coordinate system and polar coordinate
205
+ system.
206
+
207
+ >>> from sympy import symbols, pi, sqrt, atan2, cos, sin
208
+ >>> from sympy.diffgeom import Manifold, Patch, CoordSystem
209
+ >>> m = Manifold('M', 2)
210
+ >>> p = Patch('P', m)
211
+ >>> x, y = symbols('x y', real=True)
212
+ >>> r, theta = symbols('r theta', nonnegative=True)
213
+ >>> relation_dict = {
214
+ ... ('Car2D', 'Pol'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))],
215
+ ... ('Pol', 'Car2D'): [(r, theta), (r*cos(theta), r*sin(theta))]
216
+ ... }
217
+ >>> Car2D = CoordSystem('Car2D', p, (x, y), relation_dict)
218
+ >>> Pol = CoordSystem('Pol', p, (r, theta), relation_dict)
219
+
220
+ ``symbols`` property returns ``CoordinateSymbol`` instances. These symbols
221
+ are not same with the symbols used to construct the coordinate system.
222
+
223
+ >>> Car2D
224
+ Car2D
225
+ >>> Car2D.dim
226
+ 2
227
+ >>> Car2D.symbols
228
+ (x, y)
229
+ >>> _[0].func
230
+ <class 'sympy.diffgeom.diffgeom.CoordinateSymbol'>
231
+
232
+ ``transformation()`` method returns the transformation function from
233
+ one coordinate system to another. ``transform()`` method returns the
234
+ transformed coordinates.
235
+
236
+ >>> Car2D.transformation(Pol)
237
+ Lambda((x, y), Matrix([
238
+ [sqrt(x**2 + y**2)],
239
+ [ atan2(y, x)]]))
240
+ >>> Car2D.transform(Pol)
241
+ Matrix([
242
+ [sqrt(x**2 + y**2)],
243
+ [ atan2(y, x)]])
244
+ >>> Car2D.transform(Pol, [1, 2])
245
+ Matrix([
246
+ [sqrt(5)],
247
+ [atan(2)]])
248
+
249
+ ``jacobian()`` method returns the Jacobian matrix of coordinate
250
+ transformation between two systems. ``jacobian_determinant()`` method
251
+ returns the Jacobian determinant of coordinate transformation between two
252
+ systems.
253
+
254
+ >>> Pol.jacobian(Car2D)
255
+ Matrix([
256
+ [cos(theta), -r*sin(theta)],
257
+ [sin(theta), r*cos(theta)]])
258
+ >>> Pol.jacobian(Car2D, [1, pi/2])
259
+ Matrix([
260
+ [0, -1],
261
+ [1, 0]])
262
+ >>> Car2D.jacobian_determinant(Pol)
263
+ 1/sqrt(x**2 + y**2)
264
+ >>> Car2D.jacobian_determinant(Pol, [1,0])
265
+ 1
266
+
267
+ References
268
+ ==========
269
+
270
+ .. [1] https://en.wikipedia.org/wiki/Coordinate_system
271
+
272
+ """
273
+ def __new__(cls, name, patch, symbols=None, relations={}, **kwargs):
274
+ if not isinstance(name, Str):
275
+ name = Str(name)
276
+
277
+ # canonicallize the symbols
278
+ if symbols is None:
279
+ names = kwargs.get('names', None)
280
+ if names is None:
281
+ symbols = Tuple(
282
+ *[Symbol('%s_%s' % (name.name, i), real=True)
283
+ for i in range(patch.dim)]
284
+ )
285
+ else:
286
+ sympy_deprecation_warning(
287
+ f"""
288
+ The 'names' argument to CoordSystem is deprecated. Use 'symbols' instead. That
289
+ is, replace
290
+
291
+ CoordSystem(..., names={names})
292
+
293
+ with
294
+
295
+ CoordSystem(..., symbols=[{', '.join(["Symbol(" + repr(n) + ", real=True)" for n in names])}])
296
+ """,
297
+ deprecated_since_version="1.7",
298
+ active_deprecations_target="deprecated-diffgeom-mutable",
299
+ )
300
+ symbols = Tuple(
301
+ *[Symbol(n, real=True) for n in names]
302
+ )
303
+ else:
304
+ syms = []
305
+ for s in symbols:
306
+ if isinstance(s, Symbol):
307
+ syms.append(Symbol(s.name, **s._assumptions.generator))
308
+ elif isinstance(s, str):
309
+ sympy_deprecation_warning(
310
+ f"""
311
+
312
+ Passing a string as the coordinate symbol name to CoordSystem is deprecated.
313
+ Pass a Symbol with the appropriate name and assumptions instead.
314
+
315
+ That is, replace {s} with Symbol({s!r}, real=True).
316
+ """,
317
+
318
+ deprecated_since_version="1.7",
319
+ active_deprecations_target="deprecated-diffgeom-mutable",
320
+ )
321
+ syms.append(Symbol(s, real=True))
322
+ symbols = Tuple(*syms)
323
+
324
+ # canonicallize the relations
325
+ rel_temp = {}
326
+ for k,v in relations.items():
327
+ s1, s2 = k
328
+ if not isinstance(s1, Str):
329
+ s1 = Str(s1)
330
+ if not isinstance(s2, Str):
331
+ s2 = Str(s2)
332
+ key = Tuple(s1, s2)
333
+
334
+ # Old version used Lambda as a value.
335
+ if isinstance(v, Lambda):
336
+ v = (tuple(v.signature), tuple(v.expr))
337
+ else:
338
+ v = (tuple(v[0]), tuple(v[1]))
339
+ rel_temp[key] = v
340
+ relations = Dict(rel_temp)
341
+
342
+ # construct the object
343
+ obj = super().__new__(cls, name, patch, symbols, relations)
344
+
345
+ # Add deprecated attributes
346
+ obj.transforms = _deprecated_dict(
347
+ """
348
+ CoordSystem.transforms is deprecated. The CoordSystem class is now
349
+ immutable. Use the 'relations' keyword argument to the
350
+ CoordSystems() constructor to specify relations.
351
+ """, {})
352
+ obj._names = [str(n) for n in symbols]
353
+ obj.patch.coord_systems.append(obj) # deprecated
354
+ obj._dummies = [Dummy(str(n)) for n in symbols] # deprecated
355
+ obj._dummy = Dummy()
356
+
357
+ return obj
358
+
359
+ @property
360
+ def name(self):
361
+ return self.args[0]
362
+
363
+ @property
364
+ def patch(self):
365
+ return self.args[1]
366
+
367
+ @property
368
+ def manifold(self):
369
+ return self.patch.manifold
370
+
371
+ @property
372
+ def symbols(self):
373
+ return tuple(CoordinateSymbol(self, i, **s._assumptions.generator)
374
+ for i,s in enumerate(self.args[2]))
375
+
376
+ @property
377
+ def relations(self):
378
+ return self.args[3]
379
+
380
+ @property
381
+ def dim(self):
382
+ return self.patch.dim
383
+
384
+ ##########################################################################
385
+ # Finding transformation relation
386
+ ##########################################################################
387
+
388
+ def transformation(self, sys):
389
+ """
390
+ Return coordinate transformation function from *self* to *sys*.
391
+
392
+ Parameters
393
+ ==========
394
+
395
+ sys : CoordSystem
396
+
397
+ Returns
398
+ =======
399
+
400
+ sympy.Lambda
401
+
402
+ Examples
403
+ ========
404
+
405
+ >>> from sympy.diffgeom.rn import R2_r, R2_p
406
+ >>> R2_r.transformation(R2_p)
407
+ Lambda((x, y), Matrix([
408
+ [sqrt(x**2 + y**2)],
409
+ [ atan2(y, x)]]))
410
+
411
+ """
412
+ signature = self.args[2]
413
+
414
+ key = Tuple(self.name, sys.name)
415
+ if self == sys:
416
+ expr = Matrix(self.symbols)
417
+ elif key in self.relations:
418
+ expr = Matrix(self.relations[key][1])
419
+ elif key[::-1] in self.relations:
420
+ expr = Matrix(self._inverse_transformation(sys, self))
421
+ else:
422
+ expr = Matrix(self._indirect_transformation(self, sys))
423
+ return Lambda(signature, expr)
424
+
425
+ @staticmethod
426
+ def _solve_inverse(sym1, sym2, exprs, sys1_name, sys2_name):
427
+ ret = solve(
428
+ [t[0] - t[1] for t in zip(sym2, exprs)],
429
+ list(sym1), dict=True)
430
+
431
+ if len(ret) == 0:
432
+ temp = "Cannot solve inverse relation from {} to {}."
433
+ raise NotImplementedError(temp.format(sys1_name, sys2_name))
434
+ elif len(ret) > 1:
435
+ temp = "Obtained multiple inverse relation from {} to {}."
436
+ raise ValueError(temp.format(sys1_name, sys2_name))
437
+
438
+ return ret[0]
439
+
440
+ @classmethod
441
+ def _inverse_transformation(cls, sys1, sys2):
442
+ # Find the transformation relation from sys2 to sys1
443
+ forward = sys1.transform(sys2)
444
+ inv_results = cls._solve_inverse(sys1.symbols, sys2.symbols, forward,
445
+ sys1.name, sys2.name)
446
+ signature = tuple(sys1.symbols)
447
+ return [inv_results[s] for s in signature]
448
+
449
+ @classmethod
450
+ @cacheit
451
+ def _indirect_transformation(cls, sys1, sys2):
452
+ # Find the transformation relation between two indirectly connected
453
+ # coordinate systems
454
+ rel = sys1.relations
455
+ path = cls._dijkstra(sys1, sys2)
456
+
457
+ transforms = []
458
+ for s1, s2 in zip(path, path[1:]):
459
+ if (s1, s2) in rel:
460
+ transforms.append(rel[(s1, s2)])
461
+ else:
462
+ sym2, inv_exprs = rel[(s2, s1)]
463
+ sym1 = tuple(Dummy() for i in sym2)
464
+ ret = cls._solve_inverse(sym2, sym1, inv_exprs, s2, s1)
465
+ ret = tuple(ret[s] for s in sym2)
466
+ transforms.append((sym1, ret))
467
+ syms = sys1.args[2]
468
+ exprs = syms
469
+ for newsyms, newexprs in transforms:
470
+ exprs = tuple(e.subs(zip(newsyms, exprs)) for e in newexprs)
471
+ return exprs
472
+
473
+ @staticmethod
474
+ def _dijkstra(sys1, sys2):
475
+ # Use Dijkstra algorithm to find the shortest path between two indirectly-connected
476
+ # coordinate systems
477
+ # return value is the list of the names of the systems.
478
+ relations = sys1.relations
479
+ graph = {}
480
+ for s1, s2 in relations.keys():
481
+ if s1 not in graph:
482
+ graph[s1] = {s2}
483
+ else:
484
+ graph[s1].add(s2)
485
+ if s2 not in graph:
486
+ graph[s2] = {s1}
487
+ else:
488
+ graph[s2].add(s1)
489
+
490
+ path_dict = {sys:[0, [], 0] for sys in graph} # minimum distance, path, times of visited
491
+
492
+ def visit(sys):
493
+ path_dict[sys][2] = 1
494
+ for newsys in graph[sys]:
495
+ distance = path_dict[sys][0] + 1
496
+ if path_dict[newsys][0] >= distance or not path_dict[newsys][1]:
497
+ path_dict[newsys][0] = distance
498
+ path_dict[newsys][1] = list(path_dict[sys][1])
499
+ path_dict[newsys][1].append(sys)
500
+
501
+ visit(sys1.name)
502
+
503
+ while True:
504
+ min_distance = max(path_dict.values(), key=lambda x:x[0])[0]
505
+ newsys = None
506
+ for sys, lst in path_dict.items():
507
+ if 0 < lst[0] <= min_distance and not lst[2]:
508
+ min_distance = lst[0]
509
+ newsys = sys
510
+ if newsys is None:
511
+ break
512
+ visit(newsys)
513
+
514
+ result = path_dict[sys2.name][1]
515
+ result.append(sys2.name)
516
+
517
+ if result == [sys2.name]:
518
+ raise KeyError("Two coordinate systems are not connected.")
519
+ return result
520
+
521
+ def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=False):
522
+ sympy_deprecation_warning(
523
+ """
524
+ The CoordSystem.connect_to() method is deprecated. Instead,
525
+ generate a new instance of CoordSystem with the 'relations'
526
+ keyword argument (CoordSystem classes are now immutable).
527
+ """,
528
+ deprecated_since_version="1.7",
529
+ active_deprecations_target="deprecated-diffgeom-mutable",
530
+ )
531
+
532
+ from_coords, to_exprs = dummyfy(from_coords, to_exprs)
533
+ self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs)
534
+
535
+ if inverse:
536
+ to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs)
537
+
538
+ if fill_in_gaps:
539
+ self._fill_gaps_in_transformations()
540
+
541
+ @staticmethod
542
+ def _inv_transf(from_coords, to_exprs):
543
+ # Will be removed when connect_to is removed
544
+ inv_from = [i.as_dummy() for i in from_coords]
545
+ inv_to = solve(
546
+ [t[0] - t[1] for t in zip(inv_from, to_exprs)],
547
+ list(from_coords), dict=True)[0]
548
+ inv_to = [inv_to[fc] for fc in from_coords]
549
+ return Matrix(inv_from), Matrix(inv_to)
550
+
551
+ @staticmethod
552
+ def _fill_gaps_in_transformations():
553
+ # Will be removed when connect_to is removed
554
+ raise NotImplementedError
555
+
556
+ ##########################################################################
557
+ # Coordinate transformations
558
+ ##########################################################################
559
+
560
+ def transform(self, sys, coordinates=None):
561
+ """
562
+ Return the result of coordinate transformation from *self* to *sys*.
563
+ If coordinates are not given, coordinate symbols of *self* are used.
564
+
565
+ Parameters
566
+ ==========
567
+
568
+ sys : CoordSystem
569
+
570
+ coordinates : Any iterable, optional.
571
+
572
+ Returns
573
+ =======
574
+
575
+ sympy.ImmutableDenseMatrix containing CoordinateSymbol
576
+
577
+ Examples
578
+ ========
579
+
580
+ >>> from sympy.diffgeom.rn import R2_r, R2_p
581
+ >>> R2_r.transform(R2_p)
582
+ Matrix([
583
+ [sqrt(x**2 + y**2)],
584
+ [ atan2(y, x)]])
585
+ >>> R2_r.transform(R2_p, [0, 1])
586
+ Matrix([
587
+ [ 1],
588
+ [pi/2]])
589
+
590
+ """
591
+ if coordinates is None:
592
+ coordinates = self.symbols
593
+ if self != sys:
594
+ transf = self.transformation(sys)
595
+ coordinates = transf(*coordinates)
596
+ else:
597
+ coordinates = Matrix(coordinates)
598
+ return coordinates
599
+
600
+ def coord_tuple_transform_to(self, to_sys, coords):
601
+ """Transform ``coords`` to coord system ``to_sys``."""
602
+ sympy_deprecation_warning(
603
+ """
604
+ The CoordSystem.coord_tuple_transform_to() method is deprecated.
605
+ Use the CoordSystem.transform() method instead.
606
+ """,
607
+ deprecated_since_version="1.7",
608
+ active_deprecations_target="deprecated-diffgeom-mutable",
609
+ )
610
+
611
+ coords = Matrix(coords)
612
+ if self != to_sys:
613
+ with ignore_warnings(SymPyDeprecationWarning):
614
+ transf = self.transforms[to_sys]
615
+ coords = transf[1].subs(list(zip(transf[0], coords)))
616
+ return coords
617
+
618
+ def jacobian(self, sys, coordinates=None):
619
+ """
620
+ Return the jacobian matrix of a transformation on given coordinates.
621
+ If coordinates are not given, coordinate symbols of *self* are used.
622
+
623
+ Parameters
624
+ ==========
625
+
626
+ sys : CoordSystem
627
+
628
+ coordinates : Any iterable, optional.
629
+
630
+ Returns
631
+ =======
632
+
633
+ sympy.ImmutableDenseMatrix
634
+
635
+ Examples
636
+ ========
637
+
638
+ >>> from sympy.diffgeom.rn import R2_r, R2_p
639
+ >>> R2_p.jacobian(R2_r)
640
+ Matrix([
641
+ [cos(theta), -rho*sin(theta)],
642
+ [sin(theta), rho*cos(theta)]])
643
+ >>> R2_p.jacobian(R2_r, [1, 0])
644
+ Matrix([
645
+ [1, 0],
646
+ [0, 1]])
647
+
648
+ """
649
+ result = self.transform(sys).jacobian(self.symbols)
650
+ if coordinates is not None:
651
+ result = result.subs(list(zip(self.symbols, coordinates)))
652
+ return result
653
+ jacobian_matrix = jacobian
654
+
655
+ def jacobian_determinant(self, sys, coordinates=None):
656
+ """
657
+ Return the jacobian determinant of a transformation on given
658
+ coordinates. If coordinates are not given, coordinate symbols of *self*
659
+ are used.
660
+
661
+ Parameters
662
+ ==========
663
+
664
+ sys : CoordSystem
665
+
666
+ coordinates : Any iterable, optional.
667
+
668
+ Returns
669
+ =======
670
+
671
+ sympy.Expr
672
+
673
+ Examples
674
+ ========
675
+
676
+ >>> from sympy.diffgeom.rn import R2_r, R2_p
677
+ >>> R2_r.jacobian_determinant(R2_p)
678
+ 1/sqrt(x**2 + y**2)
679
+ >>> R2_r.jacobian_determinant(R2_p, [1, 0])
680
+ 1
681
+
682
+ """
683
+ return self.jacobian(sys, coordinates).det()
684
+
685
+
686
+ ##########################################################################
687
+ # Points
688
+ ##########################################################################
689
+
690
+ def point(self, coords):
691
+ """Create a ``Point`` with coordinates given in this coord system."""
692
+ return Point(self, coords)
693
+
694
+ def point_to_coords(self, point):
695
+ """Calculate the coordinates of a point in this coord system."""
696
+ return point.coords(self)
697
+
698
+ ##########################################################################
699
+ # Base fields.
700
+ ##########################################################################
701
+
702
+ def base_scalar(self, coord_index):
703
+ """Return ``BaseScalarField`` that takes a point and returns one of the coordinates."""
704
+ return BaseScalarField(self, coord_index)
705
+ coord_function = base_scalar
706
+
707
+ def base_scalars(self):
708
+ """Returns a list of all coordinate functions.
709
+ For more details see the ``base_scalar`` method of this class."""
710
+ return [self.base_scalar(i) for i in range(self.dim)]
711
+ coord_functions = base_scalars
712
+
713
+ def base_vector(self, coord_index):
714
+ """Return a basis vector field.
715
+ The basis vector field for this coordinate system. It is also an
716
+ operator on scalar fields."""
717
+ return BaseVectorField(self, coord_index)
718
+
719
+ def base_vectors(self):
720
+ """Returns a list of all base vectors.
721
+ For more details see the ``base_vector`` method of this class."""
722
+ return [self.base_vector(i) for i in range(self.dim)]
723
+
724
+ def base_oneform(self, coord_index):
725
+ """Return a basis 1-form field.
726
+ The basis one-form field for this coordinate system. It is also an
727
+ operator on vector fields."""
728
+ return Differential(self.coord_function(coord_index))
729
+
730
+ def base_oneforms(self):
731
+ """Returns a list of all base oneforms.
732
+ For more details see the ``base_oneform`` method of this class."""
733
+ return [self.base_oneform(i) for i in range(self.dim)]
734
+
735
+
736
+ class CoordinateSymbol(Symbol):
737
+ """A symbol which denotes an abstract value of i-th coordinate of
738
+ the coordinate system with given context.
739
+
740
+ Explanation
741
+ ===========
742
+
743
+ Each coordinates in coordinate system are represented by unique symbol,
744
+ such as x, y, z in Cartesian coordinate system.
745
+
746
+ You may not construct this class directly. Instead, use `symbols` method
747
+ of CoordSystem.
748
+
749
+ Parameters
750
+ ==========
751
+
752
+ coord_sys : CoordSystem
753
+
754
+ index : integer
755
+
756
+ Examples
757
+ ========
758
+
759
+ >>> from sympy import symbols, Lambda, Matrix, sqrt, atan2, cos, sin
760
+ >>> from sympy.diffgeom import Manifold, Patch, CoordSystem
761
+ >>> m = Manifold('M', 2)
762
+ >>> p = Patch('P', m)
763
+ >>> x, y = symbols('x y', real=True)
764
+ >>> r, theta = symbols('r theta', nonnegative=True)
765
+ >>> relation_dict = {
766
+ ... ('Car2D', 'Pol'): Lambda((x, y), Matrix([sqrt(x**2 + y**2), atan2(y, x)])),
767
+ ... ('Pol', 'Car2D'): Lambda((r, theta), Matrix([r*cos(theta), r*sin(theta)]))
768
+ ... }
769
+ >>> Car2D = CoordSystem('Car2D', p, [x, y], relation_dict)
770
+ >>> Pol = CoordSystem('Pol', p, [r, theta], relation_dict)
771
+ >>> x, y = Car2D.symbols
772
+
773
+ ``CoordinateSymbol`` contains its coordinate symbol and index.
774
+
775
+ >>> x.name
776
+ 'x'
777
+ >>> x.coord_sys == Car2D
778
+ True
779
+ >>> x.index
780
+ 0
781
+ >>> x.is_real
782
+ True
783
+
784
+ You can transform ``CoordinateSymbol`` into other coordinate system using
785
+ ``rewrite()`` method.
786
+
787
+ >>> x.rewrite(Pol)
788
+ r*cos(theta)
789
+ >>> sqrt(x**2 + y**2).rewrite(Pol).simplify()
790
+ r
791
+
792
+ """
793
+ def __new__(cls, coord_sys, index, **assumptions):
794
+ name = coord_sys.args[2][index].name
795
+ obj = super().__new__(cls, name, **assumptions)
796
+ obj.coord_sys = coord_sys
797
+ obj.index = index
798
+ return obj
799
+
800
+ def __getnewargs__(self):
801
+ return (self.coord_sys, self.index)
802
+
803
+ def _hashable_content(self):
804
+ return (
805
+ self.coord_sys, self.index
806
+ ) + tuple(sorted(self.assumptions0.items()))
807
+
808
+ def _eval_rewrite(self, rule, args, **hints):
809
+ if isinstance(rule, CoordSystem):
810
+ return rule.transform(self.coord_sys)[self.index]
811
+ return super()._eval_rewrite(rule, args, **hints)
812
+
813
+
814
+ class Point(Basic):
815
+ """Point defined in a coordinate system.
816
+
817
+ Explanation
818
+ ===========
819
+
820
+ Mathematically, point is defined in the manifold and does not have any coordinates
821
+ by itself. Coordinate system is what imbues the coordinates to the point by coordinate
822
+ chart. However, due to the difficulty of realizing such logic, you must supply
823
+ a coordinate system and coordinates to define a Point here.
824
+
825
+ The usage of this object after its definition is independent of the
826
+ coordinate system that was used in order to define it, however due to
827
+ limitations in the simplification routines you can arrive at complicated
828
+ expressions if you use inappropriate coordinate systems.
829
+
830
+ Parameters
831
+ ==========
832
+
833
+ coord_sys : CoordSystem
834
+
835
+ coords : list
836
+ The coordinates of the point.
837
+
838
+ Examples
839
+ ========
840
+
841
+ >>> from sympy import pi
842
+ >>> from sympy.diffgeom import Point
843
+ >>> from sympy.diffgeom.rn import R2, R2_r, R2_p
844
+ >>> rho, theta = R2_p.symbols
845
+
846
+ >>> p = Point(R2_p, [rho, 3*pi/4])
847
+
848
+ >>> p.manifold == R2
849
+ True
850
+
851
+ >>> p.coords()
852
+ Matrix([
853
+ [ rho],
854
+ [3*pi/4]])
855
+ >>> p.coords(R2_r)
856
+ Matrix([
857
+ [-sqrt(2)*rho/2],
858
+ [ sqrt(2)*rho/2]])
859
+
860
+ """
861
+
862
+ def __new__(cls, coord_sys, coords, **kwargs):
863
+ coords = Matrix(coords)
864
+ obj = super().__new__(cls, coord_sys, coords)
865
+ obj._coord_sys = coord_sys
866
+ obj._coords = coords
867
+ return obj
868
+
869
+ @property
870
+ def patch(self):
871
+ return self._coord_sys.patch
872
+
873
+ @property
874
+ def manifold(self):
875
+ return self._coord_sys.manifold
876
+
877
+ @property
878
+ def dim(self):
879
+ return self.manifold.dim
880
+
881
+ def coords(self, sys=None):
882
+ """
883
+ Coordinates of the point in given coordinate system. If coordinate system
884
+ is not passed, it returns the coordinates in the coordinate system in which
885
+ the poin was defined.
886
+ """
887
+ if sys is None:
888
+ return self._coords
889
+ else:
890
+ return self._coord_sys.transform(sys, self._coords)
891
+
892
+ @property
893
+ def free_symbols(self):
894
+ return self._coords.free_symbols
895
+
896
+
897
+ class BaseScalarField(Expr):
898
+ """Base scalar field over a manifold for a given coordinate system.
899
+
900
+ Explanation
901
+ ===========
902
+
903
+ A scalar field takes a point as an argument and returns a scalar.
904
+ A base scalar field of a coordinate system takes a point and returns one of
905
+ the coordinates of that point in the coordinate system in question.
906
+
907
+ To define a scalar field you need to choose the coordinate system and the
908
+ index of the coordinate.
909
+
910
+ The use of the scalar field after its definition is independent of the
911
+ coordinate system in which it was defined, however due to limitations in
912
+ the simplification routines you may arrive at more complicated
913
+ expression if you use unappropriate coordinate systems.
914
+ You can build complicated scalar fields by just building up SymPy
915
+ expressions containing ``BaseScalarField`` instances.
916
+
917
+ Parameters
918
+ ==========
919
+
920
+ coord_sys : CoordSystem
921
+
922
+ index : integer
923
+
924
+ Examples
925
+ ========
926
+
927
+ >>> from sympy import Function, pi
928
+ >>> from sympy.diffgeom import BaseScalarField
929
+ >>> from sympy.diffgeom.rn import R2_r, R2_p
930
+ >>> rho, _ = R2_p.symbols
931
+ >>> point = R2_p.point([rho, 0])
932
+ >>> fx, fy = R2_r.base_scalars()
933
+ >>> ftheta = BaseScalarField(R2_r, 1)
934
+
935
+ >>> fx(point)
936
+ rho
937
+ >>> fy(point)
938
+ 0
939
+
940
+ >>> (fx**2+fy**2).rcall(point)
941
+ rho**2
942
+
943
+ >>> g = Function('g')
944
+ >>> fg = g(ftheta-pi)
945
+ >>> fg.rcall(point)
946
+ g(-pi)
947
+
948
+ """
949
+
950
+ is_commutative = True
951
+
952
+ def __new__(cls, coord_sys, index, **kwargs):
953
+ index = _sympify(index)
954
+ obj = super().__new__(cls, coord_sys, index)
955
+ obj._coord_sys = coord_sys
956
+ obj._index = index
957
+ return obj
958
+
959
+ @property
960
+ def coord_sys(self):
961
+ return self.args[0]
962
+
963
+ @property
964
+ def index(self):
965
+ return self.args[1]
966
+
967
+ @property
968
+ def patch(self):
969
+ return self.coord_sys.patch
970
+
971
+ @property
972
+ def manifold(self):
973
+ return self.coord_sys.manifold
974
+
975
+ @property
976
+ def dim(self):
977
+ return self.manifold.dim
978
+
979
+ def __call__(self, *args):
980
+ """Evaluating the field at a point or doing nothing.
981
+ If the argument is a ``Point`` instance, the field is evaluated at that
982
+ point. The field is returned itself if the argument is any other
983
+ object. It is so in order to have working recursive calling mechanics
984
+ for all fields (check the ``__call__`` method of ``Expr``).
985
+ """
986
+ point = args[0]
987
+ if len(args) != 1 or not isinstance(point, Point):
988
+ return self
989
+ coords = point.coords(self._coord_sys)
990
+ # XXX Calling doit is necessary with all the Subs expressions
991
+ # XXX Calling simplify is necessary with all the trig expressions
992
+ return simplify(coords[self._index]).doit()
993
+
994
+ # XXX Workaround for limitations on the content of args
995
+ free_symbols: set[Any] = set()
996
+
997
+
998
+ class BaseVectorField(Expr):
999
+ r"""Base vector field over a manifold for a given coordinate system.
1000
+
1001
+ Explanation
1002
+ ===========
1003
+
1004
+ A vector field is an operator taking a scalar field and returning a
1005
+ directional derivative (which is also a scalar field).
1006
+ A base vector field is the same type of operator, however the derivation is
1007
+ specifically done with respect to a chosen coordinate.
1008
+
1009
+ To define a base vector field you need to choose the coordinate system and
1010
+ the index of the coordinate.
1011
+
1012
+ The use of the vector field after its definition is independent of the
1013
+ coordinate system in which it was defined, however due to limitations in the
1014
+ simplification routines you may arrive at more complicated expression if you
1015
+ use unappropriate coordinate systems.
1016
+
1017
+ Parameters
1018
+ ==========
1019
+ coord_sys : CoordSystem
1020
+
1021
+ index : integer
1022
+
1023
+ Examples
1024
+ ========
1025
+
1026
+ >>> from sympy import Function
1027
+ >>> from sympy.diffgeom.rn import R2_p, R2_r
1028
+ >>> from sympy.diffgeom import BaseVectorField
1029
+ >>> from sympy import pprint
1030
+
1031
+ >>> x, y = R2_r.symbols
1032
+ >>> rho, theta = R2_p.symbols
1033
+ >>> fx, fy = R2_r.base_scalars()
1034
+ >>> point_p = R2_p.point([rho, theta])
1035
+ >>> point_r = R2_r.point([x, y])
1036
+
1037
+ >>> g = Function('g')
1038
+ >>> s_field = g(fx, fy)
1039
+
1040
+ >>> v = BaseVectorField(R2_r, 1)
1041
+ >>> pprint(v(s_field))
1042
+ / d \|
1043
+ |---(g(x, xi))||
1044
+ \dxi /|xi=y
1045
+ >>> pprint(v(s_field).rcall(point_r).doit())
1046
+ d
1047
+ --(g(x, y))
1048
+ dy
1049
+ >>> pprint(v(s_field).rcall(point_p))
1050
+ / d \|
1051
+ |---(g(rho*cos(theta), xi))||
1052
+ \dxi /|xi=rho*sin(theta)
1053
+
1054
+ """
1055
+
1056
+ is_commutative = False
1057
+
1058
+ def __new__(cls, coord_sys, index, **kwargs):
1059
+ index = _sympify(index)
1060
+ obj = super().__new__(cls, coord_sys, index)
1061
+ obj._coord_sys = coord_sys
1062
+ obj._index = index
1063
+ return obj
1064
+
1065
+ @property
1066
+ def coord_sys(self):
1067
+ return self.args[0]
1068
+
1069
+ @property
1070
+ def index(self):
1071
+ return self.args[1]
1072
+
1073
+ @property
1074
+ def patch(self):
1075
+ return self.coord_sys.patch
1076
+
1077
+ @property
1078
+ def manifold(self):
1079
+ return self.coord_sys.manifold
1080
+
1081
+ @property
1082
+ def dim(self):
1083
+ return self.manifold.dim
1084
+
1085
+ def __call__(self, scalar_field):
1086
+ """Apply on a scalar field.
1087
+ The action of a vector field on a scalar field is a directional
1088
+ differentiation.
1089
+ If the argument is not a scalar field an error is raised.
1090
+ """
1091
+ if covariant_order(scalar_field) or contravariant_order(scalar_field):
1092
+ raise ValueError('Only scalar fields can be supplied as arguments to vector fields.')
1093
+
1094
+ if scalar_field is None:
1095
+ return self
1096
+
1097
+ base_scalars = list(scalar_field.atoms(BaseScalarField))
1098
+
1099
+ # First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r)
1100
+ d_var = self._coord_sys._dummy
1101
+ # TODO: you need a real dummy function for the next line
1102
+ d_funcs = [Function('_#_%s' % i)(d_var) for i,
1103
+ b in enumerate(base_scalars)]
1104
+ d_result = scalar_field.subs(list(zip(base_scalars, d_funcs)))
1105
+ d_result = d_result.diff(d_var)
1106
+
1107
+ # Second step: e_x(x) -> 1 and e_x(r) -> cos(atan2(x, y))
1108
+ coords = self._coord_sys.symbols
1109
+ d_funcs_deriv = [f.diff(d_var) for f in d_funcs]
1110
+ d_funcs_deriv_sub = []
1111
+ for b in base_scalars:
1112
+ jac = self._coord_sys.jacobian(b._coord_sys, coords)
1113
+ d_funcs_deriv_sub.append(jac[b._index, self._index])
1114
+ d_result = d_result.subs(list(zip(d_funcs_deriv, d_funcs_deriv_sub)))
1115
+
1116
+ # Remove the dummies
1117
+ result = d_result.subs(list(zip(d_funcs, base_scalars)))
1118
+ result = result.subs(list(zip(coords, self._coord_sys.coord_functions())))
1119
+ return result.doit()
1120
+
1121
+
1122
+ def _find_coords(expr):
1123
+ # Finds CoordinateSystems existing in expr
1124
+ fields = expr.atoms(BaseScalarField, BaseVectorField)
1125
+ result = set()
1126
+ for f in fields:
1127
+ result.add(f._coord_sys)
1128
+ return result
1129
+
1130
+
1131
+ class Commutator(Expr):
1132
+ r"""Commutator of two vector fields.
1133
+
1134
+ Explanation
1135
+ ===========
1136
+
1137
+ The commutator of two vector fields `v_1` and `v_2` is defined as the
1138
+ vector field `[v_1, v_2]` that evaluated on each scalar field `f` is equal
1139
+ to `v_1(v_2(f)) - v_2(v_1(f))`.
1140
+
1141
+ Examples
1142
+ ========
1143
+
1144
+
1145
+ >>> from sympy.diffgeom.rn import R2_p, R2_r
1146
+ >>> from sympy.diffgeom import Commutator
1147
+ >>> from sympy import simplify
1148
+
1149
+ >>> fx, fy = R2_r.base_scalars()
1150
+ >>> e_x, e_y = R2_r.base_vectors()
1151
+ >>> e_r = R2_p.base_vector(0)
1152
+
1153
+ >>> c_xy = Commutator(e_x, e_y)
1154
+ >>> c_xr = Commutator(e_x, e_r)
1155
+ >>> c_xy
1156
+ 0
1157
+
1158
+ Unfortunately, the current code is not able to compute everything:
1159
+
1160
+ >>> c_xr
1161
+ Commutator(e_x, e_rho)
1162
+ >>> simplify(c_xr(fy**2))
1163
+ -2*cos(theta)*y**2/(x**2 + y**2)
1164
+
1165
+ """
1166
+ def __new__(cls, v1, v2):
1167
+ if (covariant_order(v1) or contravariant_order(v1) != 1
1168
+ or covariant_order(v2) or contravariant_order(v2) != 1):
1169
+ raise ValueError(
1170
+ 'Only commutators of vector fields are supported.')
1171
+ if v1 == v2:
1172
+ return S.Zero
1173
+ coord_sys = set().union(*[_find_coords(v) for v in (v1, v2)])
1174
+ if len(coord_sys) == 1:
1175
+ # Only one coordinate systems is used, hence it is easy enough to
1176
+ # actually evaluate the commutator.
1177
+ if all(isinstance(v, BaseVectorField) for v in (v1, v2)):
1178
+ return S.Zero
1179
+ bases_1, bases_2 = [list(v.atoms(BaseVectorField))
1180
+ for v in (v1, v2)]
1181
+ coeffs_1 = [v1.expand().coeff(b) for b in bases_1]
1182
+ coeffs_2 = [v2.expand().coeff(b) for b in bases_2]
1183
+ res = 0
1184
+ for c1, b1 in zip(coeffs_1, bases_1):
1185
+ for c2, b2 in zip(coeffs_2, bases_2):
1186
+ res += c1*b1(c2)*b2 - c2*b2(c1)*b1
1187
+ return res
1188
+ else:
1189
+ obj = super().__new__(cls, v1, v2)
1190
+ obj._v1 = v1 # deprecated assignment
1191
+ obj._v2 = v2 # deprecated assignment
1192
+ return obj
1193
+
1194
+ @property
1195
+ def v1(self):
1196
+ return self.args[0]
1197
+
1198
+ @property
1199
+ def v2(self):
1200
+ return self.args[1]
1201
+
1202
+ def __call__(self, scalar_field):
1203
+ """Apply on a scalar field.
1204
+ If the argument is not a scalar field an error is raised.
1205
+ """
1206
+ return self.v1(self.v2(scalar_field)) - self.v2(self.v1(scalar_field))
1207
+
1208
+
1209
+ class Differential(Expr):
1210
+ r"""Return the differential (exterior derivative) of a form field.
1211
+
1212
+ Explanation
1213
+ ===========
1214
+
1215
+ The differential of a form (i.e. the exterior derivative) has a complicated
1216
+ definition in the general case.
1217
+ The differential `df` of the 0-form `f` is defined for any vector field `v`
1218
+ as `df(v) = v(f)`.
1219
+
1220
+ Examples
1221
+ ========
1222
+
1223
+ >>> from sympy import Function
1224
+ >>> from sympy.diffgeom.rn import R2_r
1225
+ >>> from sympy.diffgeom import Differential
1226
+ >>> from sympy import pprint
1227
+
1228
+ >>> fx, fy = R2_r.base_scalars()
1229
+ >>> e_x, e_y = R2_r.base_vectors()
1230
+ >>> g = Function('g')
1231
+ >>> s_field = g(fx, fy)
1232
+ >>> dg = Differential(s_field)
1233
+
1234
+ >>> dg
1235
+ d(g(x, y))
1236
+ >>> pprint(dg(e_x))
1237
+ / d \|
1238
+ |---(g(xi, y))||
1239
+ \dxi /|xi=x
1240
+ >>> pprint(dg(e_y))
1241
+ / d \|
1242
+ |---(g(x, xi))||
1243
+ \dxi /|xi=y
1244
+
1245
+ Applying the exterior derivative operator twice always results in:
1246
+
1247
+ >>> Differential(dg)
1248
+ 0
1249
+ """
1250
+
1251
+ is_commutative = False
1252
+
1253
+ def __new__(cls, form_field):
1254
+ if contravariant_order(form_field):
1255
+ raise ValueError(
1256
+ 'A vector field was supplied as an argument to Differential.')
1257
+ if isinstance(form_field, Differential):
1258
+ return S.Zero
1259
+ else:
1260
+ obj = super().__new__(cls, form_field)
1261
+ obj._form_field = form_field # deprecated assignment
1262
+ return obj
1263
+
1264
+ @property
1265
+ def form_field(self):
1266
+ return self.args[0]
1267
+
1268
+ def __call__(self, *vector_fields):
1269
+ """Apply on a list of vector_fields.
1270
+
1271
+ Explanation
1272
+ ===========
1273
+
1274
+ If the number of vector fields supplied is not equal to 1 + the order of
1275
+ the form field inside the differential the result is undefined.
1276
+
1277
+ For 1-forms (i.e. differentials of scalar fields) the evaluation is
1278
+ done as `df(v)=v(f)`. However if `v` is ``None`` instead of a vector
1279
+ field, the differential is returned unchanged. This is done in order to
1280
+ permit partial contractions for higher forms.
1281
+
1282
+ In the general case the evaluation is done by applying the form field
1283
+ inside the differential on a list with one less elements than the number
1284
+ of elements in the original list. Lowering the number of vector fields
1285
+ is achieved through replacing each pair of fields by their
1286
+ commutator.
1287
+
1288
+ If the arguments are not vectors or ``None``s an error is raised.
1289
+ """
1290
+ if any((contravariant_order(a) != 1 or covariant_order(a)) and a is not None
1291
+ for a in vector_fields):
1292
+ raise ValueError('The arguments supplied to Differential should be vector fields or Nones.')
1293
+ k = len(vector_fields)
1294
+ if k == 1:
1295
+ if vector_fields[0]:
1296
+ return vector_fields[0].rcall(self._form_field)
1297
+ return self
1298
+ else:
1299
+ # For higher form it is more complicated:
1300
+ # Invariant formula:
1301
+ # https://en.wikipedia.org/wiki/Exterior_derivative#Invariant_formula
1302
+ # df(v1, ... vn) = +/- vi(f(v1..no i..vn))
1303
+ # +/- f([vi,vj],v1..no i, no j..vn)
1304
+ f = self._form_field
1305
+ v = vector_fields
1306
+ ret = 0
1307
+ for i in range(k):
1308
+ t = v[i].rcall(f.rcall(*v[:i] + v[i + 1:]))
1309
+ ret += (-1)**i*t
1310
+ for j in range(i + 1, k):
1311
+ c = Commutator(v[i], v[j])
1312
+ if c: # TODO this is ugly - the Commutator can be Zero and
1313
+ # this causes the next line to fail
1314
+ t = f.rcall(*(c,) + v[:i] + v[i + 1:j] + v[j + 1:])
1315
+ ret += (-1)**(i + j)*t
1316
+ return ret
1317
+
1318
+
1319
+ class TensorProduct(Expr):
1320
+ """Tensor product of forms.
1321
+
1322
+ Explanation
1323
+ ===========
1324
+
1325
+ The tensor product permits the creation of multilinear functionals (i.e.
1326
+ higher order tensors) out of lower order fields (e.g. 1-forms and vector
1327
+ fields). However, the higher tensors thus created lack the interesting
1328
+ features provided by the other type of product, the wedge product, namely
1329
+ they are not antisymmetric and hence are not form fields.
1330
+
1331
+ Examples
1332
+ ========
1333
+
1334
+ >>> from sympy.diffgeom.rn import R2_r
1335
+ >>> from sympy.diffgeom import TensorProduct
1336
+
1337
+ >>> fx, fy = R2_r.base_scalars()
1338
+ >>> e_x, e_y = R2_r.base_vectors()
1339
+ >>> dx, dy = R2_r.base_oneforms()
1340
+
1341
+ >>> TensorProduct(dx, dy)(e_x, e_y)
1342
+ 1
1343
+ >>> TensorProduct(dx, dy)(e_y, e_x)
1344
+ 0
1345
+ >>> TensorProduct(dx, fx*dy)(fx*e_x, e_y)
1346
+ x**2
1347
+ >>> TensorProduct(e_x, e_y)(fx**2, fy**2)
1348
+ 4*x*y
1349
+ >>> TensorProduct(e_y, dx)(fy)
1350
+ dx
1351
+
1352
+ You can nest tensor products.
1353
+
1354
+ >>> tp1 = TensorProduct(dx, dy)
1355
+ >>> TensorProduct(tp1, dx)(e_x, e_y, e_x)
1356
+ 1
1357
+
1358
+ You can make partial contraction for instance when 'raising an index'.
1359
+ Putting ``None`` in the second argument of ``rcall`` means that the
1360
+ respective position in the tensor product is left as it is.
1361
+
1362
+ >>> TP = TensorProduct
1363
+ >>> metric = TP(dx, dx) + 3*TP(dy, dy)
1364
+ >>> metric.rcall(e_y, None)
1365
+ 3*dy
1366
+
1367
+ Or automatically pad the args with ``None`` without specifying them.
1368
+
1369
+ >>> metric.rcall(e_y)
1370
+ 3*dy
1371
+
1372
+ """
1373
+ def __new__(cls, *args):
1374
+ scalar = Mul(*[m for m in args if covariant_order(m) + contravariant_order(m) == 0])
1375
+ multifields = [m for m in args if covariant_order(m) + contravariant_order(m)]
1376
+ if multifields:
1377
+ if len(multifields) == 1:
1378
+ return scalar*multifields[0]
1379
+ return scalar*super().__new__(cls, *multifields)
1380
+ else:
1381
+ return scalar
1382
+
1383
+ def __call__(self, *fields):
1384
+ """Apply on a list of fields.
1385
+
1386
+ If the number of input fields supplied is not equal to the order of
1387
+ the tensor product field, the list of arguments is padded with ``None``'s.
1388
+
1389
+ The list of arguments is divided in sublists depending on the order of
1390
+ the forms inside the tensor product. The sublists are provided as
1391
+ arguments to these forms and the resulting expressions are given to the
1392
+ constructor of ``TensorProduct``.
1393
+
1394
+ """
1395
+ tot_order = covariant_order(self) + contravariant_order(self)
1396
+ tot_args = len(fields)
1397
+ if tot_args != tot_order:
1398
+ fields = list(fields) + [None]*(tot_order - tot_args)
1399
+ orders = [covariant_order(f) + contravariant_order(f) for f in self._args]
1400
+ indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)]
1401
+ fields = [fields[i:j] for i, j in zip([0] + indices, indices + [None])]
1402
+ multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, fields)]
1403
+ return TensorProduct(*multipliers)
1404
+
1405
+
1406
+ class WedgeProduct(TensorProduct):
1407
+ """Wedge product of forms.
1408
+
1409
+ Explanation
1410
+ ===========
1411
+
1412
+ In the context of integration only completely antisymmetric forms make
1413
+ sense. The wedge product permits the creation of such forms.
1414
+
1415
+ Examples
1416
+ ========
1417
+
1418
+ >>> from sympy.diffgeom.rn import R2_r
1419
+ >>> from sympy.diffgeom import WedgeProduct
1420
+
1421
+ >>> fx, fy = R2_r.base_scalars()
1422
+ >>> e_x, e_y = R2_r.base_vectors()
1423
+ >>> dx, dy = R2_r.base_oneforms()
1424
+
1425
+ >>> WedgeProduct(dx, dy)(e_x, e_y)
1426
+ 1
1427
+ >>> WedgeProduct(dx, dy)(e_y, e_x)
1428
+ -1
1429
+ >>> WedgeProduct(dx, fx*dy)(fx*e_x, e_y)
1430
+ x**2
1431
+ >>> WedgeProduct(e_x, e_y)(fy, None)
1432
+ -e_x
1433
+
1434
+ You can nest wedge products.
1435
+
1436
+ >>> wp1 = WedgeProduct(dx, dy)
1437
+ >>> WedgeProduct(wp1, dx)(e_x, e_y, e_x)
1438
+ 0
1439
+
1440
+ """
1441
+ # TODO the calculation of signatures is slow
1442
+ # TODO you do not need all these permutations (neither the prefactor)
1443
+ def __call__(self, *fields):
1444
+ """Apply on a list of vector_fields.
1445
+ The expression is rewritten internally in terms of tensor products and evaluated."""
1446
+ orders = (covariant_order(e) + contravariant_order(e) for e in self.args)
1447
+ mul = 1/Mul(*(factorial(o) for o in orders))
1448
+ perms = permutations(fields)
1449
+ perms_par = (Permutation(
1450
+ p).signature() for p in permutations(range(len(fields))))
1451
+ tensor_prod = TensorProduct(*self.args)
1452
+ return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)])
1453
+
1454
+
1455
+ class LieDerivative(Expr):
1456
+ """Lie derivative with respect to a vector field.
1457
+
1458
+ Explanation
1459
+ ===========
1460
+
1461
+ The transport operator that defines the Lie derivative is the pushforward of
1462
+ the field to be derived along the integral curve of the field with respect
1463
+ to which one derives.
1464
+
1465
+ Examples
1466
+ ========
1467
+
1468
+ >>> from sympy.diffgeom.rn import R2_r, R2_p
1469
+ >>> from sympy.diffgeom import (LieDerivative, TensorProduct)
1470
+
1471
+ >>> fx, fy = R2_r.base_scalars()
1472
+ >>> e_x, e_y = R2_r.base_vectors()
1473
+ >>> e_rho, e_theta = R2_p.base_vectors()
1474
+ >>> dx, dy = R2_r.base_oneforms()
1475
+
1476
+ >>> LieDerivative(e_x, fy)
1477
+ 0
1478
+ >>> LieDerivative(e_x, fx)
1479
+ 1
1480
+ >>> LieDerivative(e_x, e_x)
1481
+ 0
1482
+
1483
+ The Lie derivative of a tensor field by another tensor field is equal to
1484
+ their commutator:
1485
+
1486
+ >>> LieDerivative(e_x, e_rho)
1487
+ Commutator(e_x, e_rho)
1488
+ >>> LieDerivative(e_x + e_y, fx)
1489
+ 1
1490
+
1491
+ >>> tp = TensorProduct(dx, dy)
1492
+ >>> LieDerivative(e_x, tp)
1493
+ LieDerivative(e_x, TensorProduct(dx, dy))
1494
+ >>> LieDerivative(e_x, tp)
1495
+ LieDerivative(e_x, TensorProduct(dx, dy))
1496
+
1497
+ """
1498
+ def __new__(cls, v_field, expr):
1499
+ expr_form_ord = covariant_order(expr)
1500
+ if contravariant_order(v_field) != 1 or covariant_order(v_field):
1501
+ raise ValueError('Lie derivatives are defined only with respect to'
1502
+ ' vector fields. The supplied argument was not a '
1503
+ 'vector field.')
1504
+ if expr_form_ord > 0:
1505
+ obj = super().__new__(cls, v_field, expr)
1506
+ # deprecated assignments
1507
+ obj._v_field = v_field
1508
+ obj._expr = expr
1509
+ return obj
1510
+ if expr.atoms(BaseVectorField):
1511
+ return Commutator(v_field, expr)
1512
+ else:
1513
+ return v_field.rcall(expr)
1514
+
1515
+ @property
1516
+ def v_field(self):
1517
+ return self.args[0]
1518
+
1519
+ @property
1520
+ def expr(self):
1521
+ return self.args[1]
1522
+
1523
+ def __call__(self, *args):
1524
+ v = self.v_field
1525
+ expr = self.expr
1526
+ lead_term = v(expr(*args))
1527
+ rest = Add(*[Mul(*args[:i] + (Commutator(v, args[i]),) + args[i + 1:])
1528
+ for i in range(len(args))])
1529
+ return lead_term - rest
1530
+
1531
+
1532
+ class BaseCovarDerivativeOp(Expr):
1533
+ """Covariant derivative operator with respect to a base vector.
1534
+
1535
+ Examples
1536
+ ========
1537
+
1538
+ >>> from sympy.diffgeom.rn import R2_r
1539
+ >>> from sympy.diffgeom import BaseCovarDerivativeOp
1540
+ >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
1541
+
1542
+ >>> TP = TensorProduct
1543
+ >>> fx, fy = R2_r.base_scalars()
1544
+ >>> e_x, e_y = R2_r.base_vectors()
1545
+ >>> dx, dy = R2_r.base_oneforms()
1546
+
1547
+ >>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
1548
+ >>> ch
1549
+ [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
1550
+ >>> cvd = BaseCovarDerivativeOp(R2_r, 0, ch)
1551
+ >>> cvd(fx)
1552
+ 1
1553
+ >>> cvd(fx*e_x)
1554
+ e_x
1555
+ """
1556
+
1557
+ def __new__(cls, coord_sys, index, christoffel):
1558
+ index = _sympify(index)
1559
+ christoffel = ImmutableDenseNDimArray(christoffel)
1560
+ obj = super().__new__(cls, coord_sys, index, christoffel)
1561
+ # deprecated assignments
1562
+ obj._coord_sys = coord_sys
1563
+ obj._index = index
1564
+ obj._christoffel = christoffel
1565
+ return obj
1566
+
1567
+ @property
1568
+ def coord_sys(self):
1569
+ return self.args[0]
1570
+
1571
+ @property
1572
+ def index(self):
1573
+ return self.args[1]
1574
+
1575
+ @property
1576
+ def christoffel(self):
1577
+ return self.args[2]
1578
+
1579
+ def __call__(self, field):
1580
+ """Apply on a scalar field.
1581
+
1582
+ The action of a vector field on a scalar field is a directional
1583
+ differentiation.
1584
+ If the argument is not a scalar field the behaviour is undefined.
1585
+ """
1586
+ if covariant_order(field) != 0:
1587
+ raise NotImplementedError()
1588
+
1589
+ field = vectors_in_basis(field, self._coord_sys)
1590
+
1591
+ wrt_vector = self._coord_sys.base_vector(self._index)
1592
+ wrt_scalar = self._coord_sys.coord_function(self._index)
1593
+ vectors = list(field.atoms(BaseVectorField))
1594
+
1595
+ # First step: replace all vectors with something susceptible to
1596
+ # derivation and do the derivation
1597
+ # TODO: you need a real dummy function for the next line
1598
+ d_funcs = [Function('_#_%s' % i)(wrt_scalar) for i,
1599
+ b in enumerate(vectors)]
1600
+ d_result = field.subs(list(zip(vectors, d_funcs)))
1601
+ d_result = wrt_vector(d_result)
1602
+
1603
+ # Second step: backsubstitute the vectors in
1604
+ d_result = d_result.subs(list(zip(d_funcs, vectors)))
1605
+
1606
+ # Third step: evaluate the derivatives of the vectors
1607
+ derivs = []
1608
+ for v in vectors:
1609
+ d = Add(*[(self._christoffel[k, wrt_vector._index, v._index]
1610
+ *v._coord_sys.base_vector(k))
1611
+ for k in range(v._coord_sys.dim)])
1612
+ derivs.append(d)
1613
+ to_subs = [wrt_vector(d) for d in d_funcs]
1614
+ # XXX: This substitution can fail when there are Dummy symbols and the
1615
+ # cache is disabled: https://github.com/sympy/sympy/issues/17794
1616
+ result = d_result.subs(list(zip(to_subs, derivs)))
1617
+
1618
+ # Remove the dummies
1619
+ result = result.subs(list(zip(d_funcs, vectors)))
1620
+ return result.doit()
1621
+
1622
+
1623
+ class CovarDerivativeOp(Expr):
1624
+ """Covariant derivative operator.
1625
+
1626
+ Examples
1627
+ ========
1628
+
1629
+ >>> from sympy.diffgeom.rn import R2_r
1630
+ >>> from sympy.diffgeom import CovarDerivativeOp
1631
+ >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
1632
+ >>> TP = TensorProduct
1633
+ >>> fx, fy = R2_r.base_scalars()
1634
+ >>> e_x, e_y = R2_r.base_vectors()
1635
+ >>> dx, dy = R2_r.base_oneforms()
1636
+ >>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
1637
+
1638
+ >>> ch
1639
+ [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
1640
+ >>> cvd = CovarDerivativeOp(fx*e_x, ch)
1641
+ >>> cvd(fx)
1642
+ x
1643
+ >>> cvd(fx*e_x)
1644
+ x*e_x
1645
+
1646
+ """
1647
+
1648
+ def __new__(cls, wrt, christoffel):
1649
+ if len({v._coord_sys for v in wrt.atoms(BaseVectorField)}) > 1:
1650
+ raise NotImplementedError()
1651
+ if contravariant_order(wrt) != 1 or covariant_order(wrt):
1652
+ raise ValueError('Covariant derivatives are defined only with '
1653
+ 'respect to vector fields. The supplied argument '
1654
+ 'was not a vector field.')
1655
+ christoffel = ImmutableDenseNDimArray(christoffel)
1656
+ obj = super().__new__(cls, wrt, christoffel)
1657
+ # deprecated assignments
1658
+ obj._wrt = wrt
1659
+ obj._christoffel = christoffel
1660
+ return obj
1661
+
1662
+ @property
1663
+ def wrt(self):
1664
+ return self.args[0]
1665
+
1666
+ @property
1667
+ def christoffel(self):
1668
+ return self.args[1]
1669
+
1670
+ def __call__(self, field):
1671
+ vectors = list(self._wrt.atoms(BaseVectorField))
1672
+ base_ops = [BaseCovarDerivativeOp(v._coord_sys, v._index, self._christoffel)
1673
+ for v in vectors]
1674
+ return self._wrt.subs(list(zip(vectors, base_ops))).rcall(field)
1675
+
1676
+
1677
+ ###############################################################################
1678
+ # Integral curves on vector fields
1679
+ ###############################################################################
1680
+ def intcurve_series(vector_field, param, start_point, n=6, coord_sys=None, coeffs=False):
1681
+ r"""Return the series expansion for an integral curve of the field.
1682
+
1683
+ Explanation
1684
+ ===========
1685
+
1686
+ Integral curve is a function `\gamma` taking a parameter in `R` to a point
1687
+ in the manifold. It verifies the equation:
1688
+
1689
+ `V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
1690
+
1691
+ where the given ``vector_field`` is denoted as `V`. This holds for any
1692
+ value `t` for the parameter and any scalar field `f`.
1693
+
1694
+ This equation can also be decomposed of a basis of coordinate functions
1695
+ `V(f_i)\big(\gamma(t)\big) = \frac{d}{dt}f_i\big(\gamma(t)\big) \quad \forall i`
1696
+
1697
+ This function returns a series expansion of `\gamma(t)` in terms of the
1698
+ coordinate system ``coord_sys``. The equations and expansions are necessarily
1699
+ done in coordinate-system-dependent way as there is no other way to
1700
+ represent movement between points on the manifold (i.e. there is no such
1701
+ thing as a difference of points for a general manifold).
1702
+
1703
+ Parameters
1704
+ ==========
1705
+ vector_field
1706
+ the vector field for which an integral curve will be given
1707
+
1708
+ param
1709
+ the argument of the function `\gamma` from R to the curve
1710
+
1711
+ start_point
1712
+ the point which corresponds to `\gamma(0)`
1713
+
1714
+ n
1715
+ the order to which to expand
1716
+
1717
+ coord_sys
1718
+ the coordinate system in which to expand
1719
+ coeffs (default False) - if True return a list of elements of the expansion
1720
+
1721
+ Examples
1722
+ ========
1723
+
1724
+ Use the predefined R2 manifold:
1725
+
1726
+ >>> from sympy.abc import t, x, y
1727
+ >>> from sympy.diffgeom.rn import R2_p, R2_r
1728
+ >>> from sympy.diffgeom import intcurve_series
1729
+
1730
+ Specify a starting point and a vector field:
1731
+
1732
+ >>> start_point = R2_r.point([x, y])
1733
+ >>> vector_field = R2_r.e_x
1734
+
1735
+ Calculate the series:
1736
+
1737
+ >>> intcurve_series(vector_field, t, start_point, n=3)
1738
+ Matrix([
1739
+ [t + x],
1740
+ [ y]])
1741
+
1742
+ Or get the elements of the expansion in a list:
1743
+
1744
+ >>> series = intcurve_series(vector_field, t, start_point, n=3, coeffs=True)
1745
+ >>> series[0]
1746
+ Matrix([
1747
+ [x],
1748
+ [y]])
1749
+ >>> series[1]
1750
+ Matrix([
1751
+ [t],
1752
+ [0]])
1753
+ >>> series[2]
1754
+ Matrix([
1755
+ [0],
1756
+ [0]])
1757
+
1758
+ The series in the polar coordinate system:
1759
+
1760
+ >>> series = intcurve_series(vector_field, t, start_point,
1761
+ ... n=3, coord_sys=R2_p, coeffs=True)
1762
+ >>> series[0]
1763
+ Matrix([
1764
+ [sqrt(x**2 + y**2)],
1765
+ [ atan2(y, x)]])
1766
+ >>> series[1]
1767
+ Matrix([
1768
+ [t*x/sqrt(x**2 + y**2)],
1769
+ [ -t*y/(x**2 + y**2)]])
1770
+ >>> series[2]
1771
+ Matrix([
1772
+ [t**2*(-x**2/(x**2 + y**2)**(3/2) + 1/sqrt(x**2 + y**2))/2],
1773
+ [ t**2*x*y/(x**2 + y**2)**2]])
1774
+
1775
+ See Also
1776
+ ========
1777
+
1778
+ intcurve_diffequ
1779
+
1780
+ """
1781
+ if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
1782
+ raise ValueError('The supplied field was not a vector field.')
1783
+
1784
+ def iter_vfield(scalar_field, i):
1785
+ """Return ``vector_field`` called `i` times on ``scalar_field``."""
1786
+ return reduce(lambda s, v: v.rcall(s), [vector_field, ]*i, scalar_field)
1787
+
1788
+ def taylor_terms_per_coord(coord_function):
1789
+ """Return the series for one of the coordinates."""
1790
+ return [param**i*iter_vfield(coord_function, i).rcall(start_point)/factorial(i)
1791
+ for i in range(n)]
1792
+ coord_sys = coord_sys if coord_sys else start_point._coord_sys
1793
+ coord_functions = coord_sys.coord_functions()
1794
+ taylor_terms = [taylor_terms_per_coord(f) for f in coord_functions]
1795
+ if coeffs:
1796
+ return [Matrix(t) for t in zip(*taylor_terms)]
1797
+ else:
1798
+ return Matrix([sum(c) for c in taylor_terms])
1799
+
1800
+
1801
+ def intcurve_diffequ(vector_field, param, start_point, coord_sys=None):
1802
+ r"""Return the differential equation for an integral curve of the field.
1803
+
1804
+ Explanation
1805
+ ===========
1806
+
1807
+ Integral curve is a function `\gamma` taking a parameter in `R` to a point
1808
+ in the manifold. It verifies the equation:
1809
+
1810
+ `V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
1811
+
1812
+ where the given ``vector_field`` is denoted as `V`. This holds for any
1813
+ value `t` for the parameter and any scalar field `f`.
1814
+
1815
+ This function returns the differential equation of `\gamma(t)` in terms of the
1816
+ coordinate system ``coord_sys``. The equations and expansions are necessarily
1817
+ done in coordinate-system-dependent way as there is no other way to
1818
+ represent movement between points on the manifold (i.e. there is no such
1819
+ thing as a difference of points for a general manifold).
1820
+
1821
+ Parameters
1822
+ ==========
1823
+
1824
+ vector_field
1825
+ the vector field for which an integral curve will be given
1826
+
1827
+ param
1828
+ the argument of the function `\gamma` from R to the curve
1829
+
1830
+ start_point
1831
+ the point which corresponds to `\gamma(0)`
1832
+
1833
+ coord_sys
1834
+ the coordinate system in which to give the equations
1835
+
1836
+ Returns
1837
+ =======
1838
+
1839
+ a tuple of (equations, initial conditions)
1840
+
1841
+ Examples
1842
+ ========
1843
+
1844
+ Use the predefined R2 manifold:
1845
+
1846
+ >>> from sympy.abc import t
1847
+ >>> from sympy.diffgeom.rn import R2, R2_p, R2_r
1848
+ >>> from sympy.diffgeom import intcurve_diffequ
1849
+
1850
+ Specify a starting point and a vector field:
1851
+
1852
+ >>> start_point = R2_r.point([0, 1])
1853
+ >>> vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
1854
+
1855
+ Get the equation:
1856
+
1857
+ >>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point)
1858
+ >>> equations
1859
+ [f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]
1860
+ >>> init_cond
1861
+ [f_0(0), f_1(0) - 1]
1862
+
1863
+ The series in the polar coordinate system:
1864
+
1865
+ >>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p)
1866
+ >>> equations
1867
+ [Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]
1868
+ >>> init_cond
1869
+ [f_0(0) - 1, f_1(0) - pi/2]
1870
+
1871
+ See Also
1872
+ ========
1873
+
1874
+ intcurve_series
1875
+
1876
+ """
1877
+ if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
1878
+ raise ValueError('The supplied field was not a vector field.')
1879
+ coord_sys = coord_sys if coord_sys else start_point._coord_sys
1880
+ gammas = [Function('f_%d' % i)(param) for i in range(
1881
+ start_point._coord_sys.dim)]
1882
+ arbitrary_p = Point(coord_sys, gammas)
1883
+ coord_functions = coord_sys.coord_functions()
1884
+ equations = [simplify(diff(cf.rcall(arbitrary_p), param) - vector_field.rcall(cf).rcall(arbitrary_p))
1885
+ for cf in coord_functions]
1886
+ init_cond = [simplify(cf.rcall(arbitrary_p).subs(param, 0) - cf.rcall(start_point))
1887
+ for cf in coord_functions]
1888
+ return equations, init_cond
1889
+
1890
+
1891
+ ###############################################################################
1892
+ # Helpers
1893
+ ###############################################################################
1894
+ def dummyfy(args, exprs):
1895
+ # TODO Is this a good idea?
1896
+ d_args = Matrix([s.as_dummy() for s in args])
1897
+ reps = dict(zip(args, d_args))
1898
+ d_exprs = Matrix([_sympify(expr).subs(reps) for expr in exprs])
1899
+ return d_args, d_exprs
1900
+
1901
+ ###############################################################################
1902
+ # Helpers
1903
+ ###############################################################################
1904
+ def contravariant_order(expr, _strict=False):
1905
+ """Return the contravariant order of an expression.
1906
+
1907
+ Examples
1908
+ ========
1909
+
1910
+ >>> from sympy.diffgeom import contravariant_order
1911
+ >>> from sympy.diffgeom.rn import R2
1912
+ >>> from sympy.abc import a
1913
+
1914
+ >>> contravariant_order(a)
1915
+ 0
1916
+ >>> contravariant_order(a*R2.x + 2)
1917
+ 0
1918
+ >>> contravariant_order(a*R2.x*R2.e_y + R2.e_x)
1919
+ 1
1920
+
1921
+ """
1922
+ # TODO move some of this to class methods.
1923
+ # TODO rewrite using the .as_blah_blah methods
1924
+ if isinstance(expr, Add):
1925
+ orders = [contravariant_order(e) for e in expr.args]
1926
+ if len(set(orders)) != 1:
1927
+ raise ValueError('Misformed expression containing contravariant fields of varying order.')
1928
+ return orders[0]
1929
+ elif isinstance(expr, Mul):
1930
+ orders = [contravariant_order(e) for e in expr.args]
1931
+ not_zero = [o for o in orders if o != 0]
1932
+ if len(not_zero) > 1:
1933
+ raise ValueError('Misformed expression containing multiplication between vectors.')
1934
+ return 0 if not not_zero else not_zero[0]
1935
+ elif isinstance(expr, Pow):
1936
+ if covariant_order(expr.base) or covariant_order(expr.exp):
1937
+ raise ValueError(
1938
+ 'Misformed expression containing a power of a vector.')
1939
+ return 0
1940
+ elif isinstance(expr, BaseVectorField):
1941
+ return 1
1942
+ elif isinstance(expr, TensorProduct):
1943
+ return sum(contravariant_order(a) for a in expr.args)
1944
+ elif not _strict or expr.atoms(BaseScalarField):
1945
+ return 0
1946
+ else: # If it does not contain anything related to the diffgeom module and it is _strict
1947
+ return -1
1948
+
1949
+
1950
+ def covariant_order(expr, _strict=False):
1951
+ """Return the covariant order of an expression.
1952
+
1953
+ Examples
1954
+ ========
1955
+
1956
+ >>> from sympy.diffgeom import covariant_order
1957
+ >>> from sympy.diffgeom.rn import R2
1958
+ >>> from sympy.abc import a
1959
+
1960
+ >>> covariant_order(a)
1961
+ 0
1962
+ >>> covariant_order(a*R2.x + 2)
1963
+ 0
1964
+ >>> covariant_order(a*R2.x*R2.dy + R2.dx)
1965
+ 1
1966
+
1967
+ """
1968
+ # TODO move some of this to class methods.
1969
+ # TODO rewrite using the .as_blah_blah methods
1970
+ if isinstance(expr, Add):
1971
+ orders = [covariant_order(e) for e in expr.args]
1972
+ if len(set(orders)) != 1:
1973
+ raise ValueError('Misformed expression containing form fields of varying order.')
1974
+ return orders[0]
1975
+ elif isinstance(expr, Mul):
1976
+ orders = [covariant_order(e) for e in expr.args]
1977
+ not_zero = [o for o in orders if o != 0]
1978
+ if len(not_zero) > 1:
1979
+ raise ValueError('Misformed expression containing multiplication between forms.')
1980
+ return 0 if not not_zero else not_zero[0]
1981
+ elif isinstance(expr, Pow):
1982
+ if covariant_order(expr.base) or covariant_order(expr.exp):
1983
+ raise ValueError(
1984
+ 'Misformed expression containing a power of a form.')
1985
+ return 0
1986
+ elif isinstance(expr, Differential):
1987
+ return covariant_order(*expr.args) + 1
1988
+ elif isinstance(expr, TensorProduct):
1989
+ return sum(covariant_order(a) for a in expr.args)
1990
+ elif not _strict or expr.atoms(BaseScalarField):
1991
+ return 0
1992
+ else: # If it does not contain anything related to the diffgeom module and it is _strict
1993
+ return -1
1994
+
1995
+
1996
+ ###############################################################################
1997
+ # Coordinate transformation functions
1998
+ ###############################################################################
1999
+ def vectors_in_basis(expr, to_sys):
2000
+ """Transform all base vectors in base vectors of a specified coord basis.
2001
+ While the new base vectors are in the new coordinate system basis, any
2002
+ coefficients are kept in the old system.
2003
+
2004
+ Examples
2005
+ ========
2006
+
2007
+ >>> from sympy.diffgeom import vectors_in_basis
2008
+ >>> from sympy.diffgeom.rn import R2_r, R2_p
2009
+
2010
+ >>> vectors_in_basis(R2_r.e_x, R2_p)
2011
+ -y*e_theta/(x**2 + y**2) + x*e_rho/sqrt(x**2 + y**2)
2012
+ >>> vectors_in_basis(R2_p.e_r, R2_r)
2013
+ sin(theta)*e_y + cos(theta)*e_x
2014
+
2015
+ """
2016
+ vectors = list(expr.atoms(BaseVectorField))
2017
+ new_vectors = []
2018
+ for v in vectors:
2019
+ cs = v._coord_sys
2020
+ jac = cs.jacobian(to_sys, cs.coord_functions())
2021
+ new = (jac.T*Matrix(to_sys.base_vectors()))[v._index]
2022
+ new_vectors.append(new)
2023
+ return expr.subs(list(zip(vectors, new_vectors)))
2024
+
2025
+
2026
+ ###############################################################################
2027
+ # Coordinate-dependent functions
2028
+ ###############################################################################
2029
+ def twoform_to_matrix(expr):
2030
+ """Return the matrix representing the twoform.
2031
+
2032
+ For the twoform `w` return the matrix `M` such that `M[i,j]=w(e_i, e_j)`,
2033
+ where `e_i` is the i-th base vector field for the coordinate system in
2034
+ which the expression of `w` is given.
2035
+
2036
+ Examples
2037
+ ========
2038
+
2039
+ >>> from sympy.diffgeom.rn import R2
2040
+ >>> from sympy.diffgeom import twoform_to_matrix, TensorProduct
2041
+ >>> TP = TensorProduct
2042
+
2043
+ >>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
2044
+ Matrix([
2045
+ [1, 0],
2046
+ [0, 1]])
2047
+ >>> twoform_to_matrix(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
2048
+ Matrix([
2049
+ [x, 0],
2050
+ [0, 1]])
2051
+ >>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy) - TP(R2.dx, R2.dy)/2)
2052
+ Matrix([
2053
+ [ 1, 0],
2054
+ [-1/2, 1]])
2055
+
2056
+ """
2057
+ if covariant_order(expr) != 2 or contravariant_order(expr):
2058
+ raise ValueError('The input expression is not a two-form.')
2059
+ coord_sys = _find_coords(expr)
2060
+ if len(coord_sys) != 1:
2061
+ raise ValueError('The input expression concerns more than one '
2062
+ 'coordinate systems, hence there is no unambiguous '
2063
+ 'way to choose a coordinate system for the matrix.')
2064
+ coord_sys = coord_sys.pop()
2065
+ vectors = coord_sys.base_vectors()
2066
+ expr = expr.expand()
2067
+ matrix_content = [[expr.rcall(v1, v2) for v1 in vectors]
2068
+ for v2 in vectors]
2069
+ return Matrix(matrix_content)
2070
+
2071
+
2072
+ def metric_to_Christoffel_1st(expr):
2073
+ """Return the nested list of Christoffel symbols for the given metric.
2074
+ This returns the Christoffel symbol of first kind that represents the
2075
+ Levi-Civita connection for the given metric.
2076
+
2077
+ Examples
2078
+ ========
2079
+
2080
+ >>> from sympy.diffgeom.rn import R2
2081
+ >>> from sympy.diffgeom import metric_to_Christoffel_1st, TensorProduct
2082
+ >>> TP = TensorProduct
2083
+
2084
+ >>> metric_to_Christoffel_1st(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
2085
+ [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
2086
+ >>> metric_to_Christoffel_1st(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
2087
+ [[[1/2, 0], [0, 0]], [[0, 0], [0, 0]]]
2088
+
2089
+ """
2090
+ matrix = twoform_to_matrix(expr)
2091
+ if not matrix.is_symmetric():
2092
+ raise ValueError(
2093
+ 'The two-form representing the metric is not symmetric.')
2094
+ coord_sys = _find_coords(expr).pop()
2095
+ deriv_matrices = [matrix.applyfunc(d) for d in coord_sys.base_vectors()]
2096
+ indices = list(range(coord_sys.dim))
2097
+ christoffel = [[[(deriv_matrices[k][i, j] + deriv_matrices[j][i, k] - deriv_matrices[i][j, k])/2
2098
+ for k in indices]
2099
+ for j in indices]
2100
+ for i in indices]
2101
+ return ImmutableDenseNDimArray(christoffel)
2102
+
2103
+
2104
+ def metric_to_Christoffel_2nd(expr):
2105
+ """Return the nested list of Christoffel symbols for the given metric.
2106
+ This returns the Christoffel symbol of second kind that represents the
2107
+ Levi-Civita connection for the given metric.
2108
+
2109
+ Examples
2110
+ ========
2111
+
2112
+ >>> from sympy.diffgeom.rn import R2
2113
+ >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
2114
+ >>> TP = TensorProduct
2115
+
2116
+ >>> metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
2117
+ [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
2118
+ >>> metric_to_Christoffel_2nd(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
2119
+ [[[1/(2*x), 0], [0, 0]], [[0, 0], [0, 0]]]
2120
+
2121
+ """
2122
+ ch_1st = metric_to_Christoffel_1st(expr)
2123
+ coord_sys = _find_coords(expr).pop()
2124
+ indices = list(range(coord_sys.dim))
2125
+ # XXX workaround, inverting a matrix does not work if it contains non
2126
+ # symbols
2127
+ #matrix = twoform_to_matrix(expr).inv()
2128
+ matrix = twoform_to_matrix(expr)
2129
+ s_fields = set()
2130
+ for e in matrix:
2131
+ s_fields.update(e.atoms(BaseScalarField))
2132
+ s_fields = list(s_fields)
2133
+ dums = coord_sys.symbols
2134
+ matrix = matrix.subs(list(zip(s_fields, dums))).inv().subs(list(zip(dums, s_fields)))
2135
+ # XXX end of workaround
2136
+ christoffel = [[[Add(*[matrix[i, l]*ch_1st[l, j, k] for l in indices])
2137
+ for k in indices]
2138
+ for j in indices]
2139
+ for i in indices]
2140
+ return ImmutableDenseNDimArray(christoffel)
2141
+
2142
+
2143
+ def metric_to_Riemann_components(expr):
2144
+ """Return the components of the Riemann tensor expressed in a given basis.
2145
+
2146
+ Given a metric it calculates the components of the Riemann tensor in the
2147
+ canonical basis of the coordinate system in which the metric expression is
2148
+ given.
2149
+
2150
+ Examples
2151
+ ========
2152
+
2153
+ >>> from sympy import exp
2154
+ >>> from sympy.diffgeom.rn import R2
2155
+ >>> from sympy.diffgeom import metric_to_Riemann_components, TensorProduct
2156
+ >>> TP = TensorProduct
2157
+
2158
+ >>> metric_to_Riemann_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
2159
+ [[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]
2160
+ >>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
2161
+ R2.r**2*TP(R2.dtheta, R2.dtheta)
2162
+ >>> non_trivial_metric
2163
+ exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta)
2164
+ >>> riemann = metric_to_Riemann_components(non_trivial_metric)
2165
+ >>> riemann[0, :, :, :]
2166
+ [[[0, 0], [0, 0]], [[0, exp(-2*rho)*rho], [-exp(-2*rho)*rho, 0]]]
2167
+ >>> riemann[1, :, :, :]
2168
+ [[[0, -1/rho], [1/rho, 0]], [[0, 0], [0, 0]]]
2169
+
2170
+ """
2171
+ ch_2nd = metric_to_Christoffel_2nd(expr)
2172
+ coord_sys = _find_coords(expr).pop()
2173
+ indices = list(range(coord_sys.dim))
2174
+ deriv_ch = [[[[d(ch_2nd[i, j, k])
2175
+ for d in coord_sys.base_vectors()]
2176
+ for k in indices]
2177
+ for j in indices]
2178
+ for i in indices]
2179
+ riemann_a = [[[[deriv_ch[rho][sig][nu][mu] - deriv_ch[rho][sig][mu][nu]
2180
+ for nu in indices]
2181
+ for mu in indices]
2182
+ for sig in indices]
2183
+ for rho in indices]
2184
+ riemann_b = [[[[Add(*[ch_2nd[rho, l, mu]*ch_2nd[l, sig, nu] - ch_2nd[rho, l, nu]*ch_2nd[l, sig, mu] for l in indices])
2185
+ for nu in indices]
2186
+ for mu in indices]
2187
+ for sig in indices]
2188
+ for rho in indices]
2189
+ riemann = [[[[riemann_a[rho][sig][mu][nu] + riemann_b[rho][sig][mu][nu]
2190
+ for nu in indices]
2191
+ for mu in indices]
2192
+ for sig in indices]
2193
+ for rho in indices]
2194
+ return ImmutableDenseNDimArray(riemann)
2195
+
2196
+
2197
+ def metric_to_Ricci_components(expr):
2198
+
2199
+ """Return the components of the Ricci tensor expressed in a given basis.
2200
+
2201
+ Given a metric it calculates the components of the Ricci tensor in the
2202
+ canonical basis of the coordinate system in which the metric expression is
2203
+ given.
2204
+
2205
+ Examples
2206
+ ========
2207
+
2208
+ >>> from sympy import exp
2209
+ >>> from sympy.diffgeom.rn import R2
2210
+ >>> from sympy.diffgeom import metric_to_Ricci_components, TensorProduct
2211
+ >>> TP = TensorProduct
2212
+
2213
+ >>> metric_to_Ricci_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
2214
+ [[0, 0], [0, 0]]
2215
+ >>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
2216
+ R2.r**2*TP(R2.dtheta, R2.dtheta)
2217
+ >>> non_trivial_metric
2218
+ exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta)
2219
+ >>> metric_to_Ricci_components(non_trivial_metric)
2220
+ [[1/rho, 0], [0, exp(-2*rho)*rho]]
2221
+
2222
+ """
2223
+ riemann = metric_to_Riemann_components(expr)
2224
+ coord_sys = _find_coords(expr).pop()
2225
+ indices = list(range(coord_sys.dim))
2226
+ ricci = [[Add(*[riemann[k, i, k, j] for k in indices])
2227
+ for j in indices]
2228
+ for i in indices]
2229
+ return ImmutableDenseNDimArray(ricci)
2230
+
2231
+ ###############################################################################
2232
+ # Classes for deprecation
2233
+ ###############################################################################
2234
+
2235
+ class _deprecated_container:
2236
+ # This class gives deprecation warning.
2237
+ # When deprecated features are completely deleted, this should be removed as well.
2238
+ # See https://github.com/sympy/sympy/pull/19368
2239
+ def __init__(self, message, data):
2240
+ super().__init__(data)
2241
+ self.message = message
2242
+
2243
+ def warn(self):
2244
+ sympy_deprecation_warning(
2245
+ self.message,
2246
+ deprecated_since_version="1.7",
2247
+ active_deprecations_target="deprecated-diffgeom-mutable",
2248
+ stacklevel=4
2249
+ )
2250
+
2251
+ def __iter__(self):
2252
+ self.warn()
2253
+ return super().__iter__()
2254
+
2255
+ def __getitem__(self, key):
2256
+ self.warn()
2257
+ return super().__getitem__(key)
2258
+
2259
+ def __contains__(self, key):
2260
+ self.warn()
2261
+ return super().__contains__(key)
2262
+
2263
+
2264
+ class _deprecated_list(_deprecated_container, list):
2265
+ pass
2266
+
2267
+
2268
+ class _deprecated_dict(_deprecated_container, dict):
2269
+ pass
2270
+
2271
+
2272
+ # Import at end to avoid cyclic imports
2273
+ from sympy.simplify.simplify import simplify
venv/lib/python3.10/site-packages/sympy/diffgeom/rn.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Predefined R^n manifolds together with common coord. systems.
2
+
3
+ Coordinate systems are predefined as well as the transformation laws between
4
+ them.
5
+
6
+ Coordinate functions can be accessed as attributes of the manifold (eg `R2.x`),
7
+ as attributes of the coordinate systems (eg `R2_r.x` and `R2_p.theta`), or by
8
+ using the usual `coord_sys.coord_function(index, name)` interface.
9
+ """
10
+
11
+ from typing import Any
12
+ import warnings
13
+
14
+ from sympy.core.symbol import (Dummy, symbols)
15
+ from sympy.functions.elementary.miscellaneous import sqrt
16
+ from sympy.functions.elementary.trigonometric import (acos, atan2, cos, sin)
17
+ from .diffgeom import Manifold, Patch, CoordSystem
18
+
19
+ __all__ = [
20
+ 'R2', 'R2_origin', 'relations_2d', 'R2_r', 'R2_p',
21
+ 'R3', 'R3_origin', 'relations_3d', 'R3_r', 'R3_c', 'R3_s'
22
+ ]
23
+
24
+ ###############################################################################
25
+ # R2
26
+ ###############################################################################
27
+ R2: Any = Manifold('R^2', 2)
28
+
29
+ R2_origin: Any = Patch('origin', R2)
30
+
31
+ x, y = symbols('x y', real=True)
32
+ r, theta = symbols('rho theta', nonnegative=True)
33
+
34
+ relations_2d = {
35
+ ('rectangular', 'polar'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))],
36
+ ('polar', 'rectangular'): [(r, theta), (r*cos(theta), r*sin(theta))],
37
+ }
38
+
39
+ R2_r: Any = CoordSystem('rectangular', R2_origin, (x, y), relations_2d)
40
+ R2_p: Any = CoordSystem('polar', R2_origin, (r, theta), relations_2d)
41
+
42
+ # support deprecated feature
43
+ with warnings.catch_warnings():
44
+ warnings.simplefilter("ignore")
45
+ x, y, r, theta = symbols('x y r theta', cls=Dummy)
46
+ R2_r.connect_to(R2_p, [x, y],
47
+ [sqrt(x**2 + y**2), atan2(y, x)],
48
+ inverse=False, fill_in_gaps=False)
49
+ R2_p.connect_to(R2_r, [r, theta],
50
+ [r*cos(theta), r*sin(theta)],
51
+ inverse=False, fill_in_gaps=False)
52
+
53
+ # Defining the basis coordinate functions and adding shortcuts for them to the
54
+ # manifold and the patch.
55
+ R2.x, R2.y = R2_origin.x, R2_origin.y = R2_r.x, R2_r.y = R2_r.coord_functions()
56
+ R2.r, R2.theta = R2_origin.r, R2_origin.theta = R2_p.r, R2_p.theta = R2_p.coord_functions()
57
+
58
+ # Defining the basis vector fields and adding shortcuts for them to the
59
+ # manifold and the patch.
60
+ R2.e_x, R2.e_y = R2_origin.e_x, R2_origin.e_y = R2_r.e_x, R2_r.e_y = R2_r.base_vectors()
61
+ R2.e_r, R2.e_theta = R2_origin.e_r, R2_origin.e_theta = R2_p.e_r, R2_p.e_theta = R2_p.base_vectors()
62
+
63
+ # Defining the basis oneform fields and adding shortcuts for them to the
64
+ # manifold and the patch.
65
+ R2.dx, R2.dy = R2_origin.dx, R2_origin.dy = R2_r.dx, R2_r.dy = R2_r.base_oneforms()
66
+ R2.dr, R2.dtheta = R2_origin.dr, R2_origin.dtheta = R2_p.dr, R2_p.dtheta = R2_p.base_oneforms()
67
+
68
+ ###############################################################################
69
+ # R3
70
+ ###############################################################################
71
+ R3: Any = Manifold('R^3', 3)
72
+
73
+ R3_origin: Any = Patch('origin', R3)
74
+
75
+ x, y, z = symbols('x y z', real=True)
76
+ rho, psi, r, theta, phi = symbols('rho psi r theta phi', nonnegative=True)
77
+
78
+ relations_3d = {
79
+ ('rectangular', 'cylindrical'): [(x, y, z),
80
+ (sqrt(x**2 + y**2), atan2(y, x), z)],
81
+ ('cylindrical', 'rectangular'): [(rho, psi, z),
82
+ (rho*cos(psi), rho*sin(psi), z)],
83
+ ('rectangular', 'spherical'): [(x, y, z),
84
+ (sqrt(x**2 + y**2 + z**2),
85
+ acos(z/sqrt(x**2 + y**2 + z**2)),
86
+ atan2(y, x))],
87
+ ('spherical', 'rectangular'): [(r, theta, phi),
88
+ (r*sin(theta)*cos(phi),
89
+ r*sin(theta)*sin(phi),
90
+ r*cos(theta))],
91
+ ('cylindrical', 'spherical'): [(rho, psi, z),
92
+ (sqrt(rho**2 + z**2),
93
+ acos(z/sqrt(rho**2 + z**2)),
94
+ psi)],
95
+ ('spherical', 'cylindrical'): [(r, theta, phi),
96
+ (r*sin(theta), phi, r*cos(theta))],
97
+ }
98
+
99
+ R3_r: Any = CoordSystem('rectangular', R3_origin, (x, y, z), relations_3d)
100
+ R3_c: Any = CoordSystem('cylindrical', R3_origin, (rho, psi, z), relations_3d)
101
+ R3_s: Any = CoordSystem('spherical', R3_origin, (r, theta, phi), relations_3d)
102
+
103
+ # support deprecated feature
104
+ with warnings.catch_warnings():
105
+ warnings.simplefilter("ignore")
106
+ x, y, z, rho, psi, r, theta, phi = symbols('x y z rho psi r theta phi', cls=Dummy)
107
+ R3_r.connect_to(R3_c, [x, y, z],
108
+ [sqrt(x**2 + y**2), atan2(y, x), z],
109
+ inverse=False, fill_in_gaps=False)
110
+ R3_c.connect_to(R3_r, [rho, psi, z],
111
+ [rho*cos(psi), rho*sin(psi), z],
112
+ inverse=False, fill_in_gaps=False)
113
+ ## rectangular <-> spherical
114
+ R3_r.connect_to(R3_s, [x, y, z],
115
+ [sqrt(x**2 + y**2 + z**2), acos(z/
116
+ sqrt(x**2 + y**2 + z**2)), atan2(y, x)],
117
+ inverse=False, fill_in_gaps=False)
118
+ R3_s.connect_to(R3_r, [r, theta, phi],
119
+ [r*sin(theta)*cos(phi), r*sin(
120
+ theta)*sin(phi), r*cos(theta)],
121
+ inverse=False, fill_in_gaps=False)
122
+ ## cylindrical <-> spherical
123
+ R3_c.connect_to(R3_s, [rho, psi, z],
124
+ [sqrt(rho**2 + z**2), acos(z/sqrt(rho**2 + z**2)), psi],
125
+ inverse=False, fill_in_gaps=False)
126
+ R3_s.connect_to(R3_c, [r, theta, phi],
127
+ [r*sin(theta), phi, r*cos(theta)],
128
+ inverse=False, fill_in_gaps=False)
129
+
130
+ # Defining the basis coordinate functions.
131
+ R3_r.x, R3_r.y, R3_r.z = R3_r.coord_functions()
132
+ R3_c.rho, R3_c.psi, R3_c.z = R3_c.coord_functions()
133
+ R3_s.r, R3_s.theta, R3_s.phi = R3_s.coord_functions()
134
+
135
+ # Defining the basis vector fields.
136
+ R3_r.e_x, R3_r.e_y, R3_r.e_z = R3_r.base_vectors()
137
+ R3_c.e_rho, R3_c.e_psi, R3_c.e_z = R3_c.base_vectors()
138
+ R3_s.e_r, R3_s.e_theta, R3_s.e_phi = R3_s.base_vectors()
139
+
140
+ # Defining the basis oneform fields.
141
+ R3_r.dx, R3_r.dy, R3_r.dz = R3_r.base_oneforms()
142
+ R3_c.drho, R3_c.dpsi, R3_c.dz = R3_c.base_oneforms()
143
+ R3_s.dr, R3_s.dtheta, R3_s.dphi = R3_s.base_oneforms()
venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_class_structure.cpython-310.pyc ADDED
Binary file (1.47 kB). View file
 
venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_diffgeom.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_function_diffgeom_book.cpython-310.pyc ADDED
Binary file (4.97 kB). View file
 
venv/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_hyperbolic_space.cpython-310.pyc ADDED
Binary file (2.75 kB). View file
 
venv/lib/python3.10/site-packages/sympy/diffgeom/tests/test_class_structure.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.diffgeom import Manifold, Patch, CoordSystem, Point
2
+ from sympy.core.function import Function
3
+ from sympy.core.symbol import symbols
4
+ from sympy.testing.pytest import warns_deprecated_sympy
5
+
6
+ m = Manifold('m', 2)
7
+ p = Patch('p', m)
8
+ a, b = symbols('a b')
9
+ cs = CoordSystem('cs', p, [a, b])
10
+ x, y = symbols('x y')
11
+ f = Function('f')
12
+ s1, s2 = cs.coord_functions()
13
+ v1, v2 = cs.base_vectors()
14
+ f1, f2 = cs.base_oneforms()
15
+
16
+ def test_point():
17
+ point = Point(cs, [x, y])
18
+ assert point != Point(cs, [2, y])
19
+ #TODO assert point.subs(x, 2) == Point(cs, [2, y])
20
+ #TODO assert point.free_symbols == set([x, y])
21
+
22
+ def test_subs():
23
+ assert s1.subs(s1, s2) == s2
24
+ assert v1.subs(v1, v2) == v2
25
+ assert f1.subs(f1, f2) == f2
26
+ assert (x*f(s1) + y).subs(s1, s2) == x*f(s2) + y
27
+ assert (f(s1)*v1).subs(v1, v2) == f(s1)*v2
28
+ assert (y*f(s1)*f1).subs(f1, f2) == y*f(s1)*f2
29
+
30
+ def test_deprecated():
31
+ with warns_deprecated_sympy():
32
+ cs_wname = CoordSystem('cs', p, ['a', 'b'])
33
+ assert cs_wname == cs_wname.func(*cs_wname.args)
venv/lib/python3.10/site-packages/sympy/diffgeom/tests/test_diffgeom.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Lambda, Symbol, symbols
2
+ from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r, R3_c, R3_s, R2_origin
3
+ from sympy.diffgeom import (Manifold, Patch, CoordSystem, Commutator, Differential, TensorProduct,
4
+ WedgeProduct, BaseCovarDerivativeOp, CovarDerivativeOp, LieDerivative,
5
+ covariant_order, contravariant_order, twoform_to_matrix, metric_to_Christoffel_1st,
6
+ metric_to_Christoffel_2nd, metric_to_Riemann_components,
7
+ metric_to_Ricci_components, intcurve_diffequ, intcurve_series)
8
+ from sympy.simplify import trigsimp, simplify
9
+ from sympy.functions import sqrt, atan2, sin
10
+ from sympy.matrices import Matrix
11
+ from sympy.testing.pytest import raises, nocache_fail
12
+ from sympy.testing.pytest import warns_deprecated_sympy
13
+
14
+ TP = TensorProduct
15
+
16
+
17
+ def test_coordsys_transform():
18
+ # test inverse transforms
19
+ p, q, r, s = symbols('p q r s')
20
+ rel = {('first', 'second'): [(p, q), (q, -p)]}
21
+ R2_pq = CoordSystem('first', R2_origin, [p, q], rel)
22
+ R2_rs = CoordSystem('second', R2_origin, [r, s], rel)
23
+ r, s = R2_rs.symbols
24
+ assert R2_rs.transform(R2_pq) == Matrix([[-s], [r]])
25
+
26
+ # inverse transform impossible case
27
+ a, b = symbols('a b', positive=True)
28
+ rel = {('first', 'second'): [(a,), (-a,)]}
29
+ R2_a = CoordSystem('first', R2_origin, [a], rel)
30
+ R2_b = CoordSystem('second', R2_origin, [b], rel)
31
+ # This transformation is uninvertible because there is no positive a, b satisfying a = -b
32
+ with raises(NotImplementedError):
33
+ R2_b.transform(R2_a)
34
+
35
+ # inverse transform ambiguous case
36
+ c, d = symbols('c d')
37
+ rel = {('first', 'second'): [(c,), (c**2,)]}
38
+ R2_c = CoordSystem('first', R2_origin, [c], rel)
39
+ R2_d = CoordSystem('second', R2_origin, [d], rel)
40
+ # The transform method should throw if it finds multiple inverses for a coordinate transformation.
41
+ with raises(ValueError):
42
+ R2_d.transform(R2_c)
43
+
44
+ # test indirect transformation
45
+ a, b, c, d, e, f = symbols('a, b, c, d, e, f')
46
+ rel = {('C1', 'C2'): [(a, b), (2*a, 3*b)],
47
+ ('C2', 'C3'): [(c, d), (3*c, 2*d)]}
48
+ C1 = CoordSystem('C1', R2_origin, (a, b), rel)
49
+ C2 = CoordSystem('C2', R2_origin, (c, d), rel)
50
+ C3 = CoordSystem('C3', R2_origin, (e, f), rel)
51
+ a, b = C1.symbols
52
+ c, d = C2.symbols
53
+ e, f = C3.symbols
54
+ assert C2.transform(C1) == Matrix([c/2, d/3])
55
+ assert C1.transform(C3) == Matrix([6*a, 6*b])
56
+ assert C3.transform(C1) == Matrix([e/6, f/6])
57
+ assert C3.transform(C2) == Matrix([e/3, f/2])
58
+
59
+ a, b, c, d, e, f = symbols('a, b, c, d, e, f')
60
+ rel = {('C1', 'C2'): [(a, b), (2*a, 3*b + 1)],
61
+ ('C3', 'C2'): [(e, f), (-e - 2, 2*f)]}
62
+ C1 = CoordSystem('C1', R2_origin, (a, b), rel)
63
+ C2 = CoordSystem('C2', R2_origin, (c, d), rel)
64
+ C3 = CoordSystem('C3', R2_origin, (e, f), rel)
65
+ a, b = C1.symbols
66
+ c, d = C2.symbols
67
+ e, f = C3.symbols
68
+ assert C2.transform(C1) == Matrix([c/2, (d - 1)/3])
69
+ assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2])
70
+ assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3])
71
+ assert C3.transform(C2) == Matrix([-e - 2, 2*f])
72
+
73
+ # old signature uses Lambda
74
+ a, b, c, d, e, f = symbols('a, b, c, d, e, f')
75
+ rel = {('C1', 'C2'): Lambda((a, b), (2*a, 3*b + 1)),
76
+ ('C3', 'C2'): Lambda((e, f), (-e - 2, 2*f))}
77
+ C1 = CoordSystem('C1', R2_origin, (a, b), rel)
78
+ C2 = CoordSystem('C2', R2_origin, (c, d), rel)
79
+ C3 = CoordSystem('C3', R2_origin, (e, f), rel)
80
+ a, b = C1.symbols
81
+ c, d = C2.symbols
82
+ e, f = C3.symbols
83
+ assert C2.transform(C1) == Matrix([c/2, (d - 1)/3])
84
+ assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2])
85
+ assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3])
86
+ assert C3.transform(C2) == Matrix([-e - 2, 2*f])
87
+
88
+
89
+ def test_R2():
90
+ x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True)
91
+ point_r = R2_r.point([x0, y0])
92
+ point_p = R2_p.point([r0, theta0])
93
+
94
+ # r**2 = x**2 + y**2
95
+ assert (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_r) == 0
96
+ assert trigsimp( (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_p) ) == 0
97
+ assert trigsimp(R2.e_r(R2.x**2 + R2.y**2).rcall(point_p).doit()) == 2*r0
98
+
99
+ # polar->rect->polar == Id
100
+ a, b = symbols('a b', positive=True)
101
+ m = Matrix([[a], [b]])
102
+
103
+ #TODO assert m == R2_r.transform(R2_p, R2_p.transform(R2_r, [a, b])).applyfunc(simplify)
104
+ assert m == R2_p.transform(R2_r, R2_r.transform(R2_p, m)).applyfunc(simplify)
105
+
106
+ # deprecated method
107
+ with warns_deprecated_sympy():
108
+ assert m == R2_p.coord_tuple_transform_to(
109
+ R2_r, R2_r.coord_tuple_transform_to(R2_p, m)).applyfunc(simplify)
110
+
111
+
112
+ def test_R3():
113
+ a, b, c = symbols('a b c', positive=True)
114
+ m = Matrix([[a], [b], [c]])
115
+
116
+ assert m == R3_c.transform(R3_r, R3_r.transform(R3_c, m)).applyfunc(simplify)
117
+ #TODO assert m == R3_r.transform(R3_c, R3_c.transform(R3_r, m)).applyfunc(simplify)
118
+ assert m == R3_s.transform(
119
+ R3_r, R3_r.transform(R3_s, m)).applyfunc(simplify)
120
+ #TODO assert m == R3_r.transform(R3_s, R3_s.transform(R3_r, m)).applyfunc(simplify)
121
+ assert m == R3_s.transform(
122
+ R3_c, R3_c.transform(R3_s, m)).applyfunc(simplify)
123
+ #TODO assert m == R3_c.transform(R3_s, R3_s.transform(R3_c, m)).applyfunc(simplify)
124
+
125
+ with warns_deprecated_sympy():
126
+ assert m == R3_c.coord_tuple_transform_to(
127
+ R3_r, R3_r.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify)
128
+ #TODO assert m == R3_r.coord_tuple_transform_to(R3_c, R3_c.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify)
129
+ assert m == R3_s.coord_tuple_transform_to(
130
+ R3_r, R3_r.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify)
131
+ #TODO assert m == R3_r.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify)
132
+ assert m == R3_s.coord_tuple_transform_to(
133
+ R3_c, R3_c.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify)
134
+ #TODO assert m == R3_c.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify)
135
+
136
+
137
+ def test_CoordinateSymbol():
138
+ x, y = R2_r.symbols
139
+ r, theta = R2_p.symbols
140
+ assert y.rewrite(R2_p) == r*sin(theta)
141
+
142
+
143
+ def test_point():
144
+ x, y = symbols('x, y')
145
+ p = R2_r.point([x, y])
146
+ assert p.free_symbols == {x, y}
147
+ assert p.coords(R2_r) == p.coords() == Matrix([x, y])
148
+ assert p.coords(R2_p) == Matrix([sqrt(x**2 + y**2), atan2(y, x)])
149
+
150
+
151
+ def test_commutator():
152
+ assert Commutator(R2.e_x, R2.e_y) == 0
153
+ assert Commutator(R2.x*R2.e_x, R2.x*R2.e_x) == 0
154
+ assert Commutator(R2.x*R2.e_x, R2.x*R2.e_y) == R2.x*R2.e_y
155
+ c = Commutator(R2.e_x, R2.e_r)
156
+ assert c(R2.x) == R2.y*(R2.x**2 + R2.y**2)**(-1)*sin(R2.theta)
157
+
158
+
159
+ def test_differential():
160
+ xdy = R2.x*R2.dy
161
+ dxdy = Differential(xdy)
162
+ assert xdy.rcall(None) == xdy
163
+ assert dxdy(R2.e_x, R2.e_y) == 1
164
+ assert dxdy(R2.e_x, R2.x*R2.e_y) == R2.x
165
+ assert Differential(dxdy) == 0
166
+
167
+
168
+ def test_products():
169
+ assert TensorProduct(
170
+ R2.dx, R2.dy)(R2.e_x, R2.e_y) == R2.dx(R2.e_x)*R2.dy(R2.e_y) == 1
171
+ assert TensorProduct(R2.dx, R2.dy)(None, R2.e_y) == R2.dx
172
+ assert TensorProduct(R2.dx, R2.dy)(R2.e_x, None) == R2.dy
173
+ assert TensorProduct(R2.dx, R2.dy)(R2.e_x) == R2.dy
174
+ assert TensorProduct(R2.x, R2.dx) == R2.x*R2.dx
175
+ assert TensorProduct(
176
+ R2.e_x, R2.e_y)(R2.x, R2.y) == R2.e_x(R2.x) * R2.e_y(R2.y) == 1
177
+ assert TensorProduct(R2.e_x, R2.e_y)(None, R2.y) == R2.e_x
178
+ assert TensorProduct(R2.e_x, R2.e_y)(R2.x, None) == R2.e_y
179
+ assert TensorProduct(R2.e_x, R2.e_y)(R2.x) == R2.e_y
180
+ assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x
181
+ assert TensorProduct(
182
+ R2.dx, R2.e_y)(R2.e_x, R2.y) == R2.dx(R2.e_x) * R2.e_y(R2.y) == 1
183
+ assert TensorProduct(R2.dx, R2.e_y)(None, R2.y) == R2.dx
184
+ assert TensorProduct(R2.dx, R2.e_y)(R2.e_x, None) == R2.e_y
185
+ assert TensorProduct(R2.dx, R2.e_y)(R2.e_x) == R2.e_y
186
+ assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x
187
+ assert TensorProduct(
188
+ R2.e_x, R2.dy)(R2.x, R2.e_y) == R2.e_x(R2.x) * R2.dy(R2.e_y) == 1
189
+ assert TensorProduct(R2.e_x, R2.dy)(None, R2.e_y) == R2.e_x
190
+ assert TensorProduct(R2.e_x, R2.dy)(R2.x, None) == R2.dy
191
+ assert TensorProduct(R2.e_x, R2.dy)(R2.x) == R2.dy
192
+ assert TensorProduct(R2.e_y,R2.e_x)(R2.x**2 + R2.y**2,R2.x**2 + R2.y**2) == 4*R2.x*R2.y
193
+
194
+ assert WedgeProduct(R2.dx, R2.dy)(R2.e_x, R2.e_y) == 1
195
+ assert WedgeProduct(R2.e_x, R2.e_y)(R2.x, R2.y) == 1
196
+
197
+
198
+ def test_lie_derivative():
199
+ assert LieDerivative(R2.e_x, R2.y) == R2.e_x(R2.y) == 0
200
+ assert LieDerivative(R2.e_x, R2.x) == R2.e_x(R2.x) == 1
201
+ assert LieDerivative(R2.e_x, R2.e_x) == Commutator(R2.e_x, R2.e_x) == 0
202
+ assert LieDerivative(R2.e_x, R2.e_r) == Commutator(R2.e_x, R2.e_r)
203
+ assert LieDerivative(R2.e_x + R2.e_y, R2.x) == 1
204
+ assert LieDerivative(
205
+ R2.e_x, TensorProduct(R2.dx, R2.dy))(R2.e_x, R2.e_y) == 0
206
+
207
+
208
+ @nocache_fail
209
+ def test_covar_deriv():
210
+ ch = metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
211
+ cvd = BaseCovarDerivativeOp(R2_r, 0, ch)
212
+ assert cvd(R2.x) == 1
213
+ # This line fails if the cache is disabled:
214
+ assert cvd(R2.x*R2.e_x) == R2.e_x
215
+ cvd = CovarDerivativeOp(R2.x*R2.e_x, ch)
216
+ assert cvd(R2.x) == R2.x
217
+ assert cvd(R2.x*R2.e_x) == R2.x*R2.e_x
218
+
219
+
220
+ def test_intcurve_diffequ():
221
+ t = symbols('t')
222
+ start_point = R2_r.point([1, 0])
223
+ vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
224
+ equations, init_cond = intcurve_diffequ(vector_field, t, start_point)
225
+ assert str(equations) == '[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]'
226
+ assert str(init_cond) == '[f_0(0) - 1, f_1(0)]'
227
+ equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p)
228
+ assert str(
229
+ equations) == '[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]'
230
+ assert str(init_cond) == '[f_0(0) - 1, f_1(0)]'
231
+
232
+
233
+ def test_helpers_and_coordinate_dependent():
234
+ one_form = R2.dr + R2.dx
235
+ two_form = Differential(R2.x*R2.dr + R2.r*R2.dx)
236
+ three_form = Differential(
237
+ R2.y*two_form) + Differential(R2.x*Differential(R2.r*R2.dr))
238
+ metric = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dy, R2.dy)
239
+ metric_ambig = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dr, R2.dr)
240
+ misform_a = TensorProduct(R2.dr, R2.dr) + R2.dr
241
+ misform_b = R2.dr**4
242
+ misform_c = R2.dx*R2.dy
243
+ twoform_not_sym = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dx, R2.dy)
244
+ twoform_not_TP = WedgeProduct(R2.dx, R2.dy)
245
+
246
+ one_vector = R2.e_x + R2.e_y
247
+ two_vector = TensorProduct(R2.e_x, R2.e_y)
248
+ three_vector = TensorProduct(R2.e_x, R2.e_y, R2.e_x)
249
+ two_wp = WedgeProduct(R2.e_x,R2.e_y)
250
+
251
+ assert covariant_order(one_form) == 1
252
+ assert covariant_order(two_form) == 2
253
+ assert covariant_order(three_form) == 3
254
+ assert covariant_order(two_form + metric) == 2
255
+ assert covariant_order(two_form + metric_ambig) == 2
256
+ assert covariant_order(two_form + twoform_not_sym) == 2
257
+ assert covariant_order(two_form + twoform_not_TP) == 2
258
+
259
+ assert contravariant_order(one_vector) == 1
260
+ assert contravariant_order(two_vector) == 2
261
+ assert contravariant_order(three_vector) == 3
262
+ assert contravariant_order(two_vector + two_wp) == 2
263
+
264
+ raises(ValueError, lambda: covariant_order(misform_a))
265
+ raises(ValueError, lambda: covariant_order(misform_b))
266
+ raises(ValueError, lambda: covariant_order(misform_c))
267
+
268
+ assert twoform_to_matrix(metric) == Matrix([[1, 0], [0, 1]])
269
+ assert twoform_to_matrix(twoform_not_sym) == Matrix([[1, 0], [1, 0]])
270
+ assert twoform_to_matrix(twoform_not_TP) == Matrix([[0, -1], [1, 0]])
271
+
272
+ raises(ValueError, lambda: twoform_to_matrix(one_form))
273
+ raises(ValueError, lambda: twoform_to_matrix(three_form))
274
+ raises(ValueError, lambda: twoform_to_matrix(metric_ambig))
275
+
276
+ raises(ValueError, lambda: metric_to_Christoffel_1st(twoform_not_sym))
277
+ raises(ValueError, lambda: metric_to_Christoffel_2nd(twoform_not_sym))
278
+ raises(ValueError, lambda: metric_to_Riemann_components(twoform_not_sym))
279
+ raises(ValueError, lambda: metric_to_Ricci_components(twoform_not_sym))
280
+
281
+
282
+ def test_correct_arguments():
283
+ raises(ValueError, lambda: R2.e_x(R2.e_x))
284
+ raises(ValueError, lambda: R2.e_x(R2.dx))
285
+
286
+ raises(ValueError, lambda: Commutator(R2.e_x, R2.x))
287
+ raises(ValueError, lambda: Commutator(R2.dx, R2.e_x))
288
+
289
+ raises(ValueError, lambda: Differential(Differential(R2.e_x)))
290
+
291
+ raises(ValueError, lambda: R2.dx(R2.x))
292
+
293
+ raises(ValueError, lambda: LieDerivative(R2.dx, R2.dx))
294
+ raises(ValueError, lambda: LieDerivative(R2.x, R2.dx))
295
+
296
+ raises(ValueError, lambda: CovarDerivativeOp(R2.dx, []))
297
+ raises(ValueError, lambda: CovarDerivativeOp(R2.x, []))
298
+
299
+ a = Symbol('a')
300
+ raises(ValueError, lambda: intcurve_series(R2.dx, a, R2_r.point([1, 2])))
301
+ raises(ValueError, lambda: intcurve_series(R2.x, a, R2_r.point([1, 2])))
302
+
303
+ raises(ValueError, lambda: intcurve_diffequ(R2.dx, a, R2_r.point([1, 2])))
304
+ raises(ValueError, lambda: intcurve_diffequ(R2.x, a, R2_r.point([1, 2])))
305
+
306
+ raises(ValueError, lambda: contravariant_order(R2.e_x + R2.dx))
307
+ raises(ValueError, lambda: covariant_order(R2.e_x + R2.dx))
308
+
309
+ raises(ValueError, lambda: contravariant_order(R2.e_x*R2.e_y))
310
+ raises(ValueError, lambda: covariant_order(R2.dx*R2.dy))
311
+
312
+ def test_simplify():
313
+ x, y = R2_r.coord_functions()
314
+ dx, dy = R2_r.base_oneforms()
315
+ ex, ey = R2_r.base_vectors()
316
+ assert simplify(x) == x
317
+ assert simplify(x*y) == x*y
318
+ assert simplify(dx*dy) == dx*dy
319
+ assert simplify(ex*ey) == ex*ey
320
+ assert ((1-x)*dx)/(1-x)**2 == dx/(1-x)
321
+
322
+
323
+ def test_issue_17917():
324
+ X = R2.x*R2.e_x - R2.y*R2.e_y
325
+ Y = (R2.x**2 + R2.y**2)*R2.e_x - R2.x*R2.y*R2.e_y
326
+ assert LieDerivative(X, Y).expand() == (
327
+ R2.x**2*R2.e_x - 3*R2.y**2*R2.e_x - R2.x*R2.y*R2.e_y)
328
+
329
+ def test_deprecations():
330
+ m = Manifold('M', 2)
331
+ p = Patch('P', m)
332
+ with warns_deprecated_sympy():
333
+ CoordSystem('Car2d', p, names=['x', 'y'])
334
+
335
+ with warns_deprecated_sympy():
336
+ c = CoordSystem('Car2d', p, ['x', 'y'])
337
+
338
+ with warns_deprecated_sympy():
339
+ list(m.patches)
340
+
341
+ with warns_deprecated_sympy():
342
+ list(c.transforms)
venv/lib/python3.10/site-packages/sympy/diffgeom/tests/test_function_diffgeom_book.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r
2
+ from sympy.diffgeom import intcurve_series, Differential, WedgeProduct
3
+ from sympy.core import symbols, Function, Derivative
4
+ from sympy.simplify import trigsimp, simplify
5
+ from sympy.functions import sqrt, atan2, sin, cos
6
+ from sympy.matrices import Matrix
7
+
8
+ # Most of the functionality is covered in the
9
+ # test_functional_diffgeom_ch* tests which are based on the
10
+ # example from the paper of Sussman and Wisdom.
11
+ # If they do not cover something, additional tests are added in other test
12
+ # functions.
13
+
14
+ # From "Functional Differential Geometry" as of 2011
15
+ # by Sussman and Wisdom.
16
+
17
+
18
+ def test_functional_diffgeom_ch2():
19
+ x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True)
20
+ x, y = symbols('x, y', real=True)
21
+ f = Function('f')
22
+
23
+ assert (R2_p.point_to_coords(R2_r.point([x0, y0])) ==
24
+ Matrix([sqrt(x0**2 + y0**2), atan2(y0, x0)]))
25
+ assert (R2_r.point_to_coords(R2_p.point([r0, theta0])) ==
26
+ Matrix([r0*cos(theta0), r0*sin(theta0)]))
27
+
28
+ assert R2_p.jacobian(R2_r, [r0, theta0]) == Matrix(
29
+ [[cos(theta0), -r0*sin(theta0)], [sin(theta0), r0*cos(theta0)]])
30
+
31
+ field = f(R2.x, R2.y)
32
+ p1_in_rect = R2_r.point([x0, y0])
33
+ p1_in_polar = R2_p.point([sqrt(x0**2 + y0**2), atan2(y0, x0)])
34
+ assert field.rcall(p1_in_rect) == f(x0, y0)
35
+ assert field.rcall(p1_in_polar) == f(x0, y0)
36
+
37
+ p_r = R2_r.point([x0, y0])
38
+ p_p = R2_p.point([r0, theta0])
39
+ assert R2.x(p_r) == x0
40
+ assert R2.x(p_p) == r0*cos(theta0)
41
+ assert R2.r(p_p) == r0
42
+ assert R2.r(p_r) == sqrt(x0**2 + y0**2)
43
+ assert R2.theta(p_r) == atan2(y0, x0)
44
+
45
+ h = R2.x*R2.r**2 + R2.y**3
46
+ assert h.rcall(p_r) == x0*(x0**2 + y0**2) + y0**3
47
+ assert h.rcall(p_p) == r0**3*sin(theta0)**3 + r0**3*cos(theta0)
48
+
49
+
50
+ def test_functional_diffgeom_ch3():
51
+ x0, y0 = symbols('x0, y0', real=True)
52
+ x, y, t = symbols('x, y, t', real=True)
53
+ f = Function('f')
54
+ b1 = Function('b1')
55
+ b2 = Function('b2')
56
+ p_r = R2_r.point([x0, y0])
57
+
58
+ s_field = f(R2.x, R2.y)
59
+ v_field = b1(R2.x)*R2.e_x + b2(R2.y)*R2.e_y
60
+ assert v_field.rcall(s_field).rcall(p_r).doit() == b1(
61
+ x0)*Derivative(f(x0, y0), x0) + b2(y0)*Derivative(f(x0, y0), y0)
62
+
63
+ assert R2.e_x(R2.r**2).rcall(p_r) == 2*x0
64
+ v = R2.e_x + 2*R2.e_y
65
+ s = R2.r**2 + 3*R2.x
66
+ assert v.rcall(s).rcall(p_r).doit() == 2*x0 + 4*y0 + 3
67
+
68
+ circ = -R2.y*R2.e_x + R2.x*R2.e_y
69
+ series = intcurve_series(circ, t, R2_r.point([1, 0]), coeffs=True)
70
+ series_x, series_y = zip(*series)
71
+ assert all(
72
+ [term == cos(t).taylor_term(i, t) for i, term in enumerate(series_x)])
73
+ assert all(
74
+ [term == sin(t).taylor_term(i, t) for i, term in enumerate(series_y)])
75
+
76
+
77
+ def test_functional_diffgeom_ch4():
78
+ x0, y0, theta0 = symbols('x0, y0, theta0', real=True)
79
+ x, y, r, theta = symbols('x, y, r, theta', real=True)
80
+ r0 = symbols('r0', positive=True)
81
+ f = Function('f')
82
+ b1 = Function('b1')
83
+ b2 = Function('b2')
84
+ p_r = R2_r.point([x0, y0])
85
+ p_p = R2_p.point([r0, theta0])
86
+
87
+ f_field = b1(R2.x, R2.y)*R2.dx + b2(R2.x, R2.y)*R2.dy
88
+ assert f_field.rcall(R2.e_x).rcall(p_r) == b1(x0, y0)
89
+ assert f_field.rcall(R2.e_y).rcall(p_r) == b2(x0, y0)
90
+
91
+ s_field_r = f(R2.x, R2.y)
92
+ df = Differential(s_field_r)
93
+ assert df(R2.e_x).rcall(p_r).doit() == Derivative(f(x0, y0), x0)
94
+ assert df(R2.e_y).rcall(p_r).doit() == Derivative(f(x0, y0), y0)
95
+
96
+ s_field_p = f(R2.r, R2.theta)
97
+ df = Differential(s_field_p)
98
+ assert trigsimp(df(R2.e_x).rcall(p_p).doit()) == (
99
+ cos(theta0)*Derivative(f(r0, theta0), r0) -
100
+ sin(theta0)*Derivative(f(r0, theta0), theta0)/r0)
101
+ assert trigsimp(df(R2.e_y).rcall(p_p).doit()) == (
102
+ sin(theta0)*Derivative(f(r0, theta0), r0) +
103
+ cos(theta0)*Derivative(f(r0, theta0), theta0)/r0)
104
+
105
+ assert R2.dx(R2.e_x).rcall(p_r) == 1
106
+ assert R2.dx(R2.e_x) == 1
107
+ assert R2.dx(R2.e_y).rcall(p_r) == 0
108
+ assert R2.dx(R2.e_y) == 0
109
+
110
+ circ = -R2.y*R2.e_x + R2.x*R2.e_y
111
+ assert R2.dx(circ).rcall(p_r).doit() == -y0
112
+ assert R2.dy(circ).rcall(p_r) == x0
113
+ assert R2.dr(circ).rcall(p_r) == 0
114
+ assert simplify(R2.dtheta(circ).rcall(p_r)) == 1
115
+
116
+ assert (circ - R2.e_theta).rcall(s_field_r).rcall(p_r) == 0
117
+
118
+
119
+ def test_functional_diffgeom_ch6():
120
+ u0, u1, u2, v0, v1, v2, w0, w1, w2 = symbols('u0:3, v0:3, w0:3', real=True)
121
+
122
+ u = u0*R2.e_x + u1*R2.e_y
123
+ v = v0*R2.e_x + v1*R2.e_y
124
+ wp = WedgeProduct(R2.dx, R2.dy)
125
+ assert wp(u, v) == u0*v1 - u1*v0
126
+
127
+ u = u0*R3_r.e_x + u1*R3_r.e_y + u2*R3_r.e_z
128
+ v = v0*R3_r.e_x + v1*R3_r.e_y + v2*R3_r.e_z
129
+ w = w0*R3_r.e_x + w1*R3_r.e_y + w2*R3_r.e_z
130
+ wp = WedgeProduct(R3_r.dx, R3_r.dy, R3_r.dz)
131
+ assert wp(
132
+ u, v, w) == Matrix(3, 3, [u0, u1, u2, v0, v1, v2, w0, w1, w2]).det()
133
+
134
+ a, b, c = symbols('a, b, c', cls=Function)
135
+ a_f = a(R3_r.x, R3_r.y, R3_r.z)
136
+ b_f = b(R3_r.x, R3_r.y, R3_r.z)
137
+ c_f = c(R3_r.x, R3_r.y, R3_r.z)
138
+ theta = a_f*R3_r.dx + b_f*R3_r.dy + c_f*R3_r.dz
139
+ dtheta = Differential(theta)
140
+ da = Differential(a_f)
141
+ db = Differential(b_f)
142
+ dc = Differential(c_f)
143
+ expr = dtheta - WedgeProduct(
144
+ da, R3_r.dx) - WedgeProduct(db, R3_r.dy) - WedgeProduct(dc, R3_r.dz)
145
+ assert expr.rcall(R3_r.e_x, R3_r.e_y) == 0
venv/lib/python3.10/site-packages/sympy/diffgeom/tests/test_hyperbolic_space.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r'''
2
+ unit test describing the hyperbolic half-plane with the Poincare metric. This
3
+ is a basic model of hyperbolic geometry on the (positive) half-space
4
+
5
+ {(x,y) \in R^2 | y > 0}
6
+
7
+ with the Riemannian metric
8
+
9
+ ds^2 = (dx^2 + dy^2)/y^2
10
+
11
+ It has constant negative scalar curvature = -2
12
+
13
+ https://en.wikipedia.org/wiki/Poincare_half-plane_model
14
+ '''
15
+ from sympy.matrices.dense import diag
16
+ from sympy.diffgeom import (twoform_to_matrix,
17
+ metric_to_Christoffel_1st, metric_to_Christoffel_2nd,
18
+ metric_to_Riemann_components, metric_to_Ricci_components)
19
+ import sympy.diffgeom.rn
20
+ from sympy.tensor.array import ImmutableDenseNDimArray
21
+
22
+
23
+ def test_H2():
24
+ TP = sympy.diffgeom.TensorProduct
25
+ R2 = sympy.diffgeom.rn.R2
26
+ y = R2.y
27
+ dy = R2.dy
28
+ dx = R2.dx
29
+ g = (TP(dx, dx) + TP(dy, dy))*y**(-2)
30
+ automat = twoform_to_matrix(g)
31
+ mat = diag(y**(-2), y**(-2))
32
+ assert mat == automat
33
+
34
+ gamma1 = metric_to_Christoffel_1st(g)
35
+ assert gamma1[0, 0, 0] == 0
36
+ assert gamma1[0, 0, 1] == -y**(-3)
37
+ assert gamma1[0, 1, 0] == -y**(-3)
38
+ assert gamma1[0, 1, 1] == 0
39
+
40
+ assert gamma1[1, 1, 1] == -y**(-3)
41
+ assert gamma1[1, 1, 0] == 0
42
+ assert gamma1[1, 0, 1] == 0
43
+ assert gamma1[1, 0, 0] == y**(-3)
44
+
45
+ gamma2 = metric_to_Christoffel_2nd(g)
46
+ assert gamma2[0, 0, 0] == 0
47
+ assert gamma2[0, 0, 1] == -y**(-1)
48
+ assert gamma2[0, 1, 0] == -y**(-1)
49
+ assert gamma2[0, 1, 1] == 0
50
+
51
+ assert gamma2[1, 1, 1] == -y**(-1)
52
+ assert gamma2[1, 1, 0] == 0
53
+ assert gamma2[1, 0, 1] == 0
54
+ assert gamma2[1, 0, 0] == y**(-1)
55
+
56
+ Rm = metric_to_Riemann_components(g)
57
+ assert Rm[0, 0, 0, 0] == 0
58
+ assert Rm[0, 0, 0, 1] == 0
59
+ assert Rm[0, 0, 1, 0] == 0
60
+ assert Rm[0, 0, 1, 1] == 0
61
+
62
+ assert Rm[0, 1, 0, 0] == 0
63
+ assert Rm[0, 1, 0, 1] == -y**(-2)
64
+ assert Rm[0, 1, 1, 0] == y**(-2)
65
+ assert Rm[0, 1, 1, 1] == 0
66
+
67
+ assert Rm[1, 0, 0, 0] == 0
68
+ assert Rm[1, 0, 0, 1] == y**(-2)
69
+ assert Rm[1, 0, 1, 0] == -y**(-2)
70
+ assert Rm[1, 0, 1, 1] == 0
71
+
72
+ assert Rm[1, 1, 0, 0] == 0
73
+ assert Rm[1, 1, 0, 1] == 0
74
+ assert Rm[1, 1, 1, 0] == 0
75
+ assert Rm[1, 1, 1, 1] == 0
76
+
77
+ Ric = metric_to_Ricci_components(g)
78
+ assert Ric[0, 0] == -y**(-2)
79
+ assert Ric[0, 1] == 0
80
+ assert Ric[1, 0] == 0
81
+ assert Ric[0, 0] == -y**(-2)
82
+
83
+ assert Ric == ImmutableDenseNDimArray([-y**(-2), 0, 0, -y**(-2)], (2, 2))
84
+
85
+ ## scalar curvature is -2
86
+ #TODO - it would be nice to have index contraction built-in
87
+ R = (Ric[0, 0] + Ric[1, 1])*y**2
88
+ assert R == -2
89
+
90
+ ## Gauss curvature is -1
91
+ assert R/2 == -1
venv/lib/python3.10/site-packages/sympy/logic/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (690 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/logic/__pycache__/boolalg.cpython-310.pyc ADDED
Binary file (101 kB). View file
 
venv/lib/python3.10/site-packages/sympy/logic/__pycache__/inference.cpython-310.pyc ADDED
Binary file (9.01 kB). View file
 
venv/lib/python3.10/site-packages/sympy/logic/algorithms/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (190 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/dpll.cpython-310.pyc ADDED
Binary file (8.03 kB). View file
 
venv/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/dpll2.cpython-310.pyc ADDED
Binary file (17.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/minisat22_wrapper.cpython-310.pyc ADDED
Binary file (1.94 kB). View file
 
venv/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/pycosat_wrapper.cpython-310.pyc ADDED
Binary file (1.42 kB). View file
 
venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of DPLL algorithm
2
+
3
+ Further improvements: eliminate calls to pl_true, implement branching rules,
4
+ efficient unit propagation.
5
+
6
+ References:
7
+ - https://en.wikipedia.org/wiki/DPLL_algorithm
8
+ - https://www.researchgate.net/publication/242384772_Implementations_of_the_DPLL_Algorithm
9
+ """
10
+
11
+ from sympy.core.sorting import default_sort_key
12
+ from sympy.logic.boolalg import Or, Not, conjuncts, disjuncts, to_cnf, \
13
+ to_int_repr, _find_predicates
14
+ from sympy.assumptions.cnf import CNF
15
+ from sympy.logic.inference import pl_true, literal_symbol
16
+
17
+
18
+ def dpll_satisfiable(expr):
19
+ """
20
+ Check satisfiability of a propositional sentence.
21
+ It returns a model rather than True when it succeeds
22
+
23
+ >>> from sympy.abc import A, B
24
+ >>> from sympy.logic.algorithms.dpll import dpll_satisfiable
25
+ >>> dpll_satisfiable(A & ~B)
26
+ {A: True, B: False}
27
+ >>> dpll_satisfiable(A & ~A)
28
+ False
29
+
30
+ """
31
+ if not isinstance(expr, CNF):
32
+ clauses = conjuncts(to_cnf(expr))
33
+ else:
34
+ clauses = expr.clauses
35
+ if False in clauses:
36
+ return False
37
+ symbols = sorted(_find_predicates(expr), key=default_sort_key)
38
+ symbols_int_repr = set(range(1, len(symbols) + 1))
39
+ clauses_int_repr = to_int_repr(clauses, symbols)
40
+ result = dpll_int_repr(clauses_int_repr, symbols_int_repr, {})
41
+ if not result:
42
+ return result
43
+ output = {}
44
+ for key in result:
45
+ output.update({symbols[key - 1]: result[key]})
46
+ return output
47
+
48
+
49
+ def dpll(clauses, symbols, model):
50
+ """
51
+ Compute satisfiability in a partial model.
52
+ Clauses is an array of conjuncts.
53
+
54
+ >>> from sympy.abc import A, B, D
55
+ >>> from sympy.logic.algorithms.dpll import dpll
56
+ >>> dpll([A, B, D], [A, B], {D: False})
57
+ False
58
+
59
+ """
60
+ # compute DP kernel
61
+ P, value = find_unit_clause(clauses, model)
62
+ while P:
63
+ model.update({P: value})
64
+ symbols.remove(P)
65
+ if not value:
66
+ P = ~P
67
+ clauses = unit_propagate(clauses, P)
68
+ P, value = find_unit_clause(clauses, model)
69
+ P, value = find_pure_symbol(symbols, clauses)
70
+ while P:
71
+ model.update({P: value})
72
+ symbols.remove(P)
73
+ if not value:
74
+ P = ~P
75
+ clauses = unit_propagate(clauses, P)
76
+ P, value = find_pure_symbol(symbols, clauses)
77
+ # end DP kernel
78
+ unknown_clauses = []
79
+ for c in clauses:
80
+ val = pl_true(c, model)
81
+ if val is False:
82
+ return False
83
+ if val is not True:
84
+ unknown_clauses.append(c)
85
+ if not unknown_clauses:
86
+ return model
87
+ if not clauses:
88
+ return model
89
+ P = symbols.pop()
90
+ model_copy = model.copy()
91
+ model.update({P: True})
92
+ model_copy.update({P: False})
93
+ symbols_copy = symbols[:]
94
+ return (dpll(unit_propagate(unknown_clauses, P), symbols, model) or
95
+ dpll(unit_propagate(unknown_clauses, Not(P)), symbols_copy, model_copy))
96
+
97
+
98
+ def dpll_int_repr(clauses, symbols, model):
99
+ """
100
+ Compute satisfiability in a partial model.
101
+ Arguments are expected to be in integer representation
102
+
103
+ >>> from sympy.logic.algorithms.dpll import dpll_int_repr
104
+ >>> dpll_int_repr([{1}, {2}, {3}], {1, 2}, {3: False})
105
+ False
106
+
107
+ """
108
+ # compute DP kernel
109
+ P, value = find_unit_clause_int_repr(clauses, model)
110
+ while P:
111
+ model.update({P: value})
112
+ symbols.remove(P)
113
+ if not value:
114
+ P = -P
115
+ clauses = unit_propagate_int_repr(clauses, P)
116
+ P, value = find_unit_clause_int_repr(clauses, model)
117
+ P, value = find_pure_symbol_int_repr(symbols, clauses)
118
+ while P:
119
+ model.update({P: value})
120
+ symbols.remove(P)
121
+ if not value:
122
+ P = -P
123
+ clauses = unit_propagate_int_repr(clauses, P)
124
+ P, value = find_pure_symbol_int_repr(symbols, clauses)
125
+ # end DP kernel
126
+ unknown_clauses = []
127
+ for c in clauses:
128
+ val = pl_true_int_repr(c, model)
129
+ if val is False:
130
+ return False
131
+ if val is not True:
132
+ unknown_clauses.append(c)
133
+ if not unknown_clauses:
134
+ return model
135
+ P = symbols.pop()
136
+ model_copy = model.copy()
137
+ model.update({P: True})
138
+ model_copy.update({P: False})
139
+ symbols_copy = symbols.copy()
140
+ return (dpll_int_repr(unit_propagate_int_repr(unknown_clauses, P), symbols, model) or
141
+ dpll_int_repr(unit_propagate_int_repr(unknown_clauses, -P), symbols_copy, model_copy))
142
+
143
+ ### helper methods for DPLL
144
+
145
+
146
+ def pl_true_int_repr(clause, model={}):
147
+ """
148
+ Lightweight version of pl_true.
149
+ Argument clause represents the set of args of an Or clause. This is used
150
+ inside dpll_int_repr, it is not meant to be used directly.
151
+
152
+ >>> from sympy.logic.algorithms.dpll import pl_true_int_repr
153
+ >>> pl_true_int_repr({1, 2}, {1: False})
154
+ >>> pl_true_int_repr({1, 2}, {1: False, 2: False})
155
+ False
156
+
157
+ """
158
+ result = False
159
+ for lit in clause:
160
+ if lit < 0:
161
+ p = model.get(-lit)
162
+ if p is not None:
163
+ p = not p
164
+ else:
165
+ p = model.get(lit)
166
+ if p is True:
167
+ return True
168
+ elif p is None:
169
+ result = None
170
+ return result
171
+
172
+
173
+ def unit_propagate(clauses, symbol):
174
+ """
175
+ Returns an equivalent set of clauses
176
+ If a set of clauses contains the unit clause l, the other clauses are
177
+ simplified by the application of the two following rules:
178
+
179
+ 1. every clause containing l is removed
180
+ 2. in every clause that contains ~l this literal is deleted
181
+
182
+ Arguments are expected to be in CNF.
183
+
184
+ >>> from sympy.abc import A, B, D
185
+ >>> from sympy.logic.algorithms.dpll import unit_propagate
186
+ >>> unit_propagate([A | B, D | ~B, B], B)
187
+ [D, B]
188
+
189
+ """
190
+ output = []
191
+ for c in clauses:
192
+ if c.func != Or:
193
+ output.append(c)
194
+ continue
195
+ for arg in c.args:
196
+ if arg == ~symbol:
197
+ output.append(Or(*[x for x in c.args if x != ~symbol]))
198
+ break
199
+ if arg == symbol:
200
+ break
201
+ else:
202
+ output.append(c)
203
+ return output
204
+
205
+
206
+ def unit_propagate_int_repr(clauses, s):
207
+ """
208
+ Same as unit_propagate, but arguments are expected to be in integer
209
+ representation
210
+
211
+ >>> from sympy.logic.algorithms.dpll import unit_propagate_int_repr
212
+ >>> unit_propagate_int_repr([{1, 2}, {3, -2}, {2}], 2)
213
+ [{3}]
214
+
215
+ """
216
+ negated = {-s}
217
+ return [clause - negated for clause in clauses if s not in clause]
218
+
219
+
220
+ def find_pure_symbol(symbols, unknown_clauses):
221
+ """
222
+ Find a symbol and its value if it appears only as a positive literal
223
+ (or only as a negative) in clauses.
224
+
225
+ >>> from sympy.abc import A, B, D
226
+ >>> from sympy.logic.algorithms.dpll import find_pure_symbol
227
+ >>> find_pure_symbol([A, B, D], [A|~B,~B|~D,D|A])
228
+ (A, True)
229
+
230
+ """
231
+ for sym in symbols:
232
+ found_pos, found_neg = False, False
233
+ for c in unknown_clauses:
234
+ if not found_pos and sym in disjuncts(c):
235
+ found_pos = True
236
+ if not found_neg and Not(sym) in disjuncts(c):
237
+ found_neg = True
238
+ if found_pos != found_neg:
239
+ return sym, found_pos
240
+ return None, None
241
+
242
+
243
+ def find_pure_symbol_int_repr(symbols, unknown_clauses):
244
+ """
245
+ Same as find_pure_symbol, but arguments are expected
246
+ to be in integer representation
247
+
248
+ >>> from sympy.logic.algorithms.dpll import find_pure_symbol_int_repr
249
+ >>> find_pure_symbol_int_repr({1,2,3},
250
+ ... [{1, -2}, {-2, -3}, {3, 1}])
251
+ (1, True)
252
+
253
+ """
254
+ all_symbols = set().union(*unknown_clauses)
255
+ found_pos = all_symbols.intersection(symbols)
256
+ found_neg = all_symbols.intersection([-s for s in symbols])
257
+ for p in found_pos:
258
+ if -p not in found_neg:
259
+ return p, True
260
+ for p in found_neg:
261
+ if -p not in found_pos:
262
+ return -p, False
263
+ return None, None
264
+
265
+
266
+ def find_unit_clause(clauses, model):
267
+ """
268
+ A unit clause has only 1 variable that is not bound in the model.
269
+
270
+ >>> from sympy.abc import A, B, D
271
+ >>> from sympy.logic.algorithms.dpll import find_unit_clause
272
+ >>> find_unit_clause([A | B | D, B | ~D, A | ~B], {A:True})
273
+ (B, False)
274
+
275
+ """
276
+ for clause in clauses:
277
+ num_not_in_model = 0
278
+ for literal in disjuncts(clause):
279
+ sym = literal_symbol(literal)
280
+ if sym not in model:
281
+ num_not_in_model += 1
282
+ P, value = sym, not isinstance(literal, Not)
283
+ if num_not_in_model == 1:
284
+ return P, value
285
+ return None, None
286
+
287
+
288
+ def find_unit_clause_int_repr(clauses, model):
289
+ """
290
+ Same as find_unit_clause, but arguments are expected to be in
291
+ integer representation.
292
+
293
+ >>> from sympy.logic.algorithms.dpll import find_unit_clause_int_repr
294
+ >>> find_unit_clause_int_repr([{1, 2, 3},
295
+ ... {2, -3}, {1, -2}], {1: True})
296
+ (2, False)
297
+
298
+ """
299
+ bound = set(model) | {-sym for sym in model}
300
+ for clause in clauses:
301
+ unbound = clause - bound
302
+ if len(unbound) == 1:
303
+ p = unbound.pop()
304
+ if p < 0:
305
+ return -p, False
306
+ else:
307
+ return p, True
308
+ return None, None
venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll2.py ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of DPLL algorithm
2
+
3
+ Features:
4
+ - Clause learning
5
+ - Watch literal scheme
6
+ - VSIDS heuristic
7
+
8
+ References:
9
+ - https://en.wikipedia.org/wiki/DPLL_algorithm
10
+ """
11
+
12
+ from collections import defaultdict
13
+ from heapq import heappush, heappop
14
+
15
+ from sympy.core.sorting import ordered
16
+ from sympy.assumptions.cnf import EncodedCNF
17
+
18
+
19
+ def dpll_satisfiable(expr, all_models=False):
20
+ """
21
+ Check satisfiability of a propositional sentence.
22
+ It returns a model rather than True when it succeeds.
23
+ Returns a generator of all models if all_models is True.
24
+
25
+ Examples
26
+ ========
27
+
28
+ >>> from sympy.abc import A, B
29
+ >>> from sympy.logic.algorithms.dpll2 import dpll_satisfiable
30
+ >>> dpll_satisfiable(A & ~B)
31
+ {A: True, B: False}
32
+ >>> dpll_satisfiable(A & ~A)
33
+ False
34
+
35
+ """
36
+ if not isinstance(expr, EncodedCNF):
37
+ exprs = EncodedCNF()
38
+ exprs.add_prop(expr)
39
+ expr = exprs
40
+
41
+ # Return UNSAT when False (encoded as 0) is present in the CNF
42
+ if {0} in expr.data:
43
+ if all_models:
44
+ return (f for f in [False])
45
+ return False
46
+
47
+ solver = SATSolver(expr.data, expr.variables, set(), expr.symbols)
48
+ models = solver._find_model()
49
+
50
+ if all_models:
51
+ return _all_models(models)
52
+
53
+ try:
54
+ return next(models)
55
+ except StopIteration:
56
+ return False
57
+
58
+ # Uncomment to confirm the solution is valid (hitting set for the clauses)
59
+ #else:
60
+ #for cls in clauses_int_repr:
61
+ #assert solver.var_settings.intersection(cls)
62
+
63
+
64
+ def _all_models(models):
65
+ satisfiable = False
66
+ try:
67
+ while True:
68
+ yield next(models)
69
+ satisfiable = True
70
+ except StopIteration:
71
+ if not satisfiable:
72
+ yield False
73
+
74
+
75
+ class SATSolver:
76
+ """
77
+ Class for representing a SAT solver capable of
78
+ finding a model to a boolean theory in conjunctive
79
+ normal form.
80
+ """
81
+
82
+ def __init__(self, clauses, variables, var_settings, symbols=None,
83
+ heuristic='vsids', clause_learning='none', INTERVAL=500):
84
+
85
+ self.var_settings = var_settings
86
+ self.heuristic = heuristic
87
+ self.is_unsatisfied = False
88
+ self._unit_prop_queue = []
89
+ self.update_functions = []
90
+ self.INTERVAL = INTERVAL
91
+
92
+ if symbols is None:
93
+ self.symbols = list(ordered(variables))
94
+ else:
95
+ self.symbols = symbols
96
+
97
+ self._initialize_variables(variables)
98
+ self._initialize_clauses(clauses)
99
+
100
+ if 'vsids' == heuristic:
101
+ self._vsids_init()
102
+ self.heur_calculate = self._vsids_calculate
103
+ self.heur_lit_assigned = self._vsids_lit_assigned
104
+ self.heur_lit_unset = self._vsids_lit_unset
105
+ self.heur_clause_added = self._vsids_clause_added
106
+
107
+ # Note: Uncomment this if/when clause learning is enabled
108
+ #self.update_functions.append(self._vsids_decay)
109
+
110
+ else:
111
+ raise NotImplementedError
112
+
113
+ if 'simple' == clause_learning:
114
+ self.add_learned_clause = self._simple_add_learned_clause
115
+ self.compute_conflict = self.simple_compute_conflict
116
+ self.update_functions.append(self.simple_clean_clauses)
117
+ elif 'none' == clause_learning:
118
+ self.add_learned_clause = lambda x: None
119
+ self.compute_conflict = lambda: None
120
+ else:
121
+ raise NotImplementedError
122
+
123
+ # Create the base level
124
+ self.levels = [Level(0)]
125
+ self._current_level.varsettings = var_settings
126
+
127
+ # Keep stats
128
+ self.num_decisions = 0
129
+ self.num_learned_clauses = 0
130
+ self.original_num_clauses = len(self.clauses)
131
+
132
+ def _initialize_variables(self, variables):
133
+ """Set up the variable data structures needed."""
134
+ self.sentinels = defaultdict(set)
135
+ self.occurrence_count = defaultdict(int)
136
+ self.variable_set = [False] * (len(variables) + 1)
137
+
138
+ def _initialize_clauses(self, clauses):
139
+ """Set up the clause data structures needed.
140
+
141
+ For each clause, the following changes are made:
142
+ - Unit clauses are queued for propagation right away.
143
+ - Non-unit clauses have their first and last literals set as sentinels.
144
+ - The number of clauses a literal appears in is computed.
145
+ """
146
+ self.clauses = [list(clause) for clause in clauses]
147
+
148
+ for i, clause in enumerate(self.clauses):
149
+
150
+ # Handle the unit clauses
151
+ if 1 == len(clause):
152
+ self._unit_prop_queue.append(clause[0])
153
+ continue
154
+
155
+ self.sentinels[clause[0]].add(i)
156
+ self.sentinels[clause[-1]].add(i)
157
+
158
+ for lit in clause:
159
+ self.occurrence_count[lit] += 1
160
+
161
+ def _find_model(self):
162
+ """
163
+ Main DPLL loop. Returns a generator of models.
164
+
165
+ Variables are chosen successively, and assigned to be either
166
+ True or False. If a solution is not found with this setting,
167
+ the opposite is chosen and the search continues. The solver
168
+ halts when every variable has a setting.
169
+
170
+ Examples
171
+ ========
172
+
173
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
174
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
175
+ ... {3, -2}], {1, 2, 3}, set())
176
+ >>> list(l._find_model())
177
+ [{1: True, 2: False, 3: False}, {1: True, 2: True, 3: True}]
178
+
179
+ >>> from sympy.abc import A, B, C
180
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
181
+ ... {3, -2}], {1, 2, 3}, set(), [A, B, C])
182
+ >>> list(l._find_model())
183
+ [{A: True, B: False, C: False}, {A: True, B: True, C: True}]
184
+
185
+ """
186
+
187
+ # We use this variable to keep track of if we should flip a
188
+ # variable setting in successive rounds
189
+ flip_var = False
190
+
191
+ # Check if unit prop says the theory is unsat right off the bat
192
+ self._simplify()
193
+ if self.is_unsatisfied:
194
+ return
195
+
196
+ # While the theory still has clauses remaining
197
+ while True:
198
+ # Perform cleanup / fixup at regular intervals
199
+ if self.num_decisions % self.INTERVAL == 0:
200
+ for func in self.update_functions:
201
+ func()
202
+
203
+ if flip_var:
204
+ # We have just backtracked and we are trying to opposite literal
205
+ flip_var = False
206
+ lit = self._current_level.decision
207
+
208
+ else:
209
+ # Pick a literal to set
210
+ lit = self.heur_calculate()
211
+ self.num_decisions += 1
212
+
213
+ # Stopping condition for a satisfying theory
214
+ if 0 == lit:
215
+ yield {self.symbols[abs(lit) - 1]:
216
+ lit > 0 for lit in self.var_settings}
217
+ while self._current_level.flipped:
218
+ self._undo()
219
+ if len(self.levels) == 1:
220
+ return
221
+ flip_lit = -self._current_level.decision
222
+ self._undo()
223
+ self.levels.append(Level(flip_lit, flipped=True))
224
+ flip_var = True
225
+ continue
226
+
227
+ # Start the new decision level
228
+ self.levels.append(Level(lit))
229
+
230
+ # Assign the literal, updating the clauses it satisfies
231
+ self._assign_literal(lit)
232
+
233
+ # _simplify the theory
234
+ self._simplify()
235
+
236
+ # Check if we've made the theory unsat
237
+ if self.is_unsatisfied:
238
+
239
+ self.is_unsatisfied = False
240
+
241
+ # We unroll all of the decisions until we can flip a literal
242
+ while self._current_level.flipped:
243
+ self._undo()
244
+
245
+ # If we've unrolled all the way, the theory is unsat
246
+ if 1 == len(self.levels):
247
+ return
248
+
249
+ # Detect and add a learned clause
250
+ self.add_learned_clause(self.compute_conflict())
251
+
252
+ # Try the opposite setting of the most recent decision
253
+ flip_lit = -self._current_level.decision
254
+ self._undo()
255
+ self.levels.append(Level(flip_lit, flipped=True))
256
+ flip_var = True
257
+
258
+ ########################
259
+ # Helper Methods #
260
+ ########################
261
+ @property
262
+ def _current_level(self):
263
+ """The current decision level data structure
264
+
265
+ Examples
266
+ ========
267
+
268
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
269
+ >>> l = SATSolver([{1}, {2}], {1, 2}, set())
270
+ >>> next(l._find_model())
271
+ {1: True, 2: True}
272
+ >>> l._current_level.decision
273
+ 0
274
+ >>> l._current_level.flipped
275
+ False
276
+ >>> l._current_level.var_settings
277
+ {1, 2}
278
+
279
+ """
280
+ return self.levels[-1]
281
+
282
+ def _clause_sat(self, cls):
283
+ """Check if a clause is satisfied by the current variable setting.
284
+
285
+ Examples
286
+ ========
287
+
288
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
289
+ >>> l = SATSolver([{1}, {-1}], {1}, set())
290
+ >>> try:
291
+ ... next(l._find_model())
292
+ ... except StopIteration:
293
+ ... pass
294
+ >>> l._clause_sat(0)
295
+ False
296
+ >>> l._clause_sat(1)
297
+ True
298
+
299
+ """
300
+ for lit in self.clauses[cls]:
301
+ if lit in self.var_settings:
302
+ return True
303
+ return False
304
+
305
+ def _is_sentinel(self, lit, cls):
306
+ """Check if a literal is a sentinel of a given clause.
307
+
308
+ Examples
309
+ ========
310
+
311
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
312
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
313
+ ... {3, -2}], {1, 2, 3}, set())
314
+ >>> next(l._find_model())
315
+ {1: True, 2: False, 3: False}
316
+ >>> l._is_sentinel(2, 3)
317
+ True
318
+ >>> l._is_sentinel(-3, 1)
319
+ False
320
+
321
+ """
322
+ return cls in self.sentinels[lit]
323
+
324
+ def _assign_literal(self, lit):
325
+ """Make a literal assignment.
326
+
327
+ The literal assignment must be recorded as part of the current
328
+ decision level. Additionally, if the literal is marked as a
329
+ sentinel of any clause, then a new sentinel must be chosen. If
330
+ this is not possible, then unit propagation is triggered and
331
+ another literal is added to the queue to be set in the future.
332
+
333
+ Examples
334
+ ========
335
+
336
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
337
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
338
+ ... {3, -2}], {1, 2, 3}, set())
339
+ >>> next(l._find_model())
340
+ {1: True, 2: False, 3: False}
341
+ >>> l.var_settings
342
+ {-3, -2, 1}
343
+
344
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
345
+ ... {3, -2}], {1, 2, 3}, set())
346
+ >>> l._assign_literal(-1)
347
+ >>> try:
348
+ ... next(l._find_model())
349
+ ... except StopIteration:
350
+ ... pass
351
+ >>> l.var_settings
352
+ {-1}
353
+
354
+ """
355
+ self.var_settings.add(lit)
356
+ self._current_level.var_settings.add(lit)
357
+ self.variable_set[abs(lit)] = True
358
+ self.heur_lit_assigned(lit)
359
+
360
+ sentinel_list = list(self.sentinels[-lit])
361
+
362
+ for cls in sentinel_list:
363
+ if not self._clause_sat(cls):
364
+ other_sentinel = None
365
+ for newlit in self.clauses[cls]:
366
+ if newlit != -lit:
367
+ if self._is_sentinel(newlit, cls):
368
+ other_sentinel = newlit
369
+ elif not self.variable_set[abs(newlit)]:
370
+ self.sentinels[-lit].remove(cls)
371
+ self.sentinels[newlit].add(cls)
372
+ other_sentinel = None
373
+ break
374
+
375
+ # Check if no sentinel update exists
376
+ if other_sentinel:
377
+ self._unit_prop_queue.append(other_sentinel)
378
+
379
+ def _undo(self):
380
+ """
381
+ _undo the changes of the most recent decision level.
382
+
383
+ Examples
384
+ ========
385
+
386
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
387
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
388
+ ... {3, -2}], {1, 2, 3}, set())
389
+ >>> next(l._find_model())
390
+ {1: True, 2: False, 3: False}
391
+ >>> level = l._current_level
392
+ >>> level.decision, level.var_settings, level.flipped
393
+ (-3, {-3, -2}, False)
394
+ >>> l._undo()
395
+ >>> level = l._current_level
396
+ >>> level.decision, level.var_settings, level.flipped
397
+ (0, {1}, False)
398
+
399
+ """
400
+ # Undo the variable settings
401
+ for lit in self._current_level.var_settings:
402
+ self.var_settings.remove(lit)
403
+ self.heur_lit_unset(lit)
404
+ self.variable_set[abs(lit)] = False
405
+
406
+ # Pop the level off the stack
407
+ self.levels.pop()
408
+
409
+ #########################
410
+ # Propagation #
411
+ #########################
412
+ """
413
+ Propagation methods should attempt to soundly simplify the boolean
414
+ theory, and return True if any simplification occurred and False
415
+ otherwise.
416
+ """
417
+ def _simplify(self):
418
+ """Iterate over the various forms of propagation to simplify the theory.
419
+
420
+ Examples
421
+ ========
422
+
423
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
424
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
425
+ ... {3, -2}], {1, 2, 3}, set())
426
+ >>> l.variable_set
427
+ [False, False, False, False]
428
+ >>> l.sentinels
429
+ {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
430
+
431
+ >>> l._simplify()
432
+
433
+ >>> l.variable_set
434
+ [False, True, False, False]
435
+ >>> l.sentinels
436
+ {-3: {0, 2}, -2: {3, 4}, -1: set(), 2: {0, 3},
437
+ ...3: {2, 4}}
438
+
439
+ """
440
+ changed = True
441
+ while changed:
442
+ changed = False
443
+ changed |= self._unit_prop()
444
+ changed |= self._pure_literal()
445
+
446
+ def _unit_prop(self):
447
+ """Perform unit propagation on the current theory."""
448
+ result = len(self._unit_prop_queue) > 0
449
+ while self._unit_prop_queue:
450
+ next_lit = self._unit_prop_queue.pop()
451
+ if -next_lit in self.var_settings:
452
+ self.is_unsatisfied = True
453
+ self._unit_prop_queue = []
454
+ return False
455
+ else:
456
+ self._assign_literal(next_lit)
457
+
458
+ return result
459
+
460
+ def _pure_literal(self):
461
+ """Look for pure literals and assign them when found."""
462
+ return False
463
+
464
+ #########################
465
+ # Heuristics #
466
+ #########################
467
+ def _vsids_init(self):
468
+ """Initialize the data structures needed for the VSIDS heuristic."""
469
+ self.lit_heap = []
470
+ self.lit_scores = {}
471
+
472
+ for var in range(1, len(self.variable_set)):
473
+ self.lit_scores[var] = float(-self.occurrence_count[var])
474
+ self.lit_scores[-var] = float(-self.occurrence_count[-var])
475
+ heappush(self.lit_heap, (self.lit_scores[var], var))
476
+ heappush(self.lit_heap, (self.lit_scores[-var], -var))
477
+
478
+ def _vsids_decay(self):
479
+ """Decay the VSIDS scores for every literal.
480
+
481
+ Examples
482
+ ========
483
+
484
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
485
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
486
+ ... {3, -2}], {1, 2, 3}, set())
487
+
488
+ >>> l.lit_scores
489
+ {-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
490
+
491
+ >>> l._vsids_decay()
492
+
493
+ >>> l.lit_scores
494
+ {-3: -1.0, -2: -1.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -1.0}
495
+
496
+ """
497
+ # We divide every literal score by 2 for a decay factor
498
+ # Note: This doesn't change the heap property
499
+ for lit in self.lit_scores.keys():
500
+ self.lit_scores[lit] /= 2.0
501
+
502
+ def _vsids_calculate(self):
503
+ """
504
+ VSIDS Heuristic Calculation
505
+
506
+ Examples
507
+ ========
508
+
509
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
510
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
511
+ ... {3, -2}], {1, 2, 3}, set())
512
+
513
+ >>> l.lit_heap
514
+ [(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
515
+
516
+ >>> l._vsids_calculate()
517
+ -3
518
+
519
+ >>> l.lit_heap
520
+ [(-2.0, -2), (-2.0, 2), (0.0, -1), (0.0, 1), (-2.0, 3)]
521
+
522
+ """
523
+ if len(self.lit_heap) == 0:
524
+ return 0
525
+
526
+ # Clean out the front of the heap as long the variables are set
527
+ while self.variable_set[abs(self.lit_heap[0][1])]:
528
+ heappop(self.lit_heap)
529
+ if len(self.lit_heap) == 0:
530
+ return 0
531
+
532
+ return heappop(self.lit_heap)[1]
533
+
534
+ def _vsids_lit_assigned(self, lit):
535
+ """Handle the assignment of a literal for the VSIDS heuristic."""
536
+ pass
537
+
538
+ def _vsids_lit_unset(self, lit):
539
+ """Handle the unsetting of a literal for the VSIDS heuristic.
540
+
541
+ Examples
542
+ ========
543
+
544
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
545
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
546
+ ... {3, -2}], {1, 2, 3}, set())
547
+ >>> l.lit_heap
548
+ [(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
549
+
550
+ >>> l._vsids_lit_unset(2)
551
+
552
+ >>> l.lit_heap
553
+ [(-2.0, -3), (-2.0, -2), (-2.0, -2), (-2.0, 2), (-2.0, 3), (0.0, -1),
554
+ ...(-2.0, 2), (0.0, 1)]
555
+
556
+ """
557
+ var = abs(lit)
558
+ heappush(self.lit_heap, (self.lit_scores[var], var))
559
+ heappush(self.lit_heap, (self.lit_scores[-var], -var))
560
+
561
+ def _vsids_clause_added(self, cls):
562
+ """Handle the addition of a new clause for the VSIDS heuristic.
563
+
564
+ Examples
565
+ ========
566
+
567
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
568
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
569
+ ... {3, -2}], {1, 2, 3}, set())
570
+
571
+ >>> l.num_learned_clauses
572
+ 0
573
+ >>> l.lit_scores
574
+ {-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
575
+
576
+ >>> l._vsids_clause_added({2, -3})
577
+
578
+ >>> l.num_learned_clauses
579
+ 1
580
+ >>> l.lit_scores
581
+ {-3: -1.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -2.0}
582
+
583
+ """
584
+ self.num_learned_clauses += 1
585
+ for lit in cls:
586
+ self.lit_scores[lit] += 1
587
+
588
+ ########################
589
+ # Clause Learning #
590
+ ########################
591
+ def _simple_add_learned_clause(self, cls):
592
+ """Add a new clause to the theory.
593
+
594
+ Examples
595
+ ========
596
+
597
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
598
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
599
+ ... {3, -2}], {1, 2, 3}, set())
600
+
601
+ >>> l.num_learned_clauses
602
+ 0
603
+ >>> l.clauses
604
+ [[2, -3], [1], [3, -3], [2, -2], [3, -2]]
605
+ >>> l.sentinels
606
+ {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
607
+
608
+ >>> l._simple_add_learned_clause([3])
609
+
610
+ >>> l.clauses
611
+ [[2, -3], [1], [3, -3], [2, -2], [3, -2], [3]]
612
+ >>> l.sentinels
613
+ {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4, 5}}
614
+
615
+ """
616
+ cls_num = len(self.clauses)
617
+ self.clauses.append(cls)
618
+
619
+ for lit in cls:
620
+ self.occurrence_count[lit] += 1
621
+
622
+ self.sentinels[cls[0]].add(cls_num)
623
+ self.sentinels[cls[-1]].add(cls_num)
624
+
625
+ self.heur_clause_added(cls)
626
+
627
+ def _simple_compute_conflict(self):
628
+ """ Build a clause representing the fact that at least one decision made
629
+ so far is wrong.
630
+
631
+ Examples
632
+ ========
633
+
634
+ >>> from sympy.logic.algorithms.dpll2 import SATSolver
635
+ >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
636
+ ... {3, -2}], {1, 2, 3}, set())
637
+ >>> next(l._find_model())
638
+ {1: True, 2: False, 3: False}
639
+ >>> l._simple_compute_conflict()
640
+ [3]
641
+
642
+ """
643
+ return [-(level.decision) for level in self.levels[1:]]
644
+
645
+ def _simple_clean_clauses(self):
646
+ """Clean up learned clauses."""
647
+ pass
648
+
649
+
650
+ class Level:
651
+ """
652
+ Represents a single level in the DPLL algorithm, and contains
653
+ enough information for a sound backtracking procedure.
654
+ """
655
+
656
+ def __init__(self, decision, flipped=False):
657
+ self.decision = decision
658
+ self.var_settings = set()
659
+ self.flipped = flipped
venv/lib/python3.10/site-packages/sympy/logic/algorithms/minisat22_wrapper.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.cnf import EncodedCNF
2
+
3
+ def minisat22_satisfiable(expr, all_models=False, minimal=False):
4
+
5
+ if not isinstance(expr, EncodedCNF):
6
+ exprs = EncodedCNF()
7
+ exprs.add_prop(expr)
8
+ expr = exprs
9
+
10
+ from pysat.solvers import Minisat22
11
+
12
+ # Return UNSAT when False (encoded as 0) is present in the CNF
13
+ if {0} in expr.data:
14
+ if all_models:
15
+ return (f for f in [False])
16
+ return False
17
+
18
+ r = Minisat22(expr.data)
19
+
20
+ if minimal:
21
+ r.set_phases([-(i+1) for i in range(r.nof_vars())])
22
+
23
+ if not r.solve():
24
+ return False
25
+
26
+ if not all_models:
27
+ return {expr.symbols[abs(lit) - 1]: lit > 0 for lit in r.get_model()}
28
+
29
+ else:
30
+ # Make solutions SymPy compatible by creating a generator
31
+ def _gen(results):
32
+ satisfiable = False
33
+ while results.solve():
34
+ sol = results.get_model()
35
+ yield {expr.symbols[abs(lit) - 1]: lit > 0 for lit in sol}
36
+ if minimal:
37
+ results.add_clause([-i for i in sol if i>0])
38
+ else:
39
+ results.add_clause([-i for i in sol])
40
+ satisfiable = True
41
+ if not satisfiable:
42
+ yield False
43
+ raise StopIteration
44
+
45
+
46
+ return _gen(r)
venv/lib/python3.10/site-packages/sympy/logic/algorithms/pycosat_wrapper.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.cnf import EncodedCNF
2
+
3
+
4
+ def pycosat_satisfiable(expr, all_models=False):
5
+ import pycosat
6
+ if not isinstance(expr, EncodedCNF):
7
+ exprs = EncodedCNF()
8
+ exprs.add_prop(expr)
9
+ expr = exprs
10
+
11
+ # Return UNSAT when False (encoded as 0) is present in the CNF
12
+ if {0} in expr.data:
13
+ if all_models:
14
+ return (f for f in [False])
15
+ return False
16
+
17
+ if not all_models:
18
+ r = pycosat.solve(expr.data)
19
+ result = (r != "UNSAT")
20
+ if not result:
21
+ return result
22
+ return {expr.symbols[abs(lit) - 1]: lit > 0 for lit in r}
23
+ else:
24
+ r = pycosat.itersolve(expr.data)
25
+ result = (r != "UNSAT")
26
+ if not result:
27
+ return result
28
+
29
+ # Make solutions SymPy compatible by creating a generator
30
+ def _gen(results):
31
+ satisfiable = False
32
+ try:
33
+ while True:
34
+ sol = next(results)
35
+ yield {expr.symbols[abs(lit) - 1]: lit > 0 for lit in sol}
36
+ satisfiable = True
37
+ except StopIteration:
38
+ if not satisfiable:
39
+ yield False
40
+
41
+ return _gen(r)
venv/lib/python3.10/site-packages/sympy/logic/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/test_boolalg.cpython-310.pyc ADDED
Binary file (48.8 kB). View file
 
venv/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/test_dimacs.cpython-310.pyc ADDED
Binary file (4.42 kB). View file
 
venv/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/test_inference.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/logic/tests/test_boolalg.py ADDED
@@ -0,0 +1,1340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.ask import Q
2
+ from sympy.assumptions.refine import refine
3
+ from sympy.core.numbers import oo
4
+ from sympy.core.relational import Equality, Eq, Ne
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import (Dummy, symbols)
7
+ from sympy.functions import Piecewise
8
+ from sympy.functions.elementary.trigonometric import cos, sin
9
+ from sympy.sets.sets import (Interval, Union)
10
+ from sympy.simplify.simplify import simplify
11
+ from sympy.logic.boolalg import (
12
+ And, Boolean, Equivalent, ITE, Implies, Nand, Nor, Not, Or,
13
+ POSform, SOPform, Xor, Xnor, conjuncts, disjuncts,
14
+ distribute_or_over_and, distribute_and_over_or,
15
+ eliminate_implications, is_nnf, is_cnf, is_dnf, simplify_logic,
16
+ to_nnf, to_cnf, to_dnf, to_int_repr, bool_map, true, false,
17
+ BooleanAtom, is_literal, term_to_integer,
18
+ truth_table, as_Boolean, to_anf, is_anf, distribute_xor_over_and,
19
+ anf_coeffs, ANFform, bool_minterm, bool_maxterm, bool_monomial,
20
+ _check_pair, _convert_to_varsSOP, _convert_to_varsPOS, Exclusive,
21
+ gateinputcount)
22
+ from sympy.assumptions.cnf import CNF
23
+
24
+ from sympy.testing.pytest import raises, XFAIL, slow
25
+
26
+ from itertools import combinations, permutations, product
27
+
28
+ A, B, C, D = symbols('A:D')
29
+ a, b, c, d, e, w, x, y, z = symbols('a:e w:z')
30
+
31
+
32
+ def test_overloading():
33
+ """Test that |, & are overloaded as expected"""
34
+
35
+ assert A & B == And(A, B)
36
+ assert A | B == Or(A, B)
37
+ assert (A & B) | C == Or(And(A, B), C)
38
+ assert A >> B == Implies(A, B)
39
+ assert A << B == Implies(B, A)
40
+ assert ~A == Not(A)
41
+ assert A ^ B == Xor(A, B)
42
+
43
+
44
+ def test_And():
45
+ assert And() is true
46
+ assert And(A) == A
47
+ assert And(True) is true
48
+ assert And(False) is false
49
+ assert And(True, True) is true
50
+ assert And(True, False) is false
51
+ assert And(False, False) is false
52
+ assert And(True, A) == A
53
+ assert And(False, A) is false
54
+ assert And(True, True, True) is true
55
+ assert And(True, True, A) == A
56
+ assert And(True, False, A) is false
57
+ assert And(1, A) == A
58
+ raises(TypeError, lambda: And(2, A))
59
+ raises(TypeError, lambda: And(A < 2, A))
60
+ assert And(A < 1, A >= 1) is false
61
+ e = A > 1
62
+ assert And(e, e.canonical) == e.canonical
63
+ g, l, ge, le = A > B, B < A, A >= B, B <= A
64
+ assert And(g, l, ge, le) == And(ge, g)
65
+ assert {And(*i) for i in permutations((l,g,le,ge))} == {And(ge, g)}
66
+ assert And(And(Eq(a, 0), Eq(b, 0)), And(Ne(a, 0), Eq(c, 0))) is false
67
+
68
+
69
+ def test_Or():
70
+ assert Or() is false
71
+ assert Or(A) == A
72
+ assert Or(True) is true
73
+ assert Or(False) is false
74
+ assert Or(True, True) is true
75
+ assert Or(True, False) is true
76
+ assert Or(False, False) is false
77
+ assert Or(True, A) is true
78
+ assert Or(False, A) == A
79
+ assert Or(True, False, False) is true
80
+ assert Or(True, False, A) is true
81
+ assert Or(False, False, A) == A
82
+ assert Or(1, A) is true
83
+ raises(TypeError, lambda: Or(2, A))
84
+ raises(TypeError, lambda: Or(A < 2, A))
85
+ assert Or(A < 1, A >= 1) is true
86
+ e = A > 1
87
+ assert Or(e, e.canonical) == e
88
+ g, l, ge, le = A > B, B < A, A >= B, B <= A
89
+ assert Or(g, l, ge, le) == Or(g, ge)
90
+
91
+
92
+ def test_Xor():
93
+ assert Xor() is false
94
+ assert Xor(A) == A
95
+ assert Xor(A, A) is false
96
+ assert Xor(True, A, A) is true
97
+ assert Xor(A, A, A, A, A) == A
98
+ assert Xor(True, False, False, A, B) == ~Xor(A, B)
99
+ assert Xor(True) is true
100
+ assert Xor(False) is false
101
+ assert Xor(True, True) is false
102
+ assert Xor(True, False) is true
103
+ assert Xor(False, False) is false
104
+ assert Xor(True, A) == ~A
105
+ assert Xor(False, A) == A
106
+ assert Xor(True, False, False) is true
107
+ assert Xor(True, False, A) == ~A
108
+ assert Xor(False, False, A) == A
109
+ assert isinstance(Xor(A, B), Xor)
110
+ assert Xor(A, B, Xor(C, D)) == Xor(A, B, C, D)
111
+ assert Xor(A, B, Xor(B, C)) == Xor(A, C)
112
+ assert Xor(A < 1, A >= 1, B) == Xor(0, 1, B) == Xor(1, 0, B)
113
+ e = A > 1
114
+ assert Xor(e, e.canonical) == Xor(0, 0) == Xor(1, 1)
115
+
116
+
117
+ def test_rewrite_as_And():
118
+ expr = x ^ y
119
+ assert expr.rewrite(And) == (x | y) & (~x | ~y)
120
+
121
+
122
+ def test_rewrite_as_Or():
123
+ expr = x ^ y
124
+ assert expr.rewrite(Or) == (x & ~y) | (y & ~x)
125
+
126
+
127
+ def test_rewrite_as_Nand():
128
+ expr = (y & z) | (z & ~w)
129
+ assert expr.rewrite(Nand) == ~(~(y & z) & ~(z & ~w))
130
+
131
+
132
+ def test_rewrite_as_Nor():
133
+ expr = z & (y | ~w)
134
+ assert expr.rewrite(Nor) == ~(~z | ~(y | ~w))
135
+
136
+
137
+ def test_Not():
138
+ raises(TypeError, lambda: Not(True, False))
139
+ assert Not(True) is false
140
+ assert Not(False) is true
141
+ assert Not(0) is true
142
+ assert Not(1) is false
143
+ assert Not(2) is false
144
+
145
+
146
+ def test_Nand():
147
+ assert Nand() is false
148
+ assert Nand(A) == ~A
149
+ assert Nand(True) is false
150
+ assert Nand(False) is true
151
+ assert Nand(True, True) is false
152
+ assert Nand(True, False) is true
153
+ assert Nand(False, False) is true
154
+ assert Nand(True, A) == ~A
155
+ assert Nand(False, A) is true
156
+ assert Nand(True, True, True) is false
157
+ assert Nand(True, True, A) == ~A
158
+ assert Nand(True, False, A) is true
159
+
160
+
161
+ def test_Nor():
162
+ assert Nor() is true
163
+ assert Nor(A) == ~A
164
+ assert Nor(True) is false
165
+ assert Nor(False) is true
166
+ assert Nor(True, True) is false
167
+ assert Nor(True, False) is false
168
+ assert Nor(False, False) is true
169
+ assert Nor(True, A) is false
170
+ assert Nor(False, A) == ~A
171
+ assert Nor(True, True, True) is false
172
+ assert Nor(True, True, A) is false
173
+ assert Nor(True, False, A) is false
174
+
175
+
176
+ def test_Xnor():
177
+ assert Xnor() is true
178
+ assert Xnor(A) == ~A
179
+ assert Xnor(A, A) is true
180
+ assert Xnor(True, A, A) is false
181
+ assert Xnor(A, A, A, A, A) == ~A
182
+ assert Xnor(True) is false
183
+ assert Xnor(False) is true
184
+ assert Xnor(True, True) is true
185
+ assert Xnor(True, False) is false
186
+ assert Xnor(False, False) is true
187
+ assert Xnor(True, A) == A
188
+ assert Xnor(False, A) == ~A
189
+ assert Xnor(True, False, False) is false
190
+ assert Xnor(True, False, A) == A
191
+ assert Xnor(False, False, A) == ~A
192
+
193
+
194
+ def test_Implies():
195
+ raises(ValueError, lambda: Implies(A, B, C))
196
+ assert Implies(True, True) is true
197
+ assert Implies(True, False) is false
198
+ assert Implies(False, True) is true
199
+ assert Implies(False, False) is true
200
+ assert Implies(0, A) is true
201
+ assert Implies(1, 1) is true
202
+ assert Implies(1, 0) is false
203
+ assert A >> B == B << A
204
+ assert (A < 1) >> (A >= 1) == (A >= 1)
205
+ assert (A < 1) >> (S.One > A) is true
206
+ assert A >> A is true
207
+
208
+
209
+ def test_Equivalent():
210
+ assert Equivalent(A, B) == Equivalent(B, A) == Equivalent(A, B, A)
211
+ assert Equivalent() is true
212
+ assert Equivalent(A, A) == Equivalent(A) is true
213
+ assert Equivalent(True, True) == Equivalent(False, False) is true
214
+ assert Equivalent(True, False) == Equivalent(False, True) is false
215
+ assert Equivalent(A, True) == A
216
+ assert Equivalent(A, False) == Not(A)
217
+ assert Equivalent(A, B, True) == A & B
218
+ assert Equivalent(A, B, False) == ~A & ~B
219
+ assert Equivalent(1, A) == A
220
+ assert Equivalent(0, A) == Not(A)
221
+ assert Equivalent(A, Equivalent(B, C)) != Equivalent(Equivalent(A, B), C)
222
+ assert Equivalent(A < 1, A >= 1) is false
223
+ assert Equivalent(A < 1, A >= 1, 0) is false
224
+ assert Equivalent(A < 1, A >= 1, 1) is false
225
+ assert Equivalent(A < 1, S.One > A) == Equivalent(1, 1) == Equivalent(0, 0)
226
+ assert Equivalent(Equality(A, B), Equality(B, A)) is true
227
+
228
+
229
+ def test_Exclusive():
230
+ assert Exclusive(False, False, False) is true
231
+ assert Exclusive(True, False, False) is true
232
+ assert Exclusive(True, True, False) is false
233
+ assert Exclusive(True, True, True) is false
234
+
235
+
236
+ def test_equals():
237
+ assert Not(Or(A, B)).equals(And(Not(A), Not(B))) is True
238
+ assert Equivalent(A, B).equals((A >> B) & (B >> A)) is True
239
+ assert ((A | ~B) & (~A | B)).equals((~A & ~B) | (A & B)) is True
240
+ assert (A >> B).equals(~A >> ~B) is False
241
+ assert (A >> (B >> A)).equals(A >> (C >> A)) is False
242
+ raises(NotImplementedError, lambda: (A & B).equals(A > B))
243
+
244
+
245
+ def test_simplification_boolalg():
246
+ """
247
+ Test working of simplification methods.
248
+ """
249
+ set1 = [[0, 0, 1], [0, 1, 1], [1, 0, 0], [1, 1, 0]]
250
+ set2 = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1]]
251
+ assert SOPform([x, y, z], set1) == Or(And(Not(x), z), And(Not(z), x))
252
+ assert Not(SOPform([x, y, z], set2)) == \
253
+ Not(Or(And(Not(x), Not(z)), And(x, z)))
254
+ assert POSform([x, y, z], set1 + set2) is true
255
+ assert SOPform([x, y, z], set1 + set2) is true
256
+ assert SOPform([Dummy(), Dummy(), Dummy()], set1 + set2) is true
257
+
258
+ minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
259
+ [1, 1, 1, 1]]
260
+ dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
261
+ assert (
262
+ SOPform([w, x, y, z], minterms, dontcares) ==
263
+ Or(And(y, z), And(Not(w), Not(x))))
264
+ assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
265
+
266
+ minterms = [1, 3, 7, 11, 15]
267
+ dontcares = [0, 2, 5]
268
+ assert (
269
+ SOPform([w, x, y, z], minterms, dontcares) ==
270
+ Or(And(y, z), And(Not(w), Not(x))))
271
+ assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
272
+
273
+ minterms = [1, [0, 0, 1, 1], 7, [1, 0, 1, 1],
274
+ [1, 1, 1, 1]]
275
+ dontcares = [0, [0, 0, 1, 0], 5]
276
+ assert (
277
+ SOPform([w, x, y, z], minterms, dontcares) ==
278
+ Or(And(y, z), And(Not(w), Not(x))))
279
+ assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
280
+
281
+ minterms = [1, {y: 1, z: 1}]
282
+ dontcares = [0, [0, 0, 1, 0], 5]
283
+ assert (
284
+ SOPform([w, x, y, z], minterms, dontcares) ==
285
+ Or(And(y, z), And(Not(w), Not(x))))
286
+ assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
287
+
288
+
289
+ minterms = [{y: 1, z: 1}, 1]
290
+ dontcares = [[0, 0, 0, 0]]
291
+
292
+ minterms = [[0, 0, 0]]
293
+ raises(ValueError, lambda: SOPform([w, x, y, z], minterms))
294
+ raises(ValueError, lambda: POSform([w, x, y, z], minterms))
295
+
296
+ raises(TypeError, lambda: POSform([w, x, y, z], ["abcdefg"]))
297
+
298
+ # test simplification
299
+ ans = And(A, Or(B, C))
300
+ assert simplify_logic(A & (B | C)) == ans
301
+ assert simplify_logic((A & B) | (A & C)) == ans
302
+ assert simplify_logic(Implies(A, B)) == Or(Not(A), B)
303
+ assert simplify_logic(Equivalent(A, B)) == \
304
+ Or(And(A, B), And(Not(A), Not(B)))
305
+ assert simplify_logic(And(Equality(A, 2), C)) == And(Equality(A, 2), C)
306
+ assert simplify_logic(And(Equality(A, 2), A)) is S.false
307
+ assert simplify_logic(And(Equality(A, 2), A)) == And(Equality(A, 2), A)
308
+ assert simplify_logic(And(Equality(A, B), C)) == And(Equality(A, B), C)
309
+ assert simplify_logic(Or(And(Equality(A, 3), B), And(Equality(A, 3), C))) \
310
+ == And(Equality(A, 3), Or(B, C))
311
+ b = (~x & ~y & ~z) | (~x & ~y & z)
312
+ e = And(A, b)
313
+ assert simplify_logic(e) == A & ~x & ~y
314
+ raises(ValueError, lambda: simplify_logic(A & (B | C), form='blabla'))
315
+ assert simplify(Or(x <= y, And(x < y, z))) == (x <= y)
316
+ assert simplify(Or(x <= y, And(y > x, z))) == (x <= y)
317
+ assert simplify(Or(x >= y, And(y < x, z))) == (x >= y)
318
+
319
+ # Check that expressions with nine variables or more are not simplified
320
+ # (without the force-flag)
321
+ a, b, c, d, e, f, g, h, j = symbols('a b c d e f g h j')
322
+ expr = a & b & c & d & e & f & g & h & j | \
323
+ a & b & c & d & e & f & g & h & ~j
324
+ # This expression can be simplified to get rid of the j variables
325
+ assert simplify_logic(expr) == expr
326
+
327
+ # Test dontcare
328
+ assert simplify_logic((a & b) | c | d, dontcare=(a & b)) == c | d
329
+
330
+ # check input
331
+ ans = SOPform([x, y], [[1, 0]])
332
+ assert SOPform([x, y], [[1, 0]]) == ans
333
+ assert POSform([x, y], [[1, 0]]) == ans
334
+
335
+ raises(ValueError, lambda: SOPform([x], [[1]], [[1]]))
336
+ assert SOPform([x], [[1]], [[0]]) is true
337
+ assert SOPform([x], [[0]], [[1]]) is true
338
+ assert SOPform([x], [], []) is false
339
+
340
+ raises(ValueError, lambda: POSform([x], [[1]], [[1]]))
341
+ assert POSform([x], [[1]], [[0]]) is true
342
+ assert POSform([x], [[0]], [[1]]) is true
343
+ assert POSform([x], [], []) is false
344
+
345
+ # check working of simplify
346
+ assert simplify((A & B) | (A & C)) == And(A, Or(B, C))
347
+ assert simplify(And(x, Not(x))) == False
348
+ assert simplify(Or(x, Not(x))) == True
349
+ assert simplify(And(Eq(x, 0), Eq(x, y))) == And(Eq(x, 0), Eq(y, 0))
350
+ assert And(Eq(x - 1, 0), Eq(x, y)).simplify() == And(Eq(x, 1), Eq(y, 1))
351
+ assert And(Ne(x - 1, 0), Ne(x, y)).simplify() == And(Ne(x, 1), Ne(x, y))
352
+ assert And(Eq(x - 1, 0), Ne(x, y)).simplify() == And(Eq(x, 1), Ne(y, 1))
353
+ assert And(Eq(x - 1, 0), Eq(x, z + y), Eq(y + x, 0)).simplify(
354
+ ) == And(Eq(x, 1), Eq(y, -1), Eq(z, 2))
355
+ assert And(Eq(x - 1, 0), Eq(x + 2, 3)).simplify() == Eq(x, 1)
356
+ assert And(Ne(x - 1, 0), Ne(x + 2, 3)).simplify() == Ne(x, 1)
357
+ assert And(Eq(x - 1, 0), Eq(x + 2, 2)).simplify() == False
358
+ assert And(Ne(x - 1, 0), Ne(x + 2, 2)).simplify(
359
+ ) == And(Ne(x, 1), Ne(x, 0))
360
+
361
+
362
+ def test_bool_map():
363
+ """
364
+ Test working of bool_map function.
365
+ """
366
+
367
+ minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
368
+ [1, 1, 1, 1]]
369
+ assert bool_map(Not(Not(a)), a) == (a, {a: a})
370
+ assert bool_map(SOPform([w, x, y, z], minterms),
371
+ POSform([w, x, y, z], minterms)) == \
372
+ (And(Or(Not(w), y), Or(Not(x), y), z), {x: x, w: w, z: z, y: y})
373
+ assert bool_map(SOPform([x, z, y], [[1, 0, 1]]),
374
+ SOPform([a, b, c], [[1, 0, 1]])) != False
375
+ function1 = SOPform([x, z, y], [[1, 0, 1], [0, 0, 1]])
376
+ function2 = SOPform([a, b, c], [[1, 0, 1], [1, 0, 0]])
377
+ assert bool_map(function1, function2) == \
378
+ (function1, {y: a, z: b})
379
+ assert bool_map(Xor(x, y), ~Xor(x, y)) == False
380
+ assert bool_map(And(x, y), Or(x, y)) is None
381
+ assert bool_map(And(x, y), And(x, y, z)) is None
382
+ # issue 16179
383
+ assert bool_map(Xor(x, y, z), ~Xor(x, y, z)) == False
384
+ assert bool_map(Xor(a, x, y, z), ~Xor(a, x, y, z)) == False
385
+
386
+
387
+ def test_bool_symbol():
388
+ """Test that mixing symbols with boolean values
389
+ works as expected"""
390
+
391
+ assert And(A, True) == A
392
+ assert And(A, True, True) == A
393
+ assert And(A, False) is false
394
+ assert And(A, True, False) is false
395
+ assert Or(A, True) is true
396
+ assert Or(A, False) == A
397
+
398
+
399
+ def test_is_boolean():
400
+ assert isinstance(True, Boolean) is False
401
+ assert isinstance(true, Boolean) is True
402
+ assert 1 == True
403
+ assert 1 != true
404
+ assert (1 == true) is False
405
+ assert 0 == False
406
+ assert 0 != false
407
+ assert (0 == false) is False
408
+ assert true.is_Boolean is True
409
+ assert (A & B).is_Boolean
410
+ assert (A | B).is_Boolean
411
+ assert (~A).is_Boolean
412
+ assert (A ^ B).is_Boolean
413
+ assert A.is_Boolean != isinstance(A, Boolean)
414
+ assert isinstance(A, Boolean)
415
+
416
+
417
+ def test_subs():
418
+ assert (A & B).subs(A, True) == B
419
+ assert (A & B).subs(A, False) is false
420
+ assert (A & B).subs(B, True) == A
421
+ assert (A & B).subs(B, False) is false
422
+ assert (A & B).subs({A: True, B: True}) is true
423
+ assert (A | B).subs(A, True) is true
424
+ assert (A | B).subs(A, False) == B
425
+ assert (A | B).subs(B, True) is true
426
+ assert (A | B).subs(B, False) == A
427
+ assert (A | B).subs({A: True, B: True}) is true
428
+
429
+
430
+ """
431
+ we test for axioms of boolean algebra
432
+ see https://en.wikipedia.org/wiki/Boolean_algebra_(structure)
433
+ """
434
+
435
+
436
+ def test_commutative():
437
+ """Test for commutativity of And and Or"""
438
+ A, B = map(Boolean, symbols('A,B'))
439
+
440
+ assert A & B == B & A
441
+ assert A | B == B | A
442
+
443
+
444
+ def test_and_associativity():
445
+ """Test for associativity of And"""
446
+
447
+ assert (A & B) & C == A & (B & C)
448
+
449
+
450
+ def test_or_assicativity():
451
+ assert ((A | B) | C) == (A | (B | C))
452
+
453
+
454
+ def test_double_negation():
455
+ a = Boolean()
456
+ assert ~(~a) == a
457
+
458
+
459
+ # test methods
460
+
461
+ def test_eliminate_implications():
462
+ assert eliminate_implications(Implies(A, B, evaluate=False)) == (~A) | B
463
+ assert eliminate_implications(
464
+ A >> (C >> Not(B))) == Or(Or(Not(B), Not(C)), Not(A))
465
+ assert eliminate_implications(Equivalent(A, B, C, D)) == \
466
+ (~A | B) & (~B | C) & (~C | D) & (~D | A)
467
+
468
+
469
+ def test_conjuncts():
470
+ assert conjuncts(A & B & C) == {A, B, C}
471
+ assert conjuncts((A | B) & C) == {A | B, C}
472
+ assert conjuncts(A) == {A}
473
+ assert conjuncts(True) == {True}
474
+ assert conjuncts(False) == {False}
475
+
476
+
477
+ def test_disjuncts():
478
+ assert disjuncts(A | B | C) == {A, B, C}
479
+ assert disjuncts((A | B) & C) == {(A | B) & C}
480
+ assert disjuncts(A) == {A}
481
+ assert disjuncts(True) == {True}
482
+ assert disjuncts(False) == {False}
483
+
484
+
485
+ def test_distribute():
486
+ assert distribute_and_over_or(Or(And(A, B), C)) == And(Or(A, C), Or(B, C))
487
+ assert distribute_or_over_and(And(A, Or(B, C))) == Or(And(A, B), And(A, C))
488
+ assert distribute_xor_over_and(And(A, Xor(B, C))) == Xor(And(A, B), And(A, C))
489
+
490
+
491
+ def test_to_anf():
492
+ x, y, z = symbols('x,y,z')
493
+ assert to_anf(And(x, y)) == And(x, y)
494
+ assert to_anf(Or(x, y)) == Xor(x, y, And(x, y))
495
+ assert to_anf(Or(Implies(x, y), And(x, y), y)) == \
496
+ Xor(x, True, x & y, remove_true=False)
497
+ assert to_anf(Or(Nand(x, y), Nor(x, y), Xnor(x, y), Implies(x, y))) == True
498
+ assert to_anf(Or(x, Not(y), Nor(x,z), And(x, y), Nand(y, z))) == \
499
+ Xor(True, And(y, z), And(x, y, z), remove_true=False)
500
+ assert to_anf(Xor(x, y)) == Xor(x, y)
501
+ assert to_anf(Not(x)) == Xor(x, True, remove_true=False)
502
+ assert to_anf(Nand(x, y)) == Xor(True, And(x, y), remove_true=False)
503
+ assert to_anf(Nor(x, y)) == Xor(x, y, True, And(x, y), remove_true=False)
504
+ assert to_anf(Implies(x, y)) == Xor(x, True, And(x, y), remove_true=False)
505
+ assert to_anf(Equivalent(x, y)) == Xor(x, y, True, remove_true=False)
506
+ assert to_anf(Nand(x | y, x >> y), deep=False) == \
507
+ Xor(True, And(Or(x, y), Implies(x, y)), remove_true=False)
508
+ assert to_anf(Nor(x ^ y, x & y), deep=False) == \
509
+ Xor(True, Or(Xor(x, y), And(x, y)), remove_true=False)
510
+
511
+
512
+ def test_to_nnf():
513
+ assert to_nnf(true) is true
514
+ assert to_nnf(false) is false
515
+ assert to_nnf(A) == A
516
+ assert to_nnf(A | ~A | B) is true
517
+ assert to_nnf(A & ~A & B) is false
518
+ assert to_nnf(A >> B) == ~A | B
519
+ assert to_nnf(Equivalent(A, B, C)) == (~A | B) & (~B | C) & (~C | A)
520
+ assert to_nnf(A ^ B ^ C) == \
521
+ (A | B | C) & (~A | ~B | C) & (A | ~B | ~C) & (~A | B | ~C)
522
+ assert to_nnf(ITE(A, B, C)) == (~A | B) & (A | C)
523
+ assert to_nnf(Not(A | B | C)) == ~A & ~B & ~C
524
+ assert to_nnf(Not(A & B & C)) == ~A | ~B | ~C
525
+ assert to_nnf(Not(A >> B)) == A & ~B
526
+ assert to_nnf(Not(Equivalent(A, B, C))) == And(Or(A, B, C), Or(~A, ~B, ~C))
527
+ assert to_nnf(Not(A ^ B ^ C)) == \
528
+ (~A | B | C) & (A | ~B | C) & (A | B | ~C) & (~A | ~B | ~C)
529
+ assert to_nnf(Not(ITE(A, B, C))) == (~A | ~B) & (A | ~C)
530
+ assert to_nnf((A >> B) ^ (B >> A)) == (A & ~B) | (~A & B)
531
+ assert to_nnf((A >> B) ^ (B >> A), False) == \
532
+ (~A | ~B | A | B) & ((A & ~B) | (~A & B))
533
+ assert ITE(A, 1, 0).to_nnf() == A
534
+ assert ITE(A, 0, 1).to_nnf() == ~A
535
+ # although ITE can hold non-Boolean, it will complain if
536
+ # an attempt is made to convert the ITE to Boolean nnf
537
+ raises(TypeError, lambda: ITE(A < 1, [1], B).to_nnf())
538
+
539
+
540
+ def test_to_cnf():
541
+ assert to_cnf(~(B | C)) == And(Not(B), Not(C))
542
+ assert to_cnf((A & B) | C) == And(Or(A, C), Or(B, C))
543
+ assert to_cnf(A >> B) == (~A) | B
544
+ assert to_cnf(A >> (B & C)) == (~A | B) & (~A | C)
545
+ assert to_cnf(A & (B | C) | ~A & (B | C), True) == B | C
546
+ assert to_cnf(A & B) == And(A, B)
547
+
548
+ assert to_cnf(Equivalent(A, B)) == And(Or(A, Not(B)), Or(B, Not(A)))
549
+ assert to_cnf(Equivalent(A, B & C)) == \
550
+ (~A | B) & (~A | C) & (~B | ~C | A)
551
+ assert to_cnf(Equivalent(A, B | C), True) == \
552
+ And(Or(Not(B), A), Or(Not(C), A), Or(B, C, Not(A)))
553
+ assert to_cnf(A + 1) == A + 1
554
+
555
+
556
+ def test_issue_18904():
557
+ x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 = symbols('x1:16')
558
+ eq = (( x1 & x2 & x3 & x4 & x5 & x6 & x7 & x8 & x9 ) |
559
+ ( x1 & x2 & x3 & x4 & x5 & x6 & x7 & x10 & x9 ) |
560
+ ( x1 & x11 & x3 & x12 & x5 & x13 & x14 & x15 & x9 ))
561
+ assert is_cnf(to_cnf(eq))
562
+ raises(ValueError, lambda: to_cnf(eq, simplify=True))
563
+ for f, t in zip((And, Or), (to_cnf, to_dnf)):
564
+ eq = f(x1, x2, x3, x4, x5, x6, x7, x8, x9)
565
+ raises(ValueError, lambda: to_cnf(eq, simplify=True))
566
+ assert t(eq, simplify=True, force=True) == eq
567
+
568
+
569
+ def test_issue_9949():
570
+ assert is_cnf(to_cnf((b > -5) | (a > 2) & (a < 4)))
571
+
572
+
573
+ def test_to_CNF():
574
+ assert CNF.CNF_to_cnf(CNF.to_CNF(~(B | C))) == to_cnf(~(B | C))
575
+ assert CNF.CNF_to_cnf(CNF.to_CNF((A & B) | C)) == to_cnf((A & B) | C)
576
+ assert CNF.CNF_to_cnf(CNF.to_CNF(A >> B)) == to_cnf(A >> B)
577
+ assert CNF.CNF_to_cnf(CNF.to_CNF(A >> (B & C))) == to_cnf(A >> (B & C))
578
+ assert CNF.CNF_to_cnf(CNF.to_CNF(A & (B | C) | ~A & (B | C))) == to_cnf(A & (B | C) | ~A & (B | C))
579
+ assert CNF.CNF_to_cnf(CNF.to_CNF(A & B)) == to_cnf(A & B)
580
+
581
+
582
+ def test_to_dnf():
583
+ assert to_dnf(~(B | C)) == And(Not(B), Not(C))
584
+ assert to_dnf(A & (B | C)) == Or(And(A, B), And(A, C))
585
+ assert to_dnf(A >> B) == (~A) | B
586
+ assert to_dnf(A >> (B & C)) == (~A) | (B & C)
587
+ assert to_dnf(A | B) == A | B
588
+
589
+ assert to_dnf(Equivalent(A, B), True) == \
590
+ Or(And(A, B), And(Not(A), Not(B)))
591
+ assert to_dnf(Equivalent(A, B & C), True) == \
592
+ Or(And(A, B, C), And(Not(A), Not(B)), And(Not(A), Not(C)))
593
+ assert to_dnf(A + 1) == A + 1
594
+
595
+
596
+ def test_to_int_repr():
597
+ x, y, z = map(Boolean, symbols('x,y,z'))
598
+
599
+ def sorted_recursive(arg):
600
+ try:
601
+ return sorted(sorted_recursive(x) for x in arg)
602
+ except TypeError: # arg is not a sequence
603
+ return arg
604
+
605
+ assert sorted_recursive(to_int_repr([x | y, z | x], [x, y, z])) == \
606
+ sorted_recursive([[1, 2], [1, 3]])
607
+ assert sorted_recursive(to_int_repr([x | y, z | ~x], [x, y, z])) == \
608
+ sorted_recursive([[1, 2], [3, -1]])
609
+
610
+
611
+ def test_is_anf():
612
+ x, y = symbols('x,y')
613
+ assert is_anf(true) is True
614
+ assert is_anf(false) is True
615
+ assert is_anf(x) is True
616
+ assert is_anf(And(x, y)) is True
617
+ assert is_anf(Xor(x, y, And(x, y))) is True
618
+ assert is_anf(Xor(x, y, Or(x, y))) is False
619
+ assert is_anf(Xor(Not(x), y)) is False
620
+
621
+
622
+ def test_is_nnf():
623
+ assert is_nnf(true) is True
624
+ assert is_nnf(A) is True
625
+ assert is_nnf(~A) is True
626
+ assert is_nnf(A & B) is True
627
+ assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), False) is True
628
+ assert is_nnf((A | B) & (~A | ~B)) is True
629
+ assert is_nnf(Not(Or(A, B))) is False
630
+ assert is_nnf(A ^ B) is False
631
+ assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), True) is False
632
+
633
+
634
+ def test_is_cnf():
635
+ assert is_cnf(x) is True
636
+ assert is_cnf(x | y | z) is True
637
+ assert is_cnf(x & y & z) is True
638
+ assert is_cnf((x | y) & z) is True
639
+ assert is_cnf((x & y) | z) is False
640
+ assert is_cnf(~(x & y) | z) is False
641
+
642
+
643
+ def test_is_dnf():
644
+ assert is_dnf(x) is True
645
+ assert is_dnf(x | y | z) is True
646
+ assert is_dnf(x & y & z) is True
647
+ assert is_dnf((x & y) | z) is True
648
+ assert is_dnf((x | y) & z) is False
649
+ assert is_dnf(~(x | y) & z) is False
650
+
651
+
652
+ def test_ITE():
653
+ A, B, C = symbols('A:C')
654
+ assert ITE(True, False, True) is false
655
+ assert ITE(True, True, False) is true
656
+ assert ITE(False, True, False) is false
657
+ assert ITE(False, False, True) is true
658
+ assert isinstance(ITE(A, B, C), ITE)
659
+
660
+ A = True
661
+ assert ITE(A, B, C) == B
662
+ A = False
663
+ assert ITE(A, B, C) == C
664
+ B = True
665
+ assert ITE(And(A, B), B, C) == C
666
+ assert ITE(Or(A, False), And(B, True), False) is false
667
+ assert ITE(x, A, B) == Not(x)
668
+ assert ITE(x, B, A) == x
669
+ assert ITE(1, x, y) == x
670
+ assert ITE(0, x, y) == y
671
+ raises(TypeError, lambda: ITE(2, x, y))
672
+ raises(TypeError, lambda: ITE(1, [], y))
673
+ raises(TypeError, lambda: ITE(1, (), y))
674
+ raises(TypeError, lambda: ITE(1, y, []))
675
+ assert ITE(1, 1, 1) is S.true
676
+ assert isinstance(ITE(1, 1, 1, evaluate=False), ITE)
677
+
678
+ raises(TypeError, lambda: ITE(x > 1, y, x))
679
+ assert ITE(Eq(x, True), y, x) == ITE(x, y, x)
680
+ assert ITE(Eq(x, False), y, x) == ITE(~x, y, x)
681
+ assert ITE(Ne(x, True), y, x) == ITE(~x, y, x)
682
+ assert ITE(Ne(x, False), y, x) == ITE(x, y, x)
683
+ assert ITE(Eq(S. true, x), y, x) == ITE(x, y, x)
684
+ assert ITE(Eq(S.false, x), y, x) == ITE(~x, y, x)
685
+ assert ITE(Ne(S.true, x), y, x) == ITE(~x, y, x)
686
+ assert ITE(Ne(S.false, x), y, x) == ITE(x, y, x)
687
+ # 0 and 1 in the context are not treated as True/False
688
+ # so the equality must always be False since dissimilar
689
+ # objects cannot be equal
690
+ assert ITE(Eq(x, 0), y, x) == x
691
+ assert ITE(Eq(x, 1), y, x) == x
692
+ assert ITE(Ne(x, 0), y, x) == y
693
+ assert ITE(Ne(x, 1), y, x) == y
694
+ assert ITE(Eq(x, 0), y, z).subs(x, 0) == y
695
+ assert ITE(Eq(x, 0), y, z).subs(x, 1) == z
696
+ raises(ValueError, lambda: ITE(x > 1, y, x, z))
697
+
698
+
699
+ def test_is_literal():
700
+ assert is_literal(True) is True
701
+ assert is_literal(False) is True
702
+ assert is_literal(A) is True
703
+ assert is_literal(~A) is True
704
+ assert is_literal(Or(A, B)) is False
705
+ assert is_literal(Q.zero(A)) is True
706
+ assert is_literal(Not(Q.zero(A))) is True
707
+ assert is_literal(Or(A, B)) is False
708
+ assert is_literal(And(Q.zero(A), Q.zero(B))) is False
709
+ assert is_literal(x < 3)
710
+ assert not is_literal(x + y < 3)
711
+
712
+
713
+ def test_operators():
714
+ # Mostly test __and__, __rand__, and so on
715
+ assert True & A == A & True == A
716
+ assert False & A == A & False == False
717
+ assert A & B == And(A, B)
718
+ assert True | A == A | True == True
719
+ assert False | A == A | False == A
720
+ assert A | B == Or(A, B)
721
+ assert ~A == Not(A)
722
+ assert True >> A == A << True == A
723
+ assert False >> A == A << False == True
724
+ assert A >> True == True << A == True
725
+ assert A >> False == False << A == ~A
726
+ assert A >> B == B << A == Implies(A, B)
727
+ assert True ^ A == A ^ True == ~A
728
+ assert False ^ A == A ^ False == A
729
+ assert A ^ B == Xor(A, B)
730
+
731
+
732
+ def test_true_false():
733
+ assert true is S.true
734
+ assert false is S.false
735
+ assert true is not True
736
+ assert false is not False
737
+ assert true
738
+ assert not false
739
+ assert true == True
740
+ assert false == False
741
+ assert not (true == False)
742
+ assert not (false == True)
743
+ assert not (true == false)
744
+
745
+ assert hash(true) == hash(True)
746
+ assert hash(false) == hash(False)
747
+ assert len({true, True}) == len({false, False}) == 1
748
+
749
+ assert isinstance(true, BooleanAtom)
750
+ assert isinstance(false, BooleanAtom)
751
+ # We don't want to subclass from bool, because bool subclasses from
752
+ # int. But operators like &, |, ^, <<, >>, and ~ act differently on 0 and
753
+ # 1 then we want them to on true and false. See the docstrings of the
754
+ # various And, Or, etc. functions for examples.
755
+ assert not isinstance(true, bool)
756
+ assert not isinstance(false, bool)
757
+
758
+ # Note: using 'is' comparison is important here. We want these to return
759
+ # true and false, not True and False
760
+
761
+ assert Not(true) is false
762
+ assert Not(True) is false
763
+ assert Not(false) is true
764
+ assert Not(False) is true
765
+ assert ~true is false
766
+ assert ~false is true
767
+
768
+ for T, F in product((True, true), (False, false)):
769
+ assert And(T, F) is false
770
+ assert And(F, T) is false
771
+ assert And(F, F) is false
772
+ assert And(T, T) is true
773
+ assert And(T, x) == x
774
+ assert And(F, x) is false
775
+ if not (T is True and F is False):
776
+ assert T & F is false
777
+ assert F & T is false
778
+ if F is not False:
779
+ assert F & F is false
780
+ if T is not True:
781
+ assert T & T is true
782
+
783
+ assert Or(T, F) is true
784
+ assert Or(F, T) is true
785
+ assert Or(F, F) is false
786
+ assert Or(T, T) is true
787
+ assert Or(T, x) is true
788
+ assert Or(F, x) == x
789
+ if not (T is True and F is False):
790
+ assert T | F is true
791
+ assert F | T is true
792
+ if F is not False:
793
+ assert F | F is false
794
+ if T is not True:
795
+ assert T | T is true
796
+
797
+ assert Xor(T, F) is true
798
+ assert Xor(F, T) is true
799
+ assert Xor(F, F) is false
800
+ assert Xor(T, T) is false
801
+ assert Xor(T, x) == ~x
802
+ assert Xor(F, x) == x
803
+ if not (T is True and F is False):
804
+ assert T ^ F is true
805
+ assert F ^ T is true
806
+ if F is not False:
807
+ assert F ^ F is false
808
+ if T is not True:
809
+ assert T ^ T is false
810
+
811
+ assert Nand(T, F) is true
812
+ assert Nand(F, T) is true
813
+ assert Nand(F, F) is true
814
+ assert Nand(T, T) is false
815
+ assert Nand(T, x) == ~x
816
+ assert Nand(F, x) is true
817
+
818
+ assert Nor(T, F) is false
819
+ assert Nor(F, T) is false
820
+ assert Nor(F, F) is true
821
+ assert Nor(T, T) is false
822
+ assert Nor(T, x) is false
823
+ assert Nor(F, x) == ~x
824
+
825
+ assert Implies(T, F) is false
826
+ assert Implies(F, T) is true
827
+ assert Implies(F, F) is true
828
+ assert Implies(T, T) is true
829
+ assert Implies(T, x) == x
830
+ assert Implies(F, x) is true
831
+ assert Implies(x, T) is true
832
+ assert Implies(x, F) == ~x
833
+ if not (T is True and F is False):
834
+ assert T >> F is false
835
+ assert F << T is false
836
+ assert F >> T is true
837
+ assert T << F is true
838
+ if F is not False:
839
+ assert F >> F is true
840
+ assert F << F is true
841
+ if T is not True:
842
+ assert T >> T is true
843
+ assert T << T is true
844
+
845
+ assert Equivalent(T, F) is false
846
+ assert Equivalent(F, T) is false
847
+ assert Equivalent(F, F) is true
848
+ assert Equivalent(T, T) is true
849
+ assert Equivalent(T, x) == x
850
+ assert Equivalent(F, x) == ~x
851
+ assert Equivalent(x, T) == x
852
+ assert Equivalent(x, F) == ~x
853
+
854
+ assert ITE(T, T, T) is true
855
+ assert ITE(T, T, F) is true
856
+ assert ITE(T, F, T) is false
857
+ assert ITE(T, F, F) is false
858
+ assert ITE(F, T, T) is true
859
+ assert ITE(F, T, F) is false
860
+ assert ITE(F, F, T) is true
861
+ assert ITE(F, F, F) is false
862
+
863
+ assert all(i.simplify(1, 2) is i for i in (S.true, S.false))
864
+
865
+
866
+ def test_bool_as_set():
867
+ assert ITE(y <= 0, False, y >= 1).as_set() == Interval(1, oo)
868
+ assert And(x <= 2, x >= -2).as_set() == Interval(-2, 2)
869
+ assert Or(x >= 2, x <= -2).as_set() == Interval(-oo, -2) + Interval(2, oo)
870
+ assert Not(x > 2).as_set() == Interval(-oo, 2)
871
+ # issue 10240
872
+ assert Not(And(x > 2, x < 3)).as_set() == \
873
+ Union(Interval(-oo, 2), Interval(3, oo))
874
+ assert true.as_set() == S.UniversalSet
875
+ assert false.as_set() is S.EmptySet
876
+ assert x.as_set() == S.UniversalSet
877
+ assert And(Or(x < 1, x > 3), x < 2).as_set() == Interval.open(-oo, 1)
878
+ assert And(x < 1, sin(x) < 3).as_set() == (x < 1).as_set()
879
+ raises(NotImplementedError, lambda: (sin(x) < 1).as_set())
880
+ # watch for object morph in as_set
881
+ assert Eq(-1, cos(2*x)**2/sin(2*x)**2).as_set() is S.EmptySet
882
+
883
+
884
+ @XFAIL
885
+ def test_multivariate_bool_as_set():
886
+ x, y = symbols('x,y')
887
+
888
+ assert And(x >= 0, y >= 0).as_set() == Interval(0, oo)*Interval(0, oo)
889
+ assert Or(x >= 0, y >= 0).as_set() == S.Reals*S.Reals - \
890
+ Interval(-oo, 0, True, True)*Interval(-oo, 0, True, True)
891
+
892
+
893
+ def test_all_or_nothing():
894
+ x = symbols('x', extended_real=True)
895
+ args = x >= -oo, x <= oo
896
+ v = And(*args)
897
+ if v.func is And:
898
+ assert len(v.args) == len(args) - args.count(S.true)
899
+ else:
900
+ assert v == True
901
+ v = Or(*args)
902
+ if v.func is Or:
903
+ assert len(v.args) == 2
904
+ else:
905
+ assert v == True
906
+
907
+
908
+ def test_canonical_atoms():
909
+ assert true.canonical == true
910
+ assert false.canonical == false
911
+
912
+
913
+ def test_negated_atoms():
914
+ assert true.negated == false
915
+ assert false.negated == true
916
+
917
+
918
+ def test_issue_8777():
919
+ assert And(x > 2, x < oo).as_set() == Interval(2, oo, left_open=True)
920
+ assert And(x >= 1, x < oo).as_set() == Interval(1, oo)
921
+ assert (x < oo).as_set() == Interval(-oo, oo)
922
+ assert (x > -oo).as_set() == Interval(-oo, oo)
923
+
924
+
925
+ def test_issue_8975():
926
+ assert Or(And(-oo < x, x <= -2), And(2 <= x, x < oo)).as_set() == \
927
+ Interval(-oo, -2) + Interval(2, oo)
928
+
929
+
930
+ def test_term_to_integer():
931
+ assert term_to_integer([1, 0, 1, 0, 0, 1, 0]) == 82
932
+ assert term_to_integer('0010101000111001') == 10809
933
+
934
+
935
+ def test_issue_21971():
936
+ a, b, c, d = symbols('a b c d')
937
+ f = a & b & c | a & c
938
+ assert f.subs(a & c, d) == b & d | d
939
+ assert f.subs(a & b & c, d) == a & c | d
940
+
941
+ f = (a | b | c) & (a | c)
942
+ assert f.subs(a | c, d) == (b | d) & d
943
+ assert f.subs(a | b | c, d) == (a | c) & d
944
+
945
+ f = (a ^ b ^ c) & (a ^ c)
946
+ assert f.subs(a ^ c, d) == (b ^ d) & d
947
+ assert f.subs(a ^ b ^ c, d) == (a ^ c) & d
948
+
949
+
950
+ def test_truth_table():
951
+ assert list(truth_table(And(x, y), [x, y], input=False)) == \
952
+ [False, False, False, True]
953
+ assert list(truth_table(x | y, [x, y], input=False)) == \
954
+ [False, True, True, True]
955
+ assert list(truth_table(x >> y, [x, y], input=False)) == \
956
+ [True, True, False, True]
957
+ assert list(truth_table(And(x, y), [x, y])) == \
958
+ [([0, 0], False), ([0, 1], False), ([1, 0], False), ([1, 1], True)]
959
+
960
+
961
+ def test_issue_8571():
962
+ for t in (S.true, S.false):
963
+ raises(TypeError, lambda: +t)
964
+ raises(TypeError, lambda: -t)
965
+ raises(TypeError, lambda: abs(t))
966
+ # use int(bool(t)) to get 0 or 1
967
+ raises(TypeError, lambda: int(t))
968
+
969
+ for o in [S.Zero, S.One, x]:
970
+ for _ in range(2):
971
+ raises(TypeError, lambda: o + t)
972
+ raises(TypeError, lambda: o - t)
973
+ raises(TypeError, lambda: o % t)
974
+ raises(TypeError, lambda: o*t)
975
+ raises(TypeError, lambda: o/t)
976
+ raises(TypeError, lambda: o**t)
977
+ o, t = t, o # do again in reversed order
978
+
979
+
980
+ def test_expand_relational():
981
+ n = symbols('n', negative=True)
982
+ p, q = symbols('p q', positive=True)
983
+ r = ((n + q*(-n/q + 1))/(q*(-n/q + 1)) < 0)
984
+ assert r is not S.false
985
+ assert r.expand() is S.false
986
+ assert (q > 0).expand() is S.true
987
+
988
+
989
+ def test_issue_12717():
990
+ assert S.true.is_Atom == True
991
+ assert S.false.is_Atom == True
992
+
993
+
994
+ def test_as_Boolean():
995
+ nz = symbols('nz', nonzero=True)
996
+ assert all(as_Boolean(i) is S.true for i in (True, S.true, 1, nz))
997
+ z = symbols('z', zero=True)
998
+ assert all(as_Boolean(i) is S.false for i in (False, S.false, 0, z))
999
+ assert all(as_Boolean(i) == i for i in (x, x < 0))
1000
+ for i in (2, S(2), x + 1, []):
1001
+ raises(TypeError, lambda: as_Boolean(i))
1002
+
1003
+
1004
+ def test_binary_symbols():
1005
+ assert ITE(x < 1, y, z).binary_symbols == {y, z}
1006
+ for f in (Eq, Ne):
1007
+ assert f(x, 1).binary_symbols == set()
1008
+ assert f(x, True).binary_symbols == {x}
1009
+ assert f(x, False).binary_symbols == {x}
1010
+ assert S.true.binary_symbols == set()
1011
+ assert S.false.binary_symbols == set()
1012
+ assert x.binary_symbols == {x}
1013
+ assert And(x, Eq(y, False), Eq(z, 1)).binary_symbols == {x, y}
1014
+ assert Q.prime(x).binary_symbols == set()
1015
+ assert Q.lt(x, 1).binary_symbols == set()
1016
+ assert Q.is_true(x).binary_symbols == {x}
1017
+ assert Q.eq(x, True).binary_symbols == {x}
1018
+ assert Q.prime(x).binary_symbols == set()
1019
+
1020
+
1021
+ def test_BooleanFunction_diff():
1022
+ assert And(x, y).diff(x) == Piecewise((0, Eq(y, False)), (1, True))
1023
+
1024
+
1025
+ def test_issue_14700():
1026
+ A, B, C, D, E, F, G, H = symbols('A B C D E F G H')
1027
+ q = ((B & D & H & ~F) | (B & H & ~C & ~D) | (B & H & ~C & ~F) |
1028
+ (B & H & ~D & ~G) | (B & H & ~F & ~G) | (C & G & ~B & ~D) |
1029
+ (C & G & ~D & ~H) | (C & G & ~F & ~H) | (D & F & H & ~B) |
1030
+ (D & F & ~G & ~H) | (B & D & F & ~C & ~H) | (D & E & F & ~B & ~C) |
1031
+ (D & F & ~A & ~B & ~C) | (D & F & ~A & ~C & ~H) |
1032
+ (A & B & D & F & ~E & ~H))
1033
+ soldnf = ((B & D & H & ~F) | (D & F & H & ~B) | (B & H & ~C & ~D) |
1034
+ (B & H & ~D & ~G) | (C & G & ~B & ~D) | (C & G & ~D & ~H) |
1035
+ (C & G & ~F & ~H) | (D & F & ~G & ~H) | (D & E & F & ~C & ~H) |
1036
+ (D & F & ~A & ~C & ~H) | (A & B & D & F & ~E & ~H))
1037
+ solcnf = ((B | C | D) & (B | D | G) & (C | D | H) & (C | F | H) &
1038
+ (D | G | H) & (F | G | H) & (B | F | ~D | ~H) &
1039
+ (~B | ~D | ~F | ~H) & (D | ~B | ~C | ~G | ~H) &
1040
+ (A | H | ~C | ~D | ~F | ~G) & (H | ~C | ~D | ~E | ~F | ~G) &
1041
+ (B | E | H | ~A | ~D | ~F | ~G))
1042
+ assert simplify_logic(q, "dnf") == soldnf
1043
+ assert simplify_logic(q, "cnf") == solcnf
1044
+
1045
+ minterms = [[0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1],
1046
+ [0, 0, 1, 1], [1, 0, 1, 1]]
1047
+ dontcares = [[1, 0, 0, 0], [1, 0, 0, 1], [1, 1, 0, 0], [1, 1, 0, 1]]
1048
+ assert SOPform([w, x, y, z], minterms) == (x & ~w) | (y & z & ~x)
1049
+ # Should not be more complicated with don't cares
1050
+ assert SOPform([w, x, y, z], minterms, dontcares) == \
1051
+ (x & ~w) | (y & z & ~x)
1052
+
1053
+
1054
+ def test_relational_simplification():
1055
+ w, x, y, z = symbols('w x y z', real=True)
1056
+ d, e = symbols('d e', real=False)
1057
+ # Test all combinations or sign and order
1058
+ assert Or(x >= y, x < y).simplify() == S.true
1059
+ assert Or(x >= y, y > x).simplify() == S.true
1060
+ assert Or(x >= y, -x > -y).simplify() == S.true
1061
+ assert Or(x >= y, -y < -x).simplify() == S.true
1062
+ assert Or(-x <= -y, x < y).simplify() == S.true
1063
+ assert Or(-x <= -y, -x > -y).simplify() == S.true
1064
+ assert Or(-x <= -y, y > x).simplify() == S.true
1065
+ assert Or(-x <= -y, -y < -x).simplify() == S.true
1066
+ assert Or(y <= x, x < y).simplify() == S.true
1067
+ assert Or(y <= x, y > x).simplify() == S.true
1068
+ assert Or(y <= x, -x > -y).simplify() == S.true
1069
+ assert Or(y <= x, -y < -x).simplify() == S.true
1070
+ assert Or(-y >= -x, x < y).simplify() == S.true
1071
+ assert Or(-y >= -x, y > x).simplify() == S.true
1072
+ assert Or(-y >= -x, -x > -y).simplify() == S.true
1073
+ assert Or(-y >= -x, -y < -x).simplify() == S.true
1074
+
1075
+ assert Or(x < y, x >= y).simplify() == S.true
1076
+ assert Or(y > x, x >= y).simplify() == S.true
1077
+ assert Or(-x > -y, x >= y).simplify() == S.true
1078
+ assert Or(-y < -x, x >= y).simplify() == S.true
1079
+ assert Or(x < y, -x <= -y).simplify() == S.true
1080
+ assert Or(-x > -y, -x <= -y).simplify() == S.true
1081
+ assert Or(y > x, -x <= -y).simplify() == S.true
1082
+ assert Or(-y < -x, -x <= -y).simplify() == S.true
1083
+ assert Or(x < y, y <= x).simplify() == S.true
1084
+ assert Or(y > x, y <= x).simplify() == S.true
1085
+ assert Or(-x > -y, y <= x).simplify() == S.true
1086
+ assert Or(-y < -x, y <= x).simplify() == S.true
1087
+ assert Or(x < y, -y >= -x).simplify() == S.true
1088
+ assert Or(y > x, -y >= -x).simplify() == S.true
1089
+ assert Or(-x > -y, -y >= -x).simplify() == S.true
1090
+ assert Or(-y < -x, -y >= -x).simplify() == S.true
1091
+
1092
+ # Some other tests
1093
+ assert Or(x >= y, w < z, x <= y).simplify() == S.true
1094
+ assert And(x >= y, x < y).simplify() == S.false
1095
+ assert Or(x >= y, Eq(y, x)).simplify() == (x >= y)
1096
+ assert And(x >= y, Eq(y, x)).simplify() == Eq(x, y)
1097
+ assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \
1098
+ (Eq(x, y) & (x >= 1) & (y >= 5) & (y > z))
1099
+ assert Or(Eq(x, y), x >= y, w < y, z < y).simplify() == \
1100
+ (x >= y) | (y > z) | (w < y)
1101
+ assert And(Eq(x, y), x >= y, w < y, y >= z, z < y).simplify() == \
1102
+ Eq(x, y) & (y > z) & (w < y)
1103
+ # assert And(Eq(x, y), x >= y, w < y, y >= z, z < y).simplify(relational_minmax=True) == \
1104
+ # And(Eq(x, y), y > Max(w, z))
1105
+ # assert Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify(relational_minmax=True) == \
1106
+ # (Eq(x, y) | (x >= 1) | (y > Min(2, z)))
1107
+ assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \
1108
+ (Eq(x, y) & (x >= 1) & (y >= 5) & (y > z))
1109
+ assert (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)).simplify() == \
1110
+ (Eq(x, y) & Eq(d, e) & (d >= e))
1111
+ assert And(Eq(x, y), Eq(x, -y)).simplify() == And(Eq(x, 0), Eq(y, 0))
1112
+ assert Xor(x >= y, x <= y).simplify() == Ne(x, y)
1113
+ assert And(x > 1, x < -1, Eq(x, y)).simplify() == S.false
1114
+ # From #16690
1115
+ assert And(x >= y, Eq(y, 0)).simplify() == And(x >= 0, Eq(y, 0))
1116
+ assert Or(Ne(x, 1), Ne(x, 2)).simplify() == S.true
1117
+ assert And(Eq(x, 1), Ne(2, x)).simplify() == Eq(x, 1)
1118
+ assert Or(Eq(x, 1), Ne(2, x)).simplify() == Ne(x, 2)
1119
+
1120
+ def test_issue_8373():
1121
+ x = symbols('x', real=True)
1122
+ assert Or(x < 1, x > -1).simplify() == S.true
1123
+ assert Or(x < 1, x >= 1).simplify() == S.true
1124
+ assert And(x < 1, x >= 1).simplify() == S.false
1125
+ assert Or(x <= 1, x >= 1).simplify() == S.true
1126
+
1127
+
1128
+ def test_issue_7950():
1129
+ x = symbols('x', real=True)
1130
+ assert And(Eq(x, 1), Eq(x, 2)).simplify() == S.false
1131
+
1132
+
1133
+ @slow
1134
+ def test_relational_simplification_numerically():
1135
+ def test_simplification_numerically_function(original, simplified):
1136
+ symb = original.free_symbols
1137
+ n = len(symb)
1138
+ valuelist = list(set(combinations(list(range(-(n-1), n))*n, n)))
1139
+ for values in valuelist:
1140
+ sublist = dict(zip(symb, values))
1141
+ originalvalue = original.subs(sublist)
1142
+ simplifiedvalue = simplified.subs(sublist)
1143
+ assert originalvalue == simplifiedvalue, "Original: {}\nand"\
1144
+ " simplified: {}\ndo not evaluate to the same value for {}"\
1145
+ "".format(original, simplified, sublist)
1146
+
1147
+ w, x, y, z = symbols('w x y z', real=True)
1148
+ d, e = symbols('d e', real=False)
1149
+
1150
+ expressions = (And(Eq(x, y), x >= y, w < y, y >= z, z < y),
1151
+ And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y),
1152
+ Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y),
1153
+ And(x >= y, Eq(y, x)),
1154
+ Or(And(Eq(x, y), x >= y, w < y, Or(y >= z, z < y)),
1155
+ And(Eq(x, y), x >= 1, 2 < y, y >= -1, z < y)),
1156
+ (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)),
1157
+ )
1158
+
1159
+ for expression in expressions:
1160
+ test_simplification_numerically_function(expression,
1161
+ expression.simplify())
1162
+
1163
+
1164
+ def test_relational_simplification_patterns_numerically():
1165
+ from sympy.core import Wild
1166
+ from sympy.logic.boolalg import _simplify_patterns_and, \
1167
+ _simplify_patterns_or, _simplify_patterns_xor
1168
+ a = Wild('a')
1169
+ b = Wild('b')
1170
+ c = Wild('c')
1171
+ symb = [a, b, c]
1172
+ patternlists = [[And, _simplify_patterns_and()],
1173
+ [Or, _simplify_patterns_or()],
1174
+ [Xor, _simplify_patterns_xor()]]
1175
+ valuelist = list(set(combinations(list(range(-2, 3))*3, 3)))
1176
+ # Skip combinations of +/-2 and 0, except for all 0
1177
+ valuelist = [v for v in valuelist if any([w % 2 for w in v]) or not any(v)]
1178
+ for func, patternlist in patternlists:
1179
+ for pattern in patternlist:
1180
+ original = func(*pattern[0].args)
1181
+ simplified = pattern[1]
1182
+ for values in valuelist:
1183
+ sublist = dict(zip(symb, values))
1184
+ originalvalue = original.xreplace(sublist)
1185
+ simplifiedvalue = simplified.xreplace(sublist)
1186
+ assert originalvalue == simplifiedvalue, "Original: {}\nand"\
1187
+ " simplified: {}\ndo not evaluate to the same value for"\
1188
+ "{}".format(pattern[0], simplified, sublist)
1189
+
1190
+
1191
+ def test_issue_16803():
1192
+ n = symbols('n')
1193
+ # No simplification done, but should not raise an exception
1194
+ assert ((n > 3) | (n < 0) | ((n > 0) & (n < 3))).simplify() == \
1195
+ (n > 3) | (n < 0) | ((n > 0) & (n < 3))
1196
+
1197
+
1198
+ def test_issue_17530():
1199
+ r = {x: oo, y: oo}
1200
+ assert Or(x + y > 0, x - y < 0).subs(r)
1201
+ assert not And(x + y < 0, x - y < 0).subs(r)
1202
+ raises(TypeError, lambda: Or(x + y < 0, x - y < 0).subs(r))
1203
+ raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r))
1204
+ raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r))
1205
+
1206
+
1207
+ def test_anf_coeffs():
1208
+ assert anf_coeffs([1, 0]) == [1, 1]
1209
+ assert anf_coeffs([0, 0, 0, 1]) == [0, 0, 0, 1]
1210
+ assert anf_coeffs([0, 1, 1, 1]) == [0, 1, 1, 1]
1211
+ assert anf_coeffs([1, 1, 1, 0]) == [1, 0, 0, 1]
1212
+ assert anf_coeffs([1, 0, 0, 0]) == [1, 1, 1, 1]
1213
+ assert anf_coeffs([1, 0, 0, 1]) == [1, 1, 1, 0]
1214
+ assert anf_coeffs([1, 1, 0, 1]) == [1, 0, 1, 1]
1215
+
1216
+
1217
+ def test_ANFform():
1218
+ x, y = symbols('x,y')
1219
+ assert ANFform([x], [1, 1]) == True
1220
+ assert ANFform([x], [0, 0]) == False
1221
+ assert ANFform([x], [1, 0]) == Xor(x, True, remove_true=False)
1222
+ assert ANFform([x, y], [1, 1, 1, 0]) == \
1223
+ Xor(True, And(x, y), remove_true=False)
1224
+
1225
+
1226
+ def test_bool_minterm():
1227
+ x, y = symbols('x,y')
1228
+ assert bool_minterm(3, [x, y]) == And(x, y)
1229
+ assert bool_minterm([1, 0], [x, y]) == And(Not(y), x)
1230
+
1231
+
1232
+ def test_bool_maxterm():
1233
+ x, y = symbols('x,y')
1234
+ assert bool_maxterm(2, [x, y]) == Or(Not(x), y)
1235
+ assert bool_maxterm([0, 1], [x, y]) == Or(Not(y), x)
1236
+
1237
+
1238
+ def test_bool_monomial():
1239
+ x, y = symbols('x,y')
1240
+ assert bool_monomial(1, [x, y]) == y
1241
+ assert bool_monomial([1, 1], [x, y]) == And(x, y)
1242
+
1243
+
1244
+ def test_check_pair():
1245
+ assert _check_pair([0, 1, 0], [0, 1, 1]) == 2
1246
+ assert _check_pair([0, 1, 0], [1, 1, 1]) == -1
1247
+
1248
+
1249
+ def test_issue_19114():
1250
+ expr = (B & C) | (A & ~C) | (~A & ~B)
1251
+ # Expression is minimal, but there are multiple minimal forms possible
1252
+ res1 = (A & B) | (C & ~A) | (~B & ~C)
1253
+ result = to_dnf(expr, simplify=True)
1254
+ assert result in (expr, res1)
1255
+
1256
+
1257
+ def test_issue_20870():
1258
+ result = SOPform([a, b, c, d], [1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15])
1259
+ expected = ((d & ~b) | (a & b & c) | (a & ~c & ~d) |
1260
+ (b & ~a & ~c) | (c & ~a & ~d))
1261
+ assert result == expected
1262
+
1263
+
1264
+ def test_convert_to_varsSOP():
1265
+ assert _convert_to_varsSOP([0, 1, 0], [x, y, z]) == And(Not(x), y, Not(z))
1266
+ assert _convert_to_varsSOP([3, 1, 0], [x, y, z]) == And(y, Not(z))
1267
+
1268
+
1269
+ def test_convert_to_varsPOS():
1270
+ assert _convert_to_varsPOS([0, 1, 0], [x, y, z]) == Or(x, Not(y), z)
1271
+ assert _convert_to_varsPOS([3, 1, 0], [x, y, z]) == Or(Not(y), z)
1272
+
1273
+
1274
+ def test_gateinputcount():
1275
+ a, b, c, d, e = symbols('a:e')
1276
+ assert gateinputcount(And(a, b)) == 2
1277
+ assert gateinputcount(a | b & c & d ^ (e | a)) == 9
1278
+ assert gateinputcount(And(a, True)) == 0
1279
+ raises(TypeError, lambda: gateinputcount(a*b))
1280
+
1281
+
1282
+ def test_refine():
1283
+ # relational
1284
+ assert not refine(x < 0, ~(x < 0))
1285
+ assert refine(x < 0, (x < 0))
1286
+ assert refine(x < 0, (0 > x)) is S.true
1287
+ assert refine(x < 0, (y < 0)) == (x < 0)
1288
+ assert not refine(x <= 0, ~(x <= 0))
1289
+ assert refine(x <= 0, (x <= 0))
1290
+ assert refine(x <= 0, (0 >= x)) is S.true
1291
+ assert refine(x <= 0, (y <= 0)) == (x <= 0)
1292
+ assert not refine(x > 0, ~(x > 0))
1293
+ assert refine(x > 0, (x > 0))
1294
+ assert refine(x > 0, (0 < x)) is S.true
1295
+ assert refine(x > 0, (y > 0)) == (x > 0)
1296
+ assert not refine(x >= 0, ~(x >= 0))
1297
+ assert refine(x >= 0, (x >= 0))
1298
+ assert refine(x >= 0, (0 <= x)) is S.true
1299
+ assert refine(x >= 0, (y >= 0)) == (x >= 0)
1300
+ assert not refine(Eq(x, 0), ~(Eq(x, 0)))
1301
+ assert refine(Eq(x, 0), (Eq(x, 0)))
1302
+ assert refine(Eq(x, 0), (Eq(0, x))) is S.true
1303
+ assert refine(Eq(x, 0), (Eq(y, 0))) == Eq(x, 0)
1304
+ assert not refine(Ne(x, 0), ~(Ne(x, 0)))
1305
+ assert refine(Ne(x, 0), (Ne(0, x))) is S.true
1306
+ assert refine(Ne(x, 0), (Ne(x, 0)))
1307
+ assert refine(Ne(x, 0), (Ne(y, 0))) == (Ne(x, 0))
1308
+
1309
+ # boolean functions
1310
+ assert refine(And(x > 0, y > 0), (x > 0)) == (y > 0)
1311
+ assert refine(And(x > 0, y > 0), (x > 0) & (y > 0)) is S.true
1312
+
1313
+ # predicates
1314
+ assert refine(Q.positive(x), Q.positive(x)) is S.true
1315
+ assert refine(Q.positive(x), Q.negative(x)) is S.false
1316
+ assert refine(Q.positive(x), Q.real(x)) == Q.positive(x)
1317
+
1318
+
1319
+ def test_relational_threeterm_simplification_patterns_numerically():
1320
+ from sympy.core import Wild
1321
+ from sympy.logic.boolalg import _simplify_patterns_and3
1322
+ a = Wild('a')
1323
+ b = Wild('b')
1324
+ c = Wild('c')
1325
+ symb = [a, b, c]
1326
+ patternlists = [[And, _simplify_patterns_and3()]]
1327
+ valuelist = list(set(combinations(list(range(-2, 3))*3, 3)))
1328
+ # Skip combinations of +/-2 and 0, except for all 0
1329
+ valuelist = [v for v in valuelist if any([w % 2 for w in v]) or not any(v)]
1330
+ for func, patternlist in patternlists:
1331
+ for pattern in patternlist:
1332
+ original = func(*pattern[0].args)
1333
+ simplified = pattern[1]
1334
+ for values in valuelist:
1335
+ sublist = dict(zip(symb, values))
1336
+ originalvalue = original.xreplace(sublist)
1337
+ simplifiedvalue = simplified.xreplace(sublist)
1338
+ assert originalvalue == simplifiedvalue, "Original: {}\nand"\
1339
+ " simplified: {}\ndo not evaluate to the same value for"\
1340
+ "{}".format(pattern[0], simplified, sublist)
venv/lib/python3.10/site-packages/sympy/logic/tests/test_dimacs.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Various tests on satisfiability using dimacs cnf file syntax
2
+ You can find lots of cnf files in
3
+ ftp://dimacs.rutgers.edu/pub/challenge/satisfiability/benchmarks/cnf/
4
+ """
5
+
6
+ from sympy.logic.utilities.dimacs import load
7
+ from sympy.logic.algorithms.dpll import dpll_satisfiable
8
+
9
+
10
+ def test_f1():
11
+ assert bool(dpll_satisfiable(load(f1)))
12
+
13
+
14
+ def test_f2():
15
+ assert bool(dpll_satisfiable(load(f2)))
16
+
17
+
18
+ def test_f3():
19
+ assert bool(dpll_satisfiable(load(f3)))
20
+
21
+
22
+ def test_f4():
23
+ assert not bool(dpll_satisfiable(load(f4)))
24
+
25
+
26
+ def test_f5():
27
+ assert bool(dpll_satisfiable(load(f5)))
28
+
29
+ f1 = """c simple example
30
+ c Resolution: SATISFIABLE
31
+ c
32
+ p cnf 3 2
33
+ 1 -3 0
34
+ 2 3 -1 0
35
+ """
36
+
37
+
38
+ f2 = """c an example from Quinn's text, 16 variables and 18 clauses.
39
+ c Resolution: SATISFIABLE
40
+ c
41
+ p cnf 16 18
42
+ 1 2 0
43
+ -2 -4 0
44
+ 3 4 0
45
+ -4 -5 0
46
+ 5 -6 0
47
+ 6 -7 0
48
+ 6 7 0
49
+ 7 -16 0
50
+ 8 -9 0
51
+ -8 -14 0
52
+ 9 10 0
53
+ 9 -10 0
54
+ -10 -11 0
55
+ 10 12 0
56
+ 11 12 0
57
+ 13 14 0
58
+ 14 -15 0
59
+ 15 16 0
60
+ """
61
+
62
+ f3 = """c
63
+ p cnf 6 9
64
+ -1 0
65
+ -3 0
66
+ 2 -1 0
67
+ 2 -4 0
68
+ 5 -4 0
69
+ -1 -3 0
70
+ -4 -6 0
71
+ 1 3 -2 0
72
+ 4 6 -2 -5 0
73
+ """
74
+
75
+ f4 = """c
76
+ c file: hole6.cnf [http://people.sc.fsu.edu/~jburkardt/data/cnf/hole6.cnf]
77
+ c
78
+ c SOURCE: John Hooker ([email protected])
79
+ c
80
+ c DESCRIPTION: Pigeon hole problem of placing n (for file 'holen.cnf') pigeons
81
+ c in n+1 holes without placing 2 pigeons in the same hole
82
+ c
83
+ c NOTE: Part of the collection at the Forschungsinstitut fuer
84
+ c anwendungsorientierte Wissensverarbeitung in Ulm Germany.
85
+ c
86
+ c NOTE: Not satisfiable
87
+ c
88
+ p cnf 42 133
89
+ -1 -7 0
90
+ -1 -13 0
91
+ -1 -19 0
92
+ -1 -25 0
93
+ -1 -31 0
94
+ -1 -37 0
95
+ -7 -13 0
96
+ -7 -19 0
97
+ -7 -25 0
98
+ -7 -31 0
99
+ -7 -37 0
100
+ -13 -19 0
101
+ -13 -25 0
102
+ -13 -31 0
103
+ -13 -37 0
104
+ -19 -25 0
105
+ -19 -31 0
106
+ -19 -37 0
107
+ -25 -31 0
108
+ -25 -37 0
109
+ -31 -37 0
110
+ -2 -8 0
111
+ -2 -14 0
112
+ -2 -20 0
113
+ -2 -26 0
114
+ -2 -32 0
115
+ -2 -38 0
116
+ -8 -14 0
117
+ -8 -20 0
118
+ -8 -26 0
119
+ -8 -32 0
120
+ -8 -38 0
121
+ -14 -20 0
122
+ -14 -26 0
123
+ -14 -32 0
124
+ -14 -38 0
125
+ -20 -26 0
126
+ -20 -32 0
127
+ -20 -38 0
128
+ -26 -32 0
129
+ -26 -38 0
130
+ -32 -38 0
131
+ -3 -9 0
132
+ -3 -15 0
133
+ -3 -21 0
134
+ -3 -27 0
135
+ -3 -33 0
136
+ -3 -39 0
137
+ -9 -15 0
138
+ -9 -21 0
139
+ -9 -27 0
140
+ -9 -33 0
141
+ -9 -39 0
142
+ -15 -21 0
143
+ -15 -27 0
144
+ -15 -33 0
145
+ -15 -39 0
146
+ -21 -27 0
147
+ -21 -33 0
148
+ -21 -39 0
149
+ -27 -33 0
150
+ -27 -39 0
151
+ -33 -39 0
152
+ -4 -10 0
153
+ -4 -16 0
154
+ -4 -22 0
155
+ -4 -28 0
156
+ -4 -34 0
157
+ -4 -40 0
158
+ -10 -16 0
159
+ -10 -22 0
160
+ -10 -28 0
161
+ -10 -34 0
162
+ -10 -40 0
163
+ -16 -22 0
164
+ -16 -28 0
165
+ -16 -34 0
166
+ -16 -40 0
167
+ -22 -28 0
168
+ -22 -34 0
169
+ -22 -40 0
170
+ -28 -34 0
171
+ -28 -40 0
172
+ -34 -40 0
173
+ -5 -11 0
174
+ -5 -17 0
175
+ -5 -23 0
176
+ -5 -29 0
177
+ -5 -35 0
178
+ -5 -41 0
179
+ -11 -17 0
180
+ -11 -23 0
181
+ -11 -29 0
182
+ -11 -35 0
183
+ -11 -41 0
184
+ -17 -23 0
185
+ -17 -29 0
186
+ -17 -35 0
187
+ -17 -41 0
188
+ -23 -29 0
189
+ -23 -35 0
190
+ -23 -41 0
191
+ -29 -35 0
192
+ -29 -41 0
193
+ -35 -41 0
194
+ -6 -12 0
195
+ -6 -18 0
196
+ -6 -24 0
197
+ -6 -30 0
198
+ -6 -36 0
199
+ -6 -42 0
200
+ -12 -18 0
201
+ -12 -24 0
202
+ -12 -30 0
203
+ -12 -36 0
204
+ -12 -42 0
205
+ -18 -24 0
206
+ -18 -30 0
207
+ -18 -36 0
208
+ -18 -42 0
209
+ -24 -30 0
210
+ -24 -36 0
211
+ -24 -42 0
212
+ -30 -36 0
213
+ -30 -42 0
214
+ -36 -42 0
215
+ 6 5 4 3 2 1 0
216
+ 12 11 10 9 8 7 0
217
+ 18 17 16 15 14 13 0
218
+ 24 23 22 21 20 19 0
219
+ 30 29 28 27 26 25 0
220
+ 36 35 34 33 32 31 0
221
+ 42 41 40 39 38 37 0
222
+ """
223
+
224
+ f5 = """c simple example requiring variable selection
225
+ c
226
+ c NOTE: Satisfiable
227
+ c
228
+ p cnf 5 5
229
+ 1 2 3 0
230
+ 1 -2 3 0
231
+ 4 5 -3 0
232
+ 1 -4 -3 0
233
+ -1 -5 0
234
+ """
venv/lib/python3.10/site-packages/sympy/logic/tests/test_inference.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """For more tests on satisfiability, see test_dimacs"""
2
+
3
+ from sympy.assumptions.ask import Q
4
+ from sympy.core.symbol import symbols
5
+ from sympy.logic.boolalg import And, Implies, Equivalent, true, false
6
+ from sympy.logic.inference import literal_symbol, \
7
+ pl_true, satisfiable, valid, entails, PropKB
8
+ from sympy.logic.algorithms.dpll import dpll, dpll_satisfiable, \
9
+ find_pure_symbol, find_unit_clause, unit_propagate, \
10
+ find_pure_symbol_int_repr, find_unit_clause_int_repr, \
11
+ unit_propagate_int_repr
12
+ from sympy.logic.algorithms.dpll2 import dpll_satisfiable as dpll2_satisfiable
13
+ from sympy.testing.pytest import raises
14
+
15
+
16
+ def test_literal():
17
+ A, B = symbols('A,B')
18
+ assert literal_symbol(True) is True
19
+ assert literal_symbol(False) is False
20
+ assert literal_symbol(A) is A
21
+ assert literal_symbol(~A) is A
22
+
23
+
24
+ def test_find_pure_symbol():
25
+ A, B, C = symbols('A,B,C')
26
+ assert find_pure_symbol([A], [A]) == (A, True)
27
+ assert find_pure_symbol([A, B], [~A | B, ~B | A]) == (None, None)
28
+ assert find_pure_symbol([A, B, C], [ A | ~B, ~B | ~C, C | A]) == (A, True)
29
+ assert find_pure_symbol([A, B, C], [~A | B, B | ~C, C | A]) == (B, True)
30
+ assert find_pure_symbol([A, B, C], [~A | ~B, ~B | ~C, C | A]) == (B, False)
31
+ assert find_pure_symbol(
32
+ [A, B, C], [~A | B, ~B | ~C, C | A]) == (None, None)
33
+
34
+
35
+ def test_find_pure_symbol_int_repr():
36
+ assert find_pure_symbol_int_repr([1], [{1}]) == (1, True)
37
+ assert find_pure_symbol_int_repr([1, 2],
38
+ [{-1, 2}, {-2, 1}]) == (None, None)
39
+ assert find_pure_symbol_int_repr([1, 2, 3],
40
+ [{1, -2}, {-2, -3}, {3, 1}]) == (1, True)
41
+ assert find_pure_symbol_int_repr([1, 2, 3],
42
+ [{-1, 2}, {2, -3}, {3, 1}]) == (2, True)
43
+ assert find_pure_symbol_int_repr([1, 2, 3],
44
+ [{-1, -2}, {-2, -3}, {3, 1}]) == (2, False)
45
+ assert find_pure_symbol_int_repr([1, 2, 3],
46
+ [{-1, 2}, {-2, -3}, {3, 1}]) == (None, None)
47
+
48
+
49
+ def test_unit_clause():
50
+ A, B, C = symbols('A,B,C')
51
+ assert find_unit_clause([A], {}) == (A, True)
52
+ assert find_unit_clause([A, ~A], {}) == (A, True) # Wrong ??
53
+ assert find_unit_clause([A | B], {A: True}) == (B, True)
54
+ assert find_unit_clause([A | B], {B: True}) == (A, True)
55
+ assert find_unit_clause(
56
+ [A | B | C, B | ~C, A | ~B], {A: True}) == (B, False)
57
+ assert find_unit_clause([A | B | C, B | ~C, A | B], {A: True}) == (B, True)
58
+ assert find_unit_clause([A | B | C, B | ~C, A ], {}) == (A, True)
59
+
60
+
61
+ def test_unit_clause_int_repr():
62
+ assert find_unit_clause_int_repr(map(set, [[1]]), {}) == (1, True)
63
+ assert find_unit_clause_int_repr(map(set, [[1], [-1]]), {}) == (1, True)
64
+ assert find_unit_clause_int_repr([{1, 2}], {1: True}) == (2, True)
65
+ assert find_unit_clause_int_repr([{1, 2}], {2: True}) == (1, True)
66
+ assert find_unit_clause_int_repr(map(set,
67
+ [[1, 2, 3], [2, -3], [1, -2]]), {1: True}) == (2, False)
68
+ assert find_unit_clause_int_repr(map(set,
69
+ [[1, 2, 3], [3, -3], [1, 2]]), {1: True}) == (2, True)
70
+
71
+ A, B, C = symbols('A,B,C')
72
+ assert find_unit_clause([A | B | C, B | ~C, A ], {}) == (A, True)
73
+
74
+
75
+ def test_unit_propagate():
76
+ A, B, C = symbols('A,B,C')
77
+ assert unit_propagate([A | B], A) == []
78
+ assert unit_propagate([A | B, ~A | C, ~C | B, A], A) == [C, ~C | B, A]
79
+
80
+
81
+ def test_unit_propagate_int_repr():
82
+ assert unit_propagate_int_repr([{1, 2}], 1) == []
83
+ assert unit_propagate_int_repr(map(set,
84
+ [[1, 2], [-1, 3], [-3, 2], [1]]), 1) == [{3}, {-3, 2}]
85
+
86
+
87
+ def test_dpll():
88
+ """This is also tested in test_dimacs"""
89
+ A, B, C = symbols('A,B,C')
90
+ assert dpll([A | B], [A, B], {A: True, B: True}) == {A: True, B: True}
91
+
92
+
93
+ def test_dpll_satisfiable():
94
+ A, B, C = symbols('A,B,C')
95
+ assert dpll_satisfiable( A & ~A ) is False
96
+ assert dpll_satisfiable( A & ~B ) == {A: True, B: False}
97
+ assert dpll_satisfiable(
98
+ A | B ) in ({A: True}, {B: True}, {A: True, B: True})
99
+ assert dpll_satisfiable(
100
+ (~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
101
+ assert dpll_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False},
102
+ {A: True, C: True}, {B: True, C: True})
103
+ assert dpll_satisfiable( A & B & C ) == {A: True, B: True, C: True}
104
+ assert dpll_satisfiable( (A | B) & (A >> B) ) == {B: True}
105
+ assert dpll_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
106
+ assert dpll_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
107
+
108
+
109
+ def test_dpll2_satisfiable():
110
+ A, B, C = symbols('A,B,C')
111
+ assert dpll2_satisfiable( A & ~A ) is False
112
+ assert dpll2_satisfiable( A & ~B ) == {A: True, B: False}
113
+ assert dpll2_satisfiable(
114
+ A | B ) in ({A: True}, {B: True}, {A: True, B: True})
115
+ assert dpll2_satisfiable(
116
+ (~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
117
+ assert dpll2_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False, C: True},
118
+ {A: True, B: True, C: True})
119
+ assert dpll2_satisfiable( A & B & C ) == {A: True, B: True, C: True}
120
+ assert dpll2_satisfiable( (A | B) & (A >> B) ) in ({B: True, A: False},
121
+ {B: True, A: True})
122
+ assert dpll2_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
123
+ assert dpll2_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
124
+
125
+
126
+ def test_minisat22_satisfiable():
127
+ A, B, C = symbols('A,B,C')
128
+ minisat22_satisfiable = lambda expr: satisfiable(expr, algorithm="minisat22")
129
+ assert minisat22_satisfiable( A & ~A ) is False
130
+ assert minisat22_satisfiable( A & ~B ) == {A: True, B: False}
131
+ assert minisat22_satisfiable(
132
+ A | B ) in ({A: True}, {B: False}, {A: False, B: True}, {A: True, B: True}, {A: True, B: False})
133
+ assert minisat22_satisfiable(
134
+ (~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
135
+ assert minisat22_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False, C: True},
136
+ {A: True, B: True, C: True}, {A: False, B: True, C: True}, {A: True, B: False, C: False})
137
+ assert minisat22_satisfiable( A & B & C ) == {A: True, B: True, C: True}
138
+ assert minisat22_satisfiable( (A | B) & (A >> B) ) in ({B: True, A: False},
139
+ {B: True, A: True})
140
+ assert minisat22_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
141
+ assert minisat22_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
142
+
143
+ def test_minisat22_minimal_satisfiable():
144
+ A, B, C = symbols('A,B,C')
145
+ minisat22_satisfiable = lambda expr, minimal=True: satisfiable(expr, algorithm="minisat22", minimal=True)
146
+ assert minisat22_satisfiable( A & ~A ) is False
147
+ assert minisat22_satisfiable( A & ~B ) == {A: True, B: False}
148
+ assert minisat22_satisfiable(
149
+ A | B ) in ({A: True}, {B: False}, {A: False, B: True}, {A: True, B: True}, {A: True, B: False})
150
+ assert minisat22_satisfiable(
151
+ (~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
152
+ assert minisat22_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False, C: True},
153
+ {A: True, B: True, C: True}, {A: False, B: True, C: True}, {A: True, B: False, C: False})
154
+ assert minisat22_satisfiable( A & B & C ) == {A: True, B: True, C: True}
155
+ assert minisat22_satisfiable( (A | B) & (A >> B) ) in ({B: True, A: False},
156
+ {B: True, A: True})
157
+ assert minisat22_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
158
+ assert minisat22_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
159
+ g = satisfiable((A | B | C),algorithm="minisat22",minimal=True,all_models=True)
160
+ sol = next(g)
161
+ first_solution = {key for key, value in sol.items() if value}
162
+ sol=next(g)
163
+ second_solution = {key for key, value in sol.items() if value}
164
+ sol=next(g)
165
+ third_solution = {key for key, value in sol.items() if value}
166
+ assert not first_solution <= second_solution
167
+ assert not second_solution <= third_solution
168
+ assert not first_solution <= third_solution
169
+
170
+ def test_satisfiable():
171
+ A, B, C = symbols('A,B,C')
172
+ assert satisfiable(A & (A >> B) & ~B) is False
173
+
174
+
175
+ def test_valid():
176
+ A, B, C = symbols('A,B,C')
177
+ assert valid(A >> (B >> A)) is True
178
+ assert valid((A >> (B >> C)) >> ((A >> B) >> (A >> C))) is True
179
+ assert valid((~B >> ~A) >> (A >> B)) is True
180
+ assert valid(A | B | C) is False
181
+ assert valid(A >> B) is False
182
+
183
+
184
+ def test_pl_true():
185
+ A, B, C = symbols('A,B,C')
186
+ assert pl_true(True) is True
187
+ assert pl_true( A & B, {A: True, B: True}) is True
188
+ assert pl_true( A | B, {A: True}) is True
189
+ assert pl_true( A | B, {B: True}) is True
190
+ assert pl_true( A | B, {A: None, B: True}) is True
191
+ assert pl_true( A >> B, {A: False}) is True
192
+ assert pl_true( A | B | ~C, {A: False, B: True, C: True}) is True
193
+ assert pl_true(Equivalent(A, B), {A: False, B: False}) is True
194
+
195
+ # test for false
196
+ assert pl_true(False) is False
197
+ assert pl_true( A & B, {A: False, B: False}) is False
198
+ assert pl_true( A & B, {A: False}) is False
199
+ assert pl_true( A & B, {B: False}) is False
200
+ assert pl_true( A | B, {A: False, B: False}) is False
201
+
202
+ #test for None
203
+ assert pl_true(B, {B: None}) is None
204
+ assert pl_true( A & B, {A: True, B: None}) is None
205
+ assert pl_true( A >> B, {A: True, B: None}) is None
206
+ assert pl_true(Equivalent(A, B), {A: None}) is None
207
+ assert pl_true(Equivalent(A, B), {A: True, B: None}) is None
208
+
209
+ # Test for deep
210
+ assert pl_true(A | B, {A: False}, deep=True) is None
211
+ assert pl_true(~A & ~B, {A: False}, deep=True) is None
212
+ assert pl_true(A | B, {A: False, B: False}, deep=True) is False
213
+ assert pl_true(A & B & (~A | ~B), {A: True}, deep=True) is False
214
+ assert pl_true((C >> A) >> (B >> A), {C: True}, deep=True) is True
215
+
216
+
217
+ def test_pl_true_wrong_input():
218
+ from sympy.core.numbers import pi
219
+ raises(ValueError, lambda: pl_true('John Cleese'))
220
+ raises(ValueError, lambda: pl_true(42 + pi + pi ** 2))
221
+ raises(ValueError, lambda: pl_true(42))
222
+
223
+
224
+ def test_entails():
225
+ A, B, C = symbols('A, B, C')
226
+ assert entails(A, [A >> B, ~B]) is False
227
+ assert entails(B, [Equivalent(A, B), A]) is True
228
+ assert entails((A >> B) >> (~A >> ~B)) is False
229
+ assert entails((A >> B) >> (~B >> ~A)) is True
230
+
231
+
232
+ def test_PropKB():
233
+ A, B, C = symbols('A,B,C')
234
+ kb = PropKB()
235
+ assert kb.ask(A >> B) is False
236
+ assert kb.ask(A >> (B >> A)) is True
237
+ kb.tell(A >> B)
238
+ kb.tell(B >> C)
239
+ assert kb.ask(A) is False
240
+ assert kb.ask(B) is False
241
+ assert kb.ask(C) is False
242
+ assert kb.ask(~A) is False
243
+ assert kb.ask(~B) is False
244
+ assert kb.ask(~C) is False
245
+ assert kb.ask(A >> C) is True
246
+ kb.tell(A)
247
+ assert kb.ask(A) is True
248
+ assert kb.ask(B) is True
249
+ assert kb.ask(C) is True
250
+ assert kb.ask(~C) is False
251
+ kb.retract(A)
252
+ assert kb.ask(C) is False
253
+
254
+
255
+ def test_propKB_tolerant():
256
+ """"tolerant to bad input"""
257
+ kb = PropKB()
258
+ A, B, C = symbols('A,B,C')
259
+ assert kb.ask(B) is False
260
+
261
+ def test_satisfiable_non_symbols():
262
+ x, y = symbols('x y')
263
+ assumptions = Q.zero(x*y)
264
+ facts = Implies(Q.zero(x*y), Q.zero(x) | Q.zero(y))
265
+ query = ~Q.zero(x) & ~Q.zero(y)
266
+ refutations = [
267
+ {Q.zero(x): True, Q.zero(x*y): True},
268
+ {Q.zero(y): True, Q.zero(x*y): True},
269
+ {Q.zero(x): True, Q.zero(y): True, Q.zero(x*y): True},
270
+ {Q.zero(x): True, Q.zero(y): False, Q.zero(x*y): True},
271
+ {Q.zero(x): False, Q.zero(y): True, Q.zero(x*y): True}]
272
+ assert not satisfiable(And(assumptions, facts, query), algorithm='dpll')
273
+ assert satisfiable(And(assumptions, facts, ~query), algorithm='dpll') in refutations
274
+ assert not satisfiable(And(assumptions, facts, query), algorithm='dpll2')
275
+ assert satisfiable(And(assumptions, facts, ~query), algorithm='dpll2') in refutations
276
+
277
+ def test_satisfiable_bool():
278
+ from sympy.core.singleton import S
279
+ assert satisfiable(true) == {true: true}
280
+ assert satisfiable(S.true) == {true: true}
281
+ assert satisfiable(false) is False
282
+ assert satisfiable(S.false) is False
283
+
284
+
285
+ def test_satisfiable_all_models():
286
+ from sympy.abc import A, B
287
+ assert next(satisfiable(False, all_models=True)) is False
288
+ assert list(satisfiable((A >> ~A) & A, all_models=True)) == [False]
289
+ assert list(satisfiable(True, all_models=True)) == [{true: true}]
290
+
291
+ models = [{A: True, B: False}, {A: False, B: True}]
292
+ result = satisfiable(A ^ B, all_models=True)
293
+ models.remove(next(result))
294
+ models.remove(next(result))
295
+ raises(StopIteration, lambda: next(result))
296
+ assert not models
297
+
298
+ assert list(satisfiable(Equivalent(A, B), all_models=True)) == \
299
+ [{A: False, B: False}, {A: True, B: True}]
300
+
301
+ models = [{A: False, B: False}, {A: False, B: True}, {A: True, B: True}]
302
+ for model in satisfiable(A >> B, all_models=True):
303
+ models.remove(model)
304
+ assert not models
305
+
306
+ # This is a santiy test to check that only the required number
307
+ # of solutions are generated. The expr below has 2**100 - 1 models
308
+ # which would time out the test if all are generated at once.
309
+ from sympy.utilities.iterables import numbered_symbols
310
+ from sympy.logic.boolalg import Or
311
+ sym = numbered_symbols()
312
+ X = [next(sym) for i in range(100)]
313
+ result = satisfiable(Or(*X), all_models=True)
314
+ for i in range(10):
315
+ assert next(result)
venv/lib/python3.10/site-packages/sympy/logic/utilities/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .dimacs import load_file
2
+
3
+ __all__ = ['load_file']
venv/lib/python3.10/site-packages/sympy/logic/utilities/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (251 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/logic/utilities/__pycache__/dimacs.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .plot import plot_backends
2
+ from .plot_implicit import plot_implicit
3
+ from .textplot import textplot
4
+ from .pygletplot import PygletPlot
5
+ from .plot import PlotGrid
6
+ from .plot import (plot, plot_parametric, plot3d, plot3d_parametric_surface,
7
+ plot3d_parametric_line, plot_contour)
8
+
9
+ __all__ = [
10
+ 'plot_backends',
11
+
12
+ 'plot_implicit',
13
+
14
+ 'textplot',
15
+
16
+ 'PygletPlot',
17
+
18
+ 'PlotGrid',
19
+
20
+ 'plot', 'plot_parametric', 'plot3d', 'plot3d_parametric_surface',
21
+ 'plot3d_parametric_line', 'plot_contour'
22
+ ]
venv/lib/python3.10/site-packages/sympy/plotting/experimental_lambdify.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ rewrite of lambdify - This stuff is not stable at all.
2
+
3
+ It is for internal use in the new plotting module.
4
+ It may (will! see the Q'n'A in the source) be rewritten.
5
+
6
+ It's completely self contained. Especially it does not use lambdarepr.
7
+
8
+ It does not aim to replace the current lambdify. Most importantly it will never
9
+ ever support anything else than SymPy expressions (no Matrices, dictionaries
10
+ and so on).
11
+ """
12
+
13
+
14
+ import re
15
+ from sympy.core.numbers import (I, NumberSymbol, oo, zoo)
16
+ from sympy.core.symbol import Symbol
17
+ from sympy.utilities.iterables import numbered_symbols
18
+
19
+ # We parse the expression string into a tree that identifies functions. Then
20
+ # we translate the names of the functions and we translate also some strings
21
+ # that are not names of functions (all this according to translation
22
+ # dictionaries).
23
+ # If the translation goes to another module (like numpy) the
24
+ # module is imported and 'func' is translated to 'module.func'.
25
+ # If a function can not be translated, the inner nodes of that part of the
26
+ # tree are not translated. So if we have Integral(sqrt(x)), sqrt is not
27
+ # translated to np.sqrt and the Integral does not crash.
28
+ # A namespace for all this is generated by crawling the (func, args) tree of
29
+ # the expression. The creation of this namespace involves many ugly
30
+ # workarounds.
31
+ # The namespace consists of all the names needed for the SymPy expression and
32
+ # all the name of modules used for translation. Those modules are imported only
33
+ # as a name (import numpy as np) in order to keep the namespace small and
34
+ # manageable.
35
+
36
+ # Please, if there is a bug, do not try to fix it here! Rewrite this by using
37
+ # the method proposed in the last Q'n'A below. That way the new function will
38
+ # work just as well, be just as simple, but it wont need any new workarounds.
39
+ # If you insist on fixing it here, look at the workarounds in the function
40
+ # sympy_expression_namespace and in lambdify.
41
+
42
+ # Q: Why are you not using Python abstract syntax tree?
43
+ # A: Because it is more complicated and not much more powerful in this case.
44
+
45
+ # Q: What if I have Symbol('sin') or g=Function('f')?
46
+ # A: You will break the algorithm. We should use srepr to defend against this?
47
+ # The problem with Symbol('sin') is that it will be printed as 'sin'. The
48
+ # parser will distinguish it from the function 'sin' because functions are
49
+ # detected thanks to the opening parenthesis, but the lambda expression won't
50
+ # understand the difference if we have also the sin function.
51
+ # The solution (complicated) is to use srepr and maybe ast.
52
+ # The problem with the g=Function('f') is that it will be printed as 'f' but in
53
+ # the global namespace we have only 'g'. But as the same printer is used in the
54
+ # constructor of the namespace there will be no problem.
55
+
56
+ # Q: What if some of the printers are not printing as expected?
57
+ # A: The algorithm wont work. You must use srepr for those cases. But even
58
+ # srepr may not print well. All problems with printers should be considered
59
+ # bugs.
60
+
61
+ # Q: What about _imp_ functions?
62
+ # A: Those are taken care for by evalf. A special case treatment will work
63
+ # faster but it's not worth the code complexity.
64
+
65
+ # Q: Will ast fix all possible problems?
66
+ # A: No. You will always have to use some printer. Even srepr may not work in
67
+ # some cases. But if the printer does not work, that should be considered a
68
+ # bug.
69
+
70
+ # Q: Is there same way to fix all possible problems?
71
+ # A: Probably by constructing our strings ourself by traversing the (func,
72
+ # args) tree and creating the namespace at the same time. That actually sounds
73
+ # good.
74
+
75
+ from sympy.external import import_module
76
+ import warnings
77
+
78
+ #TODO debugging output
79
+
80
+
81
+ class vectorized_lambdify:
82
+ """ Return a sufficiently smart, vectorized and lambdified function.
83
+
84
+ Returns only reals.
85
+
86
+ Explanation
87
+ ===========
88
+
89
+ This function uses experimental_lambdify to created a lambdified
90
+ expression ready to be used with numpy. Many of the functions in SymPy
91
+ are not implemented in numpy so in some cases we resort to Python cmath or
92
+ even to evalf.
93
+
94
+ The following translations are tried:
95
+ only numpy complex
96
+ - on errors raised by SymPy trying to work with ndarray:
97
+ only Python cmath and then vectorize complex128
98
+
99
+ When using Python cmath there is no need for evalf or float/complex
100
+ because Python cmath calls those.
101
+
102
+ This function never tries to mix numpy directly with evalf because numpy
103
+ does not understand SymPy Float. If this is needed one can use the
104
+ float_wrap_evalf/complex_wrap_evalf options of experimental_lambdify or
105
+ better one can be explicit about the dtypes that numpy works with.
106
+ Check numpy bug http://projects.scipy.org/numpy/ticket/1013 to know what
107
+ types of errors to expect.
108
+ """
109
+ def __init__(self, args, expr):
110
+ self.args = args
111
+ self.expr = expr
112
+ self.np = import_module('numpy')
113
+
114
+ self.lambda_func_1 = experimental_lambdify(
115
+ args, expr, use_np=True)
116
+ self.vector_func_1 = self.lambda_func_1
117
+
118
+ self.lambda_func_2 = experimental_lambdify(
119
+ args, expr, use_python_cmath=True)
120
+ self.vector_func_2 = self.np.vectorize(
121
+ self.lambda_func_2, otypes=[complex])
122
+
123
+ self.vector_func = self.vector_func_1
124
+ self.failure = False
125
+
126
+ def __call__(self, *args):
127
+ np = self.np
128
+
129
+ try:
130
+ temp_args = (np.array(a, dtype=complex) for a in args)
131
+ results = self.vector_func(*temp_args)
132
+ results = np.ma.masked_where(
133
+ np.abs(results.imag) > 1e-7 * np.abs(results),
134
+ results.real, copy=False)
135
+ return results
136
+ except ValueError:
137
+ if self.failure:
138
+ raise
139
+
140
+ self.failure = True
141
+ self.vector_func = self.vector_func_2
142
+ warnings.warn(
143
+ 'The evaluation of the expression is problematic. '
144
+ 'We are trying a failback method that may still work. '
145
+ 'Please report this as a bug.')
146
+ return self.__call__(*args)
147
+
148
+
149
+ class lambdify:
150
+ """Returns the lambdified function.
151
+
152
+ Explanation
153
+ ===========
154
+
155
+ This function uses experimental_lambdify to create a lambdified
156
+ expression. It uses cmath to lambdify the expression. If the function
157
+ is not implemented in Python cmath, Python cmath calls evalf on those
158
+ functions.
159
+ """
160
+
161
+ def __init__(self, args, expr):
162
+ self.args = args
163
+ self.expr = expr
164
+ self.lambda_func_1 = experimental_lambdify(
165
+ args, expr, use_python_cmath=True, use_evalf=True)
166
+ self.lambda_func_2 = experimental_lambdify(
167
+ args, expr, use_python_math=True, use_evalf=True)
168
+ self.lambda_func_3 = experimental_lambdify(
169
+ args, expr, use_evalf=True, complex_wrap_evalf=True)
170
+ self.lambda_func = self.lambda_func_1
171
+ self.failure = False
172
+
173
+ def __call__(self, args):
174
+ try:
175
+ #The result can be sympy.Float. Hence wrap it with complex type.
176
+ result = complex(self.lambda_func(args))
177
+ if abs(result.imag) > 1e-7 * abs(result):
178
+ return None
179
+ return result.real
180
+ except (ZeroDivisionError, OverflowError):
181
+ return None
182
+ except TypeError as e:
183
+ if self.failure:
184
+ raise e
185
+
186
+ if self.lambda_func == self.lambda_func_1:
187
+ self.lambda_func = self.lambda_func_2
188
+ return self.__call__(args)
189
+
190
+ self.failure = True
191
+ self.lambda_func = self.lambda_func_3
192
+ warnings.warn(
193
+ 'The evaluation of the expression is problematic. '
194
+ 'We are trying a failback method that may still work. '
195
+ 'Please report this as a bug.', stacklevel=2)
196
+ return self.__call__(args)
197
+
198
+
199
+ def experimental_lambdify(*args, **kwargs):
200
+ l = Lambdifier(*args, **kwargs)
201
+ return l
202
+
203
+
204
+ class Lambdifier:
205
+ def __init__(self, args, expr, print_lambda=False, use_evalf=False,
206
+ float_wrap_evalf=False, complex_wrap_evalf=False,
207
+ use_np=False, use_python_math=False, use_python_cmath=False,
208
+ use_interval=False):
209
+
210
+ self.print_lambda = print_lambda
211
+ self.use_evalf = use_evalf
212
+ self.float_wrap_evalf = float_wrap_evalf
213
+ self.complex_wrap_evalf = complex_wrap_evalf
214
+ self.use_np = use_np
215
+ self.use_python_math = use_python_math
216
+ self.use_python_cmath = use_python_cmath
217
+ self.use_interval = use_interval
218
+
219
+ # Constructing the argument string
220
+ # - check
221
+ if not all(isinstance(a, Symbol) for a in args):
222
+ raise ValueError('The arguments must be Symbols.')
223
+ # - use numbered symbols
224
+ syms = numbered_symbols(exclude=expr.free_symbols)
225
+ newargs = [next(syms) for _ in args]
226
+ expr = expr.xreplace(dict(zip(args, newargs)))
227
+ argstr = ', '.join([str(a) for a in newargs])
228
+ del syms, newargs, args
229
+
230
+ # Constructing the translation dictionaries and making the translation
231
+ self.dict_str = self.get_dict_str()
232
+ self.dict_fun = self.get_dict_fun()
233
+ exprstr = str(expr)
234
+ newexpr = self.tree2str_translate(self.str2tree(exprstr))
235
+
236
+ # Constructing the namespaces
237
+ namespace = {}
238
+ namespace.update(self.sympy_atoms_namespace(expr))
239
+ namespace.update(self.sympy_expression_namespace(expr))
240
+ # XXX Workaround
241
+ # Ugly workaround because Pow(a,Half) prints as sqrt(a)
242
+ # and sympy_expression_namespace can not catch it.
243
+ from sympy.functions.elementary.miscellaneous import sqrt
244
+ namespace.update({'sqrt': sqrt})
245
+ namespace.update({'Eq': lambda x, y: x == y})
246
+ namespace.update({'Ne': lambda x, y: x != y})
247
+ # End workaround.
248
+ if use_python_math:
249
+ namespace.update({'math': __import__('math')})
250
+ if use_python_cmath:
251
+ namespace.update({'cmath': __import__('cmath')})
252
+ if use_np:
253
+ try:
254
+ namespace.update({'np': __import__('numpy')})
255
+ except ImportError:
256
+ raise ImportError(
257
+ 'experimental_lambdify failed to import numpy.')
258
+ if use_interval:
259
+ namespace.update({'imath': __import__(
260
+ 'sympy.plotting.intervalmath', fromlist=['intervalmath'])})
261
+ namespace.update({'math': __import__('math')})
262
+
263
+ # Construct the lambda
264
+ if self.print_lambda:
265
+ print(newexpr)
266
+ eval_str = 'lambda %s : ( %s )' % (argstr, newexpr)
267
+ self.eval_str = eval_str
268
+ exec("MYNEWLAMBDA = %s" % eval_str, namespace)
269
+ self.lambda_func = namespace['MYNEWLAMBDA']
270
+
271
+ def __call__(self, *args, **kwargs):
272
+ return self.lambda_func(*args, **kwargs)
273
+
274
+
275
+ ##############################################################################
276
+ # Dicts for translating from SymPy to other modules
277
+ ##############################################################################
278
+ ###
279
+ # builtins
280
+ ###
281
+ # Functions with different names in builtins
282
+ builtin_functions_different = {
283
+ 'Min': 'min',
284
+ 'Max': 'max',
285
+ 'Abs': 'abs',
286
+ }
287
+
288
+ # Strings that should be translated
289
+ builtin_not_functions = {
290
+ 'I': '1j',
291
+ # 'oo': '1e400',
292
+ }
293
+
294
+ ###
295
+ # numpy
296
+ ###
297
+
298
+ # Functions that are the same in numpy
299
+ numpy_functions_same = [
300
+ 'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'exp', 'log',
301
+ 'sqrt', 'floor', 'conjugate',
302
+ ]
303
+
304
+ # Functions with different names in numpy
305
+ numpy_functions_different = {
306
+ "acos": "arccos",
307
+ "acosh": "arccosh",
308
+ "arg": "angle",
309
+ "asin": "arcsin",
310
+ "asinh": "arcsinh",
311
+ "atan": "arctan",
312
+ "atan2": "arctan2",
313
+ "atanh": "arctanh",
314
+ "ceiling": "ceil",
315
+ "im": "imag",
316
+ "ln": "log",
317
+ "Max": "amax",
318
+ "Min": "amin",
319
+ "re": "real",
320
+ "Abs": "abs",
321
+ }
322
+
323
+ # Strings that should be translated
324
+ numpy_not_functions = {
325
+ 'pi': 'np.pi',
326
+ 'oo': 'np.inf',
327
+ 'E': 'np.e',
328
+ }
329
+
330
+ ###
331
+ # Python math
332
+ ###
333
+
334
+ # Functions that are the same in math
335
+ math_functions_same = [
336
+ 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2',
337
+ 'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh',
338
+ 'exp', 'log', 'erf', 'sqrt', 'floor', 'factorial', 'gamma',
339
+ ]
340
+
341
+ # Functions with different names in math
342
+ math_functions_different = {
343
+ 'ceiling': 'ceil',
344
+ 'ln': 'log',
345
+ 'loggamma': 'lgamma'
346
+ }
347
+
348
+ # Strings that should be translated
349
+ math_not_functions = {
350
+ 'pi': 'math.pi',
351
+ 'E': 'math.e',
352
+ }
353
+
354
+ ###
355
+ # Python cmath
356
+ ###
357
+
358
+ # Functions that are the same in cmath
359
+ cmath_functions_same = [
360
+ 'sin', 'cos', 'tan', 'asin', 'acos', 'atan',
361
+ 'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh',
362
+ 'exp', 'log', 'sqrt',
363
+ ]
364
+
365
+ # Functions with different names in cmath
366
+ cmath_functions_different = {
367
+ 'ln': 'log',
368
+ 'arg': 'phase',
369
+ }
370
+
371
+ # Strings that should be translated
372
+ cmath_not_functions = {
373
+ 'pi': 'cmath.pi',
374
+ 'E': 'cmath.e',
375
+ }
376
+
377
+ ###
378
+ # intervalmath
379
+ ###
380
+
381
+ interval_not_functions = {
382
+ 'pi': 'math.pi',
383
+ 'E': 'math.e'
384
+ }
385
+
386
+ interval_functions_same = [
387
+ 'sin', 'cos', 'exp', 'tan', 'atan', 'log',
388
+ 'sqrt', 'cosh', 'sinh', 'tanh', 'floor',
389
+ 'acos', 'asin', 'acosh', 'asinh', 'atanh',
390
+ 'Abs', 'And', 'Or'
391
+ ]
392
+
393
+ interval_functions_different = {
394
+ 'Min': 'imin',
395
+ 'Max': 'imax',
396
+ 'ceiling': 'ceil',
397
+
398
+ }
399
+
400
+ ###
401
+ # mpmath, etc
402
+ ###
403
+ #TODO
404
+
405
+ ###
406
+ # Create the final ordered tuples of dictionaries
407
+ ###
408
+
409
+ # For strings
410
+ def get_dict_str(self):
411
+ dict_str = dict(self.builtin_not_functions)
412
+ if self.use_np:
413
+ dict_str.update(self.numpy_not_functions)
414
+ if self.use_python_math:
415
+ dict_str.update(self.math_not_functions)
416
+ if self.use_python_cmath:
417
+ dict_str.update(self.cmath_not_functions)
418
+ if self.use_interval:
419
+ dict_str.update(self.interval_not_functions)
420
+ return dict_str
421
+
422
+ # For functions
423
+ def get_dict_fun(self):
424
+ dict_fun = dict(self.builtin_functions_different)
425
+ if self.use_np:
426
+ for s in self.numpy_functions_same:
427
+ dict_fun[s] = 'np.' + s
428
+ for k, v in self.numpy_functions_different.items():
429
+ dict_fun[k] = 'np.' + v
430
+ if self.use_python_math:
431
+ for s in self.math_functions_same:
432
+ dict_fun[s] = 'math.' + s
433
+ for k, v in self.math_functions_different.items():
434
+ dict_fun[k] = 'math.' + v
435
+ if self.use_python_cmath:
436
+ for s in self.cmath_functions_same:
437
+ dict_fun[s] = 'cmath.' + s
438
+ for k, v in self.cmath_functions_different.items():
439
+ dict_fun[k] = 'cmath.' + v
440
+ if self.use_interval:
441
+ for s in self.interval_functions_same:
442
+ dict_fun[s] = 'imath.' + s
443
+ for k, v in self.interval_functions_different.items():
444
+ dict_fun[k] = 'imath.' + v
445
+ return dict_fun
446
+
447
+ ##############################################################################
448
+ # The translator functions, tree parsers, etc.
449
+ ##############################################################################
450
+
451
+ def str2tree(self, exprstr):
452
+ """Converts an expression string to a tree.
453
+
454
+ Explanation
455
+ ===========
456
+
457
+ Functions are represented by ('func_name(', tree_of_arguments).
458
+ Other expressions are (head_string, mid_tree, tail_str).
459
+ Expressions that do not contain functions are directly returned.
460
+
461
+ Examples
462
+ ========
463
+
464
+ >>> from sympy.abc import x, y, z
465
+ >>> from sympy import Integral, sin
466
+ >>> from sympy.plotting.experimental_lambdify import Lambdifier
467
+ >>> str2tree = Lambdifier([x], x).str2tree
468
+
469
+ >>> str2tree(str(Integral(x, (x, 1, y))))
470
+ ('', ('Integral(', 'x, (x, 1, y)'), ')')
471
+ >>> str2tree(str(x+y))
472
+ 'x + y'
473
+ >>> str2tree(str(x+y*sin(z)+1))
474
+ ('x + y*', ('sin(', 'z'), ') + 1')
475
+ >>> str2tree('sin(y*(y + 1.1) + (sin(y)))')
476
+ ('', ('sin(', ('y*(y + 1.1) + (', ('sin(', 'y'), '))')), ')')
477
+ """
478
+ #matches the first 'function_name('
479
+ first_par = re.search(r'(\w+\()', exprstr)
480
+ if first_par is None:
481
+ return exprstr
482
+ else:
483
+ start = first_par.start()
484
+ end = first_par.end()
485
+ head = exprstr[:start]
486
+ func = exprstr[start:end]
487
+ tail = exprstr[end:]
488
+ count = 0
489
+ for i, c in enumerate(tail):
490
+ if c == '(':
491
+ count += 1
492
+ elif c == ')':
493
+ count -= 1
494
+ if count == -1:
495
+ break
496
+ func_tail = self.str2tree(tail[:i])
497
+ tail = self.str2tree(tail[i:])
498
+ return (head, (func, func_tail), tail)
499
+
500
+ @classmethod
501
+ def tree2str(cls, tree):
502
+ """Converts a tree to string without translations.
503
+
504
+ Examples
505
+ ========
506
+
507
+ >>> from sympy.abc import x, y, z
508
+ >>> from sympy import sin
509
+ >>> from sympy.plotting.experimental_lambdify import Lambdifier
510
+ >>> str2tree = Lambdifier([x], x).str2tree
511
+ >>> tree2str = Lambdifier([x], x).tree2str
512
+
513
+ >>> tree2str(str2tree(str(x+y*sin(z)+1)))
514
+ 'x + y*sin(z) + 1'
515
+ """
516
+ if isinstance(tree, str):
517
+ return tree
518
+ else:
519
+ return ''.join(map(cls.tree2str, tree))
520
+
521
+ def tree2str_translate(self, tree):
522
+ """Converts a tree to string with translations.
523
+
524
+ Explanation
525
+ ===========
526
+
527
+ Function names are translated by translate_func.
528
+ Other strings are translated by translate_str.
529
+ """
530
+ if isinstance(tree, str):
531
+ return self.translate_str(tree)
532
+ elif isinstance(tree, tuple) and len(tree) == 2:
533
+ return self.translate_func(tree[0][:-1], tree[1])
534
+ else:
535
+ return ''.join([self.tree2str_translate(t) for t in tree])
536
+
537
+ def translate_str(self, estr):
538
+ """Translate substrings of estr using in order the dictionaries in
539
+ dict_tuple_str."""
540
+ for pattern, repl in self.dict_str.items():
541
+ estr = re.sub(pattern, repl, estr)
542
+ return estr
543
+
544
+ def translate_func(self, func_name, argtree):
545
+ """Translate function names and the tree of arguments.
546
+
547
+ Explanation
548
+ ===========
549
+
550
+ If the function name is not in the dictionaries of dict_tuple_fun then the
551
+ function is surrounded by a float((...).evalf()).
552
+
553
+ The use of float is necessary as np.<function>(sympy.Float(..)) raises an
554
+ error."""
555
+ if func_name in self.dict_fun:
556
+ new_name = self.dict_fun[func_name]
557
+ argstr = self.tree2str_translate(argtree)
558
+ return new_name + '(' + argstr
559
+ elif func_name in ['Eq', 'Ne']:
560
+ op = {'Eq': '==', 'Ne': '!='}
561
+ return "(lambda x, y: x {} y)({}".format(op[func_name], self.tree2str_translate(argtree))
562
+ else:
563
+ template = '(%s(%s)).evalf(' if self.use_evalf else '%s(%s'
564
+ if self.float_wrap_evalf:
565
+ template = 'float(%s)' % template
566
+ elif self.complex_wrap_evalf:
567
+ template = 'complex(%s)' % template
568
+
569
+ # Wrapping should only happen on the outermost expression, which
570
+ # is the only thing we know will be a number.
571
+ float_wrap_evalf = self.float_wrap_evalf
572
+ complex_wrap_evalf = self.complex_wrap_evalf
573
+ self.float_wrap_evalf = False
574
+ self.complex_wrap_evalf = False
575
+ ret = template % (func_name, self.tree2str_translate(argtree))
576
+ self.float_wrap_evalf = float_wrap_evalf
577
+ self.complex_wrap_evalf = complex_wrap_evalf
578
+ return ret
579
+
580
+ ##############################################################################
581
+ # The namespace constructors
582
+ ##############################################################################
583
+
584
+ @classmethod
585
+ def sympy_expression_namespace(cls, expr):
586
+ """Traverses the (func, args) tree of an expression and creates a SymPy
587
+ namespace. All other modules are imported only as a module name. That way
588
+ the namespace is not polluted and rests quite small. It probably causes much
589
+ more variable lookups and so it takes more time, but there are no tests on
590
+ that for the moment."""
591
+ if expr is None:
592
+ return {}
593
+ else:
594
+ funcname = str(expr.func)
595
+ # XXX Workaround
596
+ # Here we add an ugly workaround because str(func(x))
597
+ # is not always the same as str(func). Eg
598
+ # >>> str(Integral(x))
599
+ # "Integral(x)"
600
+ # >>> str(Integral)
601
+ # "<class 'sympy.integrals.integrals.Integral'>"
602
+ # >>> str(sqrt(x))
603
+ # "sqrt(x)"
604
+ # >>> str(sqrt)
605
+ # "<function sqrt at 0x3d92de8>"
606
+ # >>> str(sin(x))
607
+ # "sin(x)"
608
+ # >>> str(sin)
609
+ # "sin"
610
+ # Either one of those can be used but not all at the same time.
611
+ # The code considers the sin example as the right one.
612
+ regexlist = [
613
+ r'<class \'sympy[\w.]*?.([\w]*)\'>$',
614
+ # the example Integral
615
+ r'<function ([\w]*) at 0x[\w]*>$', # the example sqrt
616
+ ]
617
+ for r in regexlist:
618
+ m = re.match(r, funcname)
619
+ if m is not None:
620
+ funcname = m.groups()[0]
621
+ # End of the workaround
622
+ # XXX debug: print funcname
623
+ args_dict = {}
624
+ for a in expr.args:
625
+ if (isinstance(a, Symbol) or
626
+ isinstance(a, NumberSymbol) or
627
+ a in [I, zoo, oo]):
628
+ continue
629
+ else:
630
+ args_dict.update(cls.sympy_expression_namespace(a))
631
+ args_dict.update({funcname: expr.func})
632
+ return args_dict
633
+
634
+ @staticmethod
635
+ def sympy_atoms_namespace(expr):
636
+ """For no real reason this function is separated from
637
+ sympy_expression_namespace. It can be moved to it."""
638
+ atoms = expr.atoms(Symbol, NumberSymbol, I, zoo, oo)
639
+ d = {}
640
+ for a in atoms:
641
+ # XXX debug: print 'atom:' + str(a)
642
+ d[str(a)] = a
643
+ return d
venv/lib/python3.10/site-packages/sympy/plotting/plot.py ADDED
@@ -0,0 +1,2637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plotting module for SymPy.
2
+
3
+ A plot is represented by the ``Plot`` class that contains a reference to the
4
+ backend and a list of the data series to be plotted. The data series are
5
+ instances of classes meant to simplify getting points and meshes from SymPy
6
+ expressions. ``plot_backends`` is a dictionary with all the backends.
7
+
8
+ This module gives only the essential. For all the fancy stuff use directly
9
+ the backend. You can get the backend wrapper for every plot from the
10
+ ``_backend`` attribute. Moreover the data series classes have various useful
11
+ methods like ``get_points``, ``get_meshes``, etc, that may
12
+ be useful if you wish to use another plotting library.
13
+
14
+ Especially if you need publication ready graphs and this module is not enough
15
+ for you - just get the ``_backend`` attribute and add whatever you want
16
+ directly to it. In the case of matplotlib (the common way to graph data in
17
+ python) just copy ``_backend.fig`` which is the figure and ``_backend.ax``
18
+ which is the axis and work on them as you would on any other matplotlib object.
19
+
20
+ Simplicity of code takes much greater importance than performance. Do not use it
21
+ if you care at all about performance. A new backend instance is initialized
22
+ every time you call ``show()`` and the old one is left to the garbage collector.
23
+ """
24
+
25
+
26
+ from collections.abc import Callable
27
+
28
+
29
+ from sympy.core.basic import Basic
30
+ from sympy.core.containers import Tuple
31
+ from sympy.core.expr import Expr
32
+ from sympy.core.function import arity, Function
33
+ from sympy.core.symbol import (Dummy, Symbol)
34
+ from sympy.core.sympify import sympify
35
+ from sympy.external import import_module
36
+ from sympy.printing.latex import latex
37
+ from sympy.utilities.exceptions import sympy_deprecation_warning
38
+ from sympy.utilities.iterables import is_sequence
39
+ from .experimental_lambdify import (vectorized_lambdify, lambdify)
40
+
41
+ # N.B.
42
+ # When changing the minimum module version for matplotlib, please change
43
+ # the same in the `SymPyDocTestFinder`` in `sympy/testing/runtests.py`
44
+
45
+ # Backend specific imports - textplot
46
+ from sympy.plotting.textplot import textplot
47
+
48
+ # Global variable
49
+ # Set to False when running tests / doctests so that the plots don't show.
50
+ _show = True
51
+
52
+
53
+ def unset_show():
54
+ """
55
+ Disable show(). For use in the tests.
56
+ """
57
+ global _show
58
+ _show = False
59
+
60
+ def _str_or_latex(label):
61
+ if isinstance(label, Basic):
62
+ return latex(label, mode='inline')
63
+ return str(label)
64
+
65
+ ##############################################################################
66
+ # The public interface
67
+ ##############################################################################
68
+
69
+
70
+ class Plot:
71
+ """The central class of the plotting module.
72
+
73
+ Explanation
74
+ ===========
75
+
76
+ For interactive work the function :func:`plot()` is better suited.
77
+
78
+ This class permits the plotting of SymPy expressions using numerous
79
+ backends (:external:mod:`matplotlib`, textplot, the old pyglet module for SymPy, Google
80
+ charts api, etc).
81
+
82
+ The figure can contain an arbitrary number of plots of SymPy expressions,
83
+ lists of coordinates of points, etc. Plot has a private attribute _series that
84
+ contains all data series to be plotted (expressions for lines or surfaces,
85
+ lists of points, etc (all subclasses of BaseSeries)). Those data series are
86
+ instances of classes not imported by ``from sympy import *``.
87
+
88
+ The customization of the figure is on two levels. Global options that
89
+ concern the figure as a whole (e.g. title, xlabel, scale, etc) and
90
+ per-data series options (e.g. name) and aesthetics (e.g. color, point shape,
91
+ line type, etc.).
92
+
93
+ The difference between options and aesthetics is that an aesthetic can be
94
+ a function of the coordinates (or parameters in a parametric plot). The
95
+ supported values for an aesthetic are:
96
+
97
+ - None (the backend uses default values)
98
+ - a constant
99
+ - a function of one variable (the first coordinate or parameter)
100
+ - a function of two variables (the first and second coordinate or parameters)
101
+ - a function of three variables (only in nonparametric 3D plots)
102
+
103
+ Their implementation depends on the backend so they may not work in some
104
+ backends.
105
+
106
+ If the plot is parametric and the arity of the aesthetic function permits
107
+ it the aesthetic is calculated over parameters and not over coordinates.
108
+ If the arity does not permit calculation over parameters the calculation is
109
+ done over coordinates.
110
+
111
+ Only cartesian coordinates are supported for the moment, but you can use
112
+ the parametric plots to plot in polar, spherical and cylindrical
113
+ coordinates.
114
+
115
+ The arguments for the constructor Plot must be subclasses of BaseSeries.
116
+
117
+ Any global option can be specified as a keyword argument.
118
+
119
+ The global options for a figure are:
120
+
121
+ - title : str
122
+ - xlabel : str or Symbol
123
+ - ylabel : str or Symbol
124
+ - zlabel : str or Symbol
125
+ - legend : bool
126
+ - xscale : {'linear', 'log'}
127
+ - yscale : {'linear', 'log'}
128
+ - axis : bool
129
+ - axis_center : tuple of two floats or {'center', 'auto'}
130
+ - xlim : tuple of two floats
131
+ - ylim : tuple of two floats
132
+ - aspect_ratio : tuple of two floats or {'auto'}
133
+ - autoscale : bool
134
+ - margin : float in [0, 1]
135
+ - backend : {'default', 'matplotlib', 'text'} or a subclass of BaseBackend
136
+ - size : optional tuple of two floats, (width, height); default: None
137
+
138
+ The per data series options and aesthetics are:
139
+ There are none in the base series. See below for options for subclasses.
140
+
141
+ Some data series support additional aesthetics or options:
142
+
143
+ :class:`~.LineOver1DRangeSeries`, :class:`~.Parametric2DLineSeries`, and
144
+ :class:`~.Parametric3DLineSeries` support the following:
145
+
146
+ Aesthetics:
147
+
148
+ - line_color : string, or float, or function, optional
149
+ Specifies the color for the plot, which depends on the backend being
150
+ used.
151
+
152
+ For example, if ``MatplotlibBackend`` is being used, then
153
+ Matplotlib string colors are acceptable (``"red"``, ``"r"``,
154
+ ``"cyan"``, ``"c"``, ...).
155
+ Alternatively, we can use a float number, 0 < color < 1, wrapped in a
156
+ string (for example, ``line_color="0.5"``) to specify grayscale colors.
157
+ Alternatively, We can specify a function returning a single
158
+ float value: this will be used to apply a color-loop (for example,
159
+ ``line_color=lambda x: math.cos(x)``).
160
+
161
+ Note that by setting line_color, it would be applied simultaneously
162
+ to all the series.
163
+
164
+ Options:
165
+
166
+ - label : str
167
+ - steps : bool
168
+ - integers_only : bool
169
+
170
+ :class:`~.SurfaceOver2DRangeSeries` and :class:`~.ParametricSurfaceSeries`
171
+ support the following:
172
+
173
+ Aesthetics:
174
+
175
+ - surface_color : function which returns a float.
176
+ """
177
+
178
+ def __init__(self, *args,
179
+ title=None, xlabel=None, ylabel=None, zlabel=None, aspect_ratio='auto',
180
+ xlim=None, ylim=None, axis_center='auto', axis=True,
181
+ xscale='linear', yscale='linear', legend=False, autoscale=True,
182
+ margin=0, annotations=None, markers=None, rectangles=None,
183
+ fill=None, backend='default', size=None, **kwargs):
184
+ super().__init__()
185
+
186
+ # Options for the graph as a whole.
187
+ # The possible values for each option are described in the docstring of
188
+ # Plot. They are based purely on convention, no checking is done.
189
+ self.title = title
190
+ self.xlabel = xlabel
191
+ self.ylabel = ylabel
192
+ self.zlabel = zlabel
193
+ self.aspect_ratio = aspect_ratio
194
+ self.axis_center = axis_center
195
+ self.axis = axis
196
+ self.xscale = xscale
197
+ self.yscale = yscale
198
+ self.legend = legend
199
+ self.autoscale = autoscale
200
+ self.margin = margin
201
+ self.annotations = annotations
202
+ self.markers = markers
203
+ self.rectangles = rectangles
204
+ self.fill = fill
205
+
206
+ # Contains the data objects to be plotted. The backend should be smart
207
+ # enough to iterate over this list.
208
+ self._series = []
209
+ self._series.extend(args)
210
+
211
+ # The backend type. On every show() a new backend instance is created
212
+ # in self._backend which is tightly coupled to the Plot instance
213
+ # (thanks to the parent attribute of the backend).
214
+ if isinstance(backend, str):
215
+ self.backend = plot_backends[backend]
216
+ elif (type(backend) == type) and issubclass(backend, BaseBackend):
217
+ self.backend = backend
218
+ else:
219
+ raise TypeError(
220
+ "backend must be either a string or a subclass of BaseBackend")
221
+
222
+ is_real = \
223
+ lambda lim: all(getattr(i, 'is_real', True) for i in lim)
224
+ is_finite = \
225
+ lambda lim: all(getattr(i, 'is_finite', True) for i in lim)
226
+
227
+ # reduce code repetition
228
+ def check_and_set(t_name, t):
229
+ if t:
230
+ if not is_real(t):
231
+ raise ValueError(
232
+ "All numbers from {}={} must be real".format(t_name, t))
233
+ if not is_finite(t):
234
+ raise ValueError(
235
+ "All numbers from {}={} must be finite".format(t_name, t))
236
+ setattr(self, t_name, (float(t[0]), float(t[1])))
237
+
238
+ self.xlim = None
239
+ check_and_set("xlim", xlim)
240
+ self.ylim = None
241
+ check_and_set("ylim", ylim)
242
+ self.size = None
243
+ check_and_set("size", size)
244
+
245
+
246
+ def show(self):
247
+ # TODO move this to the backend (also for save)
248
+ if hasattr(self, '_backend'):
249
+ self._backend.close()
250
+ self._backend = self.backend(self)
251
+ self._backend.show()
252
+
253
+ def save(self, path):
254
+ if hasattr(self, '_backend'):
255
+ self._backend.close()
256
+ self._backend = self.backend(self)
257
+ self._backend.save(path)
258
+
259
+ def __str__(self):
260
+ series_strs = [('[%d]: ' % i) + str(s)
261
+ for i, s in enumerate(self._series)]
262
+ return 'Plot object containing:\n' + '\n'.join(series_strs)
263
+
264
+ def __getitem__(self, index):
265
+ return self._series[index]
266
+
267
+ def __setitem__(self, index, *args):
268
+ if len(args) == 1 and isinstance(args[0], BaseSeries):
269
+ self._series[index] = args
270
+
271
+ def __delitem__(self, index):
272
+ del self._series[index]
273
+
274
+ def append(self, arg):
275
+ """Adds an element from a plot's series to an existing plot.
276
+
277
+ Examples
278
+ ========
279
+
280
+ Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the
281
+ second plot's first series object to the first, use the
282
+ ``append`` method, like so:
283
+
284
+ .. plot::
285
+ :format: doctest
286
+ :include-source: True
287
+
288
+ >>> from sympy import symbols
289
+ >>> from sympy.plotting import plot
290
+ >>> x = symbols('x')
291
+ >>> p1 = plot(x*x, show=False)
292
+ >>> p2 = plot(x, show=False)
293
+ >>> p1.append(p2[0])
294
+ >>> p1
295
+ Plot object containing:
296
+ [0]: cartesian line: x**2 for x over (-10.0, 10.0)
297
+ [1]: cartesian line: x for x over (-10.0, 10.0)
298
+ >>> p1.show()
299
+
300
+ See Also
301
+ ========
302
+
303
+ extend
304
+
305
+ """
306
+ if isinstance(arg, BaseSeries):
307
+ self._series.append(arg)
308
+ else:
309
+ raise TypeError('Must specify element of plot to append.')
310
+
311
+ def extend(self, arg):
312
+ """Adds all series from another plot.
313
+
314
+ Examples
315
+ ========
316
+
317
+ Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the
318
+ second plot to the first, use the ``extend`` method, like so:
319
+
320
+ .. plot::
321
+ :format: doctest
322
+ :include-source: True
323
+
324
+ >>> from sympy import symbols
325
+ >>> from sympy.plotting import plot
326
+ >>> x = symbols('x')
327
+ >>> p1 = plot(x**2, show=False)
328
+ >>> p2 = plot(x, -x, show=False)
329
+ >>> p1.extend(p2)
330
+ >>> p1
331
+ Plot object containing:
332
+ [0]: cartesian line: x**2 for x over (-10.0, 10.0)
333
+ [1]: cartesian line: x for x over (-10.0, 10.0)
334
+ [2]: cartesian line: -x for x over (-10.0, 10.0)
335
+ >>> p1.show()
336
+
337
+ """
338
+ if isinstance(arg, Plot):
339
+ self._series.extend(arg._series)
340
+ elif is_sequence(arg):
341
+ self._series.extend(arg)
342
+ else:
343
+ raise TypeError('Expecting Plot or sequence of BaseSeries')
344
+
345
+
346
+ class PlotGrid:
347
+ """This class helps to plot subplots from already created SymPy plots
348
+ in a single figure.
349
+
350
+ Examples
351
+ ========
352
+
353
+ .. plot::
354
+ :context: close-figs
355
+ :format: doctest
356
+ :include-source: True
357
+
358
+ >>> from sympy import symbols
359
+ >>> from sympy.plotting import plot, plot3d, PlotGrid
360
+ >>> x, y = symbols('x, y')
361
+ >>> p1 = plot(x, x**2, x**3, (x, -5, 5))
362
+ >>> p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
363
+ >>> p3 = plot(x**3, (x, -5, 5))
364
+ >>> p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))
365
+
366
+ Plotting vertically in a single line:
367
+
368
+ .. plot::
369
+ :context: close-figs
370
+ :format: doctest
371
+ :include-source: True
372
+
373
+ >>> PlotGrid(2, 1, p1, p2)
374
+ PlotGrid object containing:
375
+ Plot[0]:Plot object containing:
376
+ [0]: cartesian line: x for x over (-5.0, 5.0)
377
+ [1]: cartesian line: x**2 for x over (-5.0, 5.0)
378
+ [2]: cartesian line: x**3 for x over (-5.0, 5.0)
379
+ Plot[1]:Plot object containing:
380
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
381
+ [1]: cartesian line: x for x over (-5.0, 5.0)
382
+
383
+ Plotting horizontally in a single line:
384
+
385
+ .. plot::
386
+ :context: close-figs
387
+ :format: doctest
388
+ :include-source: True
389
+
390
+ >>> PlotGrid(1, 3, p2, p3, p4)
391
+ PlotGrid object containing:
392
+ Plot[0]:Plot object containing:
393
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
394
+ [1]: cartesian line: x for x over (-5.0, 5.0)
395
+ Plot[1]:Plot object containing:
396
+ [0]: cartesian line: x**3 for x over (-5.0, 5.0)
397
+ Plot[2]:Plot object containing:
398
+ [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
399
+
400
+ Plotting in a grid form:
401
+
402
+ .. plot::
403
+ :context: close-figs
404
+ :format: doctest
405
+ :include-source: True
406
+
407
+ >>> PlotGrid(2, 2, p1, p2, p3, p4)
408
+ PlotGrid object containing:
409
+ Plot[0]:Plot object containing:
410
+ [0]: cartesian line: x for x over (-5.0, 5.0)
411
+ [1]: cartesian line: x**2 for x over (-5.0, 5.0)
412
+ [2]: cartesian line: x**3 for x over (-5.0, 5.0)
413
+ Plot[1]:Plot object containing:
414
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
415
+ [1]: cartesian line: x for x over (-5.0, 5.0)
416
+ Plot[2]:Plot object containing:
417
+ [0]: cartesian line: x**3 for x over (-5.0, 5.0)
418
+ Plot[3]:Plot object containing:
419
+ [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
420
+
421
+ """
422
+ def __init__(self, nrows, ncolumns, *args, show=True, size=None, **kwargs):
423
+ """
424
+ Parameters
425
+ ==========
426
+
427
+ nrows :
428
+ The number of rows that should be in the grid of the
429
+ required subplot.
430
+ ncolumns :
431
+ The number of columns that should be in the grid
432
+ of the required subplot.
433
+
434
+ nrows and ncolumns together define the required grid.
435
+
436
+ Arguments
437
+ =========
438
+
439
+ A list of predefined plot objects entered in a row-wise sequence
440
+ i.e. plot objects which are to be in the top row of the required
441
+ grid are written first, then the second row objects and so on
442
+
443
+ Keyword arguments
444
+ =================
445
+
446
+ show : Boolean
447
+ The default value is set to ``True``. Set show to ``False`` and
448
+ the function will not display the subplot. The returned instance
449
+ of the ``PlotGrid`` class can then be used to save or display the
450
+ plot by calling the ``save()`` and ``show()`` methods
451
+ respectively.
452
+ size : (float, float), optional
453
+ A tuple in the form (width, height) in inches to specify the size of
454
+ the overall figure. The default value is set to ``None``, meaning
455
+ the size will be set by the default backend.
456
+ """
457
+ self.nrows = nrows
458
+ self.ncolumns = ncolumns
459
+ self._series = []
460
+ self.args = args
461
+ for arg in args:
462
+ self._series.append(arg._series)
463
+ self.backend = DefaultBackend
464
+ self.size = size
465
+ if show:
466
+ self.show()
467
+
468
+ def show(self):
469
+ if hasattr(self, '_backend'):
470
+ self._backend.close()
471
+ self._backend = self.backend(self)
472
+ self._backend.show()
473
+
474
+ def save(self, path):
475
+ if hasattr(self, '_backend'):
476
+ self._backend.close()
477
+ self._backend = self.backend(self)
478
+ self._backend.save(path)
479
+
480
+ def __str__(self):
481
+ plot_strs = [('Plot[%d]:' % i) + str(plot)
482
+ for i, plot in enumerate(self.args)]
483
+
484
+ return 'PlotGrid object containing:\n' + '\n'.join(plot_strs)
485
+
486
+
487
+ ##############################################################################
488
+ # Data Series
489
+ ##############################################################################
490
+ #TODO more general way to calculate aesthetics (see get_color_array)
491
+
492
+ ### The base class for all series
493
+ class BaseSeries:
494
+ """Base class for the data objects containing stuff to be plotted.
495
+
496
+ Explanation
497
+ ===========
498
+
499
+ The backend should check if it supports the data series that is given.
500
+ (e.g. TextBackend supports only LineOver1DRangeSeries).
501
+ It is the backend responsibility to know how to use the class of
502
+ data series that is given.
503
+
504
+ Some data series classes are grouped (using a class attribute like is_2Dline)
505
+ according to the api they present (based only on convention). The backend is
506
+ not obliged to use that api (e.g. LineOver1DRangeSeries belongs to the
507
+ is_2Dline group and presents the get_points method, but the
508
+ TextBackend does not use the get_points method).
509
+ """
510
+
511
+ # Some flags follow. The rationale for using flags instead of checking base
512
+ # classes is that setting multiple flags is simpler than multiple
513
+ # inheritance.
514
+
515
+ is_2Dline = False
516
+ # Some of the backends expect:
517
+ # - get_points returning 1D np.arrays list_x, list_y
518
+ # - get_color_array returning 1D np.array (done in Line2DBaseSeries)
519
+ # with the colors calculated at the points from get_points
520
+
521
+ is_3Dline = False
522
+ # Some of the backends expect:
523
+ # - get_points returning 1D np.arrays list_x, list_y, list_y
524
+ # - get_color_array returning 1D np.array (done in Line2DBaseSeries)
525
+ # with the colors calculated at the points from get_points
526
+
527
+ is_3Dsurface = False
528
+ # Some of the backends expect:
529
+ # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays)
530
+ # - get_points an alias for get_meshes
531
+
532
+ is_contour = False
533
+ # Some of the backends expect:
534
+ # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays)
535
+ # - get_points an alias for get_meshes
536
+
537
+ is_implicit = False
538
+ # Some of the backends expect:
539
+ # - get_meshes returning mesh_x (1D array), mesh_y(1D array,
540
+ # mesh_z (2D np.arrays)
541
+ # - get_points an alias for get_meshes
542
+ # Different from is_contour as the colormap in backend will be
543
+ # different
544
+
545
+ is_parametric = False
546
+ # The calculation of aesthetics expects:
547
+ # - get_parameter_points returning one or two np.arrays (1D or 2D)
548
+ # used for calculation aesthetics
549
+
550
+ def __init__(self):
551
+ super().__init__()
552
+
553
+ @property
554
+ def is_3D(self):
555
+ flags3D = [
556
+ self.is_3Dline,
557
+ self.is_3Dsurface
558
+ ]
559
+ return any(flags3D)
560
+
561
+ @property
562
+ def is_line(self):
563
+ flagslines = [
564
+ self.is_2Dline,
565
+ self.is_3Dline
566
+ ]
567
+ return any(flagslines)
568
+
569
+
570
+ ### 2D lines
571
+ class Line2DBaseSeries(BaseSeries):
572
+ """A base class for 2D lines.
573
+
574
+ - adding the label, steps and only_integers options
575
+ - making is_2Dline true
576
+ - defining get_segments and get_color_array
577
+ """
578
+
579
+ is_2Dline = True
580
+
581
+ _dim = 2
582
+
583
+ def __init__(self):
584
+ super().__init__()
585
+ self.label = None
586
+ self.steps = False
587
+ self.only_integers = False
588
+ self.line_color = None
589
+
590
+ def get_data(self):
591
+ """ Return lists of coordinates for plotting the line.
592
+
593
+ Returns
594
+ =======
595
+ x : list
596
+ List of x-coordinates
597
+
598
+ y : list
599
+ List of y-coordinates
600
+
601
+ z : list
602
+ List of z-coordinates in case of Parametric3DLineSeries
603
+ """
604
+ np = import_module('numpy')
605
+ points = self.get_points()
606
+ if self.steps is True:
607
+ if len(points) == 2:
608
+ x = np.array((points[0], points[0])).T.flatten()[1:]
609
+ y = np.array((points[1], points[1])).T.flatten()[:-1]
610
+ points = (x, y)
611
+ else:
612
+ x = np.repeat(points[0], 3)[2:]
613
+ y = np.repeat(points[1], 3)[:-2]
614
+ z = np.repeat(points[2], 3)[1:-1]
615
+ points = (x, y, z)
616
+ return points
617
+
618
+ def get_segments(self):
619
+ sympy_deprecation_warning(
620
+ """
621
+ The Line2DBaseSeries.get_segments() method is deprecated.
622
+
623
+ Instead, use the MatplotlibBackend.get_segments() method, or use
624
+ The get_points() or get_data() methods.
625
+ """,
626
+ deprecated_since_version="1.9",
627
+ active_deprecations_target="deprecated-get-segments")
628
+
629
+ np = import_module('numpy')
630
+ points = type(self).get_data(self)
631
+ points = np.ma.array(points).T.reshape(-1, 1, self._dim)
632
+ return np.ma.concatenate([points[:-1], points[1:]], axis=1)
633
+
634
+ def get_color_array(self):
635
+ np = import_module('numpy')
636
+ c = self.line_color
637
+ if hasattr(c, '__call__'):
638
+ f = np.vectorize(c)
639
+ nargs = arity(c)
640
+ if nargs == 1 and self.is_parametric:
641
+ x = self.get_parameter_points()
642
+ return f(centers_of_segments(x))
643
+ else:
644
+ variables = list(map(centers_of_segments, self.get_points()))
645
+ if nargs == 1:
646
+ return f(variables[0])
647
+ elif nargs == 2:
648
+ return f(*variables[:2])
649
+ else: # only if the line is 3D (otherwise raises an error)
650
+ return f(*variables)
651
+ else:
652
+ return c*np.ones(self.nb_of_points)
653
+
654
+
655
+ class List2DSeries(Line2DBaseSeries):
656
+ """Representation for a line consisting of list of points."""
657
+
658
+ def __init__(self, list_x, list_y):
659
+ np = import_module('numpy')
660
+ super().__init__()
661
+ self.list_x = np.array(list_x)
662
+ self.list_y = np.array(list_y)
663
+ self.label = 'list'
664
+
665
+ def __str__(self):
666
+ return 'list plot'
667
+
668
+ def get_points(self):
669
+ return (self.list_x, self.list_y)
670
+
671
+
672
+ class LineOver1DRangeSeries(Line2DBaseSeries):
673
+ """Representation for a line consisting of a SymPy expression over a range."""
674
+
675
+ def __init__(self, expr, var_start_end, **kwargs):
676
+ super().__init__()
677
+ self.expr = sympify(expr)
678
+ self.label = kwargs.get('label', None) or self.expr
679
+ self.var = sympify(var_start_end[0])
680
+ self.start = float(var_start_end[1])
681
+ self.end = float(var_start_end[2])
682
+ self.nb_of_points = kwargs.get('nb_of_points', 300)
683
+ self.adaptive = kwargs.get('adaptive', True)
684
+ self.depth = kwargs.get('depth', 12)
685
+ self.line_color = kwargs.get('line_color', None)
686
+ self.xscale = kwargs.get('xscale', 'linear')
687
+
688
+ def __str__(self):
689
+ return 'cartesian line: %s for %s over %s' % (
690
+ str(self.expr), str(self.var), str((self.start, self.end)))
691
+
692
+ def get_points(self):
693
+ """ Return lists of coordinates for plotting. Depending on the
694
+ ``adaptive`` option, this function will either use an adaptive algorithm
695
+ or it will uniformly sample the expression over the provided range.
696
+
697
+ Returns
698
+ =======
699
+ x : list
700
+ List of x-coordinates
701
+
702
+ y : list
703
+ List of y-coordinates
704
+
705
+
706
+ Explanation
707
+ ===========
708
+
709
+ The adaptive sampling is done by recursively checking if three
710
+ points are almost collinear. If they are not collinear, then more
711
+ points are added between those points.
712
+
713
+ References
714
+ ==========
715
+
716
+ .. [1] Adaptive polygonal approximation of parametric curves,
717
+ Luiz Henrique de Figueiredo.
718
+
719
+ """
720
+ if self.only_integers or not self.adaptive:
721
+ return self._uniform_sampling()
722
+ else:
723
+ f = lambdify([self.var], self.expr)
724
+ x_coords = []
725
+ y_coords = []
726
+ np = import_module('numpy')
727
+ def sample(p, q, depth):
728
+ """ Samples recursively if three points are almost collinear.
729
+ For depth < 6, points are added irrespective of whether they
730
+ satisfy the collinearity condition or not. The maximum depth
731
+ allowed is 12.
732
+ """
733
+ # Randomly sample to avoid aliasing.
734
+ random = 0.45 + np.random.rand() * 0.1
735
+ if self.xscale == 'log':
736
+ xnew = 10**(np.log10(p[0]) + random * (np.log10(q[0]) -
737
+ np.log10(p[0])))
738
+ else:
739
+ xnew = p[0] + random * (q[0] - p[0])
740
+ ynew = f(xnew)
741
+ new_point = np.array([xnew, ynew])
742
+
743
+ # Maximum depth
744
+ if depth > self.depth:
745
+ x_coords.append(q[0])
746
+ y_coords.append(q[1])
747
+
748
+ # Sample irrespective of whether the line is flat till the
749
+ # depth of 6. We are not using linspace to avoid aliasing.
750
+ elif depth < 6:
751
+ sample(p, new_point, depth + 1)
752
+ sample(new_point, q, depth + 1)
753
+
754
+ # Sample ten points if complex values are encountered
755
+ # at both ends. If there is a real value in between, then
756
+ # sample those points further.
757
+ elif p[1] is None and q[1] is None:
758
+ if self.xscale == 'log':
759
+ xarray = np.logspace(p[0], q[0], 10)
760
+ else:
761
+ xarray = np.linspace(p[0], q[0], 10)
762
+ yarray = list(map(f, xarray))
763
+ if not all(y is None for y in yarray):
764
+ for i in range(len(yarray) - 1):
765
+ if not (yarray[i] is None and yarray[i + 1] is None):
766
+ sample([xarray[i], yarray[i]],
767
+ [xarray[i + 1], yarray[i + 1]], depth + 1)
768
+
769
+ # Sample further if one of the end points in None (i.e. a
770
+ # complex value) or the three points are not almost collinear.
771
+ elif (p[1] is None or q[1] is None or new_point[1] is None
772
+ or not flat(p, new_point, q)):
773
+ sample(p, new_point, depth + 1)
774
+ sample(new_point, q, depth + 1)
775
+ else:
776
+ x_coords.append(q[0])
777
+ y_coords.append(q[1])
778
+
779
+ f_start = f(self.start)
780
+ f_end = f(self.end)
781
+ x_coords.append(self.start)
782
+ y_coords.append(f_start)
783
+ sample(np.array([self.start, f_start]),
784
+ np.array([self.end, f_end]), 0)
785
+
786
+ return (x_coords, y_coords)
787
+
788
+ def _uniform_sampling(self):
789
+ np = import_module('numpy')
790
+ if self.only_integers is True:
791
+ if self.xscale == 'log':
792
+ list_x = np.logspace(int(self.start), int(self.end),
793
+ num=int(self.end) - int(self.start) + 1)
794
+ else:
795
+ list_x = np.linspace(int(self.start), int(self.end),
796
+ num=int(self.end) - int(self.start) + 1)
797
+ else:
798
+ if self.xscale == 'log':
799
+ list_x = np.logspace(self.start, self.end, num=self.nb_of_points)
800
+ else:
801
+ list_x = np.linspace(self.start, self.end, num=self.nb_of_points)
802
+ f = vectorized_lambdify([self.var], self.expr)
803
+ list_y = f(list_x)
804
+ return (list_x, list_y)
805
+
806
+
807
+ class Parametric2DLineSeries(Line2DBaseSeries):
808
+ """Representation for a line consisting of two parametric SymPy expressions
809
+ over a range."""
810
+
811
+ is_parametric = True
812
+
813
+ def __init__(self, expr_x, expr_y, var_start_end, **kwargs):
814
+ super().__init__()
815
+ self.expr_x = sympify(expr_x)
816
+ self.expr_y = sympify(expr_y)
817
+ self.label = kwargs.get('label', None) or \
818
+ Tuple(self.expr_x, self.expr_y)
819
+ self.var = sympify(var_start_end[0])
820
+ self.start = float(var_start_end[1])
821
+ self.end = float(var_start_end[2])
822
+ self.nb_of_points = kwargs.get('nb_of_points', 300)
823
+ self.adaptive = kwargs.get('adaptive', True)
824
+ self.depth = kwargs.get('depth', 12)
825
+ self.line_color = kwargs.get('line_color', None)
826
+
827
+ def __str__(self):
828
+ return 'parametric cartesian line: (%s, %s) for %s over %s' % (
829
+ str(self.expr_x), str(self.expr_y), str(self.var),
830
+ str((self.start, self.end)))
831
+
832
+ def get_parameter_points(self):
833
+ np = import_module('numpy')
834
+ return np.linspace(self.start, self.end, num=self.nb_of_points)
835
+
836
+ def _uniform_sampling(self):
837
+ param = self.get_parameter_points()
838
+ fx = vectorized_lambdify([self.var], self.expr_x)
839
+ fy = vectorized_lambdify([self.var], self.expr_y)
840
+ list_x = fx(param)
841
+ list_y = fy(param)
842
+ return (list_x, list_y)
843
+
844
+ def get_points(self):
845
+ """ Return lists of coordinates for plotting. Depending on the
846
+ ``adaptive`` option, this function will either use an adaptive algorithm
847
+ or it will uniformly sample the expression over the provided range.
848
+
849
+ Returns
850
+ =======
851
+ x : list
852
+ List of x-coordinates
853
+
854
+ y : list
855
+ List of y-coordinates
856
+
857
+
858
+ Explanation
859
+ ===========
860
+
861
+ The adaptive sampling is done by recursively checking if three
862
+ points are almost collinear. If they are not collinear, then more
863
+ points are added between those points.
864
+
865
+ References
866
+ ==========
867
+
868
+ .. [1] Adaptive polygonal approximation of parametric curves,
869
+ Luiz Henrique de Figueiredo.
870
+
871
+ """
872
+ if not self.adaptive:
873
+ return self._uniform_sampling()
874
+
875
+ f_x = lambdify([self.var], self.expr_x)
876
+ f_y = lambdify([self.var], self.expr_y)
877
+ x_coords = []
878
+ y_coords = []
879
+
880
+ def sample(param_p, param_q, p, q, depth):
881
+ """ Samples recursively if three points are almost collinear.
882
+ For depth < 6, points are added irrespective of whether they
883
+ satisfy the collinearity condition or not. The maximum depth
884
+ allowed is 12.
885
+ """
886
+ # Randomly sample to avoid aliasing.
887
+ np = import_module('numpy')
888
+ random = 0.45 + np.random.rand() * 0.1
889
+ param_new = param_p + random * (param_q - param_p)
890
+ xnew = f_x(param_new)
891
+ ynew = f_y(param_new)
892
+ new_point = np.array([xnew, ynew])
893
+
894
+ # Maximum depth
895
+ if depth > self.depth:
896
+ x_coords.append(q[0])
897
+ y_coords.append(q[1])
898
+
899
+ # Sample irrespective of whether the line is flat till the
900
+ # depth of 6. We are not using linspace to avoid aliasing.
901
+ elif depth < 6:
902
+ sample(param_p, param_new, p, new_point, depth + 1)
903
+ sample(param_new, param_q, new_point, q, depth + 1)
904
+
905
+ # Sample ten points if complex values are encountered
906
+ # at both ends. If there is a real value in between, then
907
+ # sample those points further.
908
+ elif ((p[0] is None and q[1] is None) or
909
+ (p[1] is None and q[1] is None)):
910
+ param_array = np.linspace(param_p, param_q, 10)
911
+ x_array = list(map(f_x, param_array))
912
+ y_array = list(map(f_y, param_array))
913
+ if not all(x is None and y is None
914
+ for x, y in zip(x_array, y_array)):
915
+ for i in range(len(y_array) - 1):
916
+ if ((x_array[i] is not None and y_array[i] is not None) or
917
+ (x_array[i + 1] is not None and y_array[i + 1] is not None)):
918
+ point_a = [x_array[i], y_array[i]]
919
+ point_b = [x_array[i + 1], y_array[i + 1]]
920
+ sample(param_array[i], param_array[i], point_a,
921
+ point_b, depth + 1)
922
+
923
+ # Sample further if one of the end points in None (i.e. a complex
924
+ # value) or the three points are not almost collinear.
925
+ elif (p[0] is None or p[1] is None
926
+ or q[1] is None or q[0] is None
927
+ or not flat(p, new_point, q)):
928
+ sample(param_p, param_new, p, new_point, depth + 1)
929
+ sample(param_new, param_q, new_point, q, depth + 1)
930
+ else:
931
+ x_coords.append(q[0])
932
+ y_coords.append(q[1])
933
+
934
+ f_start_x = f_x(self.start)
935
+ f_start_y = f_y(self.start)
936
+ start = [f_start_x, f_start_y]
937
+ f_end_x = f_x(self.end)
938
+ f_end_y = f_y(self.end)
939
+ end = [f_end_x, f_end_y]
940
+ x_coords.append(f_start_x)
941
+ y_coords.append(f_start_y)
942
+ sample(self.start, self.end, start, end, 0)
943
+
944
+ return x_coords, y_coords
945
+
946
+
947
+ ### 3D lines
948
+ class Line3DBaseSeries(Line2DBaseSeries):
949
+ """A base class for 3D lines.
950
+
951
+ Most of the stuff is derived from Line2DBaseSeries."""
952
+
953
+ is_2Dline = False
954
+ is_3Dline = True
955
+ _dim = 3
956
+
957
+ def __init__(self):
958
+ super().__init__()
959
+
960
+
961
+ class Parametric3DLineSeries(Line3DBaseSeries):
962
+ """Representation for a 3D line consisting of three parametric SymPy
963
+ expressions and a range."""
964
+
965
+ is_parametric = True
966
+
967
+ def __init__(self, expr_x, expr_y, expr_z, var_start_end, **kwargs):
968
+ super().__init__()
969
+ self.expr_x = sympify(expr_x)
970
+ self.expr_y = sympify(expr_y)
971
+ self.expr_z = sympify(expr_z)
972
+ self.label = kwargs.get('label', None) or \
973
+ Tuple(self.expr_x, self.expr_y)
974
+ self.var = sympify(var_start_end[0])
975
+ self.start = float(var_start_end[1])
976
+ self.end = float(var_start_end[2])
977
+ self.nb_of_points = kwargs.get('nb_of_points', 300)
978
+ self.line_color = kwargs.get('line_color', None)
979
+ self._xlim = None
980
+ self._ylim = None
981
+ self._zlim = None
982
+
983
+ def __str__(self):
984
+ return '3D parametric cartesian line: (%s, %s, %s) for %s over %s' % (
985
+ str(self.expr_x), str(self.expr_y), str(self.expr_z),
986
+ str(self.var), str((self.start, self.end)))
987
+
988
+ def get_parameter_points(self):
989
+ np = import_module('numpy')
990
+ return np.linspace(self.start, self.end, num=self.nb_of_points)
991
+
992
+ def get_points(self):
993
+ np = import_module('numpy')
994
+ param = self.get_parameter_points()
995
+ fx = vectorized_lambdify([self.var], self.expr_x)
996
+ fy = vectorized_lambdify([self.var], self.expr_y)
997
+ fz = vectorized_lambdify([self.var], self.expr_z)
998
+
999
+ list_x = fx(param)
1000
+ list_y = fy(param)
1001
+ list_z = fz(param)
1002
+
1003
+ list_x = np.array(list_x, dtype=np.float64)
1004
+ list_y = np.array(list_y, dtype=np.float64)
1005
+ list_z = np.array(list_z, dtype=np.float64)
1006
+
1007
+ list_x = np.ma.masked_invalid(list_x)
1008
+ list_y = np.ma.masked_invalid(list_y)
1009
+ list_z = np.ma.masked_invalid(list_z)
1010
+
1011
+ self._xlim = (np.amin(list_x), np.amax(list_x))
1012
+ self._ylim = (np.amin(list_y), np.amax(list_y))
1013
+ self._zlim = (np.amin(list_z), np.amax(list_z))
1014
+ return list_x, list_y, list_z
1015
+
1016
+
1017
+ ### Surfaces
1018
+ class SurfaceBaseSeries(BaseSeries):
1019
+ """A base class for 3D surfaces."""
1020
+
1021
+ is_3Dsurface = True
1022
+
1023
+ def __init__(self):
1024
+ super().__init__()
1025
+ self.surface_color = None
1026
+
1027
+ def get_color_array(self):
1028
+ np = import_module('numpy')
1029
+ c = self.surface_color
1030
+ if isinstance(c, Callable):
1031
+ f = np.vectorize(c)
1032
+ nargs = arity(c)
1033
+ if self.is_parametric:
1034
+ variables = list(map(centers_of_faces, self.get_parameter_meshes()))
1035
+ if nargs == 1:
1036
+ return f(variables[0])
1037
+ elif nargs == 2:
1038
+ return f(*variables)
1039
+ variables = list(map(centers_of_faces, self.get_meshes()))
1040
+ if nargs == 1:
1041
+ return f(variables[0])
1042
+ elif nargs == 2:
1043
+ return f(*variables[:2])
1044
+ else:
1045
+ return f(*variables)
1046
+ else:
1047
+ if isinstance(self, SurfaceOver2DRangeSeries):
1048
+ return c*np.ones(min(self.nb_of_points_x, self.nb_of_points_y))
1049
+ else:
1050
+ return c*np.ones(min(self.nb_of_points_u, self.nb_of_points_v))
1051
+
1052
+
1053
+ class SurfaceOver2DRangeSeries(SurfaceBaseSeries):
1054
+ """Representation for a 3D surface consisting of a SymPy expression and 2D
1055
+ range."""
1056
+ def __init__(self, expr, var_start_end_x, var_start_end_y, **kwargs):
1057
+ super().__init__()
1058
+ self.expr = sympify(expr)
1059
+ self.var_x = sympify(var_start_end_x[0])
1060
+ self.start_x = float(var_start_end_x[1])
1061
+ self.end_x = float(var_start_end_x[2])
1062
+ self.var_y = sympify(var_start_end_y[0])
1063
+ self.start_y = float(var_start_end_y[1])
1064
+ self.end_y = float(var_start_end_y[2])
1065
+ self.nb_of_points_x = kwargs.get('nb_of_points_x', 50)
1066
+ self.nb_of_points_y = kwargs.get('nb_of_points_y', 50)
1067
+ self.surface_color = kwargs.get('surface_color', None)
1068
+
1069
+ self._xlim = (self.start_x, self.end_x)
1070
+ self._ylim = (self.start_y, self.end_y)
1071
+
1072
+ def __str__(self):
1073
+ return ('cartesian surface: %s for'
1074
+ ' %s over %s and %s over %s') % (
1075
+ str(self.expr),
1076
+ str(self.var_x),
1077
+ str((self.start_x, self.end_x)),
1078
+ str(self.var_y),
1079
+ str((self.start_y, self.end_y)))
1080
+
1081
+ def get_meshes(self):
1082
+ np = import_module('numpy')
1083
+ mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x,
1084
+ num=self.nb_of_points_x),
1085
+ np.linspace(self.start_y, self.end_y,
1086
+ num=self.nb_of_points_y))
1087
+ f = vectorized_lambdify((self.var_x, self.var_y), self.expr)
1088
+ mesh_z = f(mesh_x, mesh_y)
1089
+ mesh_z = np.array(mesh_z, dtype=np.float64)
1090
+ mesh_z = np.ma.masked_invalid(mesh_z)
1091
+ self._zlim = (np.amin(mesh_z), np.amax(mesh_z))
1092
+ return mesh_x, mesh_y, mesh_z
1093
+
1094
+
1095
+ class ParametricSurfaceSeries(SurfaceBaseSeries):
1096
+ """Representation for a 3D surface consisting of three parametric SymPy
1097
+ expressions and a range."""
1098
+
1099
+ is_parametric = True
1100
+
1101
+ def __init__(
1102
+ self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v,
1103
+ **kwargs):
1104
+ super().__init__()
1105
+ self.expr_x = sympify(expr_x)
1106
+ self.expr_y = sympify(expr_y)
1107
+ self.expr_z = sympify(expr_z)
1108
+ self.var_u = sympify(var_start_end_u[0])
1109
+ self.start_u = float(var_start_end_u[1])
1110
+ self.end_u = float(var_start_end_u[2])
1111
+ self.var_v = sympify(var_start_end_v[0])
1112
+ self.start_v = float(var_start_end_v[1])
1113
+ self.end_v = float(var_start_end_v[2])
1114
+ self.nb_of_points_u = kwargs.get('nb_of_points_u', 50)
1115
+ self.nb_of_points_v = kwargs.get('nb_of_points_v', 50)
1116
+ self.surface_color = kwargs.get('surface_color', None)
1117
+
1118
+ def __str__(self):
1119
+ return ('parametric cartesian surface: (%s, %s, %s) for'
1120
+ ' %s over %s and %s over %s') % (
1121
+ str(self.expr_x),
1122
+ str(self.expr_y),
1123
+ str(self.expr_z),
1124
+ str(self.var_u),
1125
+ str((self.start_u, self.end_u)),
1126
+ str(self.var_v),
1127
+ str((self.start_v, self.end_v)))
1128
+
1129
+ def get_parameter_meshes(self):
1130
+ np = import_module('numpy')
1131
+ return np.meshgrid(np.linspace(self.start_u, self.end_u,
1132
+ num=self.nb_of_points_u),
1133
+ np.linspace(self.start_v, self.end_v,
1134
+ num=self.nb_of_points_v))
1135
+
1136
+ def get_meshes(self):
1137
+ np = import_module('numpy')
1138
+
1139
+ mesh_u, mesh_v = self.get_parameter_meshes()
1140
+ fx = vectorized_lambdify((self.var_u, self.var_v), self.expr_x)
1141
+ fy = vectorized_lambdify((self.var_u, self.var_v), self.expr_y)
1142
+ fz = vectorized_lambdify((self.var_u, self.var_v), self.expr_z)
1143
+
1144
+ mesh_x = fx(mesh_u, mesh_v)
1145
+ mesh_y = fy(mesh_u, mesh_v)
1146
+ mesh_z = fz(mesh_u, mesh_v)
1147
+
1148
+ mesh_x = np.array(mesh_x, dtype=np.float64)
1149
+ mesh_y = np.array(mesh_y, dtype=np.float64)
1150
+ mesh_z = np.array(mesh_z, dtype=np.float64)
1151
+
1152
+ mesh_x = np.ma.masked_invalid(mesh_x)
1153
+ mesh_y = np.ma.masked_invalid(mesh_y)
1154
+ mesh_z = np.ma.masked_invalid(mesh_z)
1155
+
1156
+ self._xlim = (np.amin(mesh_x), np.amax(mesh_x))
1157
+ self._ylim = (np.amin(mesh_y), np.amax(mesh_y))
1158
+ self._zlim = (np.amin(mesh_z), np.amax(mesh_z))
1159
+
1160
+ return mesh_x, mesh_y, mesh_z
1161
+
1162
+
1163
+ ### Contours
1164
+ class ContourSeries(BaseSeries):
1165
+ """Representation for a contour plot."""
1166
+ # The code is mostly repetition of SurfaceOver2DRange.
1167
+ # Presently used in contour_plot function
1168
+
1169
+ is_contour = True
1170
+
1171
+ def __init__(self, expr, var_start_end_x, var_start_end_y):
1172
+ super().__init__()
1173
+ self.nb_of_points_x = 50
1174
+ self.nb_of_points_y = 50
1175
+ self.expr = sympify(expr)
1176
+ self.var_x = sympify(var_start_end_x[0])
1177
+ self.start_x = float(var_start_end_x[1])
1178
+ self.end_x = float(var_start_end_x[2])
1179
+ self.var_y = sympify(var_start_end_y[0])
1180
+ self.start_y = float(var_start_end_y[1])
1181
+ self.end_y = float(var_start_end_y[2])
1182
+
1183
+ self.get_points = self.get_meshes
1184
+
1185
+ self._xlim = (self.start_x, self.end_x)
1186
+ self._ylim = (self.start_y, self.end_y)
1187
+
1188
+ def __str__(self):
1189
+ return ('contour: %s for '
1190
+ '%s over %s and %s over %s') % (
1191
+ str(self.expr),
1192
+ str(self.var_x),
1193
+ str((self.start_x, self.end_x)),
1194
+ str(self.var_y),
1195
+ str((self.start_y, self.end_y)))
1196
+
1197
+ def get_meshes(self):
1198
+ np = import_module('numpy')
1199
+ mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x,
1200
+ num=self.nb_of_points_x),
1201
+ np.linspace(self.start_y, self.end_y,
1202
+ num=self.nb_of_points_y))
1203
+ f = vectorized_lambdify((self.var_x, self.var_y), self.expr)
1204
+ return (mesh_x, mesh_y, f(mesh_x, mesh_y))
1205
+
1206
+
1207
+ ##############################################################################
1208
+ # Backends
1209
+ ##############################################################################
1210
+
1211
+ class BaseBackend:
1212
+ """Base class for all backends. A backend represents the plotting library,
1213
+ which implements the necessary functionalities in order to use SymPy
1214
+ plotting functions.
1215
+
1216
+ How the plotting module works:
1217
+
1218
+ 1. Whenever a plotting function is called, the provided expressions are
1219
+ processed and a list of instances of the :class:`BaseSeries` class is
1220
+ created, containing the necessary information to plot the expressions
1221
+ (e.g. the expression, ranges, series name, ...). Eventually, these
1222
+ objects will generate the numerical data to be plotted.
1223
+ 2. A :class:`~.Plot` object is instantiated, which stores the list of
1224
+ series and the main attributes of the plot (e.g. axis labels, title, ...).
1225
+ 3. When the ``show`` command is executed, a new backend is instantiated,
1226
+ which loops through each series object to generate and plot the
1227
+ numerical data. The backend is also going to set the axis labels, title,
1228
+ ..., according to the values stored in the Plot instance.
1229
+
1230
+ The backend should check if it supports the data series that it is given
1231
+ (e.g. :class:`TextBackend` supports only :class:`LineOver1DRangeSeries`).
1232
+
1233
+ It is the backend responsibility to know how to use the class of data series
1234
+ that it's given. Note that the current implementation of the ``*Series``
1235
+ classes is "matplotlib-centric": the numerical data returned by the
1236
+ ``get_points`` and ``get_meshes`` methods is meant to be used directly by
1237
+ Matplotlib. Therefore, the new backend will have to pre-process the
1238
+ numerical data to make it compatible with the chosen plotting library.
1239
+ Keep in mind that future SymPy versions may improve the ``*Series`` classes
1240
+ in order to return numerical data "non-matplotlib-centric", hence if you code
1241
+ a new backend you have the responsibility to check if its working on each
1242
+ SymPy release.
1243
+
1244
+ Please explore the :class:`MatplotlibBackend` source code to understand how a
1245
+ backend should be coded.
1246
+
1247
+ Methods
1248
+ =======
1249
+
1250
+ In order to be used by SymPy plotting functions, a backend must implement
1251
+ the following methods:
1252
+
1253
+ * show(self): used to loop over the data series, generate the numerical
1254
+ data, plot it and set the axis labels, title, ...
1255
+ * save(self, path): used to save the current plot to the specified file
1256
+ path.
1257
+ * close(self): used to close the current plot backend (note: some plotting
1258
+ library does not support this functionality. In that case, just raise a
1259
+ warning).
1260
+
1261
+ See also
1262
+ ========
1263
+
1264
+ MatplotlibBackend
1265
+ """
1266
+ def __init__(self, parent):
1267
+ super().__init__()
1268
+ self.parent = parent
1269
+
1270
+ def show(self):
1271
+ raise NotImplementedError
1272
+
1273
+ def save(self, path):
1274
+ raise NotImplementedError
1275
+
1276
+ def close(self):
1277
+ raise NotImplementedError
1278
+
1279
+
1280
+ # Don't have to check for the success of importing matplotlib in each case;
1281
+ # we will only be using this backend if we can successfully import matploblib
1282
+ class MatplotlibBackend(BaseBackend):
1283
+ """ This class implements the functionalities to use Matplotlib with SymPy
1284
+ plotting functions.
1285
+ """
1286
+ def __init__(self, parent):
1287
+ super().__init__(parent)
1288
+ self.matplotlib = import_module('matplotlib',
1289
+ import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']},
1290
+ min_module_version='1.1.0', catch=(RuntimeError,))
1291
+ self.plt = self.matplotlib.pyplot
1292
+ self.cm = self.matplotlib.cm
1293
+ self.LineCollection = self.matplotlib.collections.LineCollection
1294
+ aspect = getattr(self.parent, 'aspect_ratio', 'auto')
1295
+ if aspect != 'auto':
1296
+ aspect = float(aspect[1]) / aspect[0]
1297
+
1298
+ if isinstance(self.parent, Plot):
1299
+ nrows, ncolumns = 1, 1
1300
+ series_list = [self.parent._series]
1301
+ elif isinstance(self.parent, PlotGrid):
1302
+ nrows, ncolumns = self.parent.nrows, self.parent.ncolumns
1303
+ series_list = self.parent._series
1304
+
1305
+ self.ax = []
1306
+ self.fig = self.plt.figure(figsize=parent.size)
1307
+
1308
+ for i, series in enumerate(series_list):
1309
+ are_3D = [s.is_3D for s in series]
1310
+
1311
+ if any(are_3D) and not all(are_3D):
1312
+ raise ValueError('The matplotlib backend cannot mix 2D and 3D.')
1313
+ elif all(are_3D):
1314
+ # mpl_toolkits.mplot3d is necessary for
1315
+ # projection='3d'
1316
+ mpl_toolkits = import_module('mpl_toolkits', # noqa
1317
+ import_kwargs={'fromlist': ['mplot3d']})
1318
+ self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, projection='3d', aspect=aspect))
1319
+
1320
+ elif not any(are_3D):
1321
+ self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, aspect=aspect))
1322
+ self.ax[i].spines['left'].set_position('zero')
1323
+ self.ax[i].spines['right'].set_color('none')
1324
+ self.ax[i].spines['bottom'].set_position('zero')
1325
+ self.ax[i].spines['top'].set_color('none')
1326
+ self.ax[i].xaxis.set_ticks_position('bottom')
1327
+ self.ax[i].yaxis.set_ticks_position('left')
1328
+
1329
+ @staticmethod
1330
+ def get_segments(x, y, z=None):
1331
+ """ Convert two list of coordinates to a list of segments to be used
1332
+ with Matplotlib's :external:class:`~matplotlib.collections.LineCollection`.
1333
+
1334
+ Parameters
1335
+ ==========
1336
+ x : list
1337
+ List of x-coordinates
1338
+
1339
+ y : list
1340
+ List of y-coordinates
1341
+
1342
+ z : list
1343
+ List of z-coordinates for a 3D line.
1344
+ """
1345
+ np = import_module('numpy')
1346
+ if z is not None:
1347
+ dim = 3
1348
+ points = (x, y, z)
1349
+ else:
1350
+ dim = 2
1351
+ points = (x, y)
1352
+ points = np.ma.array(points).T.reshape(-1, 1, dim)
1353
+ return np.ma.concatenate([points[:-1], points[1:]], axis=1)
1354
+
1355
+ def _process_series(self, series, ax, parent):
1356
+ np = import_module('numpy')
1357
+ mpl_toolkits = import_module(
1358
+ 'mpl_toolkits', import_kwargs={'fromlist': ['mplot3d']})
1359
+
1360
+ # XXX Workaround for matplotlib issue
1361
+ # https://github.com/matplotlib/matplotlib/issues/17130
1362
+ xlims, ylims, zlims = [], [], []
1363
+
1364
+ for s in series:
1365
+ # Create the collections
1366
+ if s.is_2Dline:
1367
+ x, y = s.get_data()
1368
+ if (isinstance(s.line_color, (int, float)) or
1369
+ callable(s.line_color)):
1370
+ segments = self.get_segments(x, y)
1371
+ collection = self.LineCollection(segments)
1372
+ collection.set_array(s.get_color_array())
1373
+ ax.add_collection(collection)
1374
+ else:
1375
+ lbl = _str_or_latex(s.label)
1376
+ line, = ax.plot(x, y, label=lbl, color=s.line_color)
1377
+ elif s.is_contour:
1378
+ ax.contour(*s.get_meshes())
1379
+ elif s.is_3Dline:
1380
+ x, y, z = s.get_data()
1381
+ if (isinstance(s.line_color, (int, float)) or
1382
+ callable(s.line_color)):
1383
+ art3d = mpl_toolkits.mplot3d.art3d
1384
+ segments = self.get_segments(x, y, z)
1385
+ collection = art3d.Line3DCollection(segments)
1386
+ collection.set_array(s.get_color_array())
1387
+ ax.add_collection(collection)
1388
+ else:
1389
+ lbl = _str_or_latex(s.label)
1390
+ ax.plot(x, y, z, label=lbl, color=s.line_color)
1391
+
1392
+ xlims.append(s._xlim)
1393
+ ylims.append(s._ylim)
1394
+ zlims.append(s._zlim)
1395
+ elif s.is_3Dsurface:
1396
+ x, y, z = s.get_meshes()
1397
+ collection = ax.plot_surface(x, y, z,
1398
+ cmap=getattr(self.cm, 'viridis', self.cm.jet),
1399
+ rstride=1, cstride=1, linewidth=0.1)
1400
+ if isinstance(s.surface_color, (float, int, Callable)):
1401
+ color_array = s.get_color_array()
1402
+ color_array = color_array.reshape(color_array.size)
1403
+ collection.set_array(color_array)
1404
+ else:
1405
+ collection.set_color(s.surface_color)
1406
+
1407
+ xlims.append(s._xlim)
1408
+ ylims.append(s._ylim)
1409
+ zlims.append(s._zlim)
1410
+ elif s.is_implicit:
1411
+ points = s.get_raster()
1412
+ if len(points) == 2:
1413
+ # interval math plotting
1414
+ x, y = _matplotlib_list(points[0])
1415
+ ax.fill(x, y, facecolor=s.line_color, edgecolor='None')
1416
+ else:
1417
+ # use contourf or contour depending on whether it is
1418
+ # an inequality or equality.
1419
+ # XXX: ``contour`` plots multiple lines. Should be fixed.
1420
+ ListedColormap = self.matplotlib.colors.ListedColormap
1421
+ colormap = ListedColormap(["white", s.line_color])
1422
+ xarray, yarray, zarray, plot_type = points
1423
+ if plot_type == 'contour':
1424
+ ax.contour(xarray, yarray, zarray, cmap=colormap)
1425
+ else:
1426
+ ax.contourf(xarray, yarray, zarray, cmap=colormap)
1427
+ else:
1428
+ raise NotImplementedError(
1429
+ '{} is not supported in the SymPy plotting module '
1430
+ 'with matplotlib backend. Please report this issue.'
1431
+ .format(ax))
1432
+
1433
+ Axes3D = mpl_toolkits.mplot3d.Axes3D
1434
+ if not isinstance(ax, Axes3D):
1435
+ ax.autoscale_view(
1436
+ scalex=ax.get_autoscalex_on(),
1437
+ scaley=ax.get_autoscaley_on())
1438
+ else:
1439
+ # XXX Workaround for matplotlib issue
1440
+ # https://github.com/matplotlib/matplotlib/issues/17130
1441
+ if xlims:
1442
+ xlims = np.array(xlims)
1443
+ xlim = (np.amin(xlims[:, 0]), np.amax(xlims[:, 1]))
1444
+ ax.set_xlim(xlim)
1445
+ else:
1446
+ ax.set_xlim([0, 1])
1447
+
1448
+ if ylims:
1449
+ ylims = np.array(ylims)
1450
+ ylim = (np.amin(ylims[:, 0]), np.amax(ylims[:, 1]))
1451
+ ax.set_ylim(ylim)
1452
+ else:
1453
+ ax.set_ylim([0, 1])
1454
+
1455
+ if zlims:
1456
+ zlims = np.array(zlims)
1457
+ zlim = (np.amin(zlims[:, 0]), np.amax(zlims[:, 1]))
1458
+ ax.set_zlim(zlim)
1459
+ else:
1460
+ ax.set_zlim([0, 1])
1461
+
1462
+ # Set global options.
1463
+ # TODO The 3D stuff
1464
+ # XXX The order of those is important.
1465
+ if parent.xscale and not isinstance(ax, Axes3D):
1466
+ ax.set_xscale(parent.xscale)
1467
+ if parent.yscale and not isinstance(ax, Axes3D):
1468
+ ax.set_yscale(parent.yscale)
1469
+ if not isinstance(ax, Axes3D) or self.matplotlib.__version__ >= '1.2.0': # XXX in the distant future remove this check
1470
+ ax.set_autoscale_on(parent.autoscale)
1471
+ if parent.axis_center:
1472
+ val = parent.axis_center
1473
+ if isinstance(ax, Axes3D):
1474
+ pass
1475
+ elif val == 'center':
1476
+ ax.spines['left'].set_position('center')
1477
+ ax.spines['bottom'].set_position('center')
1478
+ elif val == 'auto':
1479
+ xl, xh = ax.get_xlim()
1480
+ yl, yh = ax.get_ylim()
1481
+ pos_left = ('data', 0) if xl*xh <= 0 else 'center'
1482
+ pos_bottom = ('data', 0) if yl*yh <= 0 else 'center'
1483
+ ax.spines['left'].set_position(pos_left)
1484
+ ax.spines['bottom'].set_position(pos_bottom)
1485
+ else:
1486
+ ax.spines['left'].set_position(('data', val[0]))
1487
+ ax.spines['bottom'].set_position(('data', val[1]))
1488
+ if not parent.axis:
1489
+ ax.set_axis_off()
1490
+ if parent.legend:
1491
+ if ax.legend():
1492
+ ax.legend_.set_visible(parent.legend)
1493
+ if parent.margin:
1494
+ ax.set_xmargin(parent.margin)
1495
+ ax.set_ymargin(parent.margin)
1496
+ if parent.title:
1497
+ ax.set_title(parent.title)
1498
+ if parent.xlabel:
1499
+ xlbl = _str_or_latex(parent.xlabel)
1500
+ ax.set_xlabel(xlbl, position=(1, 0))
1501
+ if parent.ylabel:
1502
+ ylbl = _str_or_latex(parent.ylabel)
1503
+ ax.set_ylabel(ylbl, position=(0, 1))
1504
+ if isinstance(ax, Axes3D) and parent.zlabel:
1505
+ zlbl = _str_or_latex(parent.zlabel)
1506
+ ax.set_zlabel(zlbl, position=(0, 1))
1507
+ if parent.annotations:
1508
+ for a in parent.annotations:
1509
+ ax.annotate(**a)
1510
+ if parent.markers:
1511
+ for marker in parent.markers:
1512
+ # make a copy of the marker dictionary
1513
+ # so that it doesn't get altered
1514
+ m = marker.copy()
1515
+ args = m.pop('args')
1516
+ ax.plot(*args, **m)
1517
+ if parent.rectangles:
1518
+ for r in parent.rectangles:
1519
+ rect = self.matplotlib.patches.Rectangle(**r)
1520
+ ax.add_patch(rect)
1521
+ if parent.fill:
1522
+ ax.fill_between(**parent.fill)
1523
+
1524
+ # xlim and ylim should always be set at last so that plot limits
1525
+ # doesn't get altered during the process.
1526
+ if parent.xlim:
1527
+ ax.set_xlim(parent.xlim)
1528
+ if parent.ylim:
1529
+ ax.set_ylim(parent.ylim)
1530
+
1531
+
1532
+ def process_series(self):
1533
+ """
1534
+ Iterates over every ``Plot`` object and further calls
1535
+ _process_series()
1536
+ """
1537
+ parent = self.parent
1538
+ if isinstance(parent, Plot):
1539
+ series_list = [parent._series]
1540
+ else:
1541
+ series_list = parent._series
1542
+
1543
+ for i, (series, ax) in enumerate(zip(series_list, self.ax)):
1544
+ if isinstance(self.parent, PlotGrid):
1545
+ parent = self.parent.args[i]
1546
+ self._process_series(series, ax, parent)
1547
+
1548
+ def show(self):
1549
+ self.process_series()
1550
+ #TODO after fixing https://github.com/ipython/ipython/issues/1255
1551
+ # you can uncomment the next line and remove the pyplot.show() call
1552
+ #self.fig.show()
1553
+ if _show:
1554
+ self.fig.tight_layout()
1555
+ self.plt.show()
1556
+ else:
1557
+ self.close()
1558
+
1559
+ def save(self, path):
1560
+ self.process_series()
1561
+ self.fig.savefig(path)
1562
+
1563
+ def close(self):
1564
+ self.plt.close(self.fig)
1565
+
1566
+
1567
+ class TextBackend(BaseBackend):
1568
+ def __init__(self, parent):
1569
+ super().__init__(parent)
1570
+
1571
+ def show(self):
1572
+ if not _show:
1573
+ return
1574
+ if len(self.parent._series) != 1:
1575
+ raise ValueError(
1576
+ 'The TextBackend supports only one graph per Plot.')
1577
+ elif not isinstance(self.parent._series[0], LineOver1DRangeSeries):
1578
+ raise ValueError(
1579
+ 'The TextBackend supports only expressions over a 1D range')
1580
+ else:
1581
+ ser = self.parent._series[0]
1582
+ textplot(ser.expr, ser.start, ser.end)
1583
+
1584
+ def close(self):
1585
+ pass
1586
+
1587
+
1588
+ class DefaultBackend(BaseBackend):
1589
+ def __new__(cls, parent):
1590
+ matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
1591
+ if matplotlib:
1592
+ return MatplotlibBackend(parent)
1593
+ else:
1594
+ return TextBackend(parent)
1595
+
1596
+
1597
+ plot_backends = {
1598
+ 'matplotlib': MatplotlibBackend,
1599
+ 'text': TextBackend,
1600
+ 'default': DefaultBackend
1601
+ }
1602
+
1603
+
1604
+ ##############################################################################
1605
+ # Finding the centers of line segments or mesh faces
1606
+ ##############################################################################
1607
+
1608
+ def centers_of_segments(array):
1609
+ np = import_module('numpy')
1610
+ return np.mean(np.vstack((array[:-1], array[1:])), 0)
1611
+
1612
+
1613
+ def centers_of_faces(array):
1614
+ np = import_module('numpy')
1615
+ return np.mean(np.dstack((array[:-1, :-1],
1616
+ array[1:, :-1],
1617
+ array[:-1, 1:],
1618
+ array[:-1, :-1],
1619
+ )), 2)
1620
+
1621
+
1622
+ def flat(x, y, z, eps=1e-3):
1623
+ """Checks whether three points are almost collinear"""
1624
+ np = import_module('numpy')
1625
+ # Workaround plotting piecewise (#8577):
1626
+ # workaround for `lambdify` in `.experimental_lambdify` fails
1627
+ # to return numerical values in some cases. Lower-level fix
1628
+ # in `lambdify` is possible.
1629
+ vector_a = (x - y).astype(np.float64)
1630
+ vector_b = (z - y).astype(np.float64)
1631
+ dot_product = np.dot(vector_a, vector_b)
1632
+ vector_a_norm = np.linalg.norm(vector_a)
1633
+ vector_b_norm = np.linalg.norm(vector_b)
1634
+ cos_theta = dot_product / (vector_a_norm * vector_b_norm)
1635
+ return abs(cos_theta + 1) < eps
1636
+
1637
+
1638
+ def _matplotlib_list(interval_list):
1639
+ """
1640
+ Returns lists for matplotlib ``fill`` command from a list of bounding
1641
+ rectangular intervals
1642
+ """
1643
+ xlist = []
1644
+ ylist = []
1645
+ if len(interval_list):
1646
+ for intervals in interval_list:
1647
+ intervalx = intervals[0]
1648
+ intervaly = intervals[1]
1649
+ xlist.extend([intervalx.start, intervalx.start,
1650
+ intervalx.end, intervalx.end, None])
1651
+ ylist.extend([intervaly.start, intervaly.end,
1652
+ intervaly.end, intervaly.start, None])
1653
+ else:
1654
+ #XXX Ugly hack. Matplotlib does not accept empty lists for ``fill``
1655
+ xlist.extend((None, None, None, None))
1656
+ ylist.extend((None, None, None, None))
1657
+ return xlist, ylist
1658
+
1659
+
1660
+ ####New API for plotting module ####
1661
+
1662
+ # TODO: Add color arrays for plots.
1663
+ # TODO: Add more plotting options for 3d plots.
1664
+ # TODO: Adaptive sampling for 3D plots.
1665
+
1666
+ def plot(*args, show=True, **kwargs):
1667
+ """Plots a function of a single variable as a curve.
1668
+
1669
+ Parameters
1670
+ ==========
1671
+
1672
+ args :
1673
+ The first argument is the expression representing the function
1674
+ of single variable to be plotted.
1675
+
1676
+ The last argument is a 3-tuple denoting the range of the free
1677
+ variable. e.g. ``(x, 0, 5)``
1678
+
1679
+ Typical usage examples are in the following:
1680
+
1681
+ - Plotting a single expression with a single range.
1682
+ ``plot(expr, range, **kwargs)``
1683
+ - Plotting a single expression with the default range (-10, 10).
1684
+ ``plot(expr, **kwargs)``
1685
+ - Plotting multiple expressions with a single range.
1686
+ ``plot(expr1, expr2, ..., range, **kwargs)``
1687
+ - Plotting multiple expressions with multiple ranges.
1688
+ ``plot((expr1, range1), (expr2, range2), ..., **kwargs)``
1689
+
1690
+ It is best practice to specify range explicitly because default
1691
+ range may change in the future if a more advanced default range
1692
+ detection algorithm is implemented.
1693
+
1694
+ show : bool, optional
1695
+ The default value is set to ``True``. Set show to ``False`` and
1696
+ the function will not display the plot. The returned instance of
1697
+ the ``Plot`` class can then be used to save or display the plot
1698
+ by calling the ``save()`` and ``show()`` methods respectively.
1699
+
1700
+ line_color : string, or float, or function, optional
1701
+ Specifies the color for the plot.
1702
+ See ``Plot`` to see how to set color for the plots.
1703
+ Note that by setting ``line_color``, it would be applied simultaneously
1704
+ to all the series.
1705
+
1706
+ title : str, optional
1707
+ Title of the plot. It is set to the latex representation of
1708
+ the expression, if the plot has only one expression.
1709
+
1710
+ label : str, optional
1711
+ The label of the expression in the plot. It will be used when
1712
+ called with ``legend``. Default is the name of the expression.
1713
+ e.g. ``sin(x)``
1714
+
1715
+ xlabel : str or expression, optional
1716
+ Label for the x-axis.
1717
+
1718
+ ylabel : str or expression, optional
1719
+ Label for the y-axis.
1720
+
1721
+ xscale : 'linear' or 'log', optional
1722
+ Sets the scaling of the x-axis.
1723
+
1724
+ yscale : 'linear' or 'log', optional
1725
+ Sets the scaling of the y-axis.
1726
+
1727
+ axis_center : (float, float), optional
1728
+ Tuple of two floats denoting the coordinates of the center or
1729
+ {'center', 'auto'}
1730
+
1731
+ xlim : (float, float), optional
1732
+ Denotes the x-axis limits, ``(min, max)```.
1733
+
1734
+ ylim : (float, float), optional
1735
+ Denotes the y-axis limits, ``(min, max)```.
1736
+
1737
+ annotations : list, optional
1738
+ A list of dictionaries specifying the type of annotation
1739
+ required. The keys in the dictionary should be equivalent
1740
+ to the arguments of the :external:mod:`matplotlib`'s
1741
+ :external:meth:`~matplotlib.axes.Axes.annotate` method.
1742
+
1743
+ markers : list, optional
1744
+ A list of dictionaries specifying the type the markers required.
1745
+ The keys in the dictionary should be equivalent to the arguments
1746
+ of the :external:mod:`matplotlib`'s :external:func:`~matplotlib.pyplot.plot()` function
1747
+ along with the marker related keyworded arguments.
1748
+
1749
+ rectangles : list, optional
1750
+ A list of dictionaries specifying the dimensions of the
1751
+ rectangles to be plotted. The keys in the dictionary should be
1752
+ equivalent to the arguments of the :external:mod:`matplotlib`'s
1753
+ :external:class:`~matplotlib.patches.Rectangle` class.
1754
+
1755
+ fill : dict, optional
1756
+ A dictionary specifying the type of color filling required in
1757
+ the plot. The keys in the dictionary should be equivalent to the
1758
+ arguments of the :external:mod:`matplotlib`'s
1759
+ :external:meth:`~matplotlib.axes.Axes.fill_between` method.
1760
+
1761
+ adaptive : bool, optional
1762
+ The default value is set to ``True``. Set adaptive to ``False``
1763
+ and specify ``nb_of_points`` if uniform sampling is required.
1764
+
1765
+ The plotting uses an adaptive algorithm which samples
1766
+ recursively to accurately plot. The adaptive algorithm uses a
1767
+ random point near the midpoint of two points that has to be
1768
+ further sampled. Hence the same plots can appear slightly
1769
+ different.
1770
+
1771
+ depth : int, optional
1772
+ Recursion depth of the adaptive algorithm. A depth of value
1773
+ `n` samples a maximum of `2^{n}` points.
1774
+
1775
+ If the ``adaptive`` flag is set to ``False``, this will be
1776
+ ignored.
1777
+
1778
+ nb_of_points : int, optional
1779
+ Used when the ``adaptive`` is set to ``False``. The function
1780
+ is uniformly sampled at ``nb_of_points`` number of points.
1781
+
1782
+ If the ``adaptive`` flag is set to ``True``, this will be
1783
+ ignored.
1784
+
1785
+ size : (float, float), optional
1786
+ A tuple in the form (width, height) in inches to specify the size of
1787
+ the overall figure. The default value is set to ``None``, meaning
1788
+ the size will be set by the default backend.
1789
+
1790
+ Examples
1791
+ ========
1792
+
1793
+ .. plot::
1794
+ :context: close-figs
1795
+ :format: doctest
1796
+ :include-source: True
1797
+
1798
+ >>> from sympy import symbols
1799
+ >>> from sympy.plotting import plot
1800
+ >>> x = symbols('x')
1801
+
1802
+ Single Plot
1803
+
1804
+ .. plot::
1805
+ :context: close-figs
1806
+ :format: doctest
1807
+ :include-source: True
1808
+
1809
+ >>> plot(x**2, (x, -5, 5))
1810
+ Plot object containing:
1811
+ [0]: cartesian line: x**2 for x over (-5.0, 5.0)
1812
+
1813
+ Multiple plots with single range.
1814
+
1815
+ .. plot::
1816
+ :context: close-figs
1817
+ :format: doctest
1818
+ :include-source: True
1819
+
1820
+ >>> plot(x, x**2, x**3, (x, -5, 5))
1821
+ Plot object containing:
1822
+ [0]: cartesian line: x for x over (-5.0, 5.0)
1823
+ [1]: cartesian line: x**2 for x over (-5.0, 5.0)
1824
+ [2]: cartesian line: x**3 for x over (-5.0, 5.0)
1825
+
1826
+ Multiple plots with different ranges.
1827
+
1828
+ .. plot::
1829
+ :context: close-figs
1830
+ :format: doctest
1831
+ :include-source: True
1832
+
1833
+ >>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
1834
+ Plot object containing:
1835
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
1836
+ [1]: cartesian line: x for x over (-5.0, 5.0)
1837
+
1838
+ No adaptive sampling.
1839
+
1840
+ .. plot::
1841
+ :context: close-figs
1842
+ :format: doctest
1843
+ :include-source: True
1844
+
1845
+ >>> plot(x**2, adaptive=False, nb_of_points=400)
1846
+ Plot object containing:
1847
+ [0]: cartesian line: x**2 for x over (-10.0, 10.0)
1848
+
1849
+ See Also
1850
+ ========
1851
+
1852
+ Plot, LineOver1DRangeSeries
1853
+
1854
+ """
1855
+ args = list(map(sympify, args))
1856
+ free = set()
1857
+ for a in args:
1858
+ if isinstance(a, Expr):
1859
+ free |= a.free_symbols
1860
+ if len(free) > 1:
1861
+ raise ValueError(
1862
+ 'The same variable should be used in all '
1863
+ 'univariate expressions being plotted.')
1864
+ x = free.pop() if free else Symbol('x')
1865
+ kwargs.setdefault('xlabel', x)
1866
+ kwargs.setdefault('ylabel', Function('f')(x))
1867
+ series = []
1868
+ plot_expr = check_arguments(args, 1, 1)
1869
+ series = [LineOver1DRangeSeries(*arg, **kwargs) for arg in plot_expr]
1870
+
1871
+ plots = Plot(*series, **kwargs)
1872
+ if show:
1873
+ plots.show()
1874
+ return plots
1875
+
1876
+
1877
+ def plot_parametric(*args, show=True, **kwargs):
1878
+ """
1879
+ Plots a 2D parametric curve.
1880
+
1881
+ Parameters
1882
+ ==========
1883
+
1884
+ args
1885
+ Common specifications are:
1886
+
1887
+ - Plotting a single parametric curve with a range
1888
+ ``plot_parametric((expr_x, expr_y), range)``
1889
+ - Plotting multiple parametric curves with the same range
1890
+ ``plot_parametric((expr_x, expr_y), ..., range)``
1891
+ - Plotting multiple parametric curves with different ranges
1892
+ ``plot_parametric((expr_x, expr_y, range), ...)``
1893
+
1894
+ ``expr_x`` is the expression representing $x$ component of the
1895
+ parametric function.
1896
+
1897
+ ``expr_y`` is the expression representing $y$ component of the
1898
+ parametric function.
1899
+
1900
+ ``range`` is a 3-tuple denoting the parameter symbol, start and
1901
+ stop. For example, ``(u, 0, 5)``.
1902
+
1903
+ If the range is not specified, then a default range of (-10, 10)
1904
+ is used.
1905
+
1906
+ However, if the arguments are specified as
1907
+ ``(expr_x, expr_y, range), ...``, you must specify the ranges
1908
+ for each expressions manually.
1909
+
1910
+ Default range may change in the future if a more advanced
1911
+ algorithm is implemented.
1912
+
1913
+ adaptive : bool, optional
1914
+ Specifies whether to use the adaptive sampling or not.
1915
+
1916
+ The default value is set to ``True``. Set adaptive to ``False``
1917
+ and specify ``nb_of_points`` if uniform sampling is required.
1918
+
1919
+ depth : int, optional
1920
+ The recursion depth of the adaptive algorithm. A depth of
1921
+ value $n$ samples a maximum of $2^n$ points.
1922
+
1923
+ nb_of_points : int, optional
1924
+ Used when the ``adaptive`` flag is set to ``False``.
1925
+
1926
+ Specifies the number of the points used for the uniform
1927
+ sampling.
1928
+
1929
+ line_color : string, or float, or function, optional
1930
+ Specifies the color for the plot.
1931
+ See ``Plot`` to see how to set color for the plots.
1932
+ Note that by setting ``line_color``, it would be applied simultaneously
1933
+ to all the series.
1934
+
1935
+ label : str, optional
1936
+ The label of the expression in the plot. It will be used when
1937
+ called with ``legend``. Default is the name of the expression.
1938
+ e.g. ``sin(x)``
1939
+
1940
+ xlabel : str, optional
1941
+ Label for the x-axis.
1942
+
1943
+ ylabel : str, optional
1944
+ Label for the y-axis.
1945
+
1946
+ xscale : 'linear' or 'log', optional
1947
+ Sets the scaling of the x-axis.
1948
+
1949
+ yscale : 'linear' or 'log', optional
1950
+ Sets the scaling of the y-axis.
1951
+
1952
+ axis_center : (float, float), optional
1953
+ Tuple of two floats denoting the coordinates of the center or
1954
+ {'center', 'auto'}
1955
+
1956
+ xlim : (float, float), optional
1957
+ Denotes the x-axis limits, ``(min, max)```.
1958
+
1959
+ ylim : (float, float), optional
1960
+ Denotes the y-axis limits, ``(min, max)```.
1961
+
1962
+ size : (float, float), optional
1963
+ A tuple in the form (width, height) in inches to specify the size of
1964
+ the overall figure. The default value is set to ``None``, meaning
1965
+ the size will be set by the default backend.
1966
+
1967
+ Examples
1968
+ ========
1969
+
1970
+ .. plot::
1971
+ :context: reset
1972
+ :format: doctest
1973
+ :include-source: True
1974
+
1975
+ >>> from sympy import plot_parametric, symbols, cos, sin
1976
+ >>> u = symbols('u')
1977
+
1978
+ A parametric plot with a single expression:
1979
+
1980
+ .. plot::
1981
+ :context: close-figs
1982
+ :format: doctest
1983
+ :include-source: True
1984
+
1985
+ >>> plot_parametric((cos(u), sin(u)), (u, -5, 5))
1986
+ Plot object containing:
1987
+ [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
1988
+
1989
+ A parametric plot with multiple expressions with the same range:
1990
+
1991
+ .. plot::
1992
+ :context: close-figs
1993
+ :format: doctest
1994
+ :include-source: True
1995
+
1996
+ >>> plot_parametric((cos(u), sin(u)), (u, cos(u)), (u, -10, 10))
1997
+ Plot object containing:
1998
+ [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0)
1999
+ [1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0)
2000
+
2001
+ A parametric plot with multiple expressions with different ranges
2002
+ for each curve:
2003
+
2004
+ .. plot::
2005
+ :context: close-figs
2006
+ :format: doctest
2007
+ :include-source: True
2008
+
2009
+ >>> plot_parametric((cos(u), sin(u), (u, -5, 5)),
2010
+ ... (cos(u), u, (u, -5, 5)))
2011
+ Plot object containing:
2012
+ [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
2013
+ [1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0)
2014
+
2015
+ Notes
2016
+ =====
2017
+
2018
+ The plotting uses an adaptive algorithm which samples recursively to
2019
+ accurately plot the curve. The adaptive algorithm uses a random point
2020
+ near the midpoint of two points that has to be further sampled.
2021
+ Hence, repeating the same plot command can give slightly different
2022
+ results because of the random sampling.
2023
+
2024
+ If there are multiple plots, then the same optional arguments are
2025
+ applied to all the plots drawn in the same canvas. If you want to
2026
+ set these options separately, you can index the returned ``Plot``
2027
+ object and set it.
2028
+
2029
+ For example, when you specify ``line_color`` once, it would be
2030
+ applied simultaneously to both series.
2031
+
2032
+ .. plot::
2033
+ :context: close-figs
2034
+ :format: doctest
2035
+ :include-source: True
2036
+
2037
+ >>> from sympy import pi
2038
+ >>> expr1 = (u, cos(2*pi*u)/2 + 1/2)
2039
+ >>> expr2 = (u, sin(2*pi*u)/2 + 1/2)
2040
+ >>> p = plot_parametric(expr1, expr2, (u, 0, 1), line_color='blue')
2041
+
2042
+ If you want to specify the line color for the specific series, you
2043
+ should index each item and apply the property manually.
2044
+
2045
+ .. plot::
2046
+ :context: close-figs
2047
+ :format: doctest
2048
+ :include-source: True
2049
+
2050
+ >>> p[0].line_color = 'red'
2051
+ >>> p.show()
2052
+
2053
+ See Also
2054
+ ========
2055
+
2056
+ Plot, Parametric2DLineSeries
2057
+ """
2058
+ args = list(map(sympify, args))
2059
+ series = []
2060
+ plot_expr = check_arguments(args, 2, 1)
2061
+ series = [Parametric2DLineSeries(*arg, **kwargs) for arg in plot_expr]
2062
+ plots = Plot(*series, **kwargs)
2063
+ if show:
2064
+ plots.show()
2065
+ return plots
2066
+
2067
+
2068
+ def plot3d_parametric_line(*args, show=True, **kwargs):
2069
+ """
2070
+ Plots a 3D parametric line plot.
2071
+
2072
+ Usage
2073
+ =====
2074
+
2075
+ Single plot:
2076
+
2077
+ ``plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)``
2078
+
2079
+ If the range is not specified, then a default range of (-10, 10) is used.
2080
+
2081
+ Multiple plots.
2082
+
2083
+ ``plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)``
2084
+
2085
+ Ranges have to be specified for every expression.
2086
+
2087
+ Default range may change in the future if a more advanced default range
2088
+ detection algorithm is implemented.
2089
+
2090
+ Arguments
2091
+ =========
2092
+
2093
+ expr_x : Expression representing the function along x.
2094
+
2095
+ expr_y : Expression representing the function along y.
2096
+
2097
+ expr_z : Expression representing the function along z.
2098
+
2099
+ range : (:class:`~.Symbol`, float, float)
2100
+ A 3-tuple denoting the range of the parameter variable, e.g., (u, 0, 5).
2101
+
2102
+ Keyword Arguments
2103
+ =================
2104
+
2105
+ Arguments for ``Parametric3DLineSeries`` class.
2106
+
2107
+ nb_of_points : The range is uniformly sampled at ``nb_of_points``
2108
+ number of points.
2109
+
2110
+ Aesthetics:
2111
+
2112
+ line_color : string, or float, or function, optional
2113
+ Specifies the color for the plot.
2114
+ See ``Plot`` to see how to set color for the plots.
2115
+ Note that by setting ``line_color``, it would be applied simultaneously
2116
+ to all the series.
2117
+
2118
+ label : str
2119
+ The label to the plot. It will be used when called with ``legend=True``
2120
+ to denote the function with the given label in the plot.
2121
+
2122
+ If there are multiple plots, then the same series arguments are applied to
2123
+ all the plots. If you want to set these options separately, you can index
2124
+ the returned ``Plot`` object and set it.
2125
+
2126
+ Arguments for ``Plot`` class.
2127
+
2128
+ title : str
2129
+ Title of the plot.
2130
+
2131
+ size : (float, float), optional
2132
+ A tuple in the form (width, height) in inches to specify the size of
2133
+ the overall figure. The default value is set to ``None``, meaning
2134
+ the size will be set by the default backend.
2135
+
2136
+ Examples
2137
+ ========
2138
+
2139
+ .. plot::
2140
+ :context: reset
2141
+ :format: doctest
2142
+ :include-source: True
2143
+
2144
+ >>> from sympy import symbols, cos, sin
2145
+ >>> from sympy.plotting import plot3d_parametric_line
2146
+ >>> u = symbols('u')
2147
+
2148
+ Single plot.
2149
+
2150
+ .. plot::
2151
+ :context: close-figs
2152
+ :format: doctest
2153
+ :include-source: True
2154
+
2155
+ >>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5))
2156
+ Plot object containing:
2157
+ [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
2158
+
2159
+
2160
+ Multiple plots.
2161
+
2162
+ .. plot::
2163
+ :context: close-figs
2164
+ :format: doctest
2165
+ :include-source: True
2166
+
2167
+ >>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)),
2168
+ ... (sin(u), u**2, u, (u, -5, 5)))
2169
+ Plot object containing:
2170
+ [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
2171
+ [1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0)
2172
+
2173
+
2174
+ See Also
2175
+ ========
2176
+
2177
+ Plot, Parametric3DLineSeries
2178
+
2179
+ """
2180
+ args = list(map(sympify, args))
2181
+ series = []
2182
+ plot_expr = check_arguments(args, 3, 1)
2183
+ series = [Parametric3DLineSeries(*arg, **kwargs) for arg in plot_expr]
2184
+ kwargs.setdefault("xlabel", "x")
2185
+ kwargs.setdefault("ylabel", "y")
2186
+ kwargs.setdefault("zlabel", "z")
2187
+ plots = Plot(*series, **kwargs)
2188
+ if show:
2189
+ plots.show()
2190
+ return plots
2191
+
2192
+
2193
+ def plot3d(*args, show=True, **kwargs):
2194
+ """
2195
+ Plots a 3D surface plot.
2196
+
2197
+ Usage
2198
+ =====
2199
+
2200
+ Single plot
2201
+
2202
+ ``plot3d(expr, range_x, range_y, **kwargs)``
2203
+
2204
+ If the ranges are not specified, then a default range of (-10, 10) is used.
2205
+
2206
+ Multiple plot with the same range.
2207
+
2208
+ ``plot3d(expr1, expr2, range_x, range_y, **kwargs)``
2209
+
2210
+ If the ranges are not specified, then a default range of (-10, 10) is used.
2211
+
2212
+ Multiple plots with different ranges.
2213
+
2214
+ ``plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
2215
+
2216
+ Ranges have to be specified for every expression.
2217
+
2218
+ Default range may change in the future if a more advanced default range
2219
+ detection algorithm is implemented.
2220
+
2221
+ Arguments
2222
+ =========
2223
+
2224
+ expr : Expression representing the function along x.
2225
+
2226
+ range_x : (:class:`~.Symbol`, float, float)
2227
+ A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).
2228
+
2229
+ range_y : (:class:`~.Symbol`, float, float)
2230
+ A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).
2231
+
2232
+ Keyword Arguments
2233
+ =================
2234
+
2235
+ Arguments for ``SurfaceOver2DRangeSeries`` class:
2236
+
2237
+ nb_of_points_x : int
2238
+ The x range is sampled uniformly at ``nb_of_points_x`` of points.
2239
+
2240
+ nb_of_points_y : int
2241
+ The y range is sampled uniformly at ``nb_of_points_y`` of points.
2242
+
2243
+ Aesthetics:
2244
+
2245
+ surface_color : Function which returns a float
2246
+ Specifies the color for the surface of the plot.
2247
+ See :class:`~.Plot` for more details.
2248
+
2249
+ If there are multiple plots, then the same series arguments are applied to
2250
+ all the plots. If you want to set these options separately, you can index
2251
+ the returned ``Plot`` object and set it.
2252
+
2253
+ Arguments for ``Plot`` class:
2254
+
2255
+ title : str
2256
+ Title of the plot.
2257
+
2258
+ size : (float, float), optional
2259
+ A tuple in the form (width, height) in inches to specify the size of the
2260
+ overall figure. The default value is set to ``None``, meaning the size will
2261
+ be set by the default backend.
2262
+
2263
+ Examples
2264
+ ========
2265
+
2266
+ .. plot::
2267
+ :context: reset
2268
+ :format: doctest
2269
+ :include-source: True
2270
+
2271
+ >>> from sympy import symbols
2272
+ >>> from sympy.plotting import plot3d
2273
+ >>> x, y = symbols('x y')
2274
+
2275
+ Single plot
2276
+
2277
+ .. plot::
2278
+ :context: close-figs
2279
+ :format: doctest
2280
+ :include-source: True
2281
+
2282
+ >>> plot3d(x*y, (x, -5, 5), (y, -5, 5))
2283
+ Plot object containing:
2284
+ [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
2285
+
2286
+
2287
+ Multiple plots with same range
2288
+
2289
+ .. plot::
2290
+ :context: close-figs
2291
+ :format: doctest
2292
+ :include-source: True
2293
+
2294
+ >>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5))
2295
+ Plot object containing:
2296
+ [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
2297
+ [1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
2298
+
2299
+
2300
+ Multiple plots with different ranges.
2301
+
2302
+ .. plot::
2303
+ :context: close-figs
2304
+ :format: doctest
2305
+ :include-source: True
2306
+
2307
+ >>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)),
2308
+ ... (x*y, (x, -3, 3), (y, -3, 3)))
2309
+ Plot object containing:
2310
+ [0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0)
2311
+ [1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0)
2312
+
2313
+
2314
+ See Also
2315
+ ========
2316
+
2317
+ Plot, SurfaceOver2DRangeSeries
2318
+
2319
+ """
2320
+
2321
+ args = list(map(sympify, args))
2322
+ series = []
2323
+ plot_expr = check_arguments(args, 1, 2)
2324
+ series = [SurfaceOver2DRangeSeries(*arg, **kwargs) for arg in plot_expr]
2325
+ kwargs.setdefault("xlabel", series[0].var_x)
2326
+ kwargs.setdefault("ylabel", series[0].var_y)
2327
+ kwargs.setdefault("zlabel", Function('f')(series[0].var_x, series[0].var_y))
2328
+ plots = Plot(*series, **kwargs)
2329
+ if show:
2330
+ plots.show()
2331
+ return plots
2332
+
2333
+
2334
+ def plot3d_parametric_surface(*args, show=True, **kwargs):
2335
+ """
2336
+ Plots a 3D parametric surface plot.
2337
+
2338
+ Explanation
2339
+ ===========
2340
+
2341
+ Single plot.
2342
+
2343
+ ``plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)``
2344
+
2345
+ If the ranges is not specified, then a default range of (-10, 10) is used.
2346
+
2347
+ Multiple plots.
2348
+
2349
+ ``plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)``
2350
+
2351
+ Ranges have to be specified for every expression.
2352
+
2353
+ Default range may change in the future if a more advanced default range
2354
+ detection algorithm is implemented.
2355
+
2356
+ Arguments
2357
+ =========
2358
+
2359
+ expr_x : Expression representing the function along ``x``.
2360
+
2361
+ expr_y : Expression representing the function along ``y``.
2362
+
2363
+ expr_z : Expression representing the function along ``z``.
2364
+
2365
+ range_u : (:class:`~.Symbol`, float, float)
2366
+ A 3-tuple denoting the range of the u variable, e.g. (u, 0, 5).
2367
+
2368
+ range_v : (:class:`~.Symbol`, float, float)
2369
+ A 3-tuple denoting the range of the v variable, e.g. (v, 0, 5).
2370
+
2371
+ Keyword Arguments
2372
+ =================
2373
+
2374
+ Arguments for ``ParametricSurfaceSeries`` class:
2375
+
2376
+ nb_of_points_u : int
2377
+ The ``u`` range is sampled uniformly at ``nb_of_points_v`` of points
2378
+
2379
+ nb_of_points_y : int
2380
+ The ``v`` range is sampled uniformly at ``nb_of_points_y`` of points
2381
+
2382
+ Aesthetics:
2383
+
2384
+ surface_color : Function which returns a float
2385
+ Specifies the color for the surface of the plot. See
2386
+ :class:`~Plot` for more details.
2387
+
2388
+ If there are multiple plots, then the same series arguments are applied for
2389
+ all the plots. If you want to set these options separately, you can index
2390
+ the returned ``Plot`` object and set it.
2391
+
2392
+
2393
+ Arguments for ``Plot`` class:
2394
+
2395
+ title : str
2396
+ Title of the plot.
2397
+
2398
+ size : (float, float), optional
2399
+ A tuple in the form (width, height) in inches to specify the size of the
2400
+ overall figure. The default value is set to ``None``, meaning the size will
2401
+ be set by the default backend.
2402
+
2403
+ Examples
2404
+ ========
2405
+
2406
+ .. plot::
2407
+ :context: reset
2408
+ :format: doctest
2409
+ :include-source: True
2410
+
2411
+ >>> from sympy import symbols, cos, sin
2412
+ >>> from sympy.plotting import plot3d_parametric_surface
2413
+ >>> u, v = symbols('u v')
2414
+
2415
+ Single plot.
2416
+
2417
+ .. plot::
2418
+ :context: close-figs
2419
+ :format: doctest
2420
+ :include-source: True
2421
+
2422
+ >>> plot3d_parametric_surface(cos(u + v), sin(u - v), u - v,
2423
+ ... (u, -5, 5), (v, -5, 5))
2424
+ Plot object containing:
2425
+ [0]: parametric cartesian surface: (cos(u + v), sin(u - v), u - v) for u over (-5.0, 5.0) and v over (-5.0, 5.0)
2426
+
2427
+
2428
+ See Also
2429
+ ========
2430
+
2431
+ Plot, ParametricSurfaceSeries
2432
+
2433
+ """
2434
+
2435
+ args = list(map(sympify, args))
2436
+ series = []
2437
+ plot_expr = check_arguments(args, 3, 2)
2438
+ series = [ParametricSurfaceSeries(*arg, **kwargs) for arg in plot_expr]
2439
+ kwargs.setdefault("xlabel", "x")
2440
+ kwargs.setdefault("ylabel", "y")
2441
+ kwargs.setdefault("zlabel", "z")
2442
+ plots = Plot(*series, **kwargs)
2443
+ if show:
2444
+ plots.show()
2445
+ return plots
2446
+
2447
+ def plot_contour(*args, show=True, **kwargs):
2448
+ """
2449
+ Draws contour plot of a function
2450
+
2451
+ Usage
2452
+ =====
2453
+
2454
+ Single plot
2455
+
2456
+ ``plot_contour(expr, range_x, range_y, **kwargs)``
2457
+
2458
+ If the ranges are not specified, then a default range of (-10, 10) is used.
2459
+
2460
+ Multiple plot with the same range.
2461
+
2462
+ ``plot_contour(expr1, expr2, range_x, range_y, **kwargs)``
2463
+
2464
+ If the ranges are not specified, then a default range of (-10, 10) is used.
2465
+
2466
+ Multiple plots with different ranges.
2467
+
2468
+ ``plot_contour((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
2469
+
2470
+ Ranges have to be specified for every expression.
2471
+
2472
+ Default range may change in the future if a more advanced default range
2473
+ detection algorithm is implemented.
2474
+
2475
+ Arguments
2476
+ =========
2477
+
2478
+ expr : Expression representing the function along x.
2479
+
2480
+ range_x : (:class:`Symbol`, float, float)
2481
+ A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).
2482
+
2483
+ range_y : (:class:`Symbol`, float, float)
2484
+ A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).
2485
+
2486
+ Keyword Arguments
2487
+ =================
2488
+
2489
+ Arguments for ``ContourSeries`` class:
2490
+
2491
+ nb_of_points_x : int
2492
+ The x range is sampled uniformly at ``nb_of_points_x`` of points.
2493
+
2494
+ nb_of_points_y : int
2495
+ The y range is sampled uniformly at ``nb_of_points_y`` of points.
2496
+
2497
+ Aesthetics:
2498
+
2499
+ surface_color : Function which returns a float
2500
+ Specifies the color for the surface of the plot. See
2501
+ :class:`sympy.plotting.Plot` for more details.
2502
+
2503
+ If there are multiple plots, then the same series arguments are applied to
2504
+ all the plots. If you want to set these options separately, you can index
2505
+ the returned ``Plot`` object and set it.
2506
+
2507
+ Arguments for ``Plot`` class:
2508
+
2509
+ title : str
2510
+ Title of the plot.
2511
+
2512
+ size : (float, float), optional
2513
+ A tuple in the form (width, height) in inches to specify the size of
2514
+ the overall figure. The default value is set to ``None``, meaning
2515
+ the size will be set by the default backend.
2516
+
2517
+ See Also
2518
+ ========
2519
+
2520
+ Plot, ContourSeries
2521
+
2522
+ """
2523
+
2524
+ args = list(map(sympify, args))
2525
+ plot_expr = check_arguments(args, 1, 2)
2526
+ series = [ContourSeries(*arg) for arg in plot_expr]
2527
+ plot_contours = Plot(*series, **kwargs)
2528
+ if len(plot_expr[0].free_symbols) > 2:
2529
+ raise ValueError('Contour Plot cannot Plot for more than two variables.')
2530
+ if show:
2531
+ plot_contours.show()
2532
+ return plot_contours
2533
+
2534
+ def check_arguments(args, expr_len, nb_of_free_symbols):
2535
+ """
2536
+ Checks the arguments and converts into tuples of the
2537
+ form (exprs, ranges).
2538
+
2539
+ Examples
2540
+ ========
2541
+
2542
+ .. plot::
2543
+ :context: reset
2544
+ :format: doctest
2545
+ :include-source: True
2546
+
2547
+ >>> from sympy import cos, sin, symbols
2548
+ >>> from sympy.plotting.plot import check_arguments
2549
+ >>> x = symbols('x')
2550
+ >>> check_arguments([cos(x), sin(x)], 2, 1)
2551
+ [(cos(x), sin(x), (x, -10, 10))]
2552
+
2553
+ >>> check_arguments([x, x**2], 1, 1)
2554
+ [(x, (x, -10, 10)), (x**2, (x, -10, 10))]
2555
+ """
2556
+ if not args:
2557
+ return []
2558
+ if expr_len > 1 and isinstance(args[0], Expr):
2559
+ # Multiple expressions same range.
2560
+ # The arguments are tuples when the expression length is
2561
+ # greater than 1.
2562
+ if len(args) < expr_len:
2563
+ raise ValueError("len(args) should not be less than expr_len")
2564
+ for i in range(len(args)):
2565
+ if isinstance(args[i], Tuple):
2566
+ break
2567
+ else:
2568
+ i = len(args) + 1
2569
+
2570
+ exprs = Tuple(*args[:i])
2571
+ free_symbols = list(set().union(*[e.free_symbols for e in exprs]))
2572
+ if len(args) == expr_len + nb_of_free_symbols:
2573
+ #Ranges given
2574
+ plots = [exprs + Tuple(*args[expr_len:])]
2575
+ else:
2576
+ default_range = Tuple(-10, 10)
2577
+ ranges = []
2578
+ for symbol in free_symbols:
2579
+ ranges.append(Tuple(symbol) + default_range)
2580
+
2581
+ for i in range(len(free_symbols) - nb_of_free_symbols):
2582
+ ranges.append(Tuple(Dummy()) + default_range)
2583
+ plots = [exprs + Tuple(*ranges)]
2584
+ return plots
2585
+
2586
+ if isinstance(args[0], Expr) or (isinstance(args[0], Tuple) and
2587
+ len(args[0]) == expr_len and
2588
+ expr_len != 3):
2589
+ # Cannot handle expressions with number of expression = 3. It is
2590
+ # not possible to differentiate between expressions and ranges.
2591
+ #Series of plots with same range
2592
+ for i in range(len(args)):
2593
+ if isinstance(args[i], Tuple) and len(args[i]) != expr_len:
2594
+ break
2595
+ if not isinstance(args[i], Tuple):
2596
+ args[i] = Tuple(args[i])
2597
+ else:
2598
+ i = len(args) + 1
2599
+
2600
+ exprs = args[:i]
2601
+ assert all(isinstance(e, Expr) for expr in exprs for e in expr)
2602
+ free_symbols = list(set().union(*[e.free_symbols for expr in exprs
2603
+ for e in expr]))
2604
+
2605
+ if len(free_symbols) > nb_of_free_symbols:
2606
+ raise ValueError("The number of free_symbols in the expression "
2607
+ "is greater than %d" % nb_of_free_symbols)
2608
+ if len(args) == i + nb_of_free_symbols and isinstance(args[i], Tuple):
2609
+ ranges = Tuple(*list(args[
2610
+ i:i + nb_of_free_symbols]))
2611
+ plots = [expr + ranges for expr in exprs]
2612
+ return plots
2613
+ else:
2614
+ # Use default ranges.
2615
+ default_range = Tuple(-10, 10)
2616
+ ranges = []
2617
+ for symbol in free_symbols:
2618
+ ranges.append(Tuple(symbol) + default_range)
2619
+
2620
+ for i in range(nb_of_free_symbols - len(free_symbols)):
2621
+ ranges.append(Tuple(Dummy()) + default_range)
2622
+ ranges = Tuple(*ranges)
2623
+ plots = [expr + ranges for expr in exprs]
2624
+ return plots
2625
+
2626
+ elif isinstance(args[0], Tuple) and len(args[0]) == expr_len + nb_of_free_symbols:
2627
+ # Multiple plots with different ranges.
2628
+ for arg in args:
2629
+ for i in range(expr_len):
2630
+ if not isinstance(arg[i], Expr):
2631
+ raise ValueError("Expected an expression, given %s" %
2632
+ str(arg[i]))
2633
+ for i in range(nb_of_free_symbols):
2634
+ if not len(arg[i + expr_len]) == 3:
2635
+ raise ValueError("The ranges should be a tuple of "
2636
+ "length 3, got %s" % str(arg[i + expr_len]))
2637
+ return args
venv/lib/python3.10/site-packages/sympy/plotting/plot_implicit.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implicit plotting module for SymPy.
2
+
3
+ Explanation
4
+ ===========
5
+
6
+ The module implements a data series called ImplicitSeries which is used by
7
+ ``Plot`` class to plot implicit plots for different backends. The module,
8
+ by default, implements plotting using interval arithmetic. It switches to a
9
+ fall back algorithm if the expression cannot be plotted using interval arithmetic.
10
+ It is also possible to specify to use the fall back algorithm for all plots.
11
+
12
+ Boolean combinations of expressions cannot be plotted by the fall back
13
+ algorithm.
14
+
15
+ See Also
16
+ ========
17
+
18
+ sympy.plotting.plot
19
+
20
+ References
21
+ ==========
22
+
23
+ .. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for
24
+ Mathematical Formulae with Two Free Variables.
25
+
26
+ .. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval
27
+ Arithmetic. Master's thesis. University of Toronto, 1996
28
+
29
+ """
30
+
31
+
32
+ from .plot import BaseSeries, Plot
33
+ from .experimental_lambdify import experimental_lambdify, vectorized_lambdify
34
+ from .intervalmath import interval
35
+ from sympy.core.relational import (Equality, GreaterThan, LessThan,
36
+ Relational, StrictLessThan, StrictGreaterThan)
37
+ from sympy.core.containers import Tuple
38
+ from sympy.core.relational import Eq
39
+ from sympy.core.symbol import (Dummy, Symbol)
40
+ from sympy.core.sympify import sympify
41
+ from sympy.external import import_module
42
+ from sympy.logic.boolalg import BooleanFunction
43
+ from sympy.polys.polyutils import _sort_gens
44
+ from sympy.utilities.decorator import doctest_depends_on
45
+ from sympy.utilities.iterables import flatten
46
+ import warnings
47
+
48
+
49
+ class ImplicitSeries(BaseSeries):
50
+ """ Representation for Implicit plot """
51
+ is_implicit = True
52
+
53
+ def __init__(self, expr, var_start_end_x, var_start_end_y,
54
+ has_equality, use_interval_math, depth, nb_of_points,
55
+ line_color):
56
+ super().__init__()
57
+ self.expr = sympify(expr)
58
+ self.label = self.expr
59
+ self.var_x = sympify(var_start_end_x[0])
60
+ self.start_x = float(var_start_end_x[1])
61
+ self.end_x = float(var_start_end_x[2])
62
+ self.var_y = sympify(var_start_end_y[0])
63
+ self.start_y = float(var_start_end_y[1])
64
+ self.end_y = float(var_start_end_y[2])
65
+ self.get_points = self.get_raster
66
+ self.has_equality = has_equality # If the expression has equality, i.e.
67
+ #Eq, Greaterthan, LessThan.
68
+ self.nb_of_points = nb_of_points
69
+ self.use_interval_math = use_interval_math
70
+ self.depth = 4 + depth
71
+ self.line_color = line_color
72
+
73
+ def __str__(self):
74
+ return ('Implicit equation: %s for '
75
+ '%s over %s and %s over %s') % (
76
+ str(self.expr),
77
+ str(self.var_x),
78
+ str((self.start_x, self.end_x)),
79
+ str(self.var_y),
80
+ str((self.start_y, self.end_y)))
81
+
82
+ def get_raster(self):
83
+ func = experimental_lambdify((self.var_x, self.var_y), self.expr,
84
+ use_interval=True)
85
+ xinterval = interval(self.start_x, self.end_x)
86
+ yinterval = interval(self.start_y, self.end_y)
87
+ try:
88
+ func(xinterval, yinterval)
89
+ except AttributeError:
90
+ # XXX: AttributeError("'list' object has no attribute 'is_real'")
91
+ # That needs fixing somehow - we shouldn't be catching
92
+ # AttributeError here.
93
+ if self.use_interval_math:
94
+ warnings.warn("Adaptive meshing could not be applied to the"
95
+ " expression. Using uniform meshing.", stacklevel=7)
96
+ self.use_interval_math = False
97
+
98
+ if self.use_interval_math:
99
+ return self._get_raster_interval(func)
100
+ else:
101
+ return self._get_meshes_grid()
102
+
103
+ def _get_raster_interval(self, func):
104
+ """ Uses interval math to adaptively mesh and obtain the plot"""
105
+ k = self.depth
106
+ interval_list = []
107
+ #Create initial 32 divisions
108
+ np = import_module('numpy')
109
+ xsample = np.linspace(self.start_x, self.end_x, 33)
110
+ ysample = np.linspace(self.start_y, self.end_y, 33)
111
+
112
+ #Add a small jitter so that there are no false positives for equality.
113
+ # Ex: y==x becomes True for x interval(1, 2) and y interval(1, 2)
114
+ #which will draw a rectangle.
115
+ jitterx = (np.random.rand(
116
+ len(xsample)) * 2 - 1) * (self.end_x - self.start_x) / 2**20
117
+ jittery = (np.random.rand(
118
+ len(ysample)) * 2 - 1) * (self.end_y - self.start_y) / 2**20
119
+ xsample += jitterx
120
+ ysample += jittery
121
+
122
+ xinter = [interval(x1, x2) for x1, x2 in zip(xsample[:-1],
123
+ xsample[1:])]
124
+ yinter = [interval(y1, y2) for y1, y2 in zip(ysample[:-1],
125
+ ysample[1:])]
126
+ interval_list = [[x, y] for x in xinter for y in yinter]
127
+ plot_list = []
128
+
129
+ #recursive call refinepixels which subdivides the intervals which are
130
+ #neither True nor False according to the expression.
131
+ def refine_pixels(interval_list):
132
+ """ Evaluates the intervals and subdivides the interval if the
133
+ expression is partially satisfied."""
134
+ temp_interval_list = []
135
+ plot_list = []
136
+ for intervals in interval_list:
137
+
138
+ #Convert the array indices to x and y values
139
+ intervalx = intervals[0]
140
+ intervaly = intervals[1]
141
+ func_eval = func(intervalx, intervaly)
142
+ #The expression is valid in the interval. Change the contour
143
+ #array values to 1.
144
+ if func_eval[1] is False or func_eval[0] is False:
145
+ pass
146
+ elif func_eval == (True, True):
147
+ plot_list.append([intervalx, intervaly])
148
+ elif func_eval[1] is None or func_eval[0] is None:
149
+ #Subdivide
150
+ avgx = intervalx.mid
151
+ avgy = intervaly.mid
152
+ a = interval(intervalx.start, avgx)
153
+ b = interval(avgx, intervalx.end)
154
+ c = interval(intervaly.start, avgy)
155
+ d = interval(avgy, intervaly.end)
156
+ temp_interval_list.append([a, c])
157
+ temp_interval_list.append([a, d])
158
+ temp_interval_list.append([b, c])
159
+ temp_interval_list.append([b, d])
160
+ return temp_interval_list, plot_list
161
+
162
+ while k >= 0 and len(interval_list):
163
+ interval_list, plot_list_temp = refine_pixels(interval_list)
164
+ plot_list.extend(plot_list_temp)
165
+ k = k - 1
166
+ #Check whether the expression represents an equality
167
+ #If it represents an equality, then none of the intervals
168
+ #would have satisfied the expression due to floating point
169
+ #differences. Add all the undecided values to the plot.
170
+ if self.has_equality:
171
+ for intervals in interval_list:
172
+ intervalx = intervals[0]
173
+ intervaly = intervals[1]
174
+ func_eval = func(intervalx, intervaly)
175
+ if func_eval[1] and func_eval[0] is not False:
176
+ plot_list.append([intervalx, intervaly])
177
+ return plot_list, 'fill'
178
+
179
+ def _get_meshes_grid(self):
180
+ """Generates the mesh for generating a contour.
181
+
182
+ In the case of equality, ``contour`` function of matplotlib can
183
+ be used. In other cases, matplotlib's ``contourf`` is used.
184
+ """
185
+ equal = False
186
+ if isinstance(self.expr, Equality):
187
+ expr = self.expr.lhs - self.expr.rhs
188
+ equal = True
189
+
190
+ elif isinstance(self.expr, (GreaterThan, StrictGreaterThan)):
191
+ expr = self.expr.lhs - self.expr.rhs
192
+
193
+ elif isinstance(self.expr, (LessThan, StrictLessThan)):
194
+ expr = self.expr.rhs - self.expr.lhs
195
+ else:
196
+ raise NotImplementedError("The expression is not supported for "
197
+ "plotting in uniform meshed plot.")
198
+ np = import_module('numpy')
199
+ xarray = np.linspace(self.start_x, self.end_x, self.nb_of_points)
200
+ yarray = np.linspace(self.start_y, self.end_y, self.nb_of_points)
201
+ x_grid, y_grid = np.meshgrid(xarray, yarray)
202
+
203
+ func = vectorized_lambdify((self.var_x, self.var_y), expr)
204
+ z_grid = func(x_grid, y_grid)
205
+ z_grid[np.ma.where(z_grid < 0)] = -1
206
+ z_grid[np.ma.where(z_grid > 0)] = 1
207
+ if equal:
208
+ return xarray, yarray, z_grid, 'contour'
209
+ else:
210
+ return xarray, yarray, z_grid, 'contourf'
211
+
212
+
213
+ @doctest_depends_on(modules=('matplotlib',))
214
+ def plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0,
215
+ points=300, line_color="blue", show=True, **kwargs):
216
+ """A plot function to plot implicit equations / inequalities.
217
+
218
+ Arguments
219
+ =========
220
+
221
+ - expr : The equation / inequality that is to be plotted.
222
+ - x_var (optional) : symbol to plot on x-axis or tuple giving symbol
223
+ and range as ``(symbol, xmin, xmax)``
224
+ - y_var (optional) : symbol to plot on y-axis or tuple giving symbol
225
+ and range as ``(symbol, ymin, ymax)``
226
+
227
+ If neither ``x_var`` nor ``y_var`` are given then the free symbols in the
228
+ expression will be assigned in the order they are sorted.
229
+
230
+ The following keyword arguments can also be used:
231
+
232
+ - ``adaptive`` Boolean. The default value is set to True. It has to be
233
+ set to False if you want to use a mesh grid.
234
+
235
+ - ``depth`` integer. The depth of recursion for adaptive mesh grid.
236
+ Default value is 0. Takes value in the range (0, 4).
237
+
238
+ - ``points`` integer. The number of points if adaptive mesh grid is not
239
+ used. Default value is 300.
240
+
241
+ - ``show`` Boolean. Default value is True. If set to False, the plot will
242
+ not be shown. See ``Plot`` for further information.
243
+
244
+ - ``title`` string. The title for the plot.
245
+
246
+ - ``xlabel`` string. The label for the x-axis
247
+
248
+ - ``ylabel`` string. The label for the y-axis
249
+
250
+ Aesthetics options:
251
+
252
+ - ``line_color``: float or string. Specifies the color for the plot.
253
+ See ``Plot`` to see how to set color for the plots.
254
+ Default value is "Blue"
255
+
256
+ plot_implicit, by default, uses interval arithmetic to plot functions. If
257
+ the expression cannot be plotted using interval arithmetic, it defaults to
258
+ a generating a contour using a mesh grid of fixed number of points. By
259
+ setting adaptive to False, you can force plot_implicit to use the mesh
260
+ grid. The mesh grid method can be effective when adaptive plotting using
261
+ interval arithmetic, fails to plot with small line width.
262
+
263
+ Examples
264
+ ========
265
+
266
+ Plot expressions:
267
+
268
+ .. plot::
269
+ :context: reset
270
+ :format: doctest
271
+ :include-source: True
272
+
273
+ >>> from sympy import plot_implicit, symbols, Eq, And
274
+ >>> x, y = symbols('x y')
275
+
276
+ Without any ranges for the symbols in the expression:
277
+
278
+ .. plot::
279
+ :context: close-figs
280
+ :format: doctest
281
+ :include-source: True
282
+
283
+ >>> p1 = plot_implicit(Eq(x**2 + y**2, 5))
284
+
285
+ With the range for the symbols:
286
+
287
+ .. plot::
288
+ :context: close-figs
289
+ :format: doctest
290
+ :include-source: True
291
+
292
+ >>> p2 = plot_implicit(
293
+ ... Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3))
294
+
295
+ With depth of recursion as argument:
296
+
297
+ .. plot::
298
+ :context: close-figs
299
+ :format: doctest
300
+ :include-source: True
301
+
302
+ >>> p3 = plot_implicit(
303
+ ... Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2)
304
+
305
+ Using mesh grid and not using adaptive meshing:
306
+
307
+ .. plot::
308
+ :context: close-figs
309
+ :format: doctest
310
+ :include-source: True
311
+
312
+ >>> p4 = plot_implicit(
313
+ ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
314
+ ... adaptive=False)
315
+
316
+ Using mesh grid without using adaptive meshing with number of points
317
+ specified:
318
+
319
+ .. plot::
320
+ :context: close-figs
321
+ :format: doctest
322
+ :include-source: True
323
+
324
+ >>> p5 = plot_implicit(
325
+ ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
326
+ ... adaptive=False, points=400)
327
+
328
+ Plotting regions:
329
+
330
+ .. plot::
331
+ :context: close-figs
332
+ :format: doctest
333
+ :include-source: True
334
+
335
+ >>> p6 = plot_implicit(y > x**2)
336
+
337
+ Plotting Using boolean conjunctions:
338
+
339
+ .. plot::
340
+ :context: close-figs
341
+ :format: doctest
342
+ :include-source: True
343
+
344
+ >>> p7 = plot_implicit(And(y > x, y > -x))
345
+
346
+ When plotting an expression with a single variable (y - 1, for example),
347
+ specify the x or the y variable explicitly:
348
+
349
+ .. plot::
350
+ :context: close-figs
351
+ :format: doctest
352
+ :include-source: True
353
+
354
+ >>> p8 = plot_implicit(y - 1, y_var=y)
355
+ >>> p9 = plot_implicit(x - 1, x_var=x)
356
+ """
357
+ has_equality = False # Represents whether the expression contains an Equality,
358
+ #GreaterThan or LessThan
359
+
360
+ def arg_expand(bool_expr):
361
+ """
362
+ Recursively expands the arguments of an Boolean Function
363
+ """
364
+ for arg in bool_expr.args:
365
+ if isinstance(arg, BooleanFunction):
366
+ arg_expand(arg)
367
+ elif isinstance(arg, Relational):
368
+ arg_list.append(arg)
369
+
370
+ arg_list = []
371
+ if isinstance(expr, BooleanFunction):
372
+ arg_expand(expr)
373
+
374
+ #Check whether there is an equality in the expression provided.
375
+ if any(isinstance(e, (Equality, GreaterThan, LessThan))
376
+ for e in arg_list):
377
+ has_equality = True
378
+
379
+ elif not isinstance(expr, Relational):
380
+ expr = Eq(expr, 0)
381
+ has_equality = True
382
+ elif isinstance(expr, (Equality, GreaterThan, LessThan)):
383
+ has_equality = True
384
+
385
+ xyvar = [i for i in (x_var, y_var) if i is not None]
386
+ free_symbols = expr.free_symbols
387
+ range_symbols = Tuple(*flatten(xyvar)).free_symbols
388
+ undeclared = free_symbols - range_symbols
389
+ if len(free_symbols & range_symbols) > 2:
390
+ raise NotImplementedError("Implicit plotting is not implemented for "
391
+ "more than 2 variables")
392
+
393
+ #Create default ranges if the range is not provided.
394
+ default_range = Tuple(-5, 5)
395
+ def _range_tuple(s):
396
+ if isinstance(s, Symbol):
397
+ return Tuple(s) + default_range
398
+ if len(s) == 3:
399
+ return Tuple(*s)
400
+ raise ValueError('symbol or `(symbol, min, max)` expected but got %s' % s)
401
+
402
+ if len(xyvar) == 0:
403
+ xyvar = list(_sort_gens(free_symbols))
404
+ var_start_end_x = _range_tuple(xyvar[0])
405
+ x = var_start_end_x[0]
406
+ if len(xyvar) != 2:
407
+ if x in undeclared or not undeclared:
408
+ xyvar.append(Dummy('f(%s)' % x.name))
409
+ else:
410
+ xyvar.append(undeclared.pop())
411
+ var_start_end_y = _range_tuple(xyvar[1])
412
+
413
+ #Check whether the depth is greater than 4 or less than 0.
414
+ if depth > 4:
415
+ depth = 4
416
+ elif depth < 0:
417
+ depth = 0
418
+
419
+ series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y,
420
+ has_equality, adaptive, depth,
421
+ points, line_color)
422
+
423
+ #set the x and y limits
424
+ kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:])
425
+ kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:])
426
+ # set the x and y labels
427
+ kwargs.setdefault('xlabel', var_start_end_x[0])
428
+ kwargs.setdefault('ylabel', var_start_end_y[0])
429
+ p = Plot(series_argument, **kwargs)
430
+ if show:
431
+ p.show()
432
+ return p
venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__init__.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plotting module that can plot 2D and 3D functions
2
+ """
3
+
4
+ from sympy.utilities.decorator import doctest_depends_on
5
+
6
+ @doctest_depends_on(modules=('pyglet',))
7
+ def PygletPlot(*args, **kwargs):
8
+ """
9
+
10
+ Plot Examples
11
+ =============
12
+
13
+ See examples/advanced/pyglet_plotting.py for many more examples.
14
+
15
+ >>> from sympy.plotting.pygletplot import PygletPlot as Plot
16
+ >>> from sympy.abc import x, y, z
17
+
18
+ >>> Plot(x*y**3-y*x**3)
19
+ [0]: -x**3*y + x*y**3, 'mode=cartesian'
20
+
21
+ >>> p = Plot()
22
+ >>> p[1] = x*y
23
+ >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
24
+
25
+ >>> p = Plot()
26
+ >>> p[1] = x**2+y**2
27
+ >>> p[2] = -x**2-y**2
28
+
29
+
30
+ Variable Intervals
31
+ ==================
32
+
33
+ The basic format is [var, min, max, steps], but the
34
+ syntax is flexible and arguments left out are taken
35
+ from the defaults for the current coordinate mode:
36
+
37
+ >>> Plot(x**2) # implies [x,-5,5,100]
38
+ [0]: x**2, 'mode=cartesian'
39
+
40
+ >>> Plot(x**2, [], []) # [x,-1,1,40], [y,-1,1,40]
41
+ [0]: x**2, 'mode=cartesian'
42
+ >>> Plot(x**2-y**2, [100], [100]) # [x,-1,1,100], [y,-1,1,100]
43
+ [0]: x**2 - y**2, 'mode=cartesian'
44
+ >>> Plot(x**2, [x,-13,13,100])
45
+ [0]: x**2, 'mode=cartesian'
46
+ >>> Plot(x**2, [-13,13]) # [x,-13,13,100]
47
+ [0]: x**2, 'mode=cartesian'
48
+ >>> Plot(x**2, [x,-13,13]) # [x,-13,13,100]
49
+ [0]: x**2, 'mode=cartesian'
50
+ >>> Plot(1*x, [], [x], mode='cylindrical')
51
+ ... # [unbound_theta,0,2*Pi,40], [x,-1,1,20]
52
+ [0]: x, 'mode=cartesian'
53
+
54
+
55
+ Coordinate Modes
56
+ ================
57
+
58
+ Plot supports several curvilinear coordinate modes, and
59
+ they independent for each plotted function. You can specify
60
+ a coordinate mode explicitly with the 'mode' named argument,
61
+ but it can be automatically determined for Cartesian or
62
+ parametric plots, and therefore must only be specified for
63
+ polar, cylindrical, and spherical modes.
64
+
65
+ Specifically, Plot(function arguments) and Plot[n] =
66
+ (function arguments) will interpret your arguments as a
67
+ Cartesian plot if you provide one function and a parametric
68
+ plot if you provide two or three functions. Similarly, the
69
+ arguments will be interpreted as a curve if one variable is
70
+ used, and a surface if two are used.
71
+
72
+ Supported mode names by number of variables:
73
+
74
+ 1: parametric, cartesian, polar
75
+ 2: parametric, cartesian, cylindrical = polar, spherical
76
+
77
+ >>> Plot(1, mode='spherical')
78
+
79
+
80
+ Calculator-like Interface
81
+ =========================
82
+
83
+ >>> p = Plot(visible=False)
84
+ >>> f = x**2
85
+ >>> p[1] = f
86
+ >>> p[2] = f.diff(x)
87
+ >>> p[3] = f.diff(x).diff(x)
88
+ >>> p
89
+ [1]: x**2, 'mode=cartesian'
90
+ [2]: 2*x, 'mode=cartesian'
91
+ [3]: 2, 'mode=cartesian'
92
+ >>> p.show()
93
+ >>> p.clear()
94
+ >>> p
95
+ <blank plot>
96
+ >>> p[1] = x**2+y**2
97
+ >>> p[1].style = 'solid'
98
+ >>> p[2] = -x**2-y**2
99
+ >>> p[2].style = 'wireframe'
100
+ >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
101
+ >>> p[1].style = 'both'
102
+ >>> p[2].style = 'both'
103
+ >>> p.close()
104
+
105
+
106
+ Plot Window Keyboard Controls
107
+ =============================
108
+
109
+ Screen Rotation:
110
+ X,Y axis Arrow Keys, A,S,D,W, Numpad 4,6,8,2
111
+ Z axis Q,E, Numpad 7,9
112
+
113
+ Model Rotation:
114
+ Z axis Z,C, Numpad 1,3
115
+
116
+ Zoom: R,F, PgUp,PgDn, Numpad +,-
117
+
118
+ Reset Camera: X, Numpad 5
119
+
120
+ Camera Presets:
121
+ XY F1
122
+ XZ F2
123
+ YZ F3
124
+ Perspective F4
125
+
126
+ Sensitivity Modifier: SHIFT
127
+
128
+ Axes Toggle:
129
+ Visible F5
130
+ Colors F6
131
+
132
+ Close Window: ESCAPE
133
+
134
+ =============================
135
+ """
136
+
137
+ from sympy.plotting.pygletplot.plot import PygletPlot
138
+ return PygletPlot(*args, **kwargs)
venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.99 kB). View file