Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/17.attention.query_key_value.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/24.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/24.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/25.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/8.post_attention_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/8.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/8.post_attention_layernorm.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/aesaracode.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/c.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/codeprinter.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/conventions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/cxx.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/defaults.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/dot.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/fortran.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/glsl.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/gtk.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/jscode.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/julia.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/lambdarepr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/latex.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/llvmjitcode.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/maple.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/mathml.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/numpy.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/octave.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/precedence.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/preview.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/printer.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/pycode.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/python.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/rcode.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/repr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/rust.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/smtlib.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/str.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/tableform.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/tensorflow.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/theanocode.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/tree.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/conventions.py +88 -0
- venv/lib/python3.10/site-packages/sympy/printing/defaults.py +5 -0
- venv/lib/python3.10/site-packages/sympy/printing/fortran.py +782 -0
- venv/lib/python3.10/site-packages/sympy/printing/jscode.py +339 -0
- venv/lib/python3.10/site-packages/sympy/printing/latex.py +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/maple.py +311 -0
- venv/lib/python3.10/site-packages/sympy/printing/mathml.py +2126 -0
- venv/lib/python3.10/site-packages/sympy/printing/numpy.py +507 -0
- venv/lib/python3.10/site-packages/sympy/printing/pretty/__init__.py +12 -0
ckpts/universal/global_step80/zero/17.attention.query_key_value.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:68f0995291896fb0c60bf50061a75e1e24302a5f6ec758f1297fefa2c595583a
|
3 |
+
size 50332843
|
ckpts/universal/global_step80/zero/24.mlp.dense_4h_to_h.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:917a98408d3518dca6f23b61c93b96be4236af751f219fca4447feda8d625258
|
3 |
+
size 33555627
|
ckpts/universal/global_step80/zero/24.mlp.dense_4h_to_h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d87eb2ec79a76f0787ddb5442faccf4d778f2acefd2f09fb5a6dc642323684aa
|
3 |
+
size 33555533
|
ckpts/universal/global_step80/zero/25.mlp.dense_4h_to_h.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3e906612ce58afd0156b8ba63deb18e2e4917017a4172fb76b0d4aedd39dc74b
|
3 |
+
size 33555627
|
ckpts/universal/global_step80/zero/8.post_attention_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:18135723478193588f29e4a82749e5fd9a6fd160930ad51a65ef90b1a1528852
|
3 |
+
size 9372
|
ckpts/universal/global_step80/zero/8.post_attention_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:21ad7a7d222d3ce6785a94348cf4cd95bc63274a114adb0229ba8ef316dda338
|
3 |
+
size 9387
|
ckpts/universal/global_step80/zero/8.post_attention_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:60cd4e22cece5d8390f006a8c28ef20517902c794f98223d5fd98fdd9997d2d4
|
3 |
+
size 9293
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.67 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/aesaracode.cpython-310.pyc
ADDED
Binary file (19.1 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/c.cpython-310.pyc
ADDED
Binary file (26.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/codeprinter.cpython-310.pyc
ADDED
Binary file (31.1 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/conventions.cpython-310.pyc
ADDED
Binary file (2.54 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/cxx.cpython-310.pyc
ADDED
Binary file (5.4 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/defaults.cpython-310.pyc
ADDED
Binary file (294 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/dot.cpython-310.pyc
ADDED
Binary file (8.83 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/fortran.cpython-310.pyc
ADDED
Binary file (27.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/glsl.cpython-310.pyc
ADDED
Binary file (20.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/gtk.cpython-310.pyc
ADDED
Binary file (767 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/jscode.cpython-310.pyc
ADDED
Binary file (13.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/julia.cpython-310.pyc
ADDED
Binary file (23.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/lambdarepr.cpython-310.pyc
ADDED
Binary file (8.04 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/latex.cpython-310.pyc
ADDED
Binary file (116 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/llvmjitcode.cpython-310.pyc
ADDED
Binary file (15.1 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/maple.cpython-310.pyc
ADDED
Binary file (12.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/mathml.cpython-310.pyc
ADDED
Binary file (58.1 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/numpy.cpython-310.pyc
ADDED
Binary file (20.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/octave.cpython-310.pyc
ADDED
Binary file (26.6 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/precedence.cpython-310.pyc
ADDED
Binary file (3.76 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/preview.cpython-310.pyc
ADDED
Binary file (11.5 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/printer.cpython-310.pyc
ADDED
Binary file (13.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/pycode.cpython-310.pyc
ADDED
Binary file (26.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/python.cpython-310.pyc
ADDED
Binary file (2.64 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/rcode.cpython-310.pyc
ADDED
Binary file (14.1 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/repr.cpython-310.pyc
ADDED
Binary file (13.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/rust.cpython-310.pyc
ADDED
Binary file (17.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/smtlib.cpython-310.pyc
ADDED
Binary file (18.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/str.cpython-310.pyc
ADDED
Binary file (39 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/tableform.cpython-310.pyc
ADDED
Binary file (10.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/tensorflow.cpython-310.pyc
ADDED
Binary file (8.12 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/theanocode.cpython-310.pyc
ADDED
Binary file (20.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/tree.cpython-310.pyc
ADDED
Binary file (4.07 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/conventions.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A few practical conventions common to all printers.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import re
|
6 |
+
|
7 |
+
from collections.abc import Iterable
|
8 |
+
from sympy.core.function import Derivative
|
9 |
+
|
10 |
+
_name_with_digits_p = re.compile(r'^([^\W\d_]+)(\d+)$', re.U)
|
11 |
+
|
12 |
+
|
13 |
+
def split_super_sub(text):
|
14 |
+
"""Split a symbol name into a name, superscripts and subscripts
|
15 |
+
|
16 |
+
The first part of the symbol name is considered to be its actual
|
17 |
+
'name', followed by super- and subscripts. Each superscript is
|
18 |
+
preceded with a "^" character or by "__". Each subscript is preceded
|
19 |
+
by a "_" character. The three return values are the actual name, a
|
20 |
+
list with superscripts and a list with subscripts.
|
21 |
+
|
22 |
+
Examples
|
23 |
+
========
|
24 |
+
|
25 |
+
>>> from sympy.printing.conventions import split_super_sub
|
26 |
+
>>> split_super_sub('a_x^1')
|
27 |
+
('a', ['1'], ['x'])
|
28 |
+
>>> split_super_sub('var_sub1__sup_sub2')
|
29 |
+
('var', ['sup'], ['sub1', 'sub2'])
|
30 |
+
|
31 |
+
"""
|
32 |
+
if not text:
|
33 |
+
return text, [], []
|
34 |
+
|
35 |
+
pos = 0
|
36 |
+
name = None
|
37 |
+
supers = []
|
38 |
+
subs = []
|
39 |
+
while pos < len(text):
|
40 |
+
start = pos + 1
|
41 |
+
if text[pos:pos + 2] == "__":
|
42 |
+
start += 1
|
43 |
+
pos_hat = text.find("^", start)
|
44 |
+
if pos_hat < 0:
|
45 |
+
pos_hat = len(text)
|
46 |
+
pos_usc = text.find("_", start)
|
47 |
+
if pos_usc < 0:
|
48 |
+
pos_usc = len(text)
|
49 |
+
pos_next = min(pos_hat, pos_usc)
|
50 |
+
part = text[pos:pos_next]
|
51 |
+
pos = pos_next
|
52 |
+
if name is None:
|
53 |
+
name = part
|
54 |
+
elif part.startswith("^"):
|
55 |
+
supers.append(part[1:])
|
56 |
+
elif part.startswith("__"):
|
57 |
+
supers.append(part[2:])
|
58 |
+
elif part.startswith("_"):
|
59 |
+
subs.append(part[1:])
|
60 |
+
else:
|
61 |
+
raise RuntimeError("This should never happen.")
|
62 |
+
|
63 |
+
# Make a little exception when a name ends with digits, i.e. treat them
|
64 |
+
# as a subscript too.
|
65 |
+
m = _name_with_digits_p.match(name)
|
66 |
+
if m:
|
67 |
+
name, sub = m.groups()
|
68 |
+
subs.insert(0, sub)
|
69 |
+
|
70 |
+
return name, supers, subs
|
71 |
+
|
72 |
+
|
73 |
+
def requires_partial(expr):
|
74 |
+
"""Return whether a partial derivative symbol is required for printing
|
75 |
+
|
76 |
+
This requires checking how many free variables there are,
|
77 |
+
filtering out the ones that are integers. Some expressions do not have
|
78 |
+
free variables. In that case, check its variable list explicitly to
|
79 |
+
get the context of the expression.
|
80 |
+
"""
|
81 |
+
|
82 |
+
if isinstance(expr, Derivative):
|
83 |
+
return requires_partial(expr.expr)
|
84 |
+
|
85 |
+
if not isinstance(expr.free_symbols, Iterable):
|
86 |
+
return len(set(expr.variables)) > 1
|
87 |
+
|
88 |
+
return sum(not s.is_integer for s in expr.free_symbols) > 1
|
venv/lib/python3.10/site-packages/sympy/printing/defaults.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core._print_helpers import Printable
|
2 |
+
|
3 |
+
# alias for compatibility
|
4 |
+
Printable.__module__ = __name__
|
5 |
+
DefaultPrinting = Printable
|
venv/lib/python3.10/site-packages/sympy/printing/fortran.py
ADDED
@@ -0,0 +1,782 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ortran code printer
|
3 |
+
|
4 |
+
The FCodePrinter converts single SymPy expressions into single Fortran
|
5 |
+
expressions, using the functions defined in the Fortran 77 standard where
|
6 |
+
possible. Some useful pointers to Fortran can be found on wikipedia:
|
7 |
+
|
8 |
+
https://en.wikipedia.org/wiki/Fortran
|
9 |
+
|
10 |
+
Most of the code below is based on the "Professional Programmer\'s Guide to
|
11 |
+
Fortran77" by Clive G. Page:
|
12 |
+
|
13 |
+
https://www.star.le.ac.uk/~cgp/prof77.html
|
14 |
+
|
15 |
+
Fortran is a case-insensitive language. This might cause trouble because
|
16 |
+
SymPy is case sensitive. So, fcode adds underscores to variable names when
|
17 |
+
it is necessary to make them different for Fortran.
|
18 |
+
"""
|
19 |
+
|
20 |
+
from __future__ import annotations
|
21 |
+
from typing import Any
|
22 |
+
|
23 |
+
from collections import defaultdict
|
24 |
+
from itertools import chain
|
25 |
+
import string
|
26 |
+
|
27 |
+
from sympy.codegen.ast import (
|
28 |
+
Assignment, Declaration, Pointer, value_const,
|
29 |
+
float32, float64, float80, complex64, complex128, int8, int16, int32,
|
30 |
+
int64, intc, real, integer, bool_, complex_
|
31 |
+
)
|
32 |
+
from sympy.codegen.fnodes import (
|
33 |
+
allocatable, isign, dsign, cmplx, merge, literal_dp, elemental, pure,
|
34 |
+
intent_in, intent_out, intent_inout
|
35 |
+
)
|
36 |
+
from sympy.core import S, Add, N, Float, Symbol
|
37 |
+
from sympy.core.function import Function
|
38 |
+
from sympy.core.numbers import equal_valued
|
39 |
+
from sympy.core.relational import Eq
|
40 |
+
from sympy.sets import Range
|
41 |
+
from sympy.printing.codeprinter import CodePrinter
|
42 |
+
from sympy.printing.precedence import precedence, PRECEDENCE
|
43 |
+
from sympy.printing.printer import printer_context
|
44 |
+
|
45 |
+
# These are defined in the other file so we can avoid importing sympy.codegen
|
46 |
+
# from the top-level 'import sympy'. Export them here as well.
|
47 |
+
from sympy.printing.codeprinter import fcode, print_fcode # noqa:F401
|
48 |
+
|
49 |
+
known_functions = {
|
50 |
+
"sin": "sin",
|
51 |
+
"cos": "cos",
|
52 |
+
"tan": "tan",
|
53 |
+
"asin": "asin",
|
54 |
+
"acos": "acos",
|
55 |
+
"atan": "atan",
|
56 |
+
"atan2": "atan2",
|
57 |
+
"sinh": "sinh",
|
58 |
+
"cosh": "cosh",
|
59 |
+
"tanh": "tanh",
|
60 |
+
"log": "log",
|
61 |
+
"exp": "exp",
|
62 |
+
"erf": "erf",
|
63 |
+
"Abs": "abs",
|
64 |
+
"conjugate": "conjg",
|
65 |
+
"Max": "max",
|
66 |
+
"Min": "min",
|
67 |
+
}
|
68 |
+
|
69 |
+
|
70 |
+
class FCodePrinter(CodePrinter):
|
71 |
+
"""A printer to convert SymPy expressions to strings of Fortran code"""
|
72 |
+
printmethod = "_fcode"
|
73 |
+
language = "Fortran"
|
74 |
+
|
75 |
+
type_aliases = {
|
76 |
+
integer: int32,
|
77 |
+
real: float64,
|
78 |
+
complex_: complex128,
|
79 |
+
}
|
80 |
+
|
81 |
+
type_mappings = {
|
82 |
+
intc: 'integer(c_int)',
|
83 |
+
float32: 'real*4', # real(kind(0.e0))
|
84 |
+
float64: 'real*8', # real(kind(0.d0))
|
85 |
+
float80: 'real*10', # real(kind(????))
|
86 |
+
complex64: 'complex*8',
|
87 |
+
complex128: 'complex*16',
|
88 |
+
int8: 'integer*1',
|
89 |
+
int16: 'integer*2',
|
90 |
+
int32: 'integer*4',
|
91 |
+
int64: 'integer*8',
|
92 |
+
bool_: 'logical'
|
93 |
+
}
|
94 |
+
|
95 |
+
type_modules = {
|
96 |
+
intc: {'iso_c_binding': 'c_int'}
|
97 |
+
}
|
98 |
+
|
99 |
+
_default_settings: dict[str, Any] = {
|
100 |
+
'order': None,
|
101 |
+
'full_prec': 'auto',
|
102 |
+
'precision': 17,
|
103 |
+
'user_functions': {},
|
104 |
+
'human': True,
|
105 |
+
'allow_unknown_functions': False,
|
106 |
+
'source_format': 'fixed',
|
107 |
+
'contract': True,
|
108 |
+
'standard': 77,
|
109 |
+
'name_mangling': True,
|
110 |
+
}
|
111 |
+
|
112 |
+
_operators = {
|
113 |
+
'and': '.and.',
|
114 |
+
'or': '.or.',
|
115 |
+
'xor': '.neqv.',
|
116 |
+
'equivalent': '.eqv.',
|
117 |
+
'not': '.not. ',
|
118 |
+
}
|
119 |
+
|
120 |
+
_relationals = {
|
121 |
+
'!=': '/=',
|
122 |
+
}
|
123 |
+
|
124 |
+
def __init__(self, settings=None):
|
125 |
+
if not settings:
|
126 |
+
settings = {}
|
127 |
+
self.mangled_symbols = {} # Dict showing mapping of all words
|
128 |
+
self.used_name = []
|
129 |
+
self.type_aliases = dict(chain(self.type_aliases.items(),
|
130 |
+
settings.pop('type_aliases', {}).items()))
|
131 |
+
self.type_mappings = dict(chain(self.type_mappings.items(),
|
132 |
+
settings.pop('type_mappings', {}).items()))
|
133 |
+
super().__init__(settings)
|
134 |
+
self.known_functions = dict(known_functions)
|
135 |
+
userfuncs = settings.get('user_functions', {})
|
136 |
+
self.known_functions.update(userfuncs)
|
137 |
+
# leading columns depend on fixed or free format
|
138 |
+
standards = {66, 77, 90, 95, 2003, 2008}
|
139 |
+
if self._settings['standard'] not in standards:
|
140 |
+
raise ValueError("Unknown Fortran standard: %s" % self._settings[
|
141 |
+
'standard'])
|
142 |
+
self.module_uses = defaultdict(set) # e.g.: use iso_c_binding, only: c_int
|
143 |
+
|
144 |
+
@property
|
145 |
+
def _lead(self):
|
146 |
+
if self._settings['source_format'] == 'fixed':
|
147 |
+
return {'code': " ", 'cont': " @ ", 'comment': "C "}
|
148 |
+
elif self._settings['source_format'] == 'free':
|
149 |
+
return {'code': "", 'cont': " ", 'comment': "! "}
|
150 |
+
else:
|
151 |
+
raise ValueError("Unknown source format: %s" % self._settings['source_format'])
|
152 |
+
|
153 |
+
def _print_Symbol(self, expr):
|
154 |
+
if self._settings['name_mangling'] == True:
|
155 |
+
if expr not in self.mangled_symbols:
|
156 |
+
name = expr.name
|
157 |
+
while name.lower() in self.used_name:
|
158 |
+
name += '_'
|
159 |
+
self.used_name.append(name.lower())
|
160 |
+
if name == expr.name:
|
161 |
+
self.mangled_symbols[expr] = expr
|
162 |
+
else:
|
163 |
+
self.mangled_symbols[expr] = Symbol(name)
|
164 |
+
|
165 |
+
expr = expr.xreplace(self.mangled_symbols)
|
166 |
+
|
167 |
+
name = super()._print_Symbol(expr)
|
168 |
+
return name
|
169 |
+
|
170 |
+
def _rate_index_position(self, p):
|
171 |
+
return -p*5
|
172 |
+
|
173 |
+
def _get_statement(self, codestring):
|
174 |
+
return codestring
|
175 |
+
|
176 |
+
def _get_comment(self, text):
|
177 |
+
return "! {}".format(text)
|
178 |
+
|
179 |
+
def _declare_number_const(self, name, value):
|
180 |
+
return "parameter ({} = {})".format(name, self._print(value))
|
181 |
+
|
182 |
+
def _print_NumberSymbol(self, expr):
|
183 |
+
# A Number symbol that is not implemented here or with _printmethod
|
184 |
+
# is registered and evaluated
|
185 |
+
self._number_symbols.add((expr, Float(expr.evalf(self._settings['precision']))))
|
186 |
+
return str(expr)
|
187 |
+
|
188 |
+
def _format_code(self, lines):
|
189 |
+
return self._wrap_fortran(self.indent_code(lines))
|
190 |
+
|
191 |
+
def _traverse_matrix_indices(self, mat):
|
192 |
+
rows, cols = mat.shape
|
193 |
+
return ((i, j) for j in range(cols) for i in range(rows))
|
194 |
+
|
195 |
+
def _get_loop_opening_ending(self, indices):
|
196 |
+
open_lines = []
|
197 |
+
close_lines = []
|
198 |
+
for i in indices:
|
199 |
+
# fortran arrays start at 1 and end at dimension
|
200 |
+
var, start, stop = map(self._print,
|
201 |
+
[i.label, i.lower + 1, i.upper + 1])
|
202 |
+
open_lines.append("do %s = %s, %s" % (var, start, stop))
|
203 |
+
close_lines.append("end do")
|
204 |
+
return open_lines, close_lines
|
205 |
+
|
206 |
+
def _print_sign(self, expr):
|
207 |
+
from sympy.functions.elementary.complexes import Abs
|
208 |
+
arg, = expr.args
|
209 |
+
if arg.is_integer:
|
210 |
+
new_expr = merge(0, isign(1, arg), Eq(arg, 0))
|
211 |
+
elif (arg.is_complex or arg.is_infinite):
|
212 |
+
new_expr = merge(cmplx(literal_dp(0), literal_dp(0)), arg/Abs(arg), Eq(Abs(arg), literal_dp(0)))
|
213 |
+
else:
|
214 |
+
new_expr = merge(literal_dp(0), dsign(literal_dp(1), arg), Eq(arg, literal_dp(0)))
|
215 |
+
return self._print(new_expr)
|
216 |
+
|
217 |
+
|
218 |
+
def _print_Piecewise(self, expr):
|
219 |
+
if expr.args[-1].cond != True:
|
220 |
+
# We need the last conditional to be a True, otherwise the resulting
|
221 |
+
# function may not return a result.
|
222 |
+
raise ValueError("All Piecewise expressions must contain an "
|
223 |
+
"(expr, True) statement to be used as a default "
|
224 |
+
"condition. Without one, the generated "
|
225 |
+
"expression may not evaluate to anything under "
|
226 |
+
"some condition.")
|
227 |
+
lines = []
|
228 |
+
if expr.has(Assignment):
|
229 |
+
for i, (e, c) in enumerate(expr.args):
|
230 |
+
if i == 0:
|
231 |
+
lines.append("if (%s) then" % self._print(c))
|
232 |
+
elif i == len(expr.args) - 1 and c == True:
|
233 |
+
lines.append("else")
|
234 |
+
else:
|
235 |
+
lines.append("else if (%s) then" % self._print(c))
|
236 |
+
lines.append(self._print(e))
|
237 |
+
lines.append("end if")
|
238 |
+
return "\n".join(lines)
|
239 |
+
elif self._settings["standard"] >= 95:
|
240 |
+
# Only supported in F95 and newer:
|
241 |
+
# The piecewise was used in an expression, need to do inline
|
242 |
+
# operators. This has the downside that inline operators will
|
243 |
+
# not work for statements that span multiple lines (Matrix or
|
244 |
+
# Indexed expressions).
|
245 |
+
pattern = "merge({T}, {F}, {COND})"
|
246 |
+
code = self._print(expr.args[-1].expr)
|
247 |
+
terms = list(expr.args[:-1])
|
248 |
+
while terms:
|
249 |
+
e, c = terms.pop()
|
250 |
+
expr = self._print(e)
|
251 |
+
cond = self._print(c)
|
252 |
+
code = pattern.format(T=expr, F=code, COND=cond)
|
253 |
+
return code
|
254 |
+
else:
|
255 |
+
# `merge` is not supported prior to F95
|
256 |
+
raise NotImplementedError("Using Piecewise as an expression using "
|
257 |
+
"inline operators is not supported in "
|
258 |
+
"standards earlier than Fortran95.")
|
259 |
+
|
260 |
+
def _print_MatrixElement(self, expr):
|
261 |
+
return "{}({}, {})".format(self.parenthesize(expr.parent,
|
262 |
+
PRECEDENCE["Atom"], strict=True), expr.i + 1, expr.j + 1)
|
263 |
+
|
264 |
+
def _print_Add(self, expr):
|
265 |
+
# purpose: print complex numbers nicely in Fortran.
|
266 |
+
# collect the purely real and purely imaginary parts:
|
267 |
+
pure_real = []
|
268 |
+
pure_imaginary = []
|
269 |
+
mixed = []
|
270 |
+
for arg in expr.args:
|
271 |
+
if arg.is_number and arg.is_real:
|
272 |
+
pure_real.append(arg)
|
273 |
+
elif arg.is_number and arg.is_imaginary:
|
274 |
+
pure_imaginary.append(arg)
|
275 |
+
else:
|
276 |
+
mixed.append(arg)
|
277 |
+
if pure_imaginary:
|
278 |
+
if mixed:
|
279 |
+
PREC = precedence(expr)
|
280 |
+
term = Add(*mixed)
|
281 |
+
t = self._print(term)
|
282 |
+
if t.startswith('-'):
|
283 |
+
sign = "-"
|
284 |
+
t = t[1:]
|
285 |
+
else:
|
286 |
+
sign = "+"
|
287 |
+
if precedence(term) < PREC:
|
288 |
+
t = "(%s)" % t
|
289 |
+
|
290 |
+
return "cmplx(%s,%s) %s %s" % (
|
291 |
+
self._print(Add(*pure_real)),
|
292 |
+
self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
|
293 |
+
sign, t,
|
294 |
+
)
|
295 |
+
else:
|
296 |
+
return "cmplx(%s,%s)" % (
|
297 |
+
self._print(Add(*pure_real)),
|
298 |
+
self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
|
299 |
+
)
|
300 |
+
else:
|
301 |
+
return CodePrinter._print_Add(self, expr)
|
302 |
+
|
303 |
+
def _print_Function(self, expr):
|
304 |
+
# All constant function args are evaluated as floats
|
305 |
+
prec = self._settings['precision']
|
306 |
+
args = [N(a, prec) for a in expr.args]
|
307 |
+
eval_expr = expr.func(*args)
|
308 |
+
if not isinstance(eval_expr, Function):
|
309 |
+
return self._print(eval_expr)
|
310 |
+
else:
|
311 |
+
return CodePrinter._print_Function(self, expr.func(*args))
|
312 |
+
|
313 |
+
def _print_Mod(self, expr):
|
314 |
+
# NOTE : Fortran has the functions mod() and modulo(). modulo() behaves
|
315 |
+
# the same wrt to the sign of the arguments as Python and SymPy's
|
316 |
+
# modulus computations (% and Mod()) but is not available in Fortran 66
|
317 |
+
# or Fortran 77, thus we raise an error.
|
318 |
+
if self._settings['standard'] in [66, 77]:
|
319 |
+
msg = ("Python % operator and SymPy's Mod() function are not "
|
320 |
+
"supported by Fortran 66 or 77 standards.")
|
321 |
+
raise NotImplementedError(msg)
|
322 |
+
else:
|
323 |
+
x, y = expr.args
|
324 |
+
return " modulo({}, {})".format(self._print(x), self._print(y))
|
325 |
+
|
326 |
+
def _print_ImaginaryUnit(self, expr):
|
327 |
+
# purpose: print complex numbers nicely in Fortran.
|
328 |
+
return "cmplx(0,1)"
|
329 |
+
|
330 |
+
def _print_int(self, expr):
|
331 |
+
return str(expr)
|
332 |
+
|
333 |
+
def _print_Mul(self, expr):
|
334 |
+
# purpose: print complex numbers nicely in Fortran.
|
335 |
+
if expr.is_number and expr.is_imaginary:
|
336 |
+
return "cmplx(0,%s)" % (
|
337 |
+
self._print(-S.ImaginaryUnit*expr)
|
338 |
+
)
|
339 |
+
else:
|
340 |
+
return CodePrinter._print_Mul(self, expr)
|
341 |
+
|
342 |
+
def _print_Pow(self, expr):
|
343 |
+
PREC = precedence(expr)
|
344 |
+
if equal_valued(expr.exp, -1):
|
345 |
+
return '%s/%s' % (
|
346 |
+
self._print(literal_dp(1)),
|
347 |
+
self.parenthesize(expr.base, PREC)
|
348 |
+
)
|
349 |
+
elif equal_valued(expr.exp, 0.5):
|
350 |
+
if expr.base.is_integer:
|
351 |
+
# Fortran intrinsic sqrt() does not accept integer argument
|
352 |
+
if expr.base.is_Number:
|
353 |
+
return 'sqrt(%s.0d0)' % self._print(expr.base)
|
354 |
+
else:
|
355 |
+
return 'sqrt(dble(%s))' % self._print(expr.base)
|
356 |
+
else:
|
357 |
+
return 'sqrt(%s)' % self._print(expr.base)
|
358 |
+
else:
|
359 |
+
return CodePrinter._print_Pow(self, expr)
|
360 |
+
|
361 |
+
def _print_Rational(self, expr):
|
362 |
+
p, q = int(expr.p), int(expr.q)
|
363 |
+
return "%d.0d0/%d.0d0" % (p, q)
|
364 |
+
|
365 |
+
def _print_Float(self, expr):
|
366 |
+
printed = CodePrinter._print_Float(self, expr)
|
367 |
+
e = printed.find('e')
|
368 |
+
if e > -1:
|
369 |
+
return "%sd%s" % (printed[:e], printed[e + 1:])
|
370 |
+
return "%sd0" % printed
|
371 |
+
|
372 |
+
def _print_Relational(self, expr):
|
373 |
+
lhs_code = self._print(expr.lhs)
|
374 |
+
rhs_code = self._print(expr.rhs)
|
375 |
+
op = expr.rel_op
|
376 |
+
op = op if op not in self._relationals else self._relationals[op]
|
377 |
+
return "{} {} {}".format(lhs_code, op, rhs_code)
|
378 |
+
|
379 |
+
def _print_Indexed(self, expr):
|
380 |
+
inds = [ self._print(i) for i in expr.indices ]
|
381 |
+
return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
|
382 |
+
|
383 |
+
def _print_Idx(self, expr):
|
384 |
+
return self._print(expr.label)
|
385 |
+
|
386 |
+
def _print_AugmentedAssignment(self, expr):
|
387 |
+
lhs_code = self._print(expr.lhs)
|
388 |
+
rhs_code = self._print(expr.rhs)
|
389 |
+
return self._get_statement("{0} = {0} {1} {2}".format(
|
390 |
+
self._print(lhs_code), self._print(expr.binop), self._print(rhs_code)))
|
391 |
+
|
392 |
+
def _print_sum_(self, sm):
|
393 |
+
params = self._print(sm.array)
|
394 |
+
if sm.dim != None: # Must use '!= None', cannot use 'is not None'
|
395 |
+
params += ', ' + self._print(sm.dim)
|
396 |
+
if sm.mask != None: # Must use '!= None', cannot use 'is not None'
|
397 |
+
params += ', mask=' + self._print(sm.mask)
|
398 |
+
return '%s(%s)' % (sm.__class__.__name__.rstrip('_'), params)
|
399 |
+
|
400 |
+
def _print_product_(self, prod):
|
401 |
+
return self._print_sum_(prod)
|
402 |
+
|
403 |
+
def _print_Do(self, do):
|
404 |
+
excl = ['concurrent']
|
405 |
+
if do.step == 1:
|
406 |
+
excl.append('step')
|
407 |
+
step = ''
|
408 |
+
else:
|
409 |
+
step = ', {step}'
|
410 |
+
|
411 |
+
return (
|
412 |
+
'do {concurrent}{counter} = {first}, {last}'+step+'\n'
|
413 |
+
'{body}\n'
|
414 |
+
'end do\n'
|
415 |
+
).format(
|
416 |
+
concurrent='concurrent ' if do.concurrent else '',
|
417 |
+
**do.kwargs(apply=lambda arg: self._print(arg), exclude=excl)
|
418 |
+
)
|
419 |
+
|
420 |
+
def _print_ImpliedDoLoop(self, idl):
|
421 |
+
step = '' if idl.step == 1 else ', {step}'
|
422 |
+
return ('({expr}, {counter} = {first}, {last}'+step+')').format(
|
423 |
+
**idl.kwargs(apply=lambda arg: self._print(arg))
|
424 |
+
)
|
425 |
+
|
426 |
+
def _print_For(self, expr):
|
427 |
+
target = self._print(expr.target)
|
428 |
+
if isinstance(expr.iterable, Range):
|
429 |
+
start, stop, step = expr.iterable.args
|
430 |
+
else:
|
431 |
+
raise NotImplementedError("Only iterable currently supported is Range")
|
432 |
+
body = self._print(expr.body)
|
433 |
+
return ('do {target} = {start}, {stop}, {step}\n'
|
434 |
+
'{body}\n'
|
435 |
+
'end do').format(target=target, start=start, stop=stop - 1,
|
436 |
+
step=step, body=body)
|
437 |
+
|
438 |
+
def _print_Type(self, type_):
|
439 |
+
type_ = self.type_aliases.get(type_, type_)
|
440 |
+
type_str = self.type_mappings.get(type_, type_.name)
|
441 |
+
module_uses = self.type_modules.get(type_)
|
442 |
+
if module_uses:
|
443 |
+
for k, v in module_uses:
|
444 |
+
self.module_uses[k].add(v)
|
445 |
+
return type_str
|
446 |
+
|
447 |
+
def _print_Element(self, elem):
|
448 |
+
return '{symbol}({idxs})'.format(
|
449 |
+
symbol=self._print(elem.symbol),
|
450 |
+
idxs=', '.join((self._print(arg) for arg in elem.indices))
|
451 |
+
)
|
452 |
+
|
453 |
+
def _print_Extent(self, ext):
|
454 |
+
return str(ext)
|
455 |
+
|
456 |
+
def _print_Declaration(self, expr):
|
457 |
+
var = expr.variable
|
458 |
+
val = var.value
|
459 |
+
dim = var.attr_params('dimension')
|
460 |
+
intents = [intent in var.attrs for intent in (intent_in, intent_out, intent_inout)]
|
461 |
+
if intents.count(True) == 0:
|
462 |
+
intent = ''
|
463 |
+
elif intents.count(True) == 1:
|
464 |
+
intent = ', intent(%s)' % ['in', 'out', 'inout'][intents.index(True)]
|
465 |
+
else:
|
466 |
+
raise ValueError("Multiple intents specified for %s" % self)
|
467 |
+
|
468 |
+
if isinstance(var, Pointer):
|
469 |
+
raise NotImplementedError("Pointers are not available by default in Fortran.")
|
470 |
+
if self._settings["standard"] >= 90:
|
471 |
+
result = '{t}{vc}{dim}{intent}{alloc} :: {s}'.format(
|
472 |
+
t=self._print(var.type),
|
473 |
+
vc=', parameter' if value_const in var.attrs else '',
|
474 |
+
dim=', dimension(%s)' % ', '.join((self._print(arg) for arg in dim)) if dim else '',
|
475 |
+
intent=intent,
|
476 |
+
alloc=', allocatable' if allocatable in var.attrs else '',
|
477 |
+
s=self._print(var.symbol)
|
478 |
+
)
|
479 |
+
if val != None: # Must be "!= None", cannot be "is not None"
|
480 |
+
result += ' = %s' % self._print(val)
|
481 |
+
else:
|
482 |
+
if value_const in var.attrs or val:
|
483 |
+
raise NotImplementedError("F77 init./parameter statem. req. multiple lines.")
|
484 |
+
result = ' '.join((self._print(arg) for arg in [var.type, var.symbol]))
|
485 |
+
|
486 |
+
return result
|
487 |
+
|
488 |
+
|
489 |
+
def _print_Infinity(self, expr):
|
490 |
+
return '(huge(%s) + 1)' % self._print(literal_dp(0))
|
491 |
+
|
492 |
+
def _print_While(self, expr):
|
493 |
+
return 'do while ({condition})\n{body}\nend do'.format(**expr.kwargs(
|
494 |
+
apply=lambda arg: self._print(arg)))
|
495 |
+
|
496 |
+
def _print_BooleanTrue(self, expr):
|
497 |
+
return '.true.'
|
498 |
+
|
499 |
+
def _print_BooleanFalse(self, expr):
|
500 |
+
return '.false.'
|
501 |
+
|
502 |
+
def _pad_leading_columns(self, lines):
|
503 |
+
result = []
|
504 |
+
for line in lines:
|
505 |
+
if line.startswith('!'):
|
506 |
+
result.append(self._lead['comment'] + line[1:].lstrip())
|
507 |
+
else:
|
508 |
+
result.append(self._lead['code'] + line)
|
509 |
+
return result
|
510 |
+
|
511 |
+
def _wrap_fortran(self, lines):
|
512 |
+
"""Wrap long Fortran lines
|
513 |
+
|
514 |
+
Argument:
|
515 |
+
lines -- a list of lines (without \\n character)
|
516 |
+
|
517 |
+
A comment line is split at white space. Code lines are split with a more
|
518 |
+
complex rule to give nice results.
|
519 |
+
"""
|
520 |
+
# routine to find split point in a code line
|
521 |
+
my_alnum = set("_+-." + string.digits + string.ascii_letters)
|
522 |
+
my_white = set(" \t()")
|
523 |
+
|
524 |
+
def split_pos_code(line, endpos):
|
525 |
+
if len(line) <= endpos:
|
526 |
+
return len(line)
|
527 |
+
pos = endpos
|
528 |
+
split = lambda pos: \
|
529 |
+
(line[pos] in my_alnum and line[pos - 1] not in my_alnum) or \
|
530 |
+
(line[pos] not in my_alnum and line[pos - 1] in my_alnum) or \
|
531 |
+
(line[pos] in my_white and line[pos - 1] not in my_white) or \
|
532 |
+
(line[pos] not in my_white and line[pos - 1] in my_white)
|
533 |
+
while not split(pos):
|
534 |
+
pos -= 1
|
535 |
+
if pos == 0:
|
536 |
+
return endpos
|
537 |
+
return pos
|
538 |
+
# split line by line and add the split lines to result
|
539 |
+
result = []
|
540 |
+
if self._settings['source_format'] == 'free':
|
541 |
+
trailing = ' &'
|
542 |
+
else:
|
543 |
+
trailing = ''
|
544 |
+
for line in lines:
|
545 |
+
if line.startswith(self._lead['comment']):
|
546 |
+
# comment line
|
547 |
+
if len(line) > 72:
|
548 |
+
pos = line.rfind(" ", 6, 72)
|
549 |
+
if pos == -1:
|
550 |
+
pos = 72
|
551 |
+
hunk = line[:pos]
|
552 |
+
line = line[pos:].lstrip()
|
553 |
+
result.append(hunk)
|
554 |
+
while line:
|
555 |
+
pos = line.rfind(" ", 0, 66)
|
556 |
+
if pos == -1 or len(line) < 66:
|
557 |
+
pos = 66
|
558 |
+
hunk = line[:pos]
|
559 |
+
line = line[pos:].lstrip()
|
560 |
+
result.append("%s%s" % (self._lead['comment'], hunk))
|
561 |
+
else:
|
562 |
+
result.append(line)
|
563 |
+
elif line.startswith(self._lead['code']):
|
564 |
+
# code line
|
565 |
+
pos = split_pos_code(line, 72)
|
566 |
+
hunk = line[:pos].rstrip()
|
567 |
+
line = line[pos:].lstrip()
|
568 |
+
if line:
|
569 |
+
hunk += trailing
|
570 |
+
result.append(hunk)
|
571 |
+
while line:
|
572 |
+
pos = split_pos_code(line, 65)
|
573 |
+
hunk = line[:pos].rstrip()
|
574 |
+
line = line[pos:].lstrip()
|
575 |
+
if line:
|
576 |
+
hunk += trailing
|
577 |
+
result.append("%s%s" % (self._lead['cont'], hunk))
|
578 |
+
else:
|
579 |
+
result.append(line)
|
580 |
+
return result
|
581 |
+
|
582 |
+
def indent_code(self, code):
|
583 |
+
"""Accepts a string of code or a list of code lines"""
|
584 |
+
if isinstance(code, str):
|
585 |
+
code_lines = self.indent_code(code.splitlines(True))
|
586 |
+
return ''.join(code_lines)
|
587 |
+
|
588 |
+
free = self._settings['source_format'] == 'free'
|
589 |
+
code = [ line.lstrip(' \t') for line in code ]
|
590 |
+
|
591 |
+
inc_keyword = ('do ', 'if(', 'if ', 'do\n', 'else', 'program', 'interface')
|
592 |
+
dec_keyword = ('end do', 'enddo', 'end if', 'endif', 'else', 'end program', 'end interface')
|
593 |
+
|
594 |
+
increase = [ int(any(map(line.startswith, inc_keyword)))
|
595 |
+
for line in code ]
|
596 |
+
decrease = [ int(any(map(line.startswith, dec_keyword)))
|
597 |
+
for line in code ]
|
598 |
+
continuation = [ int(any(map(line.endswith, ['&', '&\n'])))
|
599 |
+
for line in code ]
|
600 |
+
|
601 |
+
level = 0
|
602 |
+
cont_padding = 0
|
603 |
+
tabwidth = 3
|
604 |
+
new_code = []
|
605 |
+
for i, line in enumerate(code):
|
606 |
+
if line in ('', '\n'):
|
607 |
+
new_code.append(line)
|
608 |
+
continue
|
609 |
+
level -= decrease[i]
|
610 |
+
|
611 |
+
if free:
|
612 |
+
padding = " "*(level*tabwidth + cont_padding)
|
613 |
+
else:
|
614 |
+
padding = " "*level*tabwidth
|
615 |
+
|
616 |
+
line = "%s%s" % (padding, line)
|
617 |
+
if not free:
|
618 |
+
line = self._pad_leading_columns([line])[0]
|
619 |
+
|
620 |
+
new_code.append(line)
|
621 |
+
|
622 |
+
if continuation[i]:
|
623 |
+
cont_padding = 2*tabwidth
|
624 |
+
else:
|
625 |
+
cont_padding = 0
|
626 |
+
level += increase[i]
|
627 |
+
|
628 |
+
if not free:
|
629 |
+
return self._wrap_fortran(new_code)
|
630 |
+
return new_code
|
631 |
+
|
632 |
+
def _print_GoTo(self, goto):
|
633 |
+
if goto.expr: # computed goto
|
634 |
+
return "go to ({labels}), {expr}".format(
|
635 |
+
labels=', '.join((self._print(arg) for arg in goto.labels)),
|
636 |
+
expr=self._print(goto.expr)
|
637 |
+
)
|
638 |
+
else:
|
639 |
+
lbl, = goto.labels
|
640 |
+
return "go to %s" % self._print(lbl)
|
641 |
+
|
642 |
+
def _print_Program(self, prog):
|
643 |
+
return (
|
644 |
+
"program {name}\n"
|
645 |
+
"{body}\n"
|
646 |
+
"end program\n"
|
647 |
+
).format(**prog.kwargs(apply=lambda arg: self._print(arg)))
|
648 |
+
|
649 |
+
def _print_Module(self, mod):
|
650 |
+
return (
|
651 |
+
"module {name}\n"
|
652 |
+
"{declarations}\n"
|
653 |
+
"\ncontains\n\n"
|
654 |
+
"{definitions}\n"
|
655 |
+
"end module\n"
|
656 |
+
).format(**mod.kwargs(apply=lambda arg: self._print(arg)))
|
657 |
+
|
658 |
+
def _print_Stream(self, strm):
|
659 |
+
if strm.name == 'stdout' and self._settings["standard"] >= 2003:
|
660 |
+
self.module_uses['iso_c_binding'].add('stdint=>input_unit')
|
661 |
+
return 'input_unit'
|
662 |
+
elif strm.name == 'stderr' and self._settings["standard"] >= 2003:
|
663 |
+
self.module_uses['iso_c_binding'].add('stdint=>error_unit')
|
664 |
+
return 'error_unit'
|
665 |
+
else:
|
666 |
+
if strm.name == 'stdout':
|
667 |
+
return '*'
|
668 |
+
else:
|
669 |
+
return strm.name
|
670 |
+
|
671 |
+
def _print_Print(self, ps):
|
672 |
+
if ps.format_string != None: # Must be '!= None', cannot be 'is not None'
|
673 |
+
fmt = self._print(ps.format_string)
|
674 |
+
else:
|
675 |
+
fmt = "*"
|
676 |
+
return "print {fmt}, {iolist}".format(fmt=fmt, iolist=', '.join(
|
677 |
+
(self._print(arg) for arg in ps.print_args)))
|
678 |
+
|
679 |
+
def _print_Return(self, rs):
|
680 |
+
arg, = rs.args
|
681 |
+
return "{result_name} = {arg}".format(
|
682 |
+
result_name=self._context.get('result_name', 'sympy_result'),
|
683 |
+
arg=self._print(arg)
|
684 |
+
)
|
685 |
+
|
686 |
+
def _print_FortranReturn(self, frs):
|
687 |
+
arg, = frs.args
|
688 |
+
if arg:
|
689 |
+
return 'return %s' % self._print(arg)
|
690 |
+
else:
|
691 |
+
return 'return'
|
692 |
+
|
693 |
+
def _head(self, entity, fp, **kwargs):
|
694 |
+
bind_C_params = fp.attr_params('bind_C')
|
695 |
+
if bind_C_params is None:
|
696 |
+
bind = ''
|
697 |
+
else:
|
698 |
+
bind = ' bind(C, name="%s")' % bind_C_params[0] if bind_C_params else ' bind(C)'
|
699 |
+
result_name = self._settings.get('result_name', None)
|
700 |
+
return (
|
701 |
+
"{entity}{name}({arg_names}){result}{bind}\n"
|
702 |
+
"{arg_declarations}"
|
703 |
+
).format(
|
704 |
+
entity=entity,
|
705 |
+
name=self._print(fp.name),
|
706 |
+
arg_names=', '.join([self._print(arg.symbol) for arg in fp.parameters]),
|
707 |
+
result=(' result(%s)' % result_name) if result_name else '',
|
708 |
+
bind=bind,
|
709 |
+
arg_declarations='\n'.join((self._print(Declaration(arg)) for arg in fp.parameters))
|
710 |
+
)
|
711 |
+
|
712 |
+
def _print_FunctionPrototype(self, fp):
|
713 |
+
entity = "{} function ".format(self._print(fp.return_type))
|
714 |
+
return (
|
715 |
+
"interface\n"
|
716 |
+
"{function_head}\n"
|
717 |
+
"end function\n"
|
718 |
+
"end interface"
|
719 |
+
).format(function_head=self._head(entity, fp))
|
720 |
+
|
721 |
+
def _print_FunctionDefinition(self, fd):
|
722 |
+
if elemental in fd.attrs:
|
723 |
+
prefix = 'elemental '
|
724 |
+
elif pure in fd.attrs:
|
725 |
+
prefix = 'pure '
|
726 |
+
else:
|
727 |
+
prefix = ''
|
728 |
+
|
729 |
+
entity = "{} function ".format(self._print(fd.return_type))
|
730 |
+
with printer_context(self, result_name=fd.name):
|
731 |
+
return (
|
732 |
+
"{prefix}{function_head}\n"
|
733 |
+
"{body}\n"
|
734 |
+
"end function\n"
|
735 |
+
).format(
|
736 |
+
prefix=prefix,
|
737 |
+
function_head=self._head(entity, fd),
|
738 |
+
body=self._print(fd.body)
|
739 |
+
)
|
740 |
+
|
741 |
+
def _print_Subroutine(self, sub):
|
742 |
+
return (
|
743 |
+
'{subroutine_head}\n'
|
744 |
+
'{body}\n'
|
745 |
+
'end subroutine\n'
|
746 |
+
).format(
|
747 |
+
subroutine_head=self._head('subroutine ', sub),
|
748 |
+
body=self._print(sub.body)
|
749 |
+
)
|
750 |
+
|
751 |
+
def _print_SubroutineCall(self, scall):
|
752 |
+
return 'call {name}({args})'.format(
|
753 |
+
name=self._print(scall.name),
|
754 |
+
args=', '.join((self._print(arg) for arg in scall.subroutine_args))
|
755 |
+
)
|
756 |
+
|
757 |
+
def _print_use_rename(self, rnm):
|
758 |
+
return "%s => %s" % tuple((self._print(arg) for arg in rnm.args))
|
759 |
+
|
760 |
+
def _print_use(self, use):
|
761 |
+
result = 'use %s' % self._print(use.namespace)
|
762 |
+
if use.rename != None: # Must be '!= None', cannot be 'is not None'
|
763 |
+
result += ', ' + ', '.join([self._print(rnm) for rnm in use.rename])
|
764 |
+
if use.only != None: # Must be '!= None', cannot be 'is not None'
|
765 |
+
result += ', only: ' + ', '.join([self._print(nly) for nly in use.only])
|
766 |
+
return result
|
767 |
+
|
768 |
+
def _print_BreakToken(self, _):
|
769 |
+
return 'exit'
|
770 |
+
|
771 |
+
def _print_ContinueToken(self, _):
|
772 |
+
return 'cycle'
|
773 |
+
|
774 |
+
def _print_ArrayConstructor(self, ac):
|
775 |
+
fmtstr = "[%s]" if self._settings["standard"] >= 2003 else '(/%s/)'
|
776 |
+
return fmtstr % ', '.join((self._print(arg) for arg in ac.elements))
|
777 |
+
|
778 |
+
def _print_ArrayElement(self, elem):
|
779 |
+
return '{symbol}({idxs})'.format(
|
780 |
+
symbol=self._print(elem.name),
|
781 |
+
idxs=', '.join((self._print(arg) for arg in elem.indices))
|
782 |
+
)
|
venv/lib/python3.10/site-packages/sympy/printing/jscode.py
ADDED
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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inter converts single SymPy expressions into single
|
5 |
+
Javascript expressions, using the functions defined in the Javascript
|
6 |
+
Math object where possible.
|
7 |
+
|
8 |
+
"""
|
9 |
+
|
10 |
+
from __future__ import annotations
|
11 |
+
from typing import Any
|
12 |
+
|
13 |
+
from sympy.core import S
|
14 |
+
from sympy.core.numbers import equal_valued
|
15 |
+
from sympy.printing.codeprinter import CodePrinter
|
16 |
+
from sympy.printing.precedence import precedence, PRECEDENCE
|
17 |
+
|
18 |
+
|
19 |
+
# dictionary mapping SymPy function to (argument_conditions, Javascript_function).
|
20 |
+
# Used in JavascriptCodePrinter._print_Function(self)
|
21 |
+
known_functions = {
|
22 |
+
'Abs': 'Math.abs',
|
23 |
+
'acos': 'Math.acos',
|
24 |
+
'acosh': 'Math.acosh',
|
25 |
+
'asin': 'Math.asin',
|
26 |
+
'asinh': 'Math.asinh',
|
27 |
+
'atan': 'Math.atan',
|
28 |
+
'atan2': 'Math.atan2',
|
29 |
+
'atanh': 'Math.atanh',
|
30 |
+
'ceiling': 'Math.ceil',
|
31 |
+
'cos': 'Math.cos',
|
32 |
+
'cosh': 'Math.cosh',
|
33 |
+
'exp': 'Math.exp',
|
34 |
+
'floor': 'Math.floor',
|
35 |
+
'log': 'Math.log',
|
36 |
+
'Max': 'Math.max',
|
37 |
+
'Min': 'Math.min',
|
38 |
+
'sign': 'Math.sign',
|
39 |
+
'sin': 'Math.sin',
|
40 |
+
'sinh': 'Math.sinh',
|
41 |
+
'tan': 'Math.tan',
|
42 |
+
'tanh': 'Math.tanh',
|
43 |
+
}
|
44 |
+
|
45 |
+
|
46 |
+
class JavascriptCodePrinter(CodePrinter):
|
47 |
+
""""A Printer to convert Python expressions to strings of JavaScript code
|
48 |
+
"""
|
49 |
+
printmethod = '_javascript'
|
50 |
+
language = 'JavaScript'
|
51 |
+
|
52 |
+
_default_settings: dict[str, Any] = {
|
53 |
+
'order': None,
|
54 |
+
'full_prec': 'auto',
|
55 |
+
'precision': 17,
|
56 |
+
'user_functions': {},
|
57 |
+
'human': True,
|
58 |
+
'allow_unknown_functions': False,
|
59 |
+
'contract': True,
|
60 |
+
}
|
61 |
+
|
62 |
+
def __init__(self, settings={}):
|
63 |
+
CodePrinter.__init__(self, settings)
|
64 |
+
self.known_functions = dict(known_functions)
|
65 |
+
userfuncs = settings.get('user_functions', {})
|
66 |
+
self.known_functions.update(userfuncs)
|
67 |
+
|
68 |
+
def _rate_index_position(self, p):
|
69 |
+
return p*5
|
70 |
+
|
71 |
+
def _get_statement(self, codestring):
|
72 |
+
return "%s;" % codestring
|
73 |
+
|
74 |
+
def _get_comment(self, text):
|
75 |
+
return "// {}".format(text)
|
76 |
+
|
77 |
+
def _declare_number_const(self, name, value):
|
78 |
+
return "var {} = {};".format(name, value.evalf(self._settings['precision']))
|
79 |
+
|
80 |
+
def _format_code(self, lines):
|
81 |
+
return self.indent_code(lines)
|
82 |
+
|
83 |
+
def _traverse_matrix_indices(self, mat):
|
84 |
+
rows, cols = mat.shape
|
85 |
+
return ((i, j) for i in range(rows) for j in range(cols))
|
86 |
+
|
87 |
+
def _get_loop_opening_ending(self, indices):
|
88 |
+
open_lines = []
|
89 |
+
close_lines = []
|
90 |
+
loopstart = "for (var %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){"
|
91 |
+
for i in indices:
|
92 |
+
# Javascript arrays start at 0 and end at dimension-1
|
93 |
+
open_lines.append(loopstart % {
|
94 |
+
'varble': self._print(i.label),
|
95 |
+
'start': self._print(i.lower),
|
96 |
+
'end': self._print(i.upper + 1)})
|
97 |
+
close_lines.append("}")
|
98 |
+
return open_lines, close_lines
|
99 |
+
|
100 |
+
def _print_Pow(self, expr):
|
101 |
+
PREC = precedence(expr)
|
102 |
+
if equal_valued(expr.exp, -1):
|
103 |
+
return '1/%s' % (self.parenthesize(expr.base, PREC))
|
104 |
+
elif equal_valued(expr.exp, 0.5):
|
105 |
+
return 'Math.sqrt(%s)' % self._print(expr.base)
|
106 |
+
elif expr.exp == S.One/3:
|
107 |
+
return 'Math.cbrt(%s)' % self._print(expr.base)
|
108 |
+
else:
|
109 |
+
return 'Math.pow(%s, %s)' % (self._print(expr.base),
|
110 |
+
self._print(expr.exp))
|
111 |
+
|
112 |
+
def _print_Rational(self, expr):
|
113 |
+
p, q = int(expr.p), int(expr.q)
|
114 |
+
return '%d/%d' % (p, q)
|
115 |
+
|
116 |
+
def _print_Mod(self, expr):
|
117 |
+
num, den = expr.args
|
118 |
+
PREC = precedence(expr)
|
119 |
+
snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args]
|
120 |
+
# % is remainder (same sign as numerator), not modulo (same sign as
|
121 |
+
# denominator), in js. Hence, % only works as modulo if both numbers
|
122 |
+
# have the same sign
|
123 |
+
if (num.is_nonnegative and den.is_nonnegative or
|
124 |
+
num.is_nonpositive and den.is_nonpositive):
|
125 |
+
return f"{snum} % {sden}"
|
126 |
+
return f"(({snum} % {sden}) + {sden}) % {sden}"
|
127 |
+
|
128 |
+
def _print_Relational(self, expr):
|
129 |
+
lhs_code = self._print(expr.lhs)
|
130 |
+
rhs_code = self._print(expr.rhs)
|
131 |
+
op = expr.rel_op
|
132 |
+
return "{} {} {}".format(lhs_code, op, rhs_code)
|
133 |
+
|
134 |
+
def _print_Indexed(self, expr):
|
135 |
+
# calculate index for 1d array
|
136 |
+
dims = expr.shape
|
137 |
+
elem = S.Zero
|
138 |
+
offset = S.One
|
139 |
+
for i in reversed(range(expr.rank)):
|
140 |
+
elem += expr.indices[i]*offset
|
141 |
+
offset *= dims[i]
|
142 |
+
return "%s[%s]" % (self._print(expr.base.label), self._print(elem))
|
143 |
+
|
144 |
+
def _print_Idx(self, expr):
|
145 |
+
return self._print(expr.label)
|
146 |
+
|
147 |
+
def _print_Exp1(self, expr):
|
148 |
+
return "Math.E"
|
149 |
+
|
150 |
+
def _print_Pi(self, expr):
|
151 |
+
return 'Math.PI'
|
152 |
+
|
153 |
+
def _print_Infinity(self, expr):
|
154 |
+
return 'Number.POSITIVE_INFINITY'
|
155 |
+
|
156 |
+
def _print_NegativeInfinity(self, expr):
|
157 |
+
return 'Number.NEGATIVE_INFINITY'
|
158 |
+
|
159 |
+
def _print_Piecewise(self, expr):
|
160 |
+
from sympy.codegen.ast import Assignment
|
161 |
+
if expr.args[-1].cond != True:
|
162 |
+
# We need the last conditional to be a True, otherwise the resulting
|
163 |
+
# function may not return a result.
|
164 |
+
raise ValueError("All Piecewise expressions must contain an "
|
165 |
+
"(expr, True) statement to be used as a default "
|
166 |
+
"condition. Without one, the generated "
|
167 |
+
"expression may not evaluate to anything under "
|
168 |
+
"some condition.")
|
169 |
+
lines = []
|
170 |
+
if expr.has(Assignment):
|
171 |
+
for i, (e, c) in enumerate(expr.args):
|
172 |
+
if i == 0:
|
173 |
+
lines.append("if (%s) {" % self._print(c))
|
174 |
+
elif i == len(expr.args) - 1 and c == True:
|
175 |
+
lines.append("else {")
|
176 |
+
else:
|
177 |
+
lines.append("else if (%s) {" % self._print(c))
|
178 |
+
code0 = self._print(e)
|
179 |
+
lines.append(code0)
|
180 |
+
lines.append("}")
|
181 |
+
return "\n".join(lines)
|
182 |
+
else:
|
183 |
+
# The piecewise was used in an expression, need to do inline
|
184 |
+
# operators. This has the downside that inline operators will
|
185 |
+
# not work for statements that span multiple lines (Matrix or
|
186 |
+
# Indexed expressions).
|
187 |
+
ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e))
|
188 |
+
for e, c in expr.args[:-1]]
|
189 |
+
last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
|
190 |
+
return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
|
191 |
+
|
192 |
+
def _print_MatrixElement(self, expr):
|
193 |
+
return "{}[{}]".format(self.parenthesize(expr.parent,
|
194 |
+
PRECEDENCE["Atom"], strict=True),
|
195 |
+
expr.j + expr.i*expr.parent.shape[1])
|
196 |
+
|
197 |
+
def indent_code(self, code):
|
198 |
+
"""Accepts a string of code or a list of code lines"""
|
199 |
+
|
200 |
+
if isinstance(code, str):
|
201 |
+
code_lines = self.indent_code(code.splitlines(True))
|
202 |
+
return ''.join(code_lines)
|
203 |
+
|
204 |
+
tab = " "
|
205 |
+
inc_token = ('{', '(', '{\n', '(\n')
|
206 |
+
dec_token = ('}', ')')
|
207 |
+
|
208 |
+
code = [ line.lstrip(' \t') for line in code ]
|
209 |
+
|
210 |
+
increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
|
211 |
+
decrease = [ int(any(map(line.startswith, dec_token)))
|
212 |
+
for line in code ]
|
213 |
+
|
214 |
+
pretty = []
|
215 |
+
level = 0
|
216 |
+
for n, line in enumerate(code):
|
217 |
+
if line in ('', '\n'):
|
218 |
+
pretty.append(line)
|
219 |
+
continue
|
220 |
+
level -= decrease[n]
|
221 |
+
pretty.append("%s%s" % (tab*level, line))
|
222 |
+
level += increase[n]
|
223 |
+
return pretty
|
224 |
+
|
225 |
+
|
226 |
+
def jscode(expr, assign_to=None, **settings):
|
227 |
+
"""Converts an expr to a string of javascript code
|
228 |
+
|
229 |
+
Parameters
|
230 |
+
==========
|
231 |
+
|
232 |
+
expr : Expr
|
233 |
+
A SymPy expression to be converted.
|
234 |
+
assign_to : optional
|
235 |
+
When given, the argument is used as the name of the variable to which
|
236 |
+
the expression is assigned. Can be a string, ``Symbol``,
|
237 |
+
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
|
238 |
+
line-wrapping, or for expressions that generate multi-line statements.
|
239 |
+
precision : integer, optional
|
240 |
+
The precision for numbers such as pi [default=15].
|
241 |
+
user_functions : dict, optional
|
242 |
+
A dictionary where keys are ``FunctionClass`` instances and values are
|
243 |
+
their string representations. Alternatively, the dictionary value can
|
244 |
+
be a list of tuples i.e. [(argument_test, js_function_string)]. See
|
245 |
+
below for examples.
|
246 |
+
human : bool, optional
|
247 |
+
If True, the result is a single string that may contain some constant
|
248 |
+
declarations for the number symbols. If False, the same information is
|
249 |
+
returned in a tuple of (symbols_to_declare, not_supported_functions,
|
250 |
+
code_text). [default=True].
|
251 |
+
contract: bool, optional
|
252 |
+
If True, ``Indexed`` instances are assumed to obey tensor contraction
|
253 |
+
rules and the corresponding nested loops over indices are generated.
|
254 |
+
Setting contract=False will not generate loops, instead the user is
|
255 |
+
responsible to provide values for the indices in the code.
|
256 |
+
[default=True].
|
257 |
+
|
258 |
+
Examples
|
259 |
+
========
|
260 |
+
|
261 |
+
>>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs
|
262 |
+
>>> x, tau = symbols("x, tau")
|
263 |
+
>>> jscode((2*tau)**Rational(7, 2))
|
264 |
+
'8*Math.sqrt(2)*Math.pow(tau, 7/2)'
|
265 |
+
>>> jscode(sin(x), assign_to="s")
|
266 |
+
's = Math.sin(x);'
|
267 |
+
|
268 |
+
Custom printing can be defined for certain types by passing a dictionary of
|
269 |
+
"type" : "function" to the ``user_functions`` kwarg. Alternatively, the
|
270 |
+
dictionary value can be a list of tuples i.e. [(argument_test,
|
271 |
+
js_function_string)].
|
272 |
+
|
273 |
+
>>> custom_functions = {
|
274 |
+
... "ceiling": "CEIL",
|
275 |
+
... "Abs": [(lambda x: not x.is_integer, "fabs"),
|
276 |
+
... (lambda x: x.is_integer, "ABS")]
|
277 |
+
... }
|
278 |
+
>>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions)
|
279 |
+
'fabs(x) + CEIL(x)'
|
280 |
+
|
281 |
+
``Piecewise`` expressions are converted into conditionals. If an
|
282 |
+
``assign_to`` variable is provided an if statement is created, otherwise
|
283 |
+
the ternary operator is used. Note that if the ``Piecewise`` lacks a
|
284 |
+
default term, represented by ``(expr, True)`` then an error will be thrown.
|
285 |
+
This is to prevent generating an expression that may not evaluate to
|
286 |
+
anything.
|
287 |
+
|
288 |
+
>>> from sympy import Piecewise
|
289 |
+
>>> expr = Piecewise((x + 1, x > 0), (x, True))
|
290 |
+
>>> print(jscode(expr, tau))
|
291 |
+
if (x > 0) {
|
292 |
+
tau = x + 1;
|
293 |
+
}
|
294 |
+
else {
|
295 |
+
tau = x;
|
296 |
+
}
|
297 |
+
|
298 |
+
Support for loops is provided through ``Indexed`` types. With
|
299 |
+
``contract=True`` these expressions will be turned into loops, whereas
|
300 |
+
``contract=False`` will just print the assignment expression that should be
|
301 |
+
looped over:
|
302 |
+
|
303 |
+
>>> from sympy import Eq, IndexedBase, Idx
|
304 |
+
>>> len_y = 5
|
305 |
+
>>> y = IndexedBase('y', shape=(len_y,))
|
306 |
+
>>> t = IndexedBase('t', shape=(len_y,))
|
307 |
+
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
|
308 |
+
>>> i = Idx('i', len_y-1)
|
309 |
+
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
|
310 |
+
>>> jscode(e.rhs, assign_to=e.lhs, contract=False)
|
311 |
+
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
|
312 |
+
|
313 |
+
Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
|
314 |
+
must be provided to ``assign_to``. Note that any expression that can be
|
315 |
+
generated normally can also exist inside a Matrix:
|
316 |
+
|
317 |
+
>>> from sympy import Matrix, MatrixSymbol
|
318 |
+
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
|
319 |
+
>>> A = MatrixSymbol('A', 3, 1)
|
320 |
+
>>> print(jscode(mat, A))
|
321 |
+
A[0] = Math.pow(x, 2);
|
322 |
+
if (x > 0) {
|
323 |
+
A[1] = x + 1;
|
324 |
+
}
|
325 |
+
else {
|
326 |
+
A[1] = x;
|
327 |
+
}
|
328 |
+
A[2] = Math.sin(x);
|
329 |
+
"""
|
330 |
+
|
331 |
+
return JavascriptCodePrinter(settings).doprint(expr, assign_to)
|
332 |
+
|
333 |
+
|
334 |
+
def print_jscode(expr, **settings):
|
335 |
+
"""Prints the Javascript representation of the given expression.
|
336 |
+
|
337 |
+
See jscode for the meaning of the optional arguments.
|
338 |
+
"""
|
339 |
+
print(jscode(expr, **settings))
|
venv/lib/python3.10/site-packages/symp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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Maple code printer
|
3 |
+
|
4 |
+
The MapleCodePrinter converts single SymPy expressions into single
|
5 |
+
Maple expressions, using the functions defined in the Maple objects where possible.
|
6 |
+
|
7 |
+
|
8 |
+
FIXME: This module is still under actively developed. Some functions may be not completed.
|
9 |
+
"""
|
10 |
+
|
11 |
+
from sympy.core import S
|
12 |
+
from sympy.core.numbers import Integer, IntegerConstant, equal_valued
|
13 |
+
from sympy.printing.codeprinter import CodePrinter
|
14 |
+
from sympy.printing.precedence import precedence, PRECEDENCE
|
15 |
+
|
16 |
+
import sympy
|
17 |
+
|
18 |
+
_known_func_same_name = (
|
19 |
+
'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinh', 'cosh', 'tanh', 'sech',
|
20 |
+
'csch', 'coth', 'exp', 'floor', 'factorial', 'bernoulli', 'euler',
|
21 |
+
'fibonacci', 'gcd', 'lcm', 'conjugate', 'Ci', 'Chi', 'Ei', 'Li', 'Si', 'Shi',
|
22 |
+
'erf', 'erfc', 'harmonic', 'LambertW',
|
23 |
+
'sqrt', # For automatic rewrites
|
24 |
+
)
|
25 |
+
|
26 |
+
known_functions = {
|
27 |
+
# SymPy -> Maple
|
28 |
+
'Abs': 'abs',
|
29 |
+
'log': 'ln',
|
30 |
+
'asin': 'arcsin',
|
31 |
+
'acos': 'arccos',
|
32 |
+
'atan': 'arctan',
|
33 |
+
'asec': 'arcsec',
|
34 |
+
'acsc': 'arccsc',
|
35 |
+
'acot': 'arccot',
|
36 |
+
'asinh': 'arcsinh',
|
37 |
+
'acosh': 'arccosh',
|
38 |
+
'atanh': 'arctanh',
|
39 |
+
'asech': 'arcsech',
|
40 |
+
'acsch': 'arccsch',
|
41 |
+
'acoth': 'arccoth',
|
42 |
+
'ceiling': 'ceil',
|
43 |
+
'Max' : 'max',
|
44 |
+
'Min' : 'min',
|
45 |
+
|
46 |
+
'factorial2': 'doublefactorial',
|
47 |
+
'RisingFactorial': 'pochhammer',
|
48 |
+
'besseli': 'BesselI',
|
49 |
+
'besselj': 'BesselJ',
|
50 |
+
'besselk': 'BesselK',
|
51 |
+
'bessely': 'BesselY',
|
52 |
+
'hankelh1': 'HankelH1',
|
53 |
+
'hankelh2': 'HankelH2',
|
54 |
+
'airyai': 'AiryAi',
|
55 |
+
'airybi': 'AiryBi',
|
56 |
+
'appellf1': 'AppellF1',
|
57 |
+
'fresnelc': 'FresnelC',
|
58 |
+
'fresnels': 'FresnelS',
|
59 |
+
'lerchphi' : 'LerchPhi',
|
60 |
+
}
|
61 |
+
|
62 |
+
for _func in _known_func_same_name:
|
63 |
+
known_functions[_func] = _func
|
64 |
+
|
65 |
+
number_symbols = {
|
66 |
+
# SymPy -> Maple
|
67 |
+
S.Pi: 'Pi',
|
68 |
+
S.Exp1: 'exp(1)',
|
69 |
+
S.Catalan: 'Catalan',
|
70 |
+
S.EulerGamma: 'gamma',
|
71 |
+
S.GoldenRatio: '(1/2 + (1/2)*sqrt(5))'
|
72 |
+
}
|
73 |
+
|
74 |
+
spec_relational_ops = {
|
75 |
+
# SymPy -> Maple
|
76 |
+
'==': '=',
|
77 |
+
'!=': '<>'
|
78 |
+
}
|
79 |
+
|
80 |
+
not_supported_symbol = [
|
81 |
+
S.ComplexInfinity
|
82 |
+
]
|
83 |
+
|
84 |
+
class MapleCodePrinter(CodePrinter):
|
85 |
+
"""
|
86 |
+
Printer which converts a SymPy expression into a maple code.
|
87 |
+
"""
|
88 |
+
printmethod = "_maple"
|
89 |
+
language = "maple"
|
90 |
+
|
91 |
+
_default_settings = {
|
92 |
+
'order': None,
|
93 |
+
'full_prec': 'auto',
|
94 |
+
'human': True,
|
95 |
+
'inline': True,
|
96 |
+
'allow_unknown_functions': True,
|
97 |
+
}
|
98 |
+
|
99 |
+
def __init__(self, settings=None):
|
100 |
+
if settings is None:
|
101 |
+
settings = {}
|
102 |
+
super().__init__(settings)
|
103 |
+
self.known_functions = dict(known_functions)
|
104 |
+
userfuncs = settings.get('user_functions', {})
|
105 |
+
self.known_functions.update(userfuncs)
|
106 |
+
|
107 |
+
def _get_statement(self, codestring):
|
108 |
+
return "%s;" % codestring
|
109 |
+
|
110 |
+
def _get_comment(self, text):
|
111 |
+
return "# {}".format(text)
|
112 |
+
|
113 |
+
def _declare_number_const(self, name, value):
|
114 |
+
return "{} := {};".format(name,
|
115 |
+
value.evalf(self._settings['precision']))
|
116 |
+
|
117 |
+
def _format_code(self, lines):
|
118 |
+
return lines
|
119 |
+
|
120 |
+
def _print_tuple(self, expr):
|
121 |
+
return self._print(list(expr))
|
122 |
+
|
123 |
+
def _print_Tuple(self, expr):
|
124 |
+
return self._print(list(expr))
|
125 |
+
|
126 |
+
def _print_Assignment(self, expr):
|
127 |
+
lhs = self._print(expr.lhs)
|
128 |
+
rhs = self._print(expr.rhs)
|
129 |
+
return "{lhs} := {rhs}".format(lhs=lhs, rhs=rhs)
|
130 |
+
|
131 |
+
def _print_Pow(self, expr, **kwargs):
|
132 |
+
PREC = precedence(expr)
|
133 |
+
if equal_valued(expr.exp, -1):
|
134 |
+
return '1/%s' % (self.parenthesize(expr.base, PREC))
|
135 |
+
elif equal_valued(expr.exp, 0.5):
|
136 |
+
return 'sqrt(%s)' % self._print(expr.base)
|
137 |
+
elif equal_valued(expr.exp, -0.5):
|
138 |
+
return '1/sqrt(%s)' % self._print(expr.base)
|
139 |
+
else:
|
140 |
+
return '{base}^{exp}'.format(
|
141 |
+
base=self.parenthesize(expr.base, PREC),
|
142 |
+
exp=self.parenthesize(expr.exp, PREC))
|
143 |
+
|
144 |
+
def _print_Piecewise(self, expr):
|
145 |
+
if (expr.args[-1].cond is not True) and (expr.args[-1].cond != S.BooleanTrue):
|
146 |
+
# We need the last conditional to be a True, otherwise the resulting
|
147 |
+
# function may not return a result.
|
148 |
+
raise ValueError("All Piecewise expressions must contain an "
|
149 |
+
"(expr, True) statement to be used as a default "
|
150 |
+
"condition. Without one, the generated "
|
151 |
+
"expression may not evaluate to anything under "
|
152 |
+
"some condition.")
|
153 |
+
_coup_list = [
|
154 |
+
("{c}, {e}".format(c=self._print(c),
|
155 |
+
e=self._print(e)) if c is not True and c is not S.BooleanTrue else "{e}".format(
|
156 |
+
e=self._print(e)))
|
157 |
+
for e, c in expr.args]
|
158 |
+
_inbrace = ', '.join(_coup_list)
|
159 |
+
return 'piecewise({_inbrace})'.format(_inbrace=_inbrace)
|
160 |
+
|
161 |
+
def _print_Rational(self, expr):
|
162 |
+
p, q = int(expr.p), int(expr.q)
|
163 |
+
return "{p}/{q}".format(p=str(p), q=str(q))
|
164 |
+
|
165 |
+
def _print_Relational(self, expr):
|
166 |
+
PREC=precedence(expr)
|
167 |
+
lhs_code = self.parenthesize(expr.lhs, PREC)
|
168 |
+
rhs_code = self.parenthesize(expr.rhs, PREC)
|
169 |
+
op = expr.rel_op
|
170 |
+
if op in spec_relational_ops:
|
171 |
+
op = spec_relational_ops[op]
|
172 |
+
return "{lhs} {rel_op} {rhs}".format(lhs=lhs_code, rel_op=op, rhs=rhs_code)
|
173 |
+
|
174 |
+
def _print_NumberSymbol(self, expr):
|
175 |
+
return number_symbols[expr]
|
176 |
+
|
177 |
+
def _print_NegativeInfinity(self, expr):
|
178 |
+
return '-infinity'
|
179 |
+
|
180 |
+
def _print_Infinity(self, expr):
|
181 |
+
return 'infinity'
|
182 |
+
|
183 |
+
def _print_Idx(self, expr):
|
184 |
+
return self._print(expr.label)
|
185 |
+
|
186 |
+
def _print_BooleanTrue(self, expr):
|
187 |
+
return "true"
|
188 |
+
|
189 |
+
def _print_BooleanFalse(self, expr):
|
190 |
+
return "false"
|
191 |
+
|
192 |
+
def _print_bool(self, expr):
|
193 |
+
return 'true' if expr else 'false'
|
194 |
+
|
195 |
+
def _print_NaN(self, expr):
|
196 |
+
return 'undefined'
|
197 |
+
|
198 |
+
def _get_matrix(self, expr, sparse=False):
|
199 |
+
if S.Zero in expr.shape:
|
200 |
+
_strM = 'Matrix([], storage = {storage})'.format(
|
201 |
+
storage='sparse' if sparse else 'rectangular')
|
202 |
+
else:
|
203 |
+
_strM = 'Matrix({list}, storage = {storage})'.format(
|
204 |
+
list=self._print(expr.tolist()),
|
205 |
+
storage='sparse' if sparse else 'rectangular')
|
206 |
+
return _strM
|
207 |
+
|
208 |
+
def _print_MatrixElement(self, expr):
|
209 |
+
return "{parent}[{i_maple}, {j_maple}]".format(
|
210 |
+
parent=self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True),
|
211 |
+
i_maple=self._print(expr.i + 1),
|
212 |
+
j_maple=self._print(expr.j + 1))
|
213 |
+
|
214 |
+
def _print_MatrixBase(self, expr):
|
215 |
+
return self._get_matrix(expr, sparse=False)
|
216 |
+
|
217 |
+
def _print_SparseRepMatrix(self, expr):
|
218 |
+
return self._get_matrix(expr, sparse=True)
|
219 |
+
|
220 |
+
def _print_Identity(self, expr):
|
221 |
+
if isinstance(expr.rows, (Integer, IntegerConstant)):
|
222 |
+
return self._print(sympy.SparseMatrix(expr))
|
223 |
+
else:
|
224 |
+
return "Matrix({var_size}, shape = identity)".format(var_size=self._print(expr.rows))
|
225 |
+
|
226 |
+
def _print_MatMul(self, expr):
|
227 |
+
PREC=precedence(expr)
|
228 |
+
_fact_list = list(expr.args)
|
229 |
+
_const = None
|
230 |
+
if not isinstance(_fact_list[0], (sympy.MatrixBase, sympy.MatrixExpr,
|
231 |
+
sympy.MatrixSlice, sympy.MatrixSymbol)):
|
232 |
+
_const, _fact_list = _fact_list[0], _fact_list[1:]
|
233 |
+
|
234 |
+
if _const is None or _const == 1:
|
235 |
+
return '.'.join(self.parenthesize(_m, PREC) for _m in _fact_list)
|
236 |
+
else:
|
237 |
+
return '{c}*{m}'.format(c=_const, m='.'.join(self.parenthesize(_m, PREC) for _m in _fact_list))
|
238 |
+
|
239 |
+
def _print_MatPow(self, expr):
|
240 |
+
# This function requires LinearAlgebra Function in Maple
|
241 |
+
return 'MatrixPower({A}, {n})'.format(A=self._print(expr.base), n=self._print(expr.exp))
|
242 |
+
|
243 |
+
def _print_HadamardProduct(self, expr):
|
244 |
+
PREC = precedence(expr)
|
245 |
+
_fact_list = list(expr.args)
|
246 |
+
return '*'.join(self.parenthesize(_m, PREC) for _m in _fact_list)
|
247 |
+
|
248 |
+
def _print_Derivative(self, expr):
|
249 |
+
_f, (_var, _order) = expr.args
|
250 |
+
|
251 |
+
if _order != 1:
|
252 |
+
_second_arg = '{var}${order}'.format(var=self._print(_var),
|
253 |
+
order=self._print(_order))
|
254 |
+
else:
|
255 |
+
_second_arg = '{var}'.format(var=self._print(_var))
|
256 |
+
return 'diff({func_expr}, {sec_arg})'.format(func_expr=self._print(_f), sec_arg=_second_arg)
|
257 |
+
|
258 |
+
|
259 |
+
def maple_code(expr, assign_to=None, **settings):
|
260 |
+
r"""Converts ``expr`` to a string of Maple code.
|
261 |
+
|
262 |
+
Parameters
|
263 |
+
==========
|
264 |
+
|
265 |
+
expr : Expr
|
266 |
+
A SymPy expression to be converted.
|
267 |
+
assign_to : optional
|
268 |
+
When given, the argument is used as the name of the variable to which
|
269 |
+
the expression is assigned. Can be a string, ``Symbol``,
|
270 |
+
``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
|
271 |
+
expressions that generate multi-line statements.
|
272 |
+
precision : integer, optional
|
273 |
+
The precision for numbers such as pi [default=16].
|
274 |
+
user_functions : dict, optional
|
275 |
+
A dictionary where keys are ``FunctionClass`` instances and values are
|
276 |
+
their string representations. Alternatively, the dictionary value can
|
277 |
+
be a list of tuples i.e. [(argument_test, cfunction_string)]. See
|
278 |
+
below for examples.
|
279 |
+
human : bool, optional
|
280 |
+
If True, the result is a single string that may contain some constant
|
281 |
+
declarations for the number symbols. If False, the same information is
|
282 |
+
returned in a tuple of (symbols_to_declare, not_supported_functions,
|
283 |
+
code_text). [default=True].
|
284 |
+
contract: bool, optional
|
285 |
+
If True, ``Indexed`` instances are assumed to obey tensor contraction
|
286 |
+
rules and the corresponding nested loops over indices are generated.
|
287 |
+
Setting contract=False will not generate loops, instead the user is
|
288 |
+
responsible to provide values for the indices in the code.
|
289 |
+
[default=True].
|
290 |
+
inline: bool, optional
|
291 |
+
If True, we try to create single-statement code instead of multiple
|
292 |
+
statements. [default=True].
|
293 |
+
|
294 |
+
"""
|
295 |
+
return MapleCodePrinter(settings).doprint(expr, assign_to)
|
296 |
+
|
297 |
+
|
298 |
+
def print_maple_code(expr, **settings):
|
299 |
+
"""Prints the Maple representation of the given expression.
|
300 |
+
|
301 |
+
See :func:`maple_code` for the meaning of the optional arguments.
|
302 |
+
|
303 |
+
Examples
|
304 |
+
========
|
305 |
+
|
306 |
+
>>> from sympy import print_maple_code, symbols
|
307 |
+
>>> x, y = symbols('x y')
|
308 |
+
>>> print_maple_code(x, assign_to=y)
|
309 |
+
y := x
|
310 |
+
"""
|
311 |
+
print(maple_code(expr, **settings))
|
venv/lib/python3.10/site-packages/sympy/printing/mathml.py
ADDED
@@ -0,0 +1,2126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A MathML printer.
|
3 |
+
"""
|
4 |
+
|
5 |
+
from __future__ import annotations
|
6 |
+
from typing import Any
|
7 |
+
|
8 |
+
from sympy.core.mul import Mul
|
9 |
+
from sympy.core.singleton import S
|
10 |
+
from sympy.core.sorting import default_sort_key
|
11 |
+
from sympy.core.sympify import sympify
|
12 |
+
from sympy.printing.conventions import split_super_sub, requires_partial
|
13 |
+
from sympy.printing.precedence import \
|
14 |
+
precedence_traditional, PRECEDENCE, PRECEDENCE_TRADITIONAL
|
15 |
+
from sympy.printing.pretty.pretty_symbology import greek_unicode
|
16 |
+
from sympy.printing.printer import Printer, print_function
|
17 |
+
|
18 |
+
from mpmath.libmp import prec_to_dps, repr_dps, to_str as mlib_to_str
|
19 |
+
|
20 |
+
|
21 |
+
class MathMLPrinterBase(Printer):
|
22 |
+
"""Contains common code required for MathMLContentPrinter and
|
23 |
+
MathMLPresentationPrinter.
|
24 |
+
"""
|
25 |
+
|
26 |
+
_default_settings: dict[str, Any] = {
|
27 |
+
"order": None,
|
28 |
+
"encoding": "utf-8",
|
29 |
+
"fold_frac_powers": False,
|
30 |
+
"fold_func_brackets": False,
|
31 |
+
"fold_short_frac": None,
|
32 |
+
"inv_trig_style": "abbreviated",
|
33 |
+
"ln_notation": False,
|
34 |
+
"long_frac_ratio": None,
|
35 |
+
"mat_delim": "[",
|
36 |
+
"mat_symbol_style": "plain",
|
37 |
+
"mul_symbol": None,
|
38 |
+
"root_notation": True,
|
39 |
+
"symbol_names": {},
|
40 |
+
"mul_symbol_mathml_numbers": '·',
|
41 |
+
}
|
42 |
+
|
43 |
+
def __init__(self, settings=None):
|
44 |
+
Printer.__init__(self, settings)
|
45 |
+
from xml.dom.minidom import Document, Text
|
46 |
+
|
47 |
+
self.dom = Document()
|
48 |
+
|
49 |
+
# Workaround to allow strings to remain unescaped
|
50 |
+
# Based on
|
51 |
+
# https://stackoverflow.com/questions/38015864/python-xml-dom-minidom-\
|
52 |
+
# please-dont-escape-my-strings/38041194
|
53 |
+
class RawText(Text):
|
54 |
+
def writexml(self, writer, indent='', addindent='', newl=''):
|
55 |
+
if self.data:
|
56 |
+
writer.write('{}{}{}'.format(indent, self.data, newl))
|
57 |
+
|
58 |
+
def createRawTextNode(data):
|
59 |
+
r = RawText()
|
60 |
+
r.data = data
|
61 |
+
r.ownerDocument = self.dom
|
62 |
+
return r
|
63 |
+
|
64 |
+
self.dom.createTextNode = createRawTextNode
|
65 |
+
|
66 |
+
def doprint(self, expr):
|
67 |
+
"""
|
68 |
+
Prints the expression as MathML.
|
69 |
+
"""
|
70 |
+
mathML = Printer._print(self, expr)
|
71 |
+
unistr = mathML.toxml()
|
72 |
+
xmlbstr = unistr.encode('ascii', 'xmlcharrefreplace')
|
73 |
+
res = xmlbstr.decode()
|
74 |
+
return res
|
75 |
+
|
76 |
+
def apply_patch(self):
|
77 |
+
# Applying the patch of xml.dom.minidom bug
|
78 |
+
# Date: 2011-11-18
|
79 |
+
# Description: http://ronrothman.com/public/leftbraned/xml-dom-minidom\
|
80 |
+
# -toprettyxml-and-silly-whitespace/#best-solution
|
81 |
+
# Issue: https://bugs.python.org/issue4147
|
82 |
+
# Patch: https://hg.python.org/cpython/rev/7262f8f276ff/
|
83 |
+
|
84 |
+
from xml.dom.minidom import Element, Text, Node, _write_data
|
85 |
+
|
86 |
+
def writexml(self, writer, indent="", addindent="", newl=""):
|
87 |
+
# indent = current indentation
|
88 |
+
# addindent = indentation to add to higher levels
|
89 |
+
# newl = newline string
|
90 |
+
writer.write(indent + "<" + self.tagName)
|
91 |
+
|
92 |
+
attrs = self._get_attributes()
|
93 |
+
a_names = list(attrs.keys())
|
94 |
+
a_names.sort()
|
95 |
+
|
96 |
+
for a_name in a_names:
|
97 |
+
writer.write(" %s=\"" % a_name)
|
98 |
+
_write_data(writer, attrs[a_name].value)
|
99 |
+
writer.write("\"")
|
100 |
+
if self.childNodes:
|
101 |
+
writer.write(">")
|
102 |
+
if (len(self.childNodes) == 1 and
|
103 |
+
self.childNodes[0].nodeType == Node.TEXT_NODE):
|
104 |
+
self.childNodes[0].writexml(writer, '', '', '')
|
105 |
+
else:
|
106 |
+
writer.write(newl)
|
107 |
+
for node in self.childNodes:
|
108 |
+
node.writexml(
|
109 |
+
writer, indent + addindent, addindent, newl)
|
110 |
+
writer.write(indent)
|
111 |
+
writer.write("</%s>%s" % (self.tagName, newl))
|
112 |
+
else:
|
113 |
+
writer.write("/>%s" % (newl))
|
114 |
+
self._Element_writexml_old = Element.writexml
|
115 |
+
Element.writexml = writexml
|
116 |
+
|
117 |
+
def writexml(self, writer, indent="", addindent="", newl=""):
|
118 |
+
_write_data(writer, "%s%s%s" % (indent, self.data, newl))
|
119 |
+
self._Text_writexml_old = Text.writexml
|
120 |
+
Text.writexml = writexml
|
121 |
+
|
122 |
+
def restore_patch(self):
|
123 |
+
from xml.dom.minidom import Element, Text
|
124 |
+
Element.writexml = self._Element_writexml_old
|
125 |
+
Text.writexml = self._Text_writexml_old
|
126 |
+
|
127 |
+
|
128 |
+
class MathMLContentPrinter(MathMLPrinterBase):
|
129 |
+
"""Prints an expression to the Content MathML markup language.
|
130 |
+
|
131 |
+
References: https://www.w3.org/TR/MathML2/chapter4.html
|
132 |
+
"""
|
133 |
+
printmethod = "_mathml_content"
|
134 |
+
|
135 |
+
def mathml_tag(self, e):
|
136 |
+
"""Returns the MathML tag for an expression."""
|
137 |
+
translate = {
|
138 |
+
'Add': 'plus',
|
139 |
+
'Mul': 'times',
|
140 |
+
'Derivative': 'diff',
|
141 |
+
'Number': 'cn',
|
142 |
+
'int': 'cn',
|
143 |
+
'Pow': 'power',
|
144 |
+
'Max': 'max',
|
145 |
+
'Min': 'min',
|
146 |
+
'Abs': 'abs',
|
147 |
+
'And': 'and',
|
148 |
+
'Or': 'or',
|
149 |
+
'Xor': 'xor',
|
150 |
+
'Not': 'not',
|
151 |
+
'Implies': 'implies',
|
152 |
+
'Symbol': 'ci',
|
153 |
+
'MatrixSymbol': 'ci',
|
154 |
+
'RandomSymbol': 'ci',
|
155 |
+
'Integral': 'int',
|
156 |
+
'Sum': 'sum',
|
157 |
+
'sin': 'sin',
|
158 |
+
'cos': 'cos',
|
159 |
+
'tan': 'tan',
|
160 |
+
'cot': 'cot',
|
161 |
+
'csc': 'csc',
|
162 |
+
'sec': 'sec',
|
163 |
+
'sinh': 'sinh',
|
164 |
+
'cosh': 'cosh',
|
165 |
+
'tanh': 'tanh',
|
166 |
+
'coth': 'coth',
|
167 |
+
'csch': 'csch',
|
168 |
+
'sech': 'sech',
|
169 |
+
'asin': 'arcsin',
|
170 |
+
'asinh': 'arcsinh',
|
171 |
+
'acos': 'arccos',
|
172 |
+
'acosh': 'arccosh',
|
173 |
+
'atan': 'arctan',
|
174 |
+
'atanh': 'arctanh',
|
175 |
+
'atan2': 'arctan',
|
176 |
+
'acot': 'arccot',
|
177 |
+
'acoth': 'arccoth',
|
178 |
+
'asec': 'arcsec',
|
179 |
+
'asech': 'arcsech',
|
180 |
+
'acsc': 'arccsc',
|
181 |
+
'acsch': 'arccsch',
|
182 |
+
'log': 'ln',
|
183 |
+
'Equality': 'eq',
|
184 |
+
'Unequality': 'neq',
|
185 |
+
'GreaterThan': 'geq',
|
186 |
+
'LessThan': 'leq',
|
187 |
+
'StrictGreaterThan': 'gt',
|
188 |
+
'StrictLessThan': 'lt',
|
189 |
+
'Union': 'union',
|
190 |
+
'Intersection': 'intersect',
|
191 |
+
}
|
192 |
+
|
193 |
+
for cls in e.__class__.__mro__:
|
194 |
+
n = cls.__name__
|
195 |
+
if n in translate:
|
196 |
+
return translate[n]
|
197 |
+
# Not found in the MRO set
|
198 |
+
n = e.__class__.__name__
|
199 |
+
return n.lower()
|
200 |
+
|
201 |
+
def _print_Mul(self, expr):
|
202 |
+
|
203 |
+
if expr.could_extract_minus_sign():
|
204 |
+
x = self.dom.createElement('apply')
|
205 |
+
x.appendChild(self.dom.createElement('minus'))
|
206 |
+
x.appendChild(self._print_Mul(-expr))
|
207 |
+
return x
|
208 |
+
|
209 |
+
from sympy.simplify import fraction
|
210 |
+
numer, denom = fraction(expr)
|
211 |
+
|
212 |
+
if denom is not S.One:
|
213 |
+
x = self.dom.createElement('apply')
|
214 |
+
x.appendChild(self.dom.createElement('divide'))
|
215 |
+
x.appendChild(self._print(numer))
|
216 |
+
x.appendChild(self._print(denom))
|
217 |
+
return x
|
218 |
+
|
219 |
+
coeff, terms = expr.as_coeff_mul()
|
220 |
+
if coeff is S.One and len(terms) == 1:
|
221 |
+
# XXX since the negative coefficient has been handled, I don't
|
222 |
+
# think a coeff of 1 can remain
|
223 |
+
return self._print(terms[0])
|
224 |
+
|
225 |
+
if self.order != 'old':
|
226 |
+
terms = Mul._from_args(terms).as_ordered_factors()
|
227 |
+
|
228 |
+
x = self.dom.createElement('apply')
|
229 |
+
x.appendChild(self.dom.createElement('times'))
|
230 |
+
if coeff != 1:
|
231 |
+
x.appendChild(self._print(coeff))
|
232 |
+
for term in terms:
|
233 |
+
x.appendChild(self._print(term))
|
234 |
+
return x
|
235 |
+
|
236 |
+
def _print_Add(self, expr, order=None):
|
237 |
+
args = self._as_ordered_terms(expr, order=order)
|
238 |
+
lastProcessed = self._print(args[0])
|
239 |
+
plusNodes = []
|
240 |
+
for arg in args[1:]:
|
241 |
+
if arg.could_extract_minus_sign():
|
242 |
+
# use minus
|
243 |
+
x = self.dom.createElement('apply')
|
244 |
+
x.appendChild(self.dom.createElement('minus'))
|
245 |
+
x.appendChild(lastProcessed)
|
246 |
+
x.appendChild(self._print(-arg))
|
247 |
+
# invert expression since this is now minused
|
248 |
+
lastProcessed = x
|
249 |
+
if arg == args[-1]:
|
250 |
+
plusNodes.append(lastProcessed)
|
251 |
+
else:
|
252 |
+
plusNodes.append(lastProcessed)
|
253 |
+
lastProcessed = self._print(arg)
|
254 |
+
if arg == args[-1]:
|
255 |
+
plusNodes.append(self._print(arg))
|
256 |
+
if len(plusNodes) == 1:
|
257 |
+
return lastProcessed
|
258 |
+
x = self.dom.createElement('apply')
|
259 |
+
x.appendChild(self.dom.createElement('plus'))
|
260 |
+
while plusNodes:
|
261 |
+
x.appendChild(plusNodes.pop(0))
|
262 |
+
return x
|
263 |
+
|
264 |
+
def _print_Piecewise(self, expr):
|
265 |
+
if expr.args[-1].cond != True:
|
266 |
+
# We need the last conditional to be a True, otherwise the resulting
|
267 |
+
# function may not return a result.
|
268 |
+
raise ValueError("All Piecewise expressions must contain an "
|
269 |
+
"(expr, True) statement to be used as a default "
|
270 |
+
"condition. Without one, the generated "
|
271 |
+
"expression may not evaluate to anything under "
|
272 |
+
"some condition.")
|
273 |
+
root = self.dom.createElement('piecewise')
|
274 |
+
for i, (e, c) in enumerate(expr.args):
|
275 |
+
if i == len(expr.args) - 1 and c == True:
|
276 |
+
piece = self.dom.createElement('otherwise')
|
277 |
+
piece.appendChild(self._print(e))
|
278 |
+
else:
|
279 |
+
piece = self.dom.createElement('piece')
|
280 |
+
piece.appendChild(self._print(e))
|
281 |
+
piece.appendChild(self._print(c))
|
282 |
+
root.appendChild(piece)
|
283 |
+
return root
|
284 |
+
|
285 |
+
def _print_MatrixBase(self, m):
|
286 |
+
x = self.dom.createElement('matrix')
|
287 |
+
for i in range(m.rows):
|
288 |
+
x_r = self.dom.createElement('matrixrow')
|
289 |
+
for j in range(m.cols):
|
290 |
+
x_r.appendChild(self._print(m[i, j]))
|
291 |
+
x.appendChild(x_r)
|
292 |
+
return x
|
293 |
+
|
294 |
+
def _print_Rational(self, e):
|
295 |
+
if e.q == 1:
|
296 |
+
# don't divide
|
297 |
+
x = self.dom.createElement('cn')
|
298 |
+
x.appendChild(self.dom.createTextNode(str(e.p)))
|
299 |
+
return x
|
300 |
+
x = self.dom.createElement('apply')
|
301 |
+
x.appendChild(self.dom.createElement('divide'))
|
302 |
+
# numerator
|
303 |
+
xnum = self.dom.createElement('cn')
|
304 |
+
xnum.appendChild(self.dom.createTextNode(str(e.p)))
|
305 |
+
# denominator
|
306 |
+
xdenom = self.dom.createElement('cn')
|
307 |
+
xdenom.appendChild(self.dom.createTextNode(str(e.q)))
|
308 |
+
x.appendChild(xnum)
|
309 |
+
x.appendChild(xdenom)
|
310 |
+
return x
|
311 |
+
|
312 |
+
def _print_Limit(self, e):
|
313 |
+
x = self.dom.createElement('apply')
|
314 |
+
x.appendChild(self.dom.createElement(self.mathml_tag(e)))
|
315 |
+
|
316 |
+
x_1 = self.dom.createElement('bvar')
|
317 |
+
x_2 = self.dom.createElement('lowlimit')
|
318 |
+
x_1.appendChild(self._print(e.args[1]))
|
319 |
+
x_2.appendChild(self._print(e.args[2]))
|
320 |
+
|
321 |
+
x.appendChild(x_1)
|
322 |
+
x.appendChild(x_2)
|
323 |
+
x.appendChild(self._print(e.args[0]))
|
324 |
+
return x
|
325 |
+
|
326 |
+
def _print_ImaginaryUnit(self, e):
|
327 |
+
return self.dom.createElement('imaginaryi')
|
328 |
+
|
329 |
+
def _print_EulerGamma(self, e):
|
330 |
+
return self.dom.createElement('eulergamma')
|
331 |
+
|
332 |
+
def _print_GoldenRatio(self, e):
|
333 |
+
"""We use unicode #x3c6 for Greek letter phi as defined here
|
334 |
+
https://www.w3.org/2003/entities/2007doc/isogrk1.html"""
|
335 |
+
x = self.dom.createElement('cn')
|
336 |
+
x.appendChild(self.dom.createTextNode("\N{GREEK SMALL LETTER PHI}"))
|
337 |
+
return x
|
338 |
+
|
339 |
+
def _print_Exp1(self, e):
|
340 |
+
return self.dom.createElement('exponentiale')
|
341 |
+
|
342 |
+
def _print_Pi(self, e):
|
343 |
+
return self.dom.createElement('pi')
|
344 |
+
|
345 |
+
def _print_Infinity(self, e):
|
346 |
+
return self.dom.createElement('infinity')
|
347 |
+
|
348 |
+
def _print_NaN(self, e):
|
349 |
+
return self.dom.createElement('notanumber')
|
350 |
+
|
351 |
+
def _print_EmptySet(self, e):
|
352 |
+
return self.dom.createElement('emptyset')
|
353 |
+
|
354 |
+
def _print_BooleanTrue(self, e):
|
355 |
+
return self.dom.createElement('true')
|
356 |
+
|
357 |
+
def _print_BooleanFalse(self, e):
|
358 |
+
return self.dom.createElement('false')
|
359 |
+
|
360 |
+
def _print_NegativeInfinity(self, e):
|
361 |
+
x = self.dom.createElement('apply')
|
362 |
+
x.appendChild(self.dom.createElement('minus'))
|
363 |
+
x.appendChild(self.dom.createElement('infinity'))
|
364 |
+
return x
|
365 |
+
|
366 |
+
def _print_Integral(self, e):
|
367 |
+
def lime_recur(limits):
|
368 |
+
x = self.dom.createElement('apply')
|
369 |
+
x.appendChild(self.dom.createElement(self.mathml_tag(e)))
|
370 |
+
bvar_elem = self.dom.createElement('bvar')
|
371 |
+
bvar_elem.appendChild(self._print(limits[0][0]))
|
372 |
+
x.appendChild(bvar_elem)
|
373 |
+
|
374 |
+
if len(limits[0]) == 3:
|
375 |
+
low_elem = self.dom.createElement('lowlimit')
|
376 |
+
low_elem.appendChild(self._print(limits[0][1]))
|
377 |
+
x.appendChild(low_elem)
|
378 |
+
up_elem = self.dom.createElement('uplimit')
|
379 |
+
up_elem.appendChild(self._print(limits[0][2]))
|
380 |
+
x.appendChild(up_elem)
|
381 |
+
if len(limits[0]) == 2:
|
382 |
+
up_elem = self.dom.createElement('uplimit')
|
383 |
+
up_elem.appendChild(self._print(limits[0][1]))
|
384 |
+
x.appendChild(up_elem)
|
385 |
+
if len(limits) == 1:
|
386 |
+
x.appendChild(self._print(e.function))
|
387 |
+
else:
|
388 |
+
x.appendChild(lime_recur(limits[1:]))
|
389 |
+
return x
|
390 |
+
|
391 |
+
limits = list(e.limits)
|
392 |
+
limits.reverse()
|
393 |
+
return lime_recur(limits)
|
394 |
+
|
395 |
+
def _print_Sum(self, e):
|
396 |
+
# Printer can be shared because Sum and Integral have the
|
397 |
+
# same internal representation.
|
398 |
+
return self._print_Integral(e)
|
399 |
+
|
400 |
+
def _print_Symbol(self, sym):
|
401 |
+
ci = self.dom.createElement(self.mathml_tag(sym))
|
402 |
+
|
403 |
+
def join(items):
|
404 |
+
if len(items) > 1:
|
405 |
+
mrow = self.dom.createElement('mml:mrow')
|
406 |
+
for i, item in enumerate(items):
|
407 |
+
if i > 0:
|
408 |
+
mo = self.dom.createElement('mml:mo')
|
409 |
+
mo.appendChild(self.dom.createTextNode(" "))
|
410 |
+
mrow.appendChild(mo)
|
411 |
+
mi = self.dom.createElement('mml:mi')
|
412 |
+
mi.appendChild(self.dom.createTextNode(item))
|
413 |
+
mrow.appendChild(mi)
|
414 |
+
return mrow
|
415 |
+
else:
|
416 |
+
mi = self.dom.createElement('mml:mi')
|
417 |
+
mi.appendChild(self.dom.createTextNode(items[0]))
|
418 |
+
return mi
|
419 |
+
|
420 |
+
# translate name, supers and subs to unicode characters
|
421 |
+
def translate(s):
|
422 |
+
if s in greek_unicode:
|
423 |
+
return greek_unicode.get(s)
|
424 |
+
else:
|
425 |
+
return s
|
426 |
+
|
427 |
+
name, supers, subs = split_super_sub(sym.name)
|
428 |
+
name = translate(name)
|
429 |
+
supers = [translate(sup) for sup in supers]
|
430 |
+
subs = [translate(sub) for sub in subs]
|
431 |
+
|
432 |
+
mname = self.dom.createElement('mml:mi')
|
433 |
+
mname.appendChild(self.dom.createTextNode(name))
|
434 |
+
if not supers:
|
435 |
+
if not subs:
|
436 |
+
ci.appendChild(self.dom.createTextNode(name))
|
437 |
+
else:
|
438 |
+
msub = self.dom.createElement('mml:msub')
|
439 |
+
msub.appendChild(mname)
|
440 |
+
msub.appendChild(join(subs))
|
441 |
+
ci.appendChild(msub)
|
442 |
+
else:
|
443 |
+
if not subs:
|
444 |
+
msup = self.dom.createElement('mml:msup')
|
445 |
+
msup.appendChild(mname)
|
446 |
+
msup.appendChild(join(supers))
|
447 |
+
ci.appendChild(msup)
|
448 |
+
else:
|
449 |
+
msubsup = self.dom.createElement('mml:msubsup')
|
450 |
+
msubsup.appendChild(mname)
|
451 |
+
msubsup.appendChild(join(subs))
|
452 |
+
msubsup.appendChild(join(supers))
|
453 |
+
ci.appendChild(msubsup)
|
454 |
+
return ci
|
455 |
+
|
456 |
+
_print_MatrixSymbol = _print_Symbol
|
457 |
+
_print_RandomSymbol = _print_Symbol
|
458 |
+
|
459 |
+
def _print_Pow(self, e):
|
460 |
+
# Here we use root instead of power if the exponent is the reciprocal
|
461 |
+
# of an integer
|
462 |
+
if (self._settings['root_notation'] and e.exp.is_Rational
|
463 |
+
and e.exp.p == 1):
|
464 |
+
x = self.dom.createElement('apply')
|
465 |
+
x.appendChild(self.dom.createElement('root'))
|
466 |
+
if e.exp.q != 2:
|
467 |
+
xmldeg = self.dom.createElement('degree')
|
468 |
+
xmlcn = self.dom.createElement('cn')
|
469 |
+
xmlcn.appendChild(self.dom.createTextNode(str(e.exp.q)))
|
470 |
+
xmldeg.appendChild(xmlcn)
|
471 |
+
x.appendChild(xmldeg)
|
472 |
+
x.appendChild(self._print(e.base))
|
473 |
+
return x
|
474 |
+
|
475 |
+
x = self.dom.createElement('apply')
|
476 |
+
x_1 = self.dom.createElement(self.mathml_tag(e))
|
477 |
+
x.appendChild(x_1)
|
478 |
+
x.appendChild(self._print(e.base))
|
479 |
+
x.appendChild(self._print(e.exp))
|
480 |
+
return x
|
481 |
+
|
482 |
+
def _print_Number(self, e):
|
483 |
+
x = self.dom.createElement(self.mathml_tag(e))
|
484 |
+
x.appendChild(self.dom.createTextNode(str(e)))
|
485 |
+
return x
|
486 |
+
|
487 |
+
def _print_Float(self, e):
|
488 |
+
x = self.dom.createElement(self.mathml_tag(e))
|
489 |
+
repr_e = mlib_to_str(e._mpf_, repr_dps(e._prec))
|
490 |
+
x.appendChild(self.dom.createTextNode(repr_e))
|
491 |
+
return x
|
492 |
+
|
493 |
+
def _print_Derivative(self, e):
|
494 |
+
x = self.dom.createElement('apply')
|
495 |
+
diff_symbol = self.mathml_tag(e)
|
496 |
+
if requires_partial(e.expr):
|
497 |
+
diff_symbol = 'partialdiff'
|
498 |
+
x.appendChild(self.dom.createElement(diff_symbol))
|
499 |
+
x_1 = self.dom.createElement('bvar')
|
500 |
+
|
501 |
+
for sym, times in reversed(e.variable_count):
|
502 |
+
x_1.appendChild(self._print(sym))
|
503 |
+
if times > 1:
|
504 |
+
degree = self.dom.createElement('degree')
|
505 |
+
degree.appendChild(self._print(sympify(times)))
|
506 |
+
x_1.appendChild(degree)
|
507 |
+
|
508 |
+
x.appendChild(x_1)
|
509 |
+
x.appendChild(self._print(e.expr))
|
510 |
+
return x
|
511 |
+
|
512 |
+
def _print_Function(self, e):
|
513 |
+
x = self.dom.createElement("apply")
|
514 |
+
x.appendChild(self.dom.createElement(self.mathml_tag(e)))
|
515 |
+
for arg in e.args:
|
516 |
+
x.appendChild(self._print(arg))
|
517 |
+
return x
|
518 |
+
|
519 |
+
def _print_Basic(self, e):
|
520 |
+
x = self.dom.createElement(self.mathml_tag(e))
|
521 |
+
for arg in e.args:
|
522 |
+
x.appendChild(self._print(arg))
|
523 |
+
return x
|
524 |
+
|
525 |
+
def _print_AssocOp(self, e):
|
526 |
+
x = self.dom.createElement('apply')
|
527 |
+
x_1 = self.dom.createElement(self.mathml_tag(e))
|
528 |
+
x.appendChild(x_1)
|
529 |
+
for arg in e.args:
|
530 |
+
x.appendChild(self._print(arg))
|
531 |
+
return x
|
532 |
+
|
533 |
+
def _print_Relational(self, e):
|
534 |
+
x = self.dom.createElement('apply')
|
535 |
+
x.appendChild(self.dom.createElement(self.mathml_tag(e)))
|
536 |
+
x.appendChild(self._print(e.lhs))
|
537 |
+
x.appendChild(self._print(e.rhs))
|
538 |
+
return x
|
539 |
+
|
540 |
+
def _print_list(self, seq):
|
541 |
+
"""MathML reference for the <list> element:
|
542 |
+
https://www.w3.org/TR/MathML2/chapter4.html#contm.list"""
|
543 |
+
dom_element = self.dom.createElement('list')
|
544 |
+
for item in seq:
|
545 |
+
dom_element.appendChild(self._print(item))
|
546 |
+
return dom_element
|
547 |
+
|
548 |
+
def _print_int(self, p):
|
549 |
+
dom_element = self.dom.createElement(self.mathml_tag(p))
|
550 |
+
dom_element.appendChild(self.dom.createTextNode(str(p)))
|
551 |
+
return dom_element
|
552 |
+
|
553 |
+
_print_Implies = _print_AssocOp
|
554 |
+
_print_Not = _print_AssocOp
|
555 |
+
_print_Xor = _print_AssocOp
|
556 |
+
|
557 |
+
def _print_FiniteSet(self, e):
|
558 |
+
x = self.dom.createElement('set')
|
559 |
+
for arg in e.args:
|
560 |
+
x.appendChild(self._print(arg))
|
561 |
+
return x
|
562 |
+
|
563 |
+
def _print_Complement(self, e):
|
564 |
+
x = self.dom.createElement('apply')
|
565 |
+
x.appendChild(self.dom.createElement('setdiff'))
|
566 |
+
for arg in e.args:
|
567 |
+
x.appendChild(self._print(arg))
|
568 |
+
return x
|
569 |
+
|
570 |
+
def _print_ProductSet(self, e):
|
571 |
+
x = self.dom.createElement('apply')
|
572 |
+
x.appendChild(self.dom.createElement('cartesianproduct'))
|
573 |
+
for arg in e.args:
|
574 |
+
x.appendChild(self._print(arg))
|
575 |
+
return x
|
576 |
+
|
577 |
+
# XXX Symmetric difference is not supported for MathML content printers.
|
578 |
+
|
579 |
+
|
580 |
+
class MathMLPresentationPrinter(MathMLPrinterBase):
|
581 |
+
"""Prints an expression to the Presentation MathML markup language.
|
582 |
+
|
583 |
+
References: https://www.w3.org/TR/MathML2/chapter3.html
|
584 |
+
"""
|
585 |
+
printmethod = "_mathml_presentation"
|
586 |
+
|
587 |
+
def mathml_tag(self, e):
|
588 |
+
"""Returns the MathML tag for an expression."""
|
589 |
+
translate = {
|
590 |
+
'Number': 'mn',
|
591 |
+
'Limit': '→',
|
592 |
+
'Derivative': 'ⅆ',
|
593 |
+
'int': 'mn',
|
594 |
+
'Symbol': 'mi',
|
595 |
+
'Integral': '∫',
|
596 |
+
'Sum': '∑',
|
597 |
+
'sin': 'sin',
|
598 |
+
'cos': 'cos',
|
599 |
+
'tan': 'tan',
|
600 |
+
'cot': 'cot',
|
601 |
+
'asin': 'arcsin',
|
602 |
+
'asinh': 'arcsinh',
|
603 |
+
'acos': 'arccos',
|
604 |
+
'acosh': 'arccosh',
|
605 |
+
'atan': 'arctan',
|
606 |
+
'atanh': 'arctanh',
|
607 |
+
'acot': 'arccot',
|
608 |
+
'atan2': 'arctan',
|
609 |
+
'Equality': '=',
|
610 |
+
'Unequality': '≠',
|
611 |
+
'GreaterThan': '≥',
|
612 |
+
'LessThan': '≤',
|
613 |
+
'StrictGreaterThan': '>',
|
614 |
+
'StrictLessThan': '<',
|
615 |
+
'lerchphi': 'Φ',
|
616 |
+
'zeta': 'ζ',
|
617 |
+
'dirichlet_eta': 'η',
|
618 |
+
'elliptic_k': 'Κ',
|
619 |
+
'lowergamma': 'γ',
|
620 |
+
'uppergamma': 'Γ',
|
621 |
+
'gamma': 'Γ',
|
622 |
+
'totient': 'ϕ',
|
623 |
+
'reduced_totient': 'λ',
|
624 |
+
'primenu': 'ν',
|
625 |
+
'primeomega': 'Ω',
|
626 |
+
'fresnels': 'S',
|
627 |
+
'fresnelc': 'C',
|
628 |
+
'LambertW': 'W',
|
629 |
+
'Heaviside': 'Θ',
|
630 |
+
'BooleanTrue': 'True',
|
631 |
+
'BooleanFalse': 'False',
|
632 |
+
'NoneType': 'None',
|
633 |
+
'mathieus': 'S',
|
634 |
+
'mathieuc': 'C',
|
635 |
+
'mathieusprime': 'S′',
|
636 |
+
'mathieucprime': 'C′',
|
637 |
+
}
|
638 |
+
|
639 |
+
def mul_symbol_selection():
|
640 |
+
if (self._settings["mul_symbol"] is None or
|
641 |
+
self._settings["mul_symbol"] == 'None'):
|
642 |
+
return '⁢'
|
643 |
+
elif self._settings["mul_symbol"] == 'times':
|
644 |
+
return '×'
|
645 |
+
elif self._settings["mul_symbol"] == 'dot':
|
646 |
+
return '·'
|
647 |
+
elif self._settings["mul_symbol"] == 'ldot':
|
648 |
+
return '․'
|
649 |
+
elif not isinstance(self._settings["mul_symbol"], str):
|
650 |
+
raise TypeError
|
651 |
+
else:
|
652 |
+
return self._settings["mul_symbol"]
|
653 |
+
for cls in e.__class__.__mro__:
|
654 |
+
n = cls.__name__
|
655 |
+
if n in translate:
|
656 |
+
return translate[n]
|
657 |
+
# Not found in the MRO set
|
658 |
+
if e.__class__.__name__ == "Mul":
|
659 |
+
return mul_symbol_selection()
|
660 |
+
n = e.__class__.__name__
|
661 |
+
return n.lower()
|
662 |
+
|
663 |
+
def parenthesize(self, item, level, strict=False):
|
664 |
+
prec_val = precedence_traditional(item)
|
665 |
+
if (prec_val < level) or ((not strict) and prec_val <= level):
|
666 |
+
brac = self.dom.createElement('mfenced')
|
667 |
+
brac.appendChild(self._print(item))
|
668 |
+
return brac
|
669 |
+
else:
|
670 |
+
return self._print(item)
|
671 |
+
|
672 |
+
def _print_Mul(self, expr):
|
673 |
+
|
674 |
+
def multiply(expr, mrow):
|
675 |
+
from sympy.simplify import fraction
|
676 |
+
numer, denom = fraction(expr)
|
677 |
+
if denom is not S.One:
|
678 |
+
frac = self.dom.createElement('mfrac')
|
679 |
+
if self._settings["fold_short_frac"] and len(str(expr)) < 7:
|
680 |
+
frac.setAttribute('bevelled', 'true')
|
681 |
+
xnum = self._print(numer)
|
682 |
+
xden = self._print(denom)
|
683 |
+
frac.appendChild(xnum)
|
684 |
+
frac.appendChild(xden)
|
685 |
+
mrow.appendChild(frac)
|
686 |
+
return mrow
|
687 |
+
|
688 |
+
coeff, terms = expr.as_coeff_mul()
|
689 |
+
if coeff is S.One and len(terms) == 1:
|
690 |
+
mrow.appendChild(self._print(terms[0]))
|
691 |
+
return mrow
|
692 |
+
if self.order != 'old':
|
693 |
+
terms = Mul._from_args(terms).as_ordered_factors()
|
694 |
+
|
695 |
+
if coeff != 1:
|
696 |
+
x = self._print(coeff)
|
697 |
+
y = self.dom.createElement('mo')
|
698 |
+
y.appendChild(self.dom.createTextNode(self.mathml_tag(expr)))
|
699 |
+
mrow.appendChild(x)
|
700 |
+
mrow.appendChild(y)
|
701 |
+
for term in terms:
|
702 |
+
mrow.appendChild(self.parenthesize(term, PRECEDENCE['Mul']))
|
703 |
+
if not term == terms[-1]:
|
704 |
+
y = self.dom.createElement('mo')
|
705 |
+
y.appendChild(self.dom.createTextNode(self.mathml_tag(expr)))
|
706 |
+
mrow.appendChild(y)
|
707 |
+
return mrow
|
708 |
+
mrow = self.dom.createElement('mrow')
|
709 |
+
if expr.could_extract_minus_sign():
|
710 |
+
x = self.dom.createElement('mo')
|
711 |
+
x.appendChild(self.dom.createTextNode('-'))
|
712 |
+
mrow.appendChild(x)
|
713 |
+
mrow = multiply(-expr, mrow)
|
714 |
+
else:
|
715 |
+
mrow = multiply(expr, mrow)
|
716 |
+
|
717 |
+
return mrow
|
718 |
+
|
719 |
+
def _print_Add(self, expr, order=None):
|
720 |
+
mrow = self.dom.createElement('mrow')
|
721 |
+
args = self._as_ordered_terms(expr, order=order)
|
722 |
+
mrow.appendChild(self._print(args[0]))
|
723 |
+
for arg in args[1:]:
|
724 |
+
if arg.could_extract_minus_sign():
|
725 |
+
# use minus
|
726 |
+
x = self.dom.createElement('mo')
|
727 |
+
x.appendChild(self.dom.createTextNode('-'))
|
728 |
+
y = self._print(-arg)
|
729 |
+
# invert expression since this is now minused
|
730 |
+
else:
|
731 |
+
x = self.dom.createElement('mo')
|
732 |
+
x.appendChild(self.dom.createTextNode('+'))
|
733 |
+
y = self._print(arg)
|
734 |
+
mrow.appendChild(x)
|
735 |
+
mrow.appendChild(y)
|
736 |
+
|
737 |
+
return mrow
|
738 |
+
|
739 |
+
def _print_MatrixBase(self, m):
|
740 |
+
table = self.dom.createElement('mtable')
|
741 |
+
for i in range(m.rows):
|
742 |
+
x = self.dom.createElement('mtr')
|
743 |
+
for j in range(m.cols):
|
744 |
+
y = self.dom.createElement('mtd')
|
745 |
+
y.appendChild(self._print(m[i, j]))
|
746 |
+
x.appendChild(y)
|
747 |
+
table.appendChild(x)
|
748 |
+
if self._settings["mat_delim"] == '':
|
749 |
+
return table
|
750 |
+
brac = self.dom.createElement('mfenced')
|
751 |
+
if self._settings["mat_delim"] == "[":
|
752 |
+
brac.setAttribute('close', ']')
|
753 |
+
brac.setAttribute('open', '[')
|
754 |
+
brac.appendChild(table)
|
755 |
+
return brac
|
756 |
+
|
757 |
+
def _get_printed_Rational(self, e, folded=None):
|
758 |
+
if e.p < 0:
|
759 |
+
p = -e.p
|
760 |
+
else:
|
761 |
+
p = e.p
|
762 |
+
x = self.dom.createElement('mfrac')
|
763 |
+
if folded or self._settings["fold_short_frac"]:
|
764 |
+
x.setAttribute('bevelled', 'true')
|
765 |
+
x.appendChild(self._print(p))
|
766 |
+
x.appendChild(self._print(e.q))
|
767 |
+
if e.p < 0:
|
768 |
+
mrow = self.dom.createElement('mrow')
|
769 |
+
mo = self.dom.createElement('mo')
|
770 |
+
mo.appendChild(self.dom.createTextNode('-'))
|
771 |
+
mrow.appendChild(mo)
|
772 |
+
mrow.appendChild(x)
|
773 |
+
return mrow
|
774 |
+
else:
|
775 |
+
return x
|
776 |
+
|
777 |
+
def _print_Rational(self, e):
|
778 |
+
if e.q == 1:
|
779 |
+
# don't divide
|
780 |
+
return self._print(e.p)
|
781 |
+
|
782 |
+
return self._get_printed_Rational(e, self._settings["fold_short_frac"])
|
783 |
+
|
784 |
+
def _print_Limit(self, e):
|
785 |
+
mrow = self.dom.createElement('mrow')
|
786 |
+
munder = self.dom.createElement('munder')
|
787 |
+
mi = self.dom.createElement('mi')
|
788 |
+
mi.appendChild(self.dom.createTextNode('lim'))
|
789 |
+
|
790 |
+
x = self.dom.createElement('mrow')
|
791 |
+
x_1 = self._print(e.args[1])
|
792 |
+
arrow = self.dom.createElement('mo')
|
793 |
+
arrow.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
|
794 |
+
x_2 = self._print(e.args[2])
|
795 |
+
x.appendChild(x_1)
|
796 |
+
x.appendChild(arrow)
|
797 |
+
x.appendChild(x_2)
|
798 |
+
|
799 |
+
munder.appendChild(mi)
|
800 |
+
munder.appendChild(x)
|
801 |
+
mrow.appendChild(munder)
|
802 |
+
mrow.appendChild(self._print(e.args[0]))
|
803 |
+
|
804 |
+
return mrow
|
805 |
+
|
806 |
+
def _print_ImaginaryUnit(self, e):
|
807 |
+
x = self.dom.createElement('mi')
|
808 |
+
x.appendChild(self.dom.createTextNode('ⅈ'))
|
809 |
+
return x
|
810 |
+
|
811 |
+
def _print_GoldenRatio(self, e):
|
812 |
+
x = self.dom.createElement('mi')
|
813 |
+
x.appendChild(self.dom.createTextNode('Φ'))
|
814 |
+
return x
|
815 |
+
|
816 |
+
def _print_Exp1(self, e):
|
817 |
+
x = self.dom.createElement('mi')
|
818 |
+
x.appendChild(self.dom.createTextNode('ⅇ'))
|
819 |
+
return x
|
820 |
+
|
821 |
+
def _print_Pi(self, e):
|
822 |
+
x = self.dom.createElement('mi')
|
823 |
+
x.appendChild(self.dom.createTextNode('π'))
|
824 |
+
return x
|
825 |
+
|
826 |
+
def _print_Infinity(self, e):
|
827 |
+
x = self.dom.createElement('mi')
|
828 |
+
x.appendChild(self.dom.createTextNode('∞'))
|
829 |
+
return x
|
830 |
+
|
831 |
+
def _print_NegativeInfinity(self, e):
|
832 |
+
mrow = self.dom.createElement('mrow')
|
833 |
+
y = self.dom.createElement('mo')
|
834 |
+
y.appendChild(self.dom.createTextNode('-'))
|
835 |
+
x = self._print_Infinity(e)
|
836 |
+
mrow.appendChild(y)
|
837 |
+
mrow.appendChild(x)
|
838 |
+
return mrow
|
839 |
+
|
840 |
+
def _print_HBar(self, e):
|
841 |
+
x = self.dom.createElement('mi')
|
842 |
+
x.appendChild(self.dom.createTextNode('ℏ'))
|
843 |
+
return x
|
844 |
+
|
845 |
+
def _print_EulerGamma(self, e):
|
846 |
+
x = self.dom.createElement('mi')
|
847 |
+
x.appendChild(self.dom.createTextNode('γ'))
|
848 |
+
return x
|
849 |
+
|
850 |
+
def _print_TribonacciConstant(self, e):
|
851 |
+
x = self.dom.createElement('mi')
|
852 |
+
x.appendChild(self.dom.createTextNode('TribonacciConstant'))
|
853 |
+
return x
|
854 |
+
|
855 |
+
def _print_Dagger(self, e):
|
856 |
+
msup = self.dom.createElement('msup')
|
857 |
+
msup.appendChild(self._print(e.args[0]))
|
858 |
+
msup.appendChild(self.dom.createTextNode('†'))
|
859 |
+
return msup
|
860 |
+
|
861 |
+
def _print_Contains(self, e):
|
862 |
+
mrow = self.dom.createElement('mrow')
|
863 |
+
mrow.appendChild(self._print(e.args[0]))
|
864 |
+
mo = self.dom.createElement('mo')
|
865 |
+
mo.appendChild(self.dom.createTextNode('∈'))
|
866 |
+
mrow.appendChild(mo)
|
867 |
+
mrow.appendChild(self._print(e.args[1]))
|
868 |
+
return mrow
|
869 |
+
|
870 |
+
def _print_HilbertSpace(self, e):
|
871 |
+
x = self.dom.createElement('mi')
|
872 |
+
x.appendChild(self.dom.createTextNode('ℋ'))
|
873 |
+
return x
|
874 |
+
|
875 |
+
def _print_ComplexSpace(self, e):
|
876 |
+
msup = self.dom.createElement('msup')
|
877 |
+
msup.appendChild(self.dom.createTextNode('𝒞'))
|
878 |
+
msup.appendChild(self._print(e.args[0]))
|
879 |
+
return msup
|
880 |
+
|
881 |
+
def _print_FockSpace(self, e):
|
882 |
+
x = self.dom.createElement('mi')
|
883 |
+
x.appendChild(self.dom.createTextNode('ℱ'))
|
884 |
+
return x
|
885 |
+
|
886 |
+
|
887 |
+
def _print_Integral(self, expr):
|
888 |
+
intsymbols = {1: "∫", 2: "∬", 3: "∭"}
|
889 |
+
|
890 |
+
mrow = self.dom.createElement('mrow')
|
891 |
+
if len(expr.limits) <= 3 and all(len(lim) == 1 for lim in expr.limits):
|
892 |
+
# Only up to three-integral signs exists
|
893 |
+
mo = self.dom.createElement('mo')
|
894 |
+
mo.appendChild(self.dom.createTextNode(intsymbols[len(expr.limits)]))
|
895 |
+
mrow.appendChild(mo)
|
896 |
+
else:
|
897 |
+
# Either more than three or limits provided
|
898 |
+
for lim in reversed(expr.limits):
|
899 |
+
mo = self.dom.createElement('mo')
|
900 |
+
mo.appendChild(self.dom.createTextNode(intsymbols[1]))
|
901 |
+
if len(lim) == 1:
|
902 |
+
mrow.appendChild(mo)
|
903 |
+
if len(lim) == 2:
|
904 |
+
msup = self.dom.createElement('msup')
|
905 |
+
msup.appendChild(mo)
|
906 |
+
msup.appendChild(self._print(lim[1]))
|
907 |
+
mrow.appendChild(msup)
|
908 |
+
if len(lim) == 3:
|
909 |
+
msubsup = self.dom.createElement('msubsup')
|
910 |
+
msubsup.appendChild(mo)
|
911 |
+
msubsup.appendChild(self._print(lim[1]))
|
912 |
+
msubsup.appendChild(self._print(lim[2]))
|
913 |
+
mrow.appendChild(msubsup)
|
914 |
+
# print function
|
915 |
+
mrow.appendChild(self.parenthesize(expr.function, PRECEDENCE["Mul"],
|
916 |
+
strict=True))
|
917 |
+
# print integration variables
|
918 |
+
for lim in reversed(expr.limits):
|
919 |
+
d = self.dom.createElement('mo')
|
920 |
+
d.appendChild(self.dom.createTextNode('ⅆ'))
|
921 |
+
mrow.appendChild(d)
|
922 |
+
mrow.appendChild(self._print(lim[0]))
|
923 |
+
return mrow
|
924 |
+
|
925 |
+
def _print_Sum(self, e):
|
926 |
+
limits = list(e.limits)
|
927 |
+
subsup = self.dom.createElement('munderover')
|
928 |
+
low_elem = self._print(limits[0][1])
|
929 |
+
up_elem = self._print(limits[0][2])
|
930 |
+
summand = self.dom.createElement('mo')
|
931 |
+
summand.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
|
932 |
+
|
933 |
+
low = self.dom.createElement('mrow')
|
934 |
+
var = self._print(limits[0][0])
|
935 |
+
equal = self.dom.createElement('mo')
|
936 |
+
equal.appendChild(self.dom.createTextNode('='))
|
937 |
+
low.appendChild(var)
|
938 |
+
low.appendChild(equal)
|
939 |
+
low.appendChild(low_elem)
|
940 |
+
|
941 |
+
subsup.appendChild(summand)
|
942 |
+
subsup.appendChild(low)
|
943 |
+
subsup.appendChild(up_elem)
|
944 |
+
|
945 |
+
mrow = self.dom.createElement('mrow')
|
946 |
+
mrow.appendChild(subsup)
|
947 |
+
if len(str(e.function)) == 1:
|
948 |
+
mrow.appendChild(self._print(e.function))
|
949 |
+
else:
|
950 |
+
fence = self.dom.createElement('mfenced')
|
951 |
+
fence.appendChild(self._print(e.function))
|
952 |
+
mrow.appendChild(fence)
|
953 |
+
|
954 |
+
return mrow
|
955 |
+
|
956 |
+
def _print_Symbol(self, sym, style='plain'):
|
957 |
+
def join(items):
|
958 |
+
if len(items) > 1:
|
959 |
+
mrow = self.dom.createElement('mrow')
|
960 |
+
for i, item in enumerate(items):
|
961 |
+
if i > 0:
|
962 |
+
mo = self.dom.createElement('mo')
|
963 |
+
mo.appendChild(self.dom.createTextNode(" "))
|
964 |
+
mrow.appendChild(mo)
|
965 |
+
mi = self.dom.createElement('mi')
|
966 |
+
mi.appendChild(self.dom.createTextNode(item))
|
967 |
+
mrow.appendChild(mi)
|
968 |
+
return mrow
|
969 |
+
else:
|
970 |
+
mi = self.dom.createElement('mi')
|
971 |
+
mi.appendChild(self.dom.createTextNode(items[0]))
|
972 |
+
return mi
|
973 |
+
|
974 |
+
# translate name, supers and subs to unicode characters
|
975 |
+
def translate(s):
|
976 |
+
if s in greek_unicode:
|
977 |
+
return greek_unicode.get(s)
|
978 |
+
else:
|
979 |
+
return s
|
980 |
+
|
981 |
+
name, supers, subs = split_super_sub(sym.name)
|
982 |
+
name = translate(name)
|
983 |
+
supers = [translate(sup) for sup in supers]
|
984 |
+
subs = [translate(sub) for sub in subs]
|
985 |
+
|
986 |
+
mname = self.dom.createElement('mi')
|
987 |
+
mname.appendChild(self.dom.createTextNode(name))
|
988 |
+
if len(supers) == 0:
|
989 |
+
if len(subs) == 0:
|
990 |
+
x = mname
|
991 |
+
else:
|
992 |
+
x = self.dom.createElement('msub')
|
993 |
+
x.appendChild(mname)
|
994 |
+
x.appendChild(join(subs))
|
995 |
+
else:
|
996 |
+
if len(subs) == 0:
|
997 |
+
x = self.dom.createElement('msup')
|
998 |
+
x.appendChild(mname)
|
999 |
+
x.appendChild(join(supers))
|
1000 |
+
else:
|
1001 |
+
x = self.dom.createElement('msubsup')
|
1002 |
+
x.appendChild(mname)
|
1003 |
+
x.appendChild(join(subs))
|
1004 |
+
x.appendChild(join(supers))
|
1005 |
+
# Set bold font?
|
1006 |
+
if style == 'bold':
|
1007 |
+
x.setAttribute('mathvariant', 'bold')
|
1008 |
+
return x
|
1009 |
+
|
1010 |
+
def _print_MatrixSymbol(self, sym):
|
1011 |
+
return self._print_Symbol(sym,
|
1012 |
+
style=self._settings['mat_symbol_style'])
|
1013 |
+
|
1014 |
+
_print_RandomSymbol = _print_Symbol
|
1015 |
+
|
1016 |
+
def _print_conjugate(self, expr):
|
1017 |
+
enc = self.dom.createElement('menclose')
|
1018 |
+
enc.setAttribute('notation', 'top')
|
1019 |
+
enc.appendChild(self._print(expr.args[0]))
|
1020 |
+
return enc
|
1021 |
+
|
1022 |
+
def _print_operator_after(self, op, expr):
|
1023 |
+
row = self.dom.createElement('mrow')
|
1024 |
+
row.appendChild(self.parenthesize(expr, PRECEDENCE["Func"]))
|
1025 |
+
mo = self.dom.createElement('mo')
|
1026 |
+
mo.appendChild(self.dom.createTextNode(op))
|
1027 |
+
row.appendChild(mo)
|
1028 |
+
return row
|
1029 |
+
|
1030 |
+
def _print_factorial(self, expr):
|
1031 |
+
return self._print_operator_after('!', expr.args[0])
|
1032 |
+
|
1033 |
+
def _print_factorial2(self, expr):
|
1034 |
+
return self._print_operator_after('!!', expr.args[0])
|
1035 |
+
|
1036 |
+
def _print_binomial(self, expr):
|
1037 |
+
brac = self.dom.createElement('mfenced')
|
1038 |
+
frac = self.dom.createElement('mfrac')
|
1039 |
+
frac.setAttribute('linethickness', '0')
|
1040 |
+
frac.appendChild(self._print(expr.args[0]))
|
1041 |
+
frac.appendChild(self._print(expr.args[1]))
|
1042 |
+
brac.appendChild(frac)
|
1043 |
+
return brac
|
1044 |
+
|
1045 |
+
def _print_Pow(self, e):
|
1046 |
+
# Here we use root instead of power if the exponent is the
|
1047 |
+
# reciprocal of an integer
|
1048 |
+
if (e.exp.is_Rational and abs(e.exp.p) == 1 and e.exp.q != 1 and
|
1049 |
+
self._settings['root_notation']):
|
1050 |
+
if e.exp.q == 2:
|
1051 |
+
x = self.dom.createElement('msqrt')
|
1052 |
+
x.appendChild(self._print(e.base))
|
1053 |
+
if e.exp.q != 2:
|
1054 |
+
x = self.dom.createElement('mroot')
|
1055 |
+
x.appendChild(self._print(e.base))
|
1056 |
+
x.appendChild(self._print(e.exp.q))
|
1057 |
+
if e.exp.p == -1:
|
1058 |
+
frac = self.dom.createElement('mfrac')
|
1059 |
+
frac.appendChild(self._print(1))
|
1060 |
+
frac.appendChild(x)
|
1061 |
+
return frac
|
1062 |
+
else:
|
1063 |
+
return x
|
1064 |
+
|
1065 |
+
if e.exp.is_Rational and e.exp.q != 1:
|
1066 |
+
if e.exp.is_negative:
|
1067 |
+
top = self.dom.createElement('mfrac')
|
1068 |
+
top.appendChild(self._print(1))
|
1069 |
+
x = self.dom.createElement('msup')
|
1070 |
+
x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
|
1071 |
+
x.appendChild(self._get_printed_Rational(-e.exp,
|
1072 |
+
self._settings['fold_frac_powers']))
|
1073 |
+
top.appendChild(x)
|
1074 |
+
return top
|
1075 |
+
else:
|
1076 |
+
x = self.dom.createElement('msup')
|
1077 |
+
x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
|
1078 |
+
x.appendChild(self._get_printed_Rational(e.exp,
|
1079 |
+
self._settings['fold_frac_powers']))
|
1080 |
+
return x
|
1081 |
+
|
1082 |
+
if e.exp.is_negative:
|
1083 |
+
top = self.dom.createElement('mfrac')
|
1084 |
+
top.appendChild(self._print(1))
|
1085 |
+
if e.exp == -1:
|
1086 |
+
top.appendChild(self._print(e.base))
|
1087 |
+
else:
|
1088 |
+
x = self.dom.createElement('msup')
|
1089 |
+
x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
|
1090 |
+
x.appendChild(self._print(-e.exp))
|
1091 |
+
top.appendChild(x)
|
1092 |
+
return top
|
1093 |
+
|
1094 |
+
x = self.dom.createElement('msup')
|
1095 |
+
x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
|
1096 |
+
x.appendChild(self._print(e.exp))
|
1097 |
+
return x
|
1098 |
+
|
1099 |
+
def _print_Number(self, e):
|
1100 |
+
x = self.dom.createElement(self.mathml_tag(e))
|
1101 |
+
x.appendChild(self.dom.createTextNode(str(e)))
|
1102 |
+
return x
|
1103 |
+
|
1104 |
+
def _print_AccumulationBounds(self, i):
|
1105 |
+
brac = self.dom.createElement('mfenced')
|
1106 |
+
brac.setAttribute('close', '\u27e9')
|
1107 |
+
brac.setAttribute('open', '\u27e8')
|
1108 |
+
brac.appendChild(self._print(i.min))
|
1109 |
+
brac.appendChild(self._print(i.max))
|
1110 |
+
return brac
|
1111 |
+
|
1112 |
+
def _print_Derivative(self, e):
|
1113 |
+
|
1114 |
+
if requires_partial(e.expr):
|
1115 |
+
d = '∂'
|
1116 |
+
else:
|
1117 |
+
d = self.mathml_tag(e)
|
1118 |
+
|
1119 |
+
# Determine denominator
|
1120 |
+
m = self.dom.createElement('mrow')
|
1121 |
+
dim = 0 # Total diff dimension, for numerator
|
1122 |
+
for sym, num in reversed(e.variable_count):
|
1123 |
+
dim += num
|
1124 |
+
if num >= 2:
|
1125 |
+
x = self.dom.createElement('msup')
|
1126 |
+
xx = self.dom.createElement('mo')
|
1127 |
+
xx.appendChild(self.dom.createTextNode(d))
|
1128 |
+
x.appendChild(xx)
|
1129 |
+
x.appendChild(self._print(num))
|
1130 |
+
else:
|
1131 |
+
x = self.dom.createElement('mo')
|
1132 |
+
x.appendChild(self.dom.createTextNode(d))
|
1133 |
+
m.appendChild(x)
|
1134 |
+
y = self._print(sym)
|
1135 |
+
m.appendChild(y)
|
1136 |
+
|
1137 |
+
mnum = self.dom.createElement('mrow')
|
1138 |
+
if dim >= 2:
|
1139 |
+
x = self.dom.createElement('msup')
|
1140 |
+
xx = self.dom.createElement('mo')
|
1141 |
+
xx.appendChild(self.dom.createTextNode(d))
|
1142 |
+
x.appendChild(xx)
|
1143 |
+
x.appendChild(self._print(dim))
|
1144 |
+
else:
|
1145 |
+
x = self.dom.createElement('mo')
|
1146 |
+
x.appendChild(self.dom.createTextNode(d))
|
1147 |
+
|
1148 |
+
mnum.appendChild(x)
|
1149 |
+
mrow = self.dom.createElement('mrow')
|
1150 |
+
frac = self.dom.createElement('mfrac')
|
1151 |
+
frac.appendChild(mnum)
|
1152 |
+
frac.appendChild(m)
|
1153 |
+
mrow.appendChild(frac)
|
1154 |
+
|
1155 |
+
# Print function
|
1156 |
+
mrow.appendChild(self._print(e.expr))
|
1157 |
+
|
1158 |
+
return mrow
|
1159 |
+
|
1160 |
+
def _print_Function(self, e):
|
1161 |
+
mrow = self.dom.createElement('mrow')
|
1162 |
+
x = self.dom.createElement('mi')
|
1163 |
+
if self.mathml_tag(e) == 'log' and self._settings["ln_notation"]:
|
1164 |
+
x.appendChild(self.dom.createTextNode('ln'))
|
1165 |
+
else:
|
1166 |
+
x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
|
1167 |
+
y = self.dom.createElement('mfenced')
|
1168 |
+
for arg in e.args:
|
1169 |
+
y.appendChild(self._print(arg))
|
1170 |
+
mrow.appendChild(x)
|
1171 |
+
mrow.appendChild(y)
|
1172 |
+
return mrow
|
1173 |
+
|
1174 |
+
def _print_Float(self, expr):
|
1175 |
+
# Based off of that in StrPrinter
|
1176 |
+
dps = prec_to_dps(expr._prec)
|
1177 |
+
str_real = mlib_to_str(expr._mpf_, dps, strip_zeros=True)
|
1178 |
+
|
1179 |
+
# Must always have a mul symbol (as 2.5 10^{20} just looks odd)
|
1180 |
+
# thus we use the number separator
|
1181 |
+
separator = self._settings['mul_symbol_mathml_numbers']
|
1182 |
+
mrow = self.dom.createElement('mrow')
|
1183 |
+
if 'e' in str_real:
|
1184 |
+
(mant, exp) = str_real.split('e')
|
1185 |
+
|
1186 |
+
if exp[0] == '+':
|
1187 |
+
exp = exp[1:]
|
1188 |
+
|
1189 |
+
mn = self.dom.createElement('mn')
|
1190 |
+
mn.appendChild(self.dom.createTextNode(mant))
|
1191 |
+
mrow.appendChild(mn)
|
1192 |
+
mo = self.dom.createElement('mo')
|
1193 |
+
mo.appendChild(self.dom.createTextNode(separator))
|
1194 |
+
mrow.appendChild(mo)
|
1195 |
+
msup = self.dom.createElement('msup')
|
1196 |
+
mn = self.dom.createElement('mn')
|
1197 |
+
mn.appendChild(self.dom.createTextNode("10"))
|
1198 |
+
msup.appendChild(mn)
|
1199 |
+
mn = self.dom.createElement('mn')
|
1200 |
+
mn.appendChild(self.dom.createTextNode(exp))
|
1201 |
+
msup.appendChild(mn)
|
1202 |
+
mrow.appendChild(msup)
|
1203 |
+
return mrow
|
1204 |
+
elif str_real == "+inf":
|
1205 |
+
return self._print_Infinity(None)
|
1206 |
+
elif str_real == "-inf":
|
1207 |
+
return self._print_NegativeInfinity(None)
|
1208 |
+
else:
|
1209 |
+
mn = self.dom.createElement('mn')
|
1210 |
+
mn.appendChild(self.dom.createTextNode(str_real))
|
1211 |
+
return mn
|
1212 |
+
|
1213 |
+
def _print_polylog(self, expr):
|
1214 |
+
mrow = self.dom.createElement('mrow')
|
1215 |
+
m = self.dom.createElement('msub')
|
1216 |
+
|
1217 |
+
mi = self.dom.createElement('mi')
|
1218 |
+
mi.appendChild(self.dom.createTextNode('Li'))
|
1219 |
+
m.appendChild(mi)
|
1220 |
+
m.appendChild(self._print(expr.args[0]))
|
1221 |
+
mrow.appendChild(m)
|
1222 |
+
brac = self.dom.createElement('mfenced')
|
1223 |
+
brac.appendChild(self._print(expr.args[1]))
|
1224 |
+
mrow.appendChild(brac)
|
1225 |
+
return mrow
|
1226 |
+
|
1227 |
+
def _print_Basic(self, e):
|
1228 |
+
mrow = self.dom.createElement('mrow')
|
1229 |
+
mi = self.dom.createElement('mi')
|
1230 |
+
mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
|
1231 |
+
mrow.appendChild(mi)
|
1232 |
+
brac = self.dom.createElement('mfenced')
|
1233 |
+
for arg in e.args:
|
1234 |
+
brac.appendChild(self._print(arg))
|
1235 |
+
mrow.appendChild(brac)
|
1236 |
+
return mrow
|
1237 |
+
|
1238 |
+
def _print_Tuple(self, e):
|
1239 |
+
mrow = self.dom.createElement('mrow')
|
1240 |
+
x = self.dom.createElement('mfenced')
|
1241 |
+
for arg in e.args:
|
1242 |
+
x.appendChild(self._print(arg))
|
1243 |
+
mrow.appendChild(x)
|
1244 |
+
return mrow
|
1245 |
+
|
1246 |
+
def _print_Interval(self, i):
|
1247 |
+
mrow = self.dom.createElement('mrow')
|
1248 |
+
brac = self.dom.createElement('mfenced')
|
1249 |
+
if i.start == i.end:
|
1250 |
+
# Most often, this type of Interval is converted to a FiniteSet
|
1251 |
+
brac.setAttribute('close', '}')
|
1252 |
+
brac.setAttribute('open', '{')
|
1253 |
+
brac.appendChild(self._print(i.start))
|
1254 |
+
else:
|
1255 |
+
if i.right_open:
|
1256 |
+
brac.setAttribute('close', ')')
|
1257 |
+
else:
|
1258 |
+
brac.setAttribute('close', ']')
|
1259 |
+
|
1260 |
+
if i.left_open:
|
1261 |
+
brac.setAttribute('open', '(')
|
1262 |
+
else:
|
1263 |
+
brac.setAttribute('open', '[')
|
1264 |
+
brac.appendChild(self._print(i.start))
|
1265 |
+
brac.appendChild(self._print(i.end))
|
1266 |
+
|
1267 |
+
mrow.appendChild(brac)
|
1268 |
+
return mrow
|
1269 |
+
|
1270 |
+
def _print_Abs(self, expr, exp=None):
|
1271 |
+
mrow = self.dom.createElement('mrow')
|
1272 |
+
x = self.dom.createElement('mfenced')
|
1273 |
+
x.setAttribute('close', '|')
|
1274 |
+
x.setAttribute('open', '|')
|
1275 |
+
x.appendChild(self._print(expr.args[0]))
|
1276 |
+
mrow.appendChild(x)
|
1277 |
+
return mrow
|
1278 |
+
|
1279 |
+
_print_Determinant = _print_Abs
|
1280 |
+
|
1281 |
+
def _print_re_im(self, c, expr):
|
1282 |
+
mrow = self.dom.createElement('mrow')
|
1283 |
+
mi = self.dom.createElement('mi')
|
1284 |
+
mi.setAttribute('mathvariant', 'fraktur')
|
1285 |
+
mi.appendChild(self.dom.createTextNode(c))
|
1286 |
+
mrow.appendChild(mi)
|
1287 |
+
brac = self.dom.createElement('mfenced')
|
1288 |
+
brac.appendChild(self._print(expr))
|
1289 |
+
mrow.appendChild(brac)
|
1290 |
+
return mrow
|
1291 |
+
|
1292 |
+
def _print_re(self, expr, exp=None):
|
1293 |
+
return self._print_re_im('R', expr.args[0])
|
1294 |
+
|
1295 |
+
def _print_im(self, expr, exp=None):
|
1296 |
+
return self._print_re_im('I', expr.args[0])
|
1297 |
+
|
1298 |
+
def _print_AssocOp(self, e):
|
1299 |
+
mrow = self.dom.createElement('mrow')
|
1300 |
+
mi = self.dom.createElement('mi')
|
1301 |
+
mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
|
1302 |
+
mrow.appendChild(mi)
|
1303 |
+
for arg in e.args:
|
1304 |
+
mrow.appendChild(self._print(arg))
|
1305 |
+
return mrow
|
1306 |
+
|
1307 |
+
def _print_SetOp(self, expr, symbol, prec):
|
1308 |
+
mrow = self.dom.createElement('mrow')
|
1309 |
+
mrow.appendChild(self.parenthesize(expr.args[0], prec))
|
1310 |
+
for arg in expr.args[1:]:
|
1311 |
+
x = self.dom.createElement('mo')
|
1312 |
+
x.appendChild(self.dom.createTextNode(symbol))
|
1313 |
+
y = self.parenthesize(arg, prec)
|
1314 |
+
mrow.appendChild(x)
|
1315 |
+
mrow.appendChild(y)
|
1316 |
+
return mrow
|
1317 |
+
|
1318 |
+
def _print_Union(self, expr):
|
1319 |
+
prec = PRECEDENCE_TRADITIONAL['Union']
|
1320 |
+
return self._print_SetOp(expr, '∪', prec)
|
1321 |
+
|
1322 |
+
def _print_Intersection(self, expr):
|
1323 |
+
prec = PRECEDENCE_TRADITIONAL['Intersection']
|
1324 |
+
return self._print_SetOp(expr, '∩', prec)
|
1325 |
+
|
1326 |
+
def _print_Complement(self, expr):
|
1327 |
+
prec = PRECEDENCE_TRADITIONAL['Complement']
|
1328 |
+
return self._print_SetOp(expr, '∖', prec)
|
1329 |
+
|
1330 |
+
def _print_SymmetricDifference(self, expr):
|
1331 |
+
prec = PRECEDENCE_TRADITIONAL['SymmetricDifference']
|
1332 |
+
return self._print_SetOp(expr, '∆', prec)
|
1333 |
+
|
1334 |
+
def _print_ProductSet(self, expr):
|
1335 |
+
prec = PRECEDENCE_TRADITIONAL['ProductSet']
|
1336 |
+
return self._print_SetOp(expr, '×', prec)
|
1337 |
+
|
1338 |
+
def _print_FiniteSet(self, s):
|
1339 |
+
return self._print_set(s.args)
|
1340 |
+
|
1341 |
+
def _print_set(self, s):
|
1342 |
+
items = sorted(s, key=default_sort_key)
|
1343 |
+
brac = self.dom.createElement('mfenced')
|
1344 |
+
brac.setAttribute('close', '}')
|
1345 |
+
brac.setAttribute('open', '{')
|
1346 |
+
for item in items:
|
1347 |
+
brac.appendChild(self._print(item))
|
1348 |
+
return brac
|
1349 |
+
|
1350 |
+
_print_frozenset = _print_set
|
1351 |
+
|
1352 |
+
def _print_LogOp(self, args, symbol):
|
1353 |
+
mrow = self.dom.createElement('mrow')
|
1354 |
+
if args[0].is_Boolean and not args[0].is_Not:
|
1355 |
+
brac = self.dom.createElement('mfenced')
|
1356 |
+
brac.appendChild(self._print(args[0]))
|
1357 |
+
mrow.appendChild(brac)
|
1358 |
+
else:
|
1359 |
+
mrow.appendChild(self._print(args[0]))
|
1360 |
+
for arg in args[1:]:
|
1361 |
+
x = self.dom.createElement('mo')
|
1362 |
+
x.appendChild(self.dom.createTextNode(symbol))
|
1363 |
+
if arg.is_Boolean and not arg.is_Not:
|
1364 |
+
y = self.dom.createElement('mfenced')
|
1365 |
+
y.appendChild(self._print(arg))
|
1366 |
+
else:
|
1367 |
+
y = self._print(arg)
|
1368 |
+
mrow.appendChild(x)
|
1369 |
+
mrow.appendChild(y)
|
1370 |
+
return mrow
|
1371 |
+
|
1372 |
+
def _print_BasisDependent(self, expr):
|
1373 |
+
from sympy.vector import Vector
|
1374 |
+
|
1375 |
+
if expr == expr.zero:
|
1376 |
+
# Not clear if this is ever called
|
1377 |
+
return self._print(expr.zero)
|
1378 |
+
if isinstance(expr, Vector):
|
1379 |
+
items = expr.separate().items()
|
1380 |
+
else:
|
1381 |
+
items = [(0, expr)]
|
1382 |
+
|
1383 |
+
mrow = self.dom.createElement('mrow')
|
1384 |
+
for system, vect in items:
|
1385 |
+
inneritems = list(vect.components.items())
|
1386 |
+
inneritems.sort(key = lambda x:x[0].__str__())
|
1387 |
+
for i, (k, v) in enumerate(inneritems):
|
1388 |
+
if v == 1:
|
1389 |
+
if i: # No + for first item
|
1390 |
+
mo = self.dom.createElement('mo')
|
1391 |
+
mo.appendChild(self.dom.createTextNode('+'))
|
1392 |
+
mrow.appendChild(mo)
|
1393 |
+
mrow.appendChild(self._print(k))
|
1394 |
+
elif v == -1:
|
1395 |
+
mo = self.dom.createElement('mo')
|
1396 |
+
mo.appendChild(self.dom.createTextNode('-'))
|
1397 |
+
mrow.appendChild(mo)
|
1398 |
+
mrow.appendChild(self._print(k))
|
1399 |
+
else:
|
1400 |
+
if i: # No + for first item
|
1401 |
+
mo = self.dom.createElement('mo')
|
1402 |
+
mo.appendChild(self.dom.createTextNode('+'))
|
1403 |
+
mrow.appendChild(mo)
|
1404 |
+
mbrac = self.dom.createElement('mfenced')
|
1405 |
+
mbrac.appendChild(self._print(v))
|
1406 |
+
mrow.appendChild(mbrac)
|
1407 |
+
mo = self.dom.createElement('mo')
|
1408 |
+
mo.appendChild(self.dom.createTextNode('⁢'))
|
1409 |
+
mrow.appendChild(mo)
|
1410 |
+
mrow.appendChild(self._print(k))
|
1411 |
+
return mrow
|
1412 |
+
|
1413 |
+
|
1414 |
+
def _print_And(self, expr):
|
1415 |
+
args = sorted(expr.args, key=default_sort_key)
|
1416 |
+
return self._print_LogOp(args, '∧')
|
1417 |
+
|
1418 |
+
def _print_Or(self, expr):
|
1419 |
+
args = sorted(expr.args, key=default_sort_key)
|
1420 |
+
return self._print_LogOp(args, '∨')
|
1421 |
+
|
1422 |
+
def _print_Xor(self, expr):
|
1423 |
+
args = sorted(expr.args, key=default_sort_key)
|
1424 |
+
return self._print_LogOp(args, '⊻')
|
1425 |
+
|
1426 |
+
def _print_Implies(self, expr):
|
1427 |
+
return self._print_LogOp(expr.args, '⇒')
|
1428 |
+
|
1429 |
+
def _print_Equivalent(self, expr):
|
1430 |
+
args = sorted(expr.args, key=default_sort_key)
|
1431 |
+
return self._print_LogOp(args, '⇔')
|
1432 |
+
|
1433 |
+
def _print_Not(self, e):
|
1434 |
+
mrow = self.dom.createElement('mrow')
|
1435 |
+
mo = self.dom.createElement('mo')
|
1436 |
+
mo.appendChild(self.dom.createTextNode('¬'))
|
1437 |
+
mrow.appendChild(mo)
|
1438 |
+
if (e.args[0].is_Boolean):
|
1439 |
+
x = self.dom.createElement('mfenced')
|
1440 |
+
x.appendChild(self._print(e.args[0]))
|
1441 |
+
else:
|
1442 |
+
x = self._print(e.args[0])
|
1443 |
+
mrow.appendChild(x)
|
1444 |
+
return mrow
|
1445 |
+
|
1446 |
+
def _print_bool(self, e):
|
1447 |
+
mi = self.dom.createElement('mi')
|
1448 |
+
mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
|
1449 |
+
return mi
|
1450 |
+
|
1451 |
+
_print_BooleanTrue = _print_bool
|
1452 |
+
_print_BooleanFalse = _print_bool
|
1453 |
+
|
1454 |
+
def _print_NoneType(self, e):
|
1455 |
+
mi = self.dom.createElement('mi')
|
1456 |
+
mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
|
1457 |
+
return mi
|
1458 |
+
|
1459 |
+
def _print_Range(self, s):
|
1460 |
+
dots = "\u2026"
|
1461 |
+
brac = self.dom.createElement('mfenced')
|
1462 |
+
brac.setAttribute('close', '}')
|
1463 |
+
brac.setAttribute('open', '{')
|
1464 |
+
|
1465 |
+
if s.start.is_infinite and s.stop.is_infinite:
|
1466 |
+
if s.step.is_positive:
|
1467 |
+
printset = dots, -1, 0, 1, dots
|
1468 |
+
else:
|
1469 |
+
printset = dots, 1, 0, -1, dots
|
1470 |
+
elif s.start.is_infinite:
|
1471 |
+
printset = dots, s[-1] - s.step, s[-1]
|
1472 |
+
elif s.stop.is_infinite:
|
1473 |
+
it = iter(s)
|
1474 |
+
printset = next(it), next(it), dots
|
1475 |
+
elif len(s) > 4:
|
1476 |
+
it = iter(s)
|
1477 |
+
printset = next(it), next(it), dots, s[-1]
|
1478 |
+
else:
|
1479 |
+
printset = tuple(s)
|
1480 |
+
|
1481 |
+
for el in printset:
|
1482 |
+
if el == dots:
|
1483 |
+
mi = self.dom.createElement('mi')
|
1484 |
+
mi.appendChild(self.dom.createTextNode(dots))
|
1485 |
+
brac.appendChild(mi)
|
1486 |
+
else:
|
1487 |
+
brac.appendChild(self._print(el))
|
1488 |
+
|
1489 |
+
return brac
|
1490 |
+
|
1491 |
+
def _hprint_variadic_function(self, expr):
|
1492 |
+
args = sorted(expr.args, key=default_sort_key)
|
1493 |
+
mrow = self.dom.createElement('mrow')
|
1494 |
+
mo = self.dom.createElement('mo')
|
1495 |
+
mo.appendChild(self.dom.createTextNode((str(expr.func)).lower()))
|
1496 |
+
mrow.appendChild(mo)
|
1497 |
+
brac = self.dom.createElement('mfenced')
|
1498 |
+
for symbol in args:
|
1499 |
+
brac.appendChild(self._print(symbol))
|
1500 |
+
mrow.appendChild(brac)
|
1501 |
+
return mrow
|
1502 |
+
|
1503 |
+
_print_Min = _print_Max = _hprint_variadic_function
|
1504 |
+
|
1505 |
+
def _print_exp(self, expr):
|
1506 |
+
msup = self.dom.createElement('msup')
|
1507 |
+
msup.appendChild(self._print_Exp1(None))
|
1508 |
+
msup.appendChild(self._print(expr.args[0]))
|
1509 |
+
return msup
|
1510 |
+
|
1511 |
+
def _print_Relational(self, e):
|
1512 |
+
mrow = self.dom.createElement('mrow')
|
1513 |
+
mrow.appendChild(self._print(e.lhs))
|
1514 |
+
x = self.dom.createElement('mo')
|
1515 |
+
x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
|
1516 |
+
mrow.appendChild(x)
|
1517 |
+
mrow.appendChild(self._print(e.rhs))
|
1518 |
+
return mrow
|
1519 |
+
|
1520 |
+
def _print_int(self, p):
|
1521 |
+
dom_element = self.dom.createElement(self.mathml_tag(p))
|
1522 |
+
dom_element.appendChild(self.dom.createTextNode(str(p)))
|
1523 |
+
return dom_element
|
1524 |
+
|
1525 |
+
def _print_BaseScalar(self, e):
|
1526 |
+
msub = self.dom.createElement('msub')
|
1527 |
+
index, system = e._id
|
1528 |
+
mi = self.dom.createElement('mi')
|
1529 |
+
mi.setAttribute('mathvariant', 'bold')
|
1530 |
+
mi.appendChild(self.dom.createTextNode(system._variable_names[index]))
|
1531 |
+
msub.appendChild(mi)
|
1532 |
+
mi = self.dom.createElement('mi')
|
1533 |
+
mi.setAttribute('mathvariant', 'bold')
|
1534 |
+
mi.appendChild(self.dom.createTextNode(system._name))
|
1535 |
+
msub.appendChild(mi)
|
1536 |
+
return msub
|
1537 |
+
|
1538 |
+
def _print_BaseVector(self, e):
|
1539 |
+
msub = self.dom.createElement('msub')
|
1540 |
+
index, system = e._id
|
1541 |
+
mover = self.dom.createElement('mover')
|
1542 |
+
mi = self.dom.createElement('mi')
|
1543 |
+
mi.setAttribute('mathvariant', 'bold')
|
1544 |
+
mi.appendChild(self.dom.createTextNode(system._vector_names[index]))
|
1545 |
+
mover.appendChild(mi)
|
1546 |
+
mo = self.dom.createElement('mo')
|
1547 |
+
mo.appendChild(self.dom.createTextNode('^'))
|
1548 |
+
mover.appendChild(mo)
|
1549 |
+
msub.appendChild(mover)
|
1550 |
+
mi = self.dom.createElement('mi')
|
1551 |
+
mi.setAttribute('mathvariant', 'bold')
|
1552 |
+
mi.appendChild(self.dom.createTextNode(system._name))
|
1553 |
+
msub.appendChild(mi)
|
1554 |
+
return msub
|
1555 |
+
|
1556 |
+
def _print_VectorZero(self, e):
|
1557 |
+
mover = self.dom.createElement('mover')
|
1558 |
+
mi = self.dom.createElement('mi')
|
1559 |
+
mi.setAttribute('mathvariant', 'bold')
|
1560 |
+
mi.appendChild(self.dom.createTextNode("0"))
|
1561 |
+
mover.appendChild(mi)
|
1562 |
+
mo = self.dom.createElement('mo')
|
1563 |
+
mo.appendChild(self.dom.createTextNode('^'))
|
1564 |
+
mover.appendChild(mo)
|
1565 |
+
return mover
|
1566 |
+
|
1567 |
+
def _print_Cross(self, expr):
|
1568 |
+
mrow = self.dom.createElement('mrow')
|
1569 |
+
vec1 = expr._expr1
|
1570 |
+
vec2 = expr._expr2
|
1571 |
+
mrow.appendChild(self.parenthesize(vec1, PRECEDENCE['Mul']))
|
1572 |
+
mo = self.dom.createElement('mo')
|
1573 |
+
mo.appendChild(self.dom.createTextNode('×'))
|
1574 |
+
mrow.appendChild(mo)
|
1575 |
+
mrow.appendChild(self.parenthesize(vec2, PRECEDENCE['Mul']))
|
1576 |
+
return mrow
|
1577 |
+
|
1578 |
+
def _print_Curl(self, expr):
|
1579 |
+
mrow = self.dom.createElement('mrow')
|
1580 |
+
mo = self.dom.createElement('mo')
|
1581 |
+
mo.appendChild(self.dom.createTextNode('∇'))
|
1582 |
+
mrow.appendChild(mo)
|
1583 |
+
mo = self.dom.createElement('mo')
|
1584 |
+
mo.appendChild(self.dom.createTextNode('×'))
|
1585 |
+
mrow.appendChild(mo)
|
1586 |
+
mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
|
1587 |
+
return mrow
|
1588 |
+
|
1589 |
+
def _print_Divergence(self, expr):
|
1590 |
+
mrow = self.dom.createElement('mrow')
|
1591 |
+
mo = self.dom.createElement('mo')
|
1592 |
+
mo.appendChild(self.dom.createTextNode('∇'))
|
1593 |
+
mrow.appendChild(mo)
|
1594 |
+
mo = self.dom.createElement('mo')
|
1595 |
+
mo.appendChild(self.dom.createTextNode('·'))
|
1596 |
+
mrow.appendChild(mo)
|
1597 |
+
mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
|
1598 |
+
return mrow
|
1599 |
+
|
1600 |
+
def _print_Dot(self, expr):
|
1601 |
+
mrow = self.dom.createElement('mrow')
|
1602 |
+
vec1 = expr._expr1
|
1603 |
+
vec2 = expr._expr2
|
1604 |
+
mrow.appendChild(self.parenthesize(vec1, PRECEDENCE['Mul']))
|
1605 |
+
mo = self.dom.createElement('mo')
|
1606 |
+
mo.appendChild(self.dom.createTextNode('·'))
|
1607 |
+
mrow.appendChild(mo)
|
1608 |
+
mrow.appendChild(self.parenthesize(vec2, PRECEDENCE['Mul']))
|
1609 |
+
return mrow
|
1610 |
+
|
1611 |
+
def _print_Gradient(self, expr):
|
1612 |
+
mrow = self.dom.createElement('mrow')
|
1613 |
+
mo = self.dom.createElement('mo')
|
1614 |
+
mo.appendChild(self.dom.createTextNode('∇'))
|
1615 |
+
mrow.appendChild(mo)
|
1616 |
+
mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
|
1617 |
+
return mrow
|
1618 |
+
|
1619 |
+
def _print_Laplacian(self, expr):
|
1620 |
+
mrow = self.dom.createElement('mrow')
|
1621 |
+
mo = self.dom.createElement('mo')
|
1622 |
+
mo.appendChild(self.dom.createTextNode('∆'))
|
1623 |
+
mrow.appendChild(mo)
|
1624 |
+
mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
|
1625 |
+
return mrow
|
1626 |
+
|
1627 |
+
def _print_Integers(self, e):
|
1628 |
+
x = self.dom.createElement('mi')
|
1629 |
+
x.setAttribute('mathvariant', 'normal')
|
1630 |
+
x.appendChild(self.dom.createTextNode('ℤ'))
|
1631 |
+
return x
|
1632 |
+
|
1633 |
+
def _print_Complexes(self, e):
|
1634 |
+
x = self.dom.createElement('mi')
|
1635 |
+
x.setAttribute('mathvariant', 'normal')
|
1636 |
+
x.appendChild(self.dom.createTextNode('ℂ'))
|
1637 |
+
return x
|
1638 |
+
|
1639 |
+
def _print_Reals(self, e):
|
1640 |
+
x = self.dom.createElement('mi')
|
1641 |
+
x.setAttribute('mathvariant', 'normal')
|
1642 |
+
x.appendChild(self.dom.createTextNode('ℝ'))
|
1643 |
+
return x
|
1644 |
+
|
1645 |
+
def _print_Naturals(self, e):
|
1646 |
+
x = self.dom.createElement('mi')
|
1647 |
+
x.setAttribute('mathvariant', 'normal')
|
1648 |
+
x.appendChild(self.dom.createTextNode('ℕ'))
|
1649 |
+
return x
|
1650 |
+
|
1651 |
+
def _print_Naturals0(self, e):
|
1652 |
+
sub = self.dom.createElement('msub')
|
1653 |
+
x = self.dom.createElement('mi')
|
1654 |
+
x.setAttribute('mathvariant', 'normal')
|
1655 |
+
x.appendChild(self.dom.createTextNode('ℕ'))
|
1656 |
+
sub.appendChild(x)
|
1657 |
+
sub.appendChild(self._print(S.Zero))
|
1658 |
+
return sub
|
1659 |
+
|
1660 |
+
def _print_SingularityFunction(self, expr):
|
1661 |
+
shift = expr.args[0] - expr.args[1]
|
1662 |
+
power = expr.args[2]
|
1663 |
+
sup = self.dom.createElement('msup')
|
1664 |
+
brac = self.dom.createElement('mfenced')
|
1665 |
+
brac.setAttribute('close', '\u27e9')
|
1666 |
+
brac.setAttribute('open', '\u27e8')
|
1667 |
+
brac.appendChild(self._print(shift))
|
1668 |
+
sup.appendChild(brac)
|
1669 |
+
sup.appendChild(self._print(power))
|
1670 |
+
return sup
|
1671 |
+
|
1672 |
+
def _print_NaN(self, e):
|
1673 |
+
x = self.dom.createElement('mi')
|
1674 |
+
x.appendChild(self.dom.createTextNode('NaN'))
|
1675 |
+
return x
|
1676 |
+
|
1677 |
+
def _print_number_function(self, e, name):
|
1678 |
+
# Print name_arg[0] for one argument or name_arg[0](arg[1])
|
1679 |
+
# for more than one argument
|
1680 |
+
sub = self.dom.createElement('msub')
|
1681 |
+
mi = self.dom.createElement('mi')
|
1682 |
+
mi.appendChild(self.dom.createTextNode(name))
|
1683 |
+
sub.appendChild(mi)
|
1684 |
+
sub.appendChild(self._print(e.args[0]))
|
1685 |
+
if len(e.args) == 1:
|
1686 |
+
return sub
|
1687 |
+
# TODO: copy-pasted from _print_Function: can we do better?
|
1688 |
+
mrow = self.dom.createElement('mrow')
|
1689 |
+
y = self.dom.createElement('mfenced')
|
1690 |
+
for arg in e.args[1:]:
|
1691 |
+
y.appendChild(self._print(arg))
|
1692 |
+
mrow.appendChild(sub)
|
1693 |
+
mrow.appendChild(y)
|
1694 |
+
return mrow
|
1695 |
+
|
1696 |
+
def _print_bernoulli(self, e):
|
1697 |
+
return self._print_number_function(e, 'B')
|
1698 |
+
|
1699 |
+
_print_bell = _print_bernoulli
|
1700 |
+
|
1701 |
+
def _print_catalan(self, e):
|
1702 |
+
return self._print_number_function(e, 'C')
|
1703 |
+
|
1704 |
+
def _print_euler(self, e):
|
1705 |
+
return self._print_number_function(e, 'E')
|
1706 |
+
|
1707 |
+
def _print_fibonacci(self, e):
|
1708 |
+
return self._print_number_function(e, 'F')
|
1709 |
+
|
1710 |
+
def _print_lucas(self, e):
|
1711 |
+
return self._print_number_function(e, 'L')
|
1712 |
+
|
1713 |
+
def _print_stieltjes(self, e):
|
1714 |
+
return self._print_number_function(e, 'γ')
|
1715 |
+
|
1716 |
+
def _print_tribonacci(self, e):
|
1717 |
+
return self._print_number_function(e, 'T')
|
1718 |
+
|
1719 |
+
def _print_ComplexInfinity(self, e):
|
1720 |
+
x = self.dom.createElement('mover')
|
1721 |
+
mo = self.dom.createElement('mo')
|
1722 |
+
mo.appendChild(self.dom.createTextNode('∞'))
|
1723 |
+
x.appendChild(mo)
|
1724 |
+
mo = self.dom.createElement('mo')
|
1725 |
+
mo.appendChild(self.dom.createTextNode('~'))
|
1726 |
+
x.appendChild(mo)
|
1727 |
+
return x
|
1728 |
+
|
1729 |
+
def _print_EmptySet(self, e):
|
1730 |
+
x = self.dom.createElement('mo')
|
1731 |
+
x.appendChild(self.dom.createTextNode('∅'))
|
1732 |
+
return x
|
1733 |
+
|
1734 |
+
def _print_UniversalSet(self, e):
|
1735 |
+
x = self.dom.createElement('mo')
|
1736 |
+
x.appendChild(self.dom.createTextNode('𝕌'))
|
1737 |
+
return x
|
1738 |
+
|
1739 |
+
def _print_Adjoint(self, expr):
|
1740 |
+
from sympy.matrices import MatrixSymbol
|
1741 |
+
mat = expr.arg
|
1742 |
+
sup = self.dom.createElement('msup')
|
1743 |
+
if not isinstance(mat, MatrixSymbol):
|
1744 |
+
brac = self.dom.createElement('mfenced')
|
1745 |
+
brac.appendChild(self._print(mat))
|
1746 |
+
sup.appendChild(brac)
|
1747 |
+
else:
|
1748 |
+
sup.appendChild(self._print(mat))
|
1749 |
+
mo = self.dom.createElement('mo')
|
1750 |
+
mo.appendChild(self.dom.createTextNode('†'))
|
1751 |
+
sup.appendChild(mo)
|
1752 |
+
return sup
|
1753 |
+
|
1754 |
+
def _print_Transpose(self, expr):
|
1755 |
+
from sympy.matrices import MatrixSymbol
|
1756 |
+
mat = expr.arg
|
1757 |
+
sup = self.dom.createElement('msup')
|
1758 |
+
if not isinstance(mat, MatrixSymbol):
|
1759 |
+
brac = self.dom.createElement('mfenced')
|
1760 |
+
brac.appendChild(self._print(mat))
|
1761 |
+
sup.appendChild(brac)
|
1762 |
+
else:
|
1763 |
+
sup.appendChild(self._print(mat))
|
1764 |
+
mo = self.dom.createElement('mo')
|
1765 |
+
mo.appendChild(self.dom.createTextNode('T'))
|
1766 |
+
sup.appendChild(mo)
|
1767 |
+
return sup
|
1768 |
+
|
1769 |
+
def _print_Inverse(self, expr):
|
1770 |
+
from sympy.matrices import MatrixSymbol
|
1771 |
+
mat = expr.arg
|
1772 |
+
sup = self.dom.createElement('msup')
|
1773 |
+
if not isinstance(mat, MatrixSymbol):
|
1774 |
+
brac = self.dom.createElement('mfenced')
|
1775 |
+
brac.appendChild(self._print(mat))
|
1776 |
+
sup.appendChild(brac)
|
1777 |
+
else:
|
1778 |
+
sup.appendChild(self._print(mat))
|
1779 |
+
sup.appendChild(self._print(-1))
|
1780 |
+
return sup
|
1781 |
+
|
1782 |
+
def _print_MatMul(self, expr):
|
1783 |
+
from sympy.matrices.expressions.matmul import MatMul
|
1784 |
+
|
1785 |
+
x = self.dom.createElement('mrow')
|
1786 |
+
args = expr.args
|
1787 |
+
if isinstance(args[0], Mul):
|
1788 |
+
args = args[0].as_ordered_factors() + list(args[1:])
|
1789 |
+
else:
|
1790 |
+
args = list(args)
|
1791 |
+
|
1792 |
+
if isinstance(expr, MatMul) and expr.could_extract_minus_sign():
|
1793 |
+
if args[0] == -1:
|
1794 |
+
args = args[1:]
|
1795 |
+
else:
|
1796 |
+
args[0] = -args[0]
|
1797 |
+
mo = self.dom.createElement('mo')
|
1798 |
+
mo.appendChild(self.dom.createTextNode('-'))
|
1799 |
+
x.appendChild(mo)
|
1800 |
+
|
1801 |
+
for arg in args[:-1]:
|
1802 |
+
x.appendChild(self.parenthesize(arg, precedence_traditional(expr),
|
1803 |
+
False))
|
1804 |
+
mo = self.dom.createElement('mo')
|
1805 |
+
mo.appendChild(self.dom.createTextNode('⁢'))
|
1806 |
+
x.appendChild(mo)
|
1807 |
+
x.appendChild(self.parenthesize(args[-1], precedence_traditional(expr),
|
1808 |
+
False))
|
1809 |
+
return x
|
1810 |
+
|
1811 |
+
def _print_MatPow(self, expr):
|
1812 |
+
from sympy.matrices import MatrixSymbol
|
1813 |
+
base, exp = expr.base, expr.exp
|
1814 |
+
sup = self.dom.createElement('msup')
|
1815 |
+
if not isinstance(base, MatrixSymbol):
|
1816 |
+
brac = self.dom.createElement('mfenced')
|
1817 |
+
brac.appendChild(self._print(base))
|
1818 |
+
sup.appendChild(brac)
|
1819 |
+
else:
|
1820 |
+
sup.appendChild(self._print(base))
|
1821 |
+
sup.appendChild(self._print(exp))
|
1822 |
+
return sup
|
1823 |
+
|
1824 |
+
def _print_HadamardProduct(self, expr):
|
1825 |
+
x = self.dom.createElement('mrow')
|
1826 |
+
args = expr.args
|
1827 |
+
for arg in args[:-1]:
|
1828 |
+
x.appendChild(
|
1829 |
+
self.parenthesize(arg, precedence_traditional(expr), False))
|
1830 |
+
mo = self.dom.createElement('mo')
|
1831 |
+
mo.appendChild(self.dom.createTextNode('∘'))
|
1832 |
+
x.appendChild(mo)
|
1833 |
+
x.appendChild(
|
1834 |
+
self.parenthesize(args[-1], precedence_traditional(expr), False))
|
1835 |
+
return x
|
1836 |
+
|
1837 |
+
def _print_ZeroMatrix(self, Z):
|
1838 |
+
x = self.dom.createElement('mn')
|
1839 |
+
x.appendChild(self.dom.createTextNode('𝟘'))
|
1840 |
+
return x
|
1841 |
+
|
1842 |
+
def _print_OneMatrix(self, Z):
|
1843 |
+
x = self.dom.createElement('mn')
|
1844 |
+
x.appendChild(self.dom.createTextNode('𝟙'))
|
1845 |
+
return x
|
1846 |
+
|
1847 |
+
def _print_Identity(self, I):
|
1848 |
+
x = self.dom.createElement('mi')
|
1849 |
+
x.appendChild(self.dom.createTextNode('𝕀'))
|
1850 |
+
return x
|
1851 |
+
|
1852 |
+
def _print_floor(self, e):
|
1853 |
+
mrow = self.dom.createElement('mrow')
|
1854 |
+
x = self.dom.createElement('mfenced')
|
1855 |
+
x.setAttribute('close', '\u230B')
|
1856 |
+
x.setAttribute('open', '\u230A')
|
1857 |
+
x.appendChild(self._print(e.args[0]))
|
1858 |
+
mrow.appendChild(x)
|
1859 |
+
return mrow
|
1860 |
+
|
1861 |
+
def _print_ceiling(self, e):
|
1862 |
+
mrow = self.dom.createElement('mrow')
|
1863 |
+
x = self.dom.createElement('mfenced')
|
1864 |
+
x.setAttribute('close', '\u2309')
|
1865 |
+
x.setAttribute('open', '\u2308')
|
1866 |
+
x.appendChild(self._print(e.args[0]))
|
1867 |
+
mrow.appendChild(x)
|
1868 |
+
return mrow
|
1869 |
+
|
1870 |
+
def _print_Lambda(self, e):
|
1871 |
+
x = self.dom.createElement('mfenced')
|
1872 |
+
mrow = self.dom.createElement('mrow')
|
1873 |
+
symbols = e.args[0]
|
1874 |
+
if len(symbols) == 1:
|
1875 |
+
symbols = self._print(symbols[0])
|
1876 |
+
else:
|
1877 |
+
symbols = self._print(symbols)
|
1878 |
+
mrow.appendChild(symbols)
|
1879 |
+
mo = self.dom.createElement('mo')
|
1880 |
+
mo.appendChild(self.dom.createTextNode('↦'))
|
1881 |
+
mrow.appendChild(mo)
|
1882 |
+
mrow.appendChild(self._print(e.args[1]))
|
1883 |
+
x.appendChild(mrow)
|
1884 |
+
return x
|
1885 |
+
|
1886 |
+
def _print_tuple(self, e):
|
1887 |
+
x = self.dom.createElement('mfenced')
|
1888 |
+
for i in e:
|
1889 |
+
x.appendChild(self._print(i))
|
1890 |
+
return x
|
1891 |
+
|
1892 |
+
def _print_IndexedBase(self, e):
|
1893 |
+
return self._print(e.label)
|
1894 |
+
|
1895 |
+
def _print_Indexed(self, e):
|
1896 |
+
x = self.dom.createElement('msub')
|
1897 |
+
x.appendChild(self._print(e.base))
|
1898 |
+
if len(e.indices) == 1:
|
1899 |
+
x.appendChild(self._print(e.indices[0]))
|
1900 |
+
return x
|
1901 |
+
x.appendChild(self._print(e.indices))
|
1902 |
+
return x
|
1903 |
+
|
1904 |
+
def _print_MatrixElement(self, e):
|
1905 |
+
x = self.dom.createElement('msub')
|
1906 |
+
x.appendChild(self.parenthesize(e.parent, PRECEDENCE["Atom"], strict = True))
|
1907 |
+
brac = self.dom.createElement('mfenced')
|
1908 |
+
brac.setAttribute("close", "")
|
1909 |
+
brac.setAttribute("open", "")
|
1910 |
+
for i in e.indices:
|
1911 |
+
brac.appendChild(self._print(i))
|
1912 |
+
x.appendChild(brac)
|
1913 |
+
return x
|
1914 |
+
|
1915 |
+
def _print_elliptic_f(self, e):
|
1916 |
+
x = self.dom.createElement('mrow')
|
1917 |
+
mi = self.dom.createElement('mi')
|
1918 |
+
mi.appendChild(self.dom.createTextNode('𝖥'))
|
1919 |
+
x.appendChild(mi)
|
1920 |
+
y = self.dom.createElement('mfenced')
|
1921 |
+
y.setAttribute("separators", "|")
|
1922 |
+
for i in e.args:
|
1923 |
+
y.appendChild(self._print(i))
|
1924 |
+
x.appendChild(y)
|
1925 |
+
return x
|
1926 |
+
|
1927 |
+
def _print_elliptic_e(self, e):
|
1928 |
+
x = self.dom.createElement('mrow')
|
1929 |
+
mi = self.dom.createElement('mi')
|
1930 |
+
mi.appendChild(self.dom.createTextNode('𝖤'))
|
1931 |
+
x.appendChild(mi)
|
1932 |
+
y = self.dom.createElement('mfenced')
|
1933 |
+
y.setAttribute("separators", "|")
|
1934 |
+
for i in e.args:
|
1935 |
+
y.appendChild(self._print(i))
|
1936 |
+
x.appendChild(y)
|
1937 |
+
return x
|
1938 |
+
|
1939 |
+
def _print_elliptic_pi(self, e):
|
1940 |
+
x = self.dom.createElement('mrow')
|
1941 |
+
mi = self.dom.createElement('mi')
|
1942 |
+
mi.appendChild(self.dom.createTextNode('𝛱'))
|
1943 |
+
x.appendChild(mi)
|
1944 |
+
y = self.dom.createElement('mfenced')
|
1945 |
+
if len(e.args) == 2:
|
1946 |
+
y.setAttribute("separators", "|")
|
1947 |
+
else:
|
1948 |
+
y.setAttribute("separators", ";|")
|
1949 |
+
for i in e.args:
|
1950 |
+
y.appendChild(self._print(i))
|
1951 |
+
x.appendChild(y)
|
1952 |
+
return x
|
1953 |
+
|
1954 |
+
def _print_Ei(self, e):
|
1955 |
+
x = self.dom.createElement('mrow')
|
1956 |
+
mi = self.dom.createElement('mi')
|
1957 |
+
mi.appendChild(self.dom.createTextNode('Ei'))
|
1958 |
+
x.appendChild(mi)
|
1959 |
+
x.appendChild(self._print(e.args))
|
1960 |
+
return x
|
1961 |
+
|
1962 |
+
def _print_expint(self, e):
|
1963 |
+
x = self.dom.createElement('mrow')
|
1964 |
+
y = self.dom.createElement('msub')
|
1965 |
+
mo = self.dom.createElement('mo')
|
1966 |
+
mo.appendChild(self.dom.createTextNode('E'))
|
1967 |
+
y.appendChild(mo)
|
1968 |
+
y.appendChild(self._print(e.args[0]))
|
1969 |
+
x.appendChild(y)
|
1970 |
+
x.appendChild(self._print(e.args[1:]))
|
1971 |
+
return x
|
1972 |
+
|
1973 |
+
def _print_jacobi(self, e):
|
1974 |
+
x = self.dom.createElement('mrow')
|
1975 |
+
y = self.dom.createElement('msubsup')
|
1976 |
+
mo = self.dom.createElement('mo')
|
1977 |
+
mo.appendChild(self.dom.createTextNode('P'))
|
1978 |
+
y.appendChild(mo)
|
1979 |
+
y.appendChild(self._print(e.args[0]))
|
1980 |
+
y.appendChild(self._print(e.args[1:3]))
|
1981 |
+
x.appendChild(y)
|
1982 |
+
x.appendChild(self._print(e.args[3:]))
|
1983 |
+
return x
|
1984 |
+
|
1985 |
+
def _print_gegenbauer(self, e):
|
1986 |
+
x = self.dom.createElement('mrow')
|
1987 |
+
y = self.dom.createElement('msubsup')
|
1988 |
+
mo = self.dom.createElement('mo')
|
1989 |
+
mo.appendChild(self.dom.createTextNode('C'))
|
1990 |
+
y.appendChild(mo)
|
1991 |
+
y.appendChild(self._print(e.args[0]))
|
1992 |
+
y.appendChild(self._print(e.args[1:2]))
|
1993 |
+
x.appendChild(y)
|
1994 |
+
x.appendChild(self._print(e.args[2:]))
|
1995 |
+
return x
|
1996 |
+
|
1997 |
+
def _print_chebyshevt(self, e):
|
1998 |
+
x = self.dom.createElement('mrow')
|
1999 |
+
y = self.dom.createElement('msub')
|
2000 |
+
mo = self.dom.createElement('mo')
|
2001 |
+
mo.appendChild(self.dom.createTextNode('T'))
|
2002 |
+
y.appendChild(mo)
|
2003 |
+
y.appendChild(self._print(e.args[0]))
|
2004 |
+
x.appendChild(y)
|
2005 |
+
x.appendChild(self._print(e.args[1:]))
|
2006 |
+
return x
|
2007 |
+
|
2008 |
+
def _print_chebyshevu(self, e):
|
2009 |
+
x = self.dom.createElement('mrow')
|
2010 |
+
y = self.dom.createElement('msub')
|
2011 |
+
mo = self.dom.createElement('mo')
|
2012 |
+
mo.appendChild(self.dom.createTextNode('U'))
|
2013 |
+
y.appendChild(mo)
|
2014 |
+
y.appendChild(self._print(e.args[0]))
|
2015 |
+
x.appendChild(y)
|
2016 |
+
x.appendChild(self._print(e.args[1:]))
|
2017 |
+
return x
|
2018 |
+
|
2019 |
+
def _print_legendre(self, e):
|
2020 |
+
x = self.dom.createElement('mrow')
|
2021 |
+
y = self.dom.createElement('msub')
|
2022 |
+
mo = self.dom.createElement('mo')
|
2023 |
+
mo.appendChild(self.dom.createTextNode('P'))
|
2024 |
+
y.appendChild(mo)
|
2025 |
+
y.appendChild(self._print(e.args[0]))
|
2026 |
+
x.appendChild(y)
|
2027 |
+
x.appendChild(self._print(e.args[1:]))
|
2028 |
+
return x
|
2029 |
+
|
2030 |
+
def _print_assoc_legendre(self, e):
|
2031 |
+
x = self.dom.createElement('mrow')
|
2032 |
+
y = self.dom.createElement('msubsup')
|
2033 |
+
mo = self.dom.createElement('mo')
|
2034 |
+
mo.appendChild(self.dom.createTextNode('P'))
|
2035 |
+
y.appendChild(mo)
|
2036 |
+
y.appendChild(self._print(e.args[0]))
|
2037 |
+
y.appendChild(self._print(e.args[1:2]))
|
2038 |
+
x.appendChild(y)
|
2039 |
+
x.appendChild(self._print(e.args[2:]))
|
2040 |
+
return x
|
2041 |
+
|
2042 |
+
def _print_laguerre(self, e):
|
2043 |
+
x = self.dom.createElement('mrow')
|
2044 |
+
y = self.dom.createElement('msub')
|
2045 |
+
mo = self.dom.createElement('mo')
|
2046 |
+
mo.appendChild(self.dom.createTextNode('L'))
|
2047 |
+
y.appendChild(mo)
|
2048 |
+
y.appendChild(self._print(e.args[0]))
|
2049 |
+
x.appendChild(y)
|
2050 |
+
x.appendChild(self._print(e.args[1:]))
|
2051 |
+
return x
|
2052 |
+
|
2053 |
+
def _print_assoc_laguerre(self, e):
|
2054 |
+
x = self.dom.createElement('mrow')
|
2055 |
+
y = self.dom.createElement('msubsup')
|
2056 |
+
mo = self.dom.createElement('mo')
|
2057 |
+
mo.appendChild(self.dom.createTextNode('L'))
|
2058 |
+
y.appendChild(mo)
|
2059 |
+
y.appendChild(self._print(e.args[0]))
|
2060 |
+
y.appendChild(self._print(e.args[1:2]))
|
2061 |
+
x.appendChild(y)
|
2062 |
+
x.appendChild(self._print(e.args[2:]))
|
2063 |
+
return x
|
2064 |
+
|
2065 |
+
def _print_hermite(self, e):
|
2066 |
+
x = self.dom.createElement('mrow')
|
2067 |
+
y = self.dom.createElement('msub')
|
2068 |
+
mo = self.dom.createElement('mo')
|
2069 |
+
mo.appendChild(self.dom.createTextNode('H'))
|
2070 |
+
y.appendChild(mo)
|
2071 |
+
y.appendChild(self._print(e.args[0]))
|
2072 |
+
x.appendChild(y)
|
2073 |
+
x.appendChild(self._print(e.args[1:]))
|
2074 |
+
return x
|
2075 |
+
|
2076 |
+
|
2077 |
+
@print_function(MathMLPrinterBase)
|
2078 |
+
def mathml(expr, printer='content', **settings):
|
2079 |
+
"""Returns the MathML representation of expr. If printer is presentation
|
2080 |
+
then prints Presentation MathML else prints content MathML.
|
2081 |
+
"""
|
2082 |
+
if printer == 'presentation':
|
2083 |
+
return MathMLPresentationPrinter(settings).doprint(expr)
|
2084 |
+
else:
|
2085 |
+
return MathMLContentPrinter(settings).doprint(expr)
|
2086 |
+
|
2087 |
+
|
2088 |
+
def print_mathml(expr, printer='content', **settings):
|
2089 |
+
"""
|
2090 |
+
Prints a pretty representation of the MathML code for expr. If printer is
|
2091 |
+
presentation then prints Presentation MathML else prints content MathML.
|
2092 |
+
|
2093 |
+
Examples
|
2094 |
+
========
|
2095 |
+
|
2096 |
+
>>> ##
|
2097 |
+
>>> from sympy import print_mathml
|
2098 |
+
>>> from sympy.abc import x
|
2099 |
+
>>> print_mathml(x+1) #doctest: +NORMALIZE_WHITESPACE
|
2100 |
+
<apply>
|
2101 |
+
<plus/>
|
2102 |
+
<ci>x</ci>
|
2103 |
+
<cn>1</cn>
|
2104 |
+
</apply>
|
2105 |
+
>>> print_mathml(x+1, printer='presentation')
|
2106 |
+
<mrow>
|
2107 |
+
<mi>x</mi>
|
2108 |
+
<mo>+</mo>
|
2109 |
+
<mn>1</mn>
|
2110 |
+
</mrow>
|
2111 |
+
|
2112 |
+
"""
|
2113 |
+
if printer == 'presentation':
|
2114 |
+
s = MathMLPresentationPrinter(settings)
|
2115 |
+
else:
|
2116 |
+
s = MathMLContentPrinter(settings)
|
2117 |
+
xml = s._print(sympify(expr))
|
2118 |
+
s.apply_patch()
|
2119 |
+
pretty_xml = xml.toprettyxml()
|
2120 |
+
s.restore_patch()
|
2121 |
+
|
2122 |
+
print(pretty_xml)
|
2123 |
+
|
2124 |
+
|
2125 |
+
# For backward compatibility
|
2126 |
+
MathMLPrinter = MathMLContentPrinter
|
venv/lib/python3.10/site-packages/sympy/printing/numpy.py
ADDED
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import S
|
2 |
+
from sympy.core.function import Lambda
|
3 |
+
from sympy.core.power import Pow
|
4 |
+
from .pycode import PythonCodePrinter, _known_functions_math, _print_known_const, _print_known_func, _unpack_integral_limits, ArrayPrinter
|
5 |
+
from .codeprinter import CodePrinter
|
6 |
+
|
7 |
+
|
8 |
+
_not_in_numpy = 'erf erfc factorial gamma loggamma'.split()
|
9 |
+
_in_numpy = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_numpy]
|
10 |
+
_known_functions_numpy = dict(_in_numpy, **{
|
11 |
+
'acos': 'arccos',
|
12 |
+
'acosh': 'arccosh',
|
13 |
+
'asin': 'arcsin',
|
14 |
+
'asinh': 'arcsinh',
|
15 |
+
'atan': 'arctan',
|
16 |
+
'atan2': 'arctan2',
|
17 |
+
'atanh': 'arctanh',
|
18 |
+
'exp2': 'exp2',
|
19 |
+
'sign': 'sign',
|
20 |
+
'logaddexp': 'logaddexp',
|
21 |
+
'logaddexp2': 'logaddexp2',
|
22 |
+
})
|
23 |
+
_known_constants_numpy = {
|
24 |
+
'Exp1': 'e',
|
25 |
+
'Pi': 'pi',
|
26 |
+
'EulerGamma': 'euler_gamma',
|
27 |
+
'NaN': 'nan',
|
28 |
+
'Infinity': 'PINF',
|
29 |
+
'NegativeInfinity': 'NINF'
|
30 |
+
}
|
31 |
+
|
32 |
+
_numpy_known_functions = {k: 'numpy.' + v for k, v in _known_functions_numpy.items()}
|
33 |
+
_numpy_known_constants = {k: 'numpy.' + v for k, v in _known_constants_numpy.items()}
|
34 |
+
|
35 |
+
class NumPyPrinter(ArrayPrinter, PythonCodePrinter):
|
36 |
+
"""
|
37 |
+
Numpy printer which handles vectorized piecewise functions,
|
38 |
+
logical operators, etc.
|
39 |
+
"""
|
40 |
+
|
41 |
+
_module = 'numpy'
|
42 |
+
_kf = _numpy_known_functions
|
43 |
+
_kc = _numpy_known_constants
|
44 |
+
|
45 |
+
def __init__(self, settings=None):
|
46 |
+
"""
|
47 |
+
`settings` is passed to CodePrinter.__init__()
|
48 |
+
`module` specifies the array module to use, currently 'NumPy', 'CuPy'
|
49 |
+
or 'JAX'.
|
50 |
+
"""
|
51 |
+
self.language = "Python with {}".format(self._module)
|
52 |
+
self.printmethod = "_{}code".format(self._module)
|
53 |
+
|
54 |
+
self._kf = {**PythonCodePrinter._kf, **self._kf}
|
55 |
+
|
56 |
+
super().__init__(settings=settings)
|
57 |
+
|
58 |
+
|
59 |
+
def _print_seq(self, seq):
|
60 |
+
"General sequence printer: converts to tuple"
|
61 |
+
# Print tuples here instead of lists because numba supports
|
62 |
+
# tuples in nopython mode.
|
63 |
+
delimiter=', '
|
64 |
+
return '({},)'.format(delimiter.join(self._print(item) for item in seq))
|
65 |
+
|
66 |
+
def _print_MatMul(self, expr):
|
67 |
+
"Matrix multiplication printer"
|
68 |
+
if expr.as_coeff_matrices()[0] is not S.One:
|
69 |
+
expr_list = expr.as_coeff_matrices()[1]+[(expr.as_coeff_matrices()[0])]
|
70 |
+
return '({})'.format(').dot('.join(self._print(i) for i in expr_list))
|
71 |
+
return '({})'.format(').dot('.join(self._print(i) for i in expr.args))
|
72 |
+
|
73 |
+
def _print_MatPow(self, expr):
|
74 |
+
"Matrix power printer"
|
75 |
+
return '{}({}, {})'.format(self._module_format(self._module + '.linalg.matrix_power'),
|
76 |
+
self._print(expr.args[0]), self._print(expr.args[1]))
|
77 |
+
|
78 |
+
def _print_Inverse(self, expr):
|
79 |
+
"Matrix inverse printer"
|
80 |
+
return '{}({})'.format(self._module_format(self._module + '.linalg.inv'),
|
81 |
+
self._print(expr.args[0]))
|
82 |
+
|
83 |
+
def _print_DotProduct(self, expr):
|
84 |
+
# DotProduct allows any shape order, but numpy.dot does matrix
|
85 |
+
# multiplication, so we have to make sure it gets 1 x n by n x 1.
|
86 |
+
arg1, arg2 = expr.args
|
87 |
+
if arg1.shape[0] != 1:
|
88 |
+
arg1 = arg1.T
|
89 |
+
if arg2.shape[1] != 1:
|
90 |
+
arg2 = arg2.T
|
91 |
+
|
92 |
+
return "%s(%s, %s)" % (self._module_format(self._module + '.dot'),
|
93 |
+
self._print(arg1),
|
94 |
+
self._print(arg2))
|
95 |
+
|
96 |
+
def _print_MatrixSolve(self, expr):
|
97 |
+
return "%s(%s, %s)" % (self._module_format(self._module + '.linalg.solve'),
|
98 |
+
self._print(expr.matrix),
|
99 |
+
self._print(expr.vector))
|
100 |
+
|
101 |
+
def _print_ZeroMatrix(self, expr):
|
102 |
+
return '{}({})'.format(self._module_format(self._module + '.zeros'),
|
103 |
+
self._print(expr.shape))
|
104 |
+
|
105 |
+
def _print_OneMatrix(self, expr):
|
106 |
+
return '{}({})'.format(self._module_format(self._module + '.ones'),
|
107 |
+
self._print(expr.shape))
|
108 |
+
|
109 |
+
def _print_FunctionMatrix(self, expr):
|
110 |
+
from sympy.abc import i, j
|
111 |
+
lamda = expr.lamda
|
112 |
+
if not isinstance(lamda, Lambda):
|
113 |
+
lamda = Lambda((i, j), lamda(i, j))
|
114 |
+
return '{}(lambda {}: {}, {})'.format(self._module_format(self._module + '.fromfunction'),
|
115 |
+
', '.join(self._print(arg) for arg in lamda.args[0]),
|
116 |
+
self._print(lamda.args[1]), self._print(expr.shape))
|
117 |
+
|
118 |
+
def _print_HadamardProduct(self, expr):
|
119 |
+
func = self._module_format(self._module + '.multiply')
|
120 |
+
return ''.join('{}({}, '.format(func, self._print(arg)) \
|
121 |
+
for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),
|
122 |
+
')' * (len(expr.args) - 1))
|
123 |
+
|
124 |
+
def _print_KroneckerProduct(self, expr):
|
125 |
+
func = self._module_format(self._module + '.kron')
|
126 |
+
return ''.join('{}({}, '.format(func, self._print(arg)) \
|
127 |
+
for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),
|
128 |
+
')' * (len(expr.args) - 1))
|
129 |
+
|
130 |
+
def _print_Adjoint(self, expr):
|
131 |
+
return '{}({}({}))'.format(
|
132 |
+
self._module_format(self._module + '.conjugate'),
|
133 |
+
self._module_format(self._module + '.transpose'),
|
134 |
+
self._print(expr.args[0]))
|
135 |
+
|
136 |
+
def _print_DiagonalOf(self, expr):
|
137 |
+
vect = '{}({})'.format(
|
138 |
+
self._module_format(self._module + '.diag'),
|
139 |
+
self._print(expr.arg))
|
140 |
+
return '{}({}, (-1, 1))'.format(
|
141 |
+
self._module_format(self._module + '.reshape'), vect)
|
142 |
+
|
143 |
+
def _print_DiagMatrix(self, expr):
|
144 |
+
return '{}({})'.format(self._module_format(self._module + '.diagflat'),
|
145 |
+
self._print(expr.args[0]))
|
146 |
+
|
147 |
+
def _print_DiagonalMatrix(self, expr):
|
148 |
+
return '{}({}, {}({}, {}))'.format(self._module_format(self._module + '.multiply'),
|
149 |
+
self._print(expr.arg), self._module_format(self._module + '.eye'),
|
150 |
+
self._print(expr.shape[0]), self._print(expr.shape[1]))
|
151 |
+
|
152 |
+
def _print_Piecewise(self, expr):
|
153 |
+
"Piecewise function printer"
|
154 |
+
from sympy.logic.boolalg import ITE, simplify_logic
|
155 |
+
def print_cond(cond):
|
156 |
+
""" Problem having an ITE in the cond. """
|
157 |
+
if cond.has(ITE):
|
158 |
+
return self._print(simplify_logic(cond))
|
159 |
+
else:
|
160 |
+
return self._print(cond)
|
161 |
+
exprs = '[{}]'.format(','.join(self._print(arg.expr) for arg in expr.args))
|
162 |
+
conds = '[{}]'.format(','.join(print_cond(arg.cond) for arg in expr.args))
|
163 |
+
# If [default_value, True] is a (expr, cond) sequence in a Piecewise object
|
164 |
+
# it will behave the same as passing the 'default' kwarg to select()
|
165 |
+
# *as long as* it is the last element in expr.args.
|
166 |
+
# If this is not the case, it may be triggered prematurely.
|
167 |
+
return '{}({}, {}, default={})'.format(
|
168 |
+
self._module_format(self._module + '.select'), conds, exprs,
|
169 |
+
self._print(S.NaN))
|
170 |
+
|
171 |
+
def _print_Relational(self, expr):
|
172 |
+
"Relational printer for Equality and Unequality"
|
173 |
+
op = {
|
174 |
+
'==' :'equal',
|
175 |
+
'!=' :'not_equal',
|
176 |
+
'<' :'less',
|
177 |
+
'<=' :'less_equal',
|
178 |
+
'>' :'greater',
|
179 |
+
'>=' :'greater_equal',
|
180 |
+
}
|
181 |
+
if expr.rel_op in op:
|
182 |
+
lhs = self._print(expr.lhs)
|
183 |
+
rhs = self._print(expr.rhs)
|
184 |
+
return '{op}({lhs}, {rhs})'.format(op=self._module_format(self._module + '.'+op[expr.rel_op]),
|
185 |
+
lhs=lhs, rhs=rhs)
|
186 |
+
return super()._print_Relational(expr)
|
187 |
+
|
188 |
+
def _print_And(self, expr):
|
189 |
+
"Logical And printer"
|
190 |
+
# We have to override LambdaPrinter because it uses Python 'and' keyword.
|
191 |
+
# If LambdaPrinter didn't define it, we could use StrPrinter's
|
192 |
+
# version of the function and add 'logical_and' to NUMPY_TRANSLATIONS.
|
193 |
+
return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_and'), ','.join(self._print(i) for i in expr.args))
|
194 |
+
|
195 |
+
def _print_Or(self, expr):
|
196 |
+
"Logical Or printer"
|
197 |
+
# We have to override LambdaPrinter because it uses Python 'or' keyword.
|
198 |
+
# If LambdaPrinter didn't define it, we could use StrPrinter's
|
199 |
+
# version of the function and add 'logical_or' to NUMPY_TRANSLATIONS.
|
200 |
+
return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_or'), ','.join(self._print(i) for i in expr.args))
|
201 |
+
|
202 |
+
def _print_Not(self, expr):
|
203 |
+
"Logical Not printer"
|
204 |
+
# We have to override LambdaPrinter because it uses Python 'not' keyword.
|
205 |
+
# If LambdaPrinter didn't define it, we would still have to define our
|
206 |
+
# own because StrPrinter doesn't define it.
|
207 |
+
return '{}({})'.format(self._module_format(self._module + '.logical_not'), ','.join(self._print(i) for i in expr.args))
|
208 |
+
|
209 |
+
def _print_Pow(self, expr, rational=False):
|
210 |
+
# XXX Workaround for negative integer power error
|
211 |
+
if expr.exp.is_integer and expr.exp.is_negative:
|
212 |
+
expr = Pow(expr.base, expr.exp.evalf(), evaluate=False)
|
213 |
+
return self._hprint_Pow(expr, rational=rational, sqrt=self._module + '.sqrt')
|
214 |
+
|
215 |
+
def _print_Min(self, expr):
|
216 |
+
return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amin'), ','.join(self._print(i) for i in expr.args))
|
217 |
+
|
218 |
+
def _print_Max(self, expr):
|
219 |
+
return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amax'), ','.join(self._print(i) for i in expr.args))
|
220 |
+
|
221 |
+
def _print_arg(self, expr):
|
222 |
+
return "%s(%s)" % (self._module_format(self._module + '.angle'), self._print(expr.args[0]))
|
223 |
+
|
224 |
+
def _print_im(self, expr):
|
225 |
+
return "%s(%s)" % (self._module_format(self._module + '.imag'), self._print(expr.args[0]))
|
226 |
+
|
227 |
+
def _print_Mod(self, expr):
|
228 |
+
return "%s(%s)" % (self._module_format(self._module + '.mod'), ', '.join(
|
229 |
+
(self._print(arg) for arg in expr.args)))
|
230 |
+
|
231 |
+
def _print_re(self, expr):
|
232 |
+
return "%s(%s)" % (self._module_format(self._module + '.real'), self._print(expr.args[0]))
|
233 |
+
|
234 |
+
def _print_sinc(self, expr):
|
235 |
+
return "%s(%s)" % (self._module_format(self._module + '.sinc'), self._print(expr.args[0]/S.Pi))
|
236 |
+
|
237 |
+
def _print_MatrixBase(self, expr):
|
238 |
+
func = self.known_functions.get(expr.__class__.__name__, None)
|
239 |
+
if func is None:
|
240 |
+
func = self._module_format(self._module + '.array')
|
241 |
+
return "%s(%s)" % (func, self._print(expr.tolist()))
|
242 |
+
|
243 |
+
def _print_Identity(self, expr):
|
244 |
+
shape = expr.shape
|
245 |
+
if all(dim.is_Integer for dim in shape):
|
246 |
+
return "%s(%s)" % (self._module_format(self._module + '.eye'), self._print(expr.shape[0]))
|
247 |
+
else:
|
248 |
+
raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices")
|
249 |
+
|
250 |
+
def _print_BlockMatrix(self, expr):
|
251 |
+
return '{}({})'.format(self._module_format(self._module + '.block'),
|
252 |
+
self._print(expr.args[0].tolist()))
|
253 |
+
|
254 |
+
def _print_NDimArray(self, expr):
|
255 |
+
if len(expr.shape) == 1:
|
256 |
+
return self._module + '.array(' + self._print(expr.args[0]) + ')'
|
257 |
+
if len(expr.shape) == 2:
|
258 |
+
return self._print(expr.tomatrix())
|
259 |
+
# Should be possible to extend to more dimensions
|
260 |
+
return CodePrinter._print_not_supported(self, expr)
|
261 |
+
|
262 |
+
_add = "add"
|
263 |
+
_einsum = "einsum"
|
264 |
+
_transpose = "transpose"
|
265 |
+
_ones = "ones"
|
266 |
+
_zeros = "zeros"
|
267 |
+
|
268 |
+
_print_lowergamma = CodePrinter._print_not_supported
|
269 |
+
_print_uppergamma = CodePrinter._print_not_supported
|
270 |
+
_print_fresnelc = CodePrinter._print_not_supported
|
271 |
+
_print_fresnels = CodePrinter._print_not_supported
|
272 |
+
|
273 |
+
for func in _numpy_known_functions:
|
274 |
+
setattr(NumPyPrinter, f'_print_{func}', _print_known_func)
|
275 |
+
|
276 |
+
for const in _numpy_known_constants:
|
277 |
+
setattr(NumPyPrinter, f'_print_{const}', _print_known_const)
|
278 |
+
|
279 |
+
|
280 |
+
_known_functions_scipy_special = {
|
281 |
+
'Ei': 'expi',
|
282 |
+
'erf': 'erf',
|
283 |
+
'erfc': 'erfc',
|
284 |
+
'besselj': 'jv',
|
285 |
+
'bessely': 'yv',
|
286 |
+
'besseli': 'iv',
|
287 |
+
'besselk': 'kv',
|
288 |
+
'cosm1': 'cosm1',
|
289 |
+
'powm1': 'powm1',
|
290 |
+
'factorial': 'factorial',
|
291 |
+
'gamma': 'gamma',
|
292 |
+
'loggamma': 'gammaln',
|
293 |
+
'digamma': 'psi',
|
294 |
+
'polygamma': 'polygamma',
|
295 |
+
'RisingFactorial': 'poch',
|
296 |
+
'jacobi': 'eval_jacobi',
|
297 |
+
'gegenbauer': 'eval_gegenbauer',
|
298 |
+
'chebyshevt': 'eval_chebyt',
|
299 |
+
'chebyshevu': 'eval_chebyu',
|
300 |
+
'legendre': 'eval_legendre',
|
301 |
+
'hermite': 'eval_hermite',
|
302 |
+
'laguerre': 'eval_laguerre',
|
303 |
+
'assoc_laguerre': 'eval_genlaguerre',
|
304 |
+
'beta': 'beta',
|
305 |
+
'LambertW' : 'lambertw',
|
306 |
+
}
|
307 |
+
|
308 |
+
_known_constants_scipy_constants = {
|
309 |
+
'GoldenRatio': 'golden_ratio',
|
310 |
+
'Pi': 'pi',
|
311 |
+
}
|
312 |
+
_scipy_known_functions = {k : "scipy.special." + v for k, v in _known_functions_scipy_special.items()}
|
313 |
+
_scipy_known_constants = {k : "scipy.constants." + v for k, v in _known_constants_scipy_constants.items()}
|
314 |
+
|
315 |
+
class SciPyPrinter(NumPyPrinter):
|
316 |
+
|
317 |
+
_kf = {**NumPyPrinter._kf, **_scipy_known_functions}
|
318 |
+
_kc = {**NumPyPrinter._kc, **_scipy_known_constants}
|
319 |
+
|
320 |
+
def __init__(self, settings=None):
|
321 |
+
super().__init__(settings=settings)
|
322 |
+
self.language = "Python with SciPy and NumPy"
|
323 |
+
|
324 |
+
def _print_SparseRepMatrix(self, expr):
|
325 |
+
i, j, data = [], [], []
|
326 |
+
for (r, c), v in expr.todok().items():
|
327 |
+
i.append(r)
|
328 |
+
j.append(c)
|
329 |
+
data.append(v)
|
330 |
+
|
331 |
+
return "{name}(({data}, ({i}, {j})), shape={shape})".format(
|
332 |
+
name=self._module_format('scipy.sparse.coo_matrix'),
|
333 |
+
data=data, i=i, j=j, shape=expr.shape
|
334 |
+
)
|
335 |
+
|
336 |
+
_print_ImmutableSparseMatrix = _print_SparseRepMatrix
|
337 |
+
|
338 |
+
# SciPy's lpmv has a different order of arguments from assoc_legendre
|
339 |
+
def _print_assoc_legendre(self, expr):
|
340 |
+
return "{0}({2}, {1}, {3})".format(
|
341 |
+
self._module_format('scipy.special.lpmv'),
|
342 |
+
self._print(expr.args[0]),
|
343 |
+
self._print(expr.args[1]),
|
344 |
+
self._print(expr.args[2]))
|
345 |
+
|
346 |
+
def _print_lowergamma(self, expr):
|
347 |
+
return "{0}({2})*{1}({2}, {3})".format(
|
348 |
+
self._module_format('scipy.special.gamma'),
|
349 |
+
self._module_format('scipy.special.gammainc'),
|
350 |
+
self._print(expr.args[0]),
|
351 |
+
self._print(expr.args[1]))
|
352 |
+
|
353 |
+
def _print_uppergamma(self, expr):
|
354 |
+
return "{0}({2})*{1}({2}, {3})".format(
|
355 |
+
self._module_format('scipy.special.gamma'),
|
356 |
+
self._module_format('scipy.special.gammaincc'),
|
357 |
+
self._print(expr.args[0]),
|
358 |
+
self._print(expr.args[1]))
|
359 |
+
|
360 |
+
def _print_betainc(self, expr):
|
361 |
+
betainc = self._module_format('scipy.special.betainc')
|
362 |
+
beta = self._module_format('scipy.special.beta')
|
363 |
+
args = [self._print(arg) for arg in expr.args]
|
364 |
+
return f"({betainc}({args[0]}, {args[1]}, {args[3]}) - {betainc}({args[0]}, {args[1]}, {args[2]})) \
|
365 |
+
* {beta}({args[0]}, {args[1]})"
|
366 |
+
|
367 |
+
def _print_betainc_regularized(self, expr):
|
368 |
+
return "{0}({1}, {2}, {4}) - {0}({1}, {2}, {3})".format(
|
369 |
+
self._module_format('scipy.special.betainc'),
|
370 |
+
self._print(expr.args[0]),
|
371 |
+
self._print(expr.args[1]),
|
372 |
+
self._print(expr.args[2]),
|
373 |
+
self._print(expr.args[3]))
|
374 |
+
|
375 |
+
def _print_fresnels(self, expr):
|
376 |
+
return "{}({})[0]".format(
|
377 |
+
self._module_format("scipy.special.fresnel"),
|
378 |
+
self._print(expr.args[0]))
|
379 |
+
|
380 |
+
def _print_fresnelc(self, expr):
|
381 |
+
return "{}({})[1]".format(
|
382 |
+
self._module_format("scipy.special.fresnel"),
|
383 |
+
self._print(expr.args[0]))
|
384 |
+
|
385 |
+
def _print_airyai(self, expr):
|
386 |
+
return "{}({})[0]".format(
|
387 |
+
self._module_format("scipy.special.airy"),
|
388 |
+
self._print(expr.args[0]))
|
389 |
+
|
390 |
+
def _print_airyaiprime(self, expr):
|
391 |
+
return "{}({})[1]".format(
|
392 |
+
self._module_format("scipy.special.airy"),
|
393 |
+
self._print(expr.args[0]))
|
394 |
+
|
395 |
+
def _print_airybi(self, expr):
|
396 |
+
return "{}({})[2]".format(
|
397 |
+
self._module_format("scipy.special.airy"),
|
398 |
+
self._print(expr.args[0]))
|
399 |
+
|
400 |
+
def _print_airybiprime(self, expr):
|
401 |
+
return "{}({})[3]".format(
|
402 |
+
self._module_format("scipy.special.airy"),
|
403 |
+
self._print(expr.args[0]))
|
404 |
+
|
405 |
+
def _print_bernoulli(self, expr):
|
406 |
+
# scipy's bernoulli is inconsistent with SymPy's so rewrite
|
407 |
+
return self._print(expr._eval_rewrite_as_zeta(*expr.args))
|
408 |
+
|
409 |
+
def _print_harmonic(self, expr):
|
410 |
+
return self._print(expr._eval_rewrite_as_zeta(*expr.args))
|
411 |
+
|
412 |
+
def _print_Integral(self, e):
|
413 |
+
integration_vars, limits = _unpack_integral_limits(e)
|
414 |
+
|
415 |
+
if len(limits) == 1:
|
416 |
+
# nicer (but not necessary) to prefer quad over nquad for 1D case
|
417 |
+
module_str = self._module_format("scipy.integrate.quad")
|
418 |
+
limit_str = "%s, %s" % tuple(map(self._print, limits[0]))
|
419 |
+
else:
|
420 |
+
module_str = self._module_format("scipy.integrate.nquad")
|
421 |
+
limit_str = "({})".format(", ".join(
|
422 |
+
"(%s, %s)" % tuple(map(self._print, l)) for l in limits))
|
423 |
+
|
424 |
+
return "{}(lambda {}: {}, {})[0]".format(
|
425 |
+
module_str,
|
426 |
+
", ".join(map(self._print, integration_vars)),
|
427 |
+
self._print(e.args[0]),
|
428 |
+
limit_str)
|
429 |
+
|
430 |
+
def _print_Si(self, expr):
|
431 |
+
return "{}({})[0]".format(
|
432 |
+
self._module_format("scipy.special.sici"),
|
433 |
+
self._print(expr.args[0]))
|
434 |
+
|
435 |
+
def _print_Ci(self, expr):
|
436 |
+
return "{}({})[1]".format(
|
437 |
+
self._module_format("scipy.special.sici"),
|
438 |
+
self._print(expr.args[0]))
|
439 |
+
|
440 |
+
for func in _scipy_known_functions:
|
441 |
+
setattr(SciPyPrinter, f'_print_{func}', _print_known_func)
|
442 |
+
|
443 |
+
for const in _scipy_known_constants:
|
444 |
+
setattr(SciPyPrinter, f'_print_{const}', _print_known_const)
|
445 |
+
|
446 |
+
|
447 |
+
_cupy_known_functions = {k : "cupy." + v for k, v in _known_functions_numpy.items()}
|
448 |
+
_cupy_known_constants = {k : "cupy." + v for k, v in _known_constants_numpy.items()}
|
449 |
+
|
450 |
+
class CuPyPrinter(NumPyPrinter):
|
451 |
+
"""
|
452 |
+
CuPy printer which handles vectorized piecewise functions,
|
453 |
+
logical operators, etc.
|
454 |
+
"""
|
455 |
+
|
456 |
+
_module = 'cupy'
|
457 |
+
_kf = _cupy_known_functions
|
458 |
+
_kc = _cupy_known_constants
|
459 |
+
|
460 |
+
def __init__(self, settings=None):
|
461 |
+
super().__init__(settings=settings)
|
462 |
+
|
463 |
+
for func in _cupy_known_functions:
|
464 |
+
setattr(CuPyPrinter, f'_print_{func}', _print_known_func)
|
465 |
+
|
466 |
+
for const in _cupy_known_constants:
|
467 |
+
setattr(CuPyPrinter, f'_print_{const}', _print_known_const)
|
468 |
+
|
469 |
+
|
470 |
+
_jax_known_functions = {k: 'jax.numpy.' + v for k, v in _known_functions_numpy.items()}
|
471 |
+
_jax_known_constants = {k: 'jax.numpy.' + v for k, v in _known_constants_numpy.items()}
|
472 |
+
|
473 |
+
class JaxPrinter(NumPyPrinter):
|
474 |
+
"""
|
475 |
+
JAX printer which handles vectorized piecewise functions,
|
476 |
+
logical operators, etc.
|
477 |
+
"""
|
478 |
+
_module = "jax.numpy"
|
479 |
+
|
480 |
+
_kf = _jax_known_functions
|
481 |
+
_kc = _jax_known_constants
|
482 |
+
|
483 |
+
def __init__(self, settings=None):
|
484 |
+
super().__init__(settings=settings)
|
485 |
+
|
486 |
+
# These need specific override to allow for the lack of "jax.numpy.reduce"
|
487 |
+
def _print_And(self, expr):
|
488 |
+
"Logical And printer"
|
489 |
+
return "{}({}.asarray([{}]), axis=0)".format(
|
490 |
+
self._module_format(self._module + ".all"),
|
491 |
+
self._module_format(self._module),
|
492 |
+
",".join(self._print(i) for i in expr.args),
|
493 |
+
)
|
494 |
+
|
495 |
+
def _print_Or(self, expr):
|
496 |
+
"Logical Or printer"
|
497 |
+
return "{}({}.asarray([{}]), axis=0)".format(
|
498 |
+
self._module_format(self._module + ".any"),
|
499 |
+
self._module_format(self._module),
|
500 |
+
",".join(self._print(i) for i in expr.args),
|
501 |
+
)
|
502 |
+
|
503 |
+
for func in _jax_known_functions:
|
504 |
+
setattr(JaxPrinter, f'_print_{func}', _print_known_func)
|
505 |
+
|
506 |
+
for const in _jax_known_constants:
|
507 |
+
setattr(JaxPrinter, f'_print_{const}', _print_known_const)
|
venv/lib/python3.10/site-packages/sympy/printing/pretty/__init__.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""ASCII-ART 2D pretty-printer"""
|
2 |
+
|
3 |
+
from .pretty import (pretty, pretty_print, pprint, pprint_use_unicode,
|
4 |
+
pprint_try_use_unicode, pager_print)
|
5 |
+
|
6 |
+
# if unicode output is available -- let's use it
|
7 |
+
pprint_try_use_unicode()
|
8 |
+
|
9 |
+
__all__ = [
|
10 |
+
'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
|
11 |
+
'pprint_try_use_unicode', 'pager_print',
|
12 |
+
]
|