diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec47a2d60a81c7f290f002cfc52bb86f615381c8 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/algorithms.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/algorithms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07a61ab09732c5c571ada4f621a4c55298698448 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/algorithms.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..314dd943be7ca1f58902dc2a4f1ee58cd26517e7 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/ast.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/ast.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bc7ada3589f75ada31fcf02ec5186b0b0e5c9d3 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/ast.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c0746a69e82a4be727b964da99c05d70177ec4c Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/matrix_nodes.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/matrix_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59e91b584b79e4eaf54c9f6647967347438df10e Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/matrix_nodes.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55f17db12fe167c361730006deebd56a0458034c Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/pyutils.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/pyutils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81bf053768c779978f0ebfb13bc1aa9e6c4d11b5 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/pyutils.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/rewriting.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/rewriting.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80b5a408734b821c2d04f1d6cc51603bd5e9e991 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/rewriting.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/scipy_nodes.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/scipy_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8589620278b0ce7da02dd0927ec7a2451bc7210d Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/scipy_nodes.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb93582976dd3bf59d0010b5cb175db5b15ba124 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/cartan_matrix.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/cartan_matrix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13c212db16f1e85c8b0d8ebc8b736bf41202c4ae Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/cartan_matrix.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/cartan_type.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/cartan_type.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ee8e6f3e7192071362eb1a86a0089462f2aabcd Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/cartan_type.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/dynkin_diagram.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/dynkin_diagram.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60d2e17201b38ba202b214327347a1568e2c40ac Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/dynkin_diagram.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/root_system.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/root_system.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93be13182165578e56471a88e850984a97f27fb6 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/root_system.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_a.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_a.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82cd40d8586c47f1fb115d2a151894d97463408f Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_a.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_b.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_b.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27d0b4428ee20e301137b28f77560891988880da Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_b.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_c.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_c.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..147dfcc793a518277235f70b86a18fc914826bb7 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_c.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_d.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_d.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5127803b7a5cfd5d07ed4f9176bcef664f3cd668 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_d.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_e.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_e.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ea983e48629ae4ff68a0f4d3aad60bc91788b68 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_e.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_f.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_f.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b4fbe250155a6af3faa5efcbcedc5ce572d1169 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_f.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_g.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_g.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3915ee00451026daf0604ad37dfbe1bc13f9db4b Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_g.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/weyl_group.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/weyl_group.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..133c619c1c29b4226def04727512287895522f1e Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/weyl_group.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ad2868532c185199d0bd2e63d77f3410a15e6d4 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_cartan_matrix.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_cartan_matrix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d0b4c4a1d187e242e36e39f3523513a645c6bb4 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_cartan_matrix.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_dynkin_diagram.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_dynkin_diagram.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee82559983617a84904585a488b47745aad8220b Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_dynkin_diagram.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_root_system.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_root_system.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68bfde20436899b622433668fe9cf9d6d627b762 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_root_system.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_type_A.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_type_A.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b11ea452017259136e67a42863d9220f99f1d35 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_type_A.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_type_C.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_type_C.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcfd5d1a5ad80ee134d5e300cdfc8e1e754ec9f7 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_type_C.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_and.png b/llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_and.png new file mode 100644 index 0000000000000000000000000000000000000000..07cac5b54f8a39774c151fc70a00552ba83fe5fc --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_and.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:115d0b9b81ed40f93fe9e216b4f6384cf71093e3bbb64a5d648b8b9858c645a0 +size 6864 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_or.png b/llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_or.png new file mode 100644 index 0000000000000000000000000000000000000000..7f9cc7cf23bec219b8d6101c4cbae235a2c678d1 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_or.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e41ba0d3dbf2a20f82bb79a4cbba5bb458dec396ccbdba5ed195d6b200ca7f2e +size 8809 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_xor.png b/llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_xor.png new file mode 100644 index 0000000000000000000000000000000000000000..cafdc56f650a8c4d7af38fdfd8206891aa9d6cc2 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_xor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92e71558103d03df0ea5c47876277968b5d4ca8ab8cf43b80b73cce9d962052c +size 10002 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..134785794d63e7fb28440d6aa71c06294e9916a8 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/__init__.py @@ -0,0 +1,116 @@ +"""Printing subsystem""" + +from .pretty import pager_print, pretty, pretty_print, pprint, pprint_use_unicode, pprint_try_use_unicode + +from .latex import latex, print_latex, multiline_latex + +from .mathml import mathml, print_mathml + +from .python import python, print_python + +from .pycode import pycode + +from .codeprinter import print_ccode, print_fcode + +from .codeprinter import ccode, fcode, cxxcode # noqa:F811 + +from .smtlib import smtlib_code + +from .glsl import glsl_code, print_glsl + +from .rcode import rcode, print_rcode + +from .jscode import jscode, print_jscode + +from .julia import julia_code + +from .mathematica import mathematica_code + +from .octave import octave_code + +from .rust import rust_code + +from .gtk import print_gtk + +from .preview import preview + +from .repr import srepr + +from .tree import print_tree + +from .str import StrPrinter, sstr, sstrrepr + +from .tableform import TableForm + +from .dot import dotprint + +from .maple import maple_code, print_maple_code + +__all__ = [ + # sympy.printing.pretty + 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode', + 'pprint_try_use_unicode', + + # sympy.printing.latex + 'latex', 'print_latex', 'multiline_latex', + + # sympy.printing.mathml + 'mathml', 'print_mathml', + + # sympy.printing.python + 'python', 'print_python', + + # sympy.printing.pycode + 'pycode', + + # sympy.printing.codeprinter + 'ccode', 'print_ccode', 'cxxcode', 'fcode', 'print_fcode', + + # sympy.printing.smtlib + 'smtlib_code', + + # sympy.printing.glsl + 'glsl_code', 'print_glsl', + + # sympy.printing.rcode + 'rcode', 'print_rcode', + + # sympy.printing.jscode + 'jscode', 'print_jscode', + + # sympy.printing.julia + 'julia_code', + + # sympy.printing.mathematica + 'mathematica_code', + + # sympy.printing.octave + 'octave_code', + + # sympy.printing.rust + 'rust_code', + + # sympy.printing.gtk + 'print_gtk', + + # sympy.printing.preview + 'preview', + + # sympy.printing.repr + 'srepr', + + # sympy.printing.tree + 'print_tree', + + # sympy.printing.str + 'StrPrinter', 'sstr', 'sstrrepr', + + # sympy.printing.tableform + 'TableForm', + + # sympy.printing.dot + 'dotprint', + + # sympy.printing.maple + 'maple_code', 'print_maple_code', +] diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/aesaracode.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/aesaracode.py new file mode 100644 index 0000000000000000000000000000000000000000..87117e06fadbad7dfa1fc3afba30e7e254133097 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/aesaracode.py @@ -0,0 +1,539 @@ +from __future__ import annotations +from typing import Any + +from sympy.external import import_module +from sympy.printing.printer import Printer +from sympy.utilities.iterables import is_sequence +import sympy +from functools import partial + + +aesara = import_module('aesara') + +if aesara: + aes = aesara.scalar + aet = aesara.tensor + from aesara.tensor import nlinalg + from aesara.tensor.elemwise import Elemwise + from aesara.tensor.elemwise import DimShuffle + + # `true_divide` replaced `true_div` in Aesara 2.8.11 (released 2023) to + # match NumPy + # XXX: Remove this when not needed to support older versions. + true_divide = getattr(aet, 'true_divide', None) + if true_divide is None: + true_divide = aet.true_div + + mapping = { + sympy.Add: aet.add, + sympy.Mul: aet.mul, + sympy.Abs: aet.abs, + sympy.sign: aet.sgn, + sympy.ceiling: aet.ceil, + sympy.floor: aet.floor, + sympy.log: aet.log, + sympy.exp: aet.exp, + sympy.sqrt: aet.sqrt, + sympy.cos: aet.cos, + sympy.acos: aet.arccos, + sympy.sin: aet.sin, + sympy.asin: aet.arcsin, + sympy.tan: aet.tan, + sympy.atan: aet.arctan, + sympy.atan2: aet.arctan2, + sympy.cosh: aet.cosh, + sympy.acosh: aet.arccosh, + sympy.sinh: aet.sinh, + sympy.asinh: aet.arcsinh, + sympy.tanh: aet.tanh, + sympy.atanh: aet.arctanh, + sympy.re: aet.real, + sympy.im: aet.imag, + sympy.arg: aet.angle, + sympy.erf: aet.erf, + sympy.gamma: aet.gamma, + sympy.loggamma: aet.gammaln, + sympy.Pow: aet.pow, + sympy.Eq: aet.eq, + sympy.StrictGreaterThan: aet.gt, + sympy.StrictLessThan: aet.lt, + sympy.LessThan: aet.le, + sympy.GreaterThan: aet.ge, + sympy.And: aet.bitwise_and, # bitwise + sympy.Or: aet.bitwise_or, # bitwise + sympy.Not: aet.invert, # bitwise + sympy.Xor: aet.bitwise_xor, # bitwise + sympy.Max: aet.maximum, # Sympy accept >2 inputs, Aesara only 2 + sympy.Min: aet.minimum, # Sympy accept >2 inputs, Aesara only 2 + sympy.conjugate: aet.conj, + sympy.core.numbers.ImaginaryUnit: lambda:aet.complex(0,1), + # Matrices + sympy.MatAdd: Elemwise(aes.add), + sympy.HadamardProduct: Elemwise(aes.mul), + sympy.Trace: nlinalg.trace, + sympy.Determinant : nlinalg.det, + sympy.Inverse: nlinalg.matrix_inverse, + sympy.Transpose: DimShuffle((False, False), [1, 0]), + } + + +class AesaraPrinter(Printer): + """ Code printer which creates Aesara symbolic expression graphs. + + Parameters + ========== + + cache : dict + Cache dictionary to use. If None (default) will use + the global cache. To create a printer which does not depend on or alter + global state pass an empty dictionary. Note: the dictionary is not + copied on initialization of the printer and will be updated in-place, + so using the same dict object when creating multiple printers or making + multiple calls to :func:`.aesara_code` or :func:`.aesara_function` means + the cache is shared between all these applications. + + Attributes + ========== + + cache : dict + A cache of Aesara variables which have been created for SymPy + symbol-like objects (e.g. :class:`sympy.core.symbol.Symbol` or + :class:`sympy.matrices.expressions.MatrixSymbol`). This is used to + ensure that all references to a given symbol in an expression (or + multiple expressions) are printed as the same Aesara variable, which is + created only once. Symbols are differentiated only by name and type. The + format of the cache's contents should be considered opaque to the user. + """ + printmethod = "_aesara" + + def __init__(self, *args, **kwargs): + self.cache = kwargs.pop('cache', {}) + super().__init__(*args, **kwargs) + + def _get_key(self, s, name=None, dtype=None, broadcastable=None): + """ Get the cache key for a SymPy object. + + Parameters + ========== + + s : sympy.core.basic.Basic + SymPy object to get key for. + + name : str + Name of object, if it does not have a ``name`` attribute. + """ + + if name is None: + name = s.name + + return (name, type(s), s.args, dtype, broadcastable) + + def _get_or_create(self, s, name=None, dtype=None, broadcastable=None): + """ + Get the Aesara variable for a SymPy symbol from the cache, or create it + if it does not exist. + """ + + # Defaults + if name is None: + name = s.name + if dtype is None: + dtype = 'floatX' + if broadcastable is None: + broadcastable = () + + key = self._get_key(s, name, dtype=dtype, broadcastable=broadcastable) + + if key in self.cache: + return self.cache[key] + + value = aet.tensor(name=name, dtype=dtype, broadcastable=broadcastable) + self.cache[key] = value + return value + + def _print_Symbol(self, s, **kwargs): + dtype = kwargs.get('dtypes', {}).get(s) + bc = kwargs.get('broadcastables', {}).get(s) + return self._get_or_create(s, dtype=dtype, broadcastable=bc) + + def _print_AppliedUndef(self, s, **kwargs): + name = str(type(s)) + '_' + str(s.args[0]) + dtype = kwargs.get('dtypes', {}).get(s) + bc = kwargs.get('broadcastables', {}).get(s) + return self._get_or_create(s, name=name, dtype=dtype, broadcastable=bc) + + def _print_Basic(self, expr, **kwargs): + op = mapping[type(expr)] + children = [self._print(arg, **kwargs) for arg in expr.args] + return op(*children) + + def _print_Number(self, n, **kwargs): + # Integers already taken care of below, interpret as float + return float(n.evalf()) + + def _print_MatrixSymbol(self, X, **kwargs): + dtype = kwargs.get('dtypes', {}).get(X) + return self._get_or_create(X, dtype=dtype, broadcastable=(None, None)) + + def _print_DenseMatrix(self, X, **kwargs): + if not hasattr(aet, 'stacklists'): + raise NotImplementedError( + "Matrix translation not yet supported in this version of Aesara") + + return aet.stacklists([ + [self._print(arg, **kwargs) for arg in L] + for L in X.tolist() + ]) + + _print_ImmutableMatrix = _print_ImmutableDenseMatrix = _print_DenseMatrix + + def _print_MatMul(self, expr, **kwargs): + children = [self._print(arg, **kwargs) for arg in expr.args] + result = children[0] + for child in children[1:]: + result = aet.dot(result, child) + return result + + def _print_MatPow(self, expr, **kwargs): + children = [self._print(arg, **kwargs) for arg in expr.args] + result = 1 + if isinstance(children[1], int) and children[1] > 0: + for i in range(children[1]): + result = aet.dot(result, children[0]) + else: + raise NotImplementedError('''Only non-negative integer + powers of matrices can be handled by Aesara at the moment''') + return result + + def _print_MatrixSlice(self, expr, **kwargs): + parent = self._print(expr.parent, **kwargs) + rowslice = self._print(slice(*expr.rowslice), **kwargs) + colslice = self._print(slice(*expr.colslice), **kwargs) + return parent[rowslice, colslice] + + def _print_BlockMatrix(self, expr, **kwargs): + nrows, ncols = expr.blocks.shape + blocks = [[self._print(expr.blocks[r, c], **kwargs) + for c in range(ncols)] + for r in range(nrows)] + return aet.join(0, *[aet.join(1, *row) for row in blocks]) + + + def _print_slice(self, expr, **kwargs): + return slice(*[self._print(i, **kwargs) + if isinstance(i, sympy.Basic) else i + for i in (expr.start, expr.stop, expr.step)]) + + def _print_Pi(self, expr, **kwargs): + return 3.141592653589793 + + def _print_Piecewise(self, expr, **kwargs): + import numpy as np + e, cond = expr.args[0].args # First condition and corresponding value + + # Print conditional expression and value for first condition + p_cond = self._print(cond, **kwargs) + p_e = self._print(e, **kwargs) + + # One condition only + if len(expr.args) == 1: + # Return value if condition else NaN + return aet.switch(p_cond, p_e, np.nan) + + # Return value_1 if condition_1 else evaluate remaining conditions + p_remaining = self._print(sympy.Piecewise(*expr.args[1:]), **kwargs) + return aet.switch(p_cond, p_e, p_remaining) + + def _print_Rational(self, expr, **kwargs): + return true_divide(self._print(expr.p, **kwargs), + self._print(expr.q, **kwargs)) + + def _print_Integer(self, expr, **kwargs): + return expr.p + + def _print_factorial(self, expr, **kwargs): + return self._print(sympy.gamma(expr.args[0] + 1), **kwargs) + + def _print_Derivative(self, deriv, **kwargs): + from aesara.gradient import Rop + + rv = self._print(deriv.expr, **kwargs) + for var in deriv.variables: + var = self._print(var, **kwargs) + rv = Rop(rv, var, aet.ones_like(var)) + return rv + + def emptyPrinter(self, expr): + return expr + + def doprint(self, expr, dtypes=None, broadcastables=None): + """ Convert a SymPy expression to a Aesara graph variable. + + The ``dtypes`` and ``broadcastables`` arguments are used to specify the + data type, dimension, and broadcasting behavior of the Aesara variables + corresponding to the free symbols in ``expr``. Each is a mapping from + SymPy symbols to the value of the corresponding argument to + ``aesara.tensor.var.TensorVariable``. + + See the corresponding `documentation page`__ for more information on + broadcasting in Aesara. + + .. __: https://aesara.readthedocs.io/en/latest/tutorial/broadcasting.html + + Parameters + ========== + + expr : sympy.core.expr.Expr + SymPy expression to print. + + dtypes : dict + Mapping from SymPy symbols to Aesara datatypes to use when creating + new Aesara variables for those symbols. Corresponds to the ``dtype`` + argument to ``aesara.tensor.var.TensorVariable``. Defaults to ``'floatX'`` + for symbols not included in the mapping. + + broadcastables : dict + Mapping from SymPy symbols to the value of the ``broadcastable`` + argument to ``aesara.tensor.var.TensorVariable`` to use when creating Aesara + variables for those symbols. Defaults to the empty tuple for symbols + not included in the mapping (resulting in a scalar). + + Returns + ======= + + aesara.graph.basic.Variable + A variable corresponding to the expression's value in a Aesara + symbolic expression graph. + + """ + if dtypes is None: + dtypes = {} + if broadcastables is None: + broadcastables = {} + + return self._print(expr, dtypes=dtypes, broadcastables=broadcastables) + + +global_cache: dict[Any, Any] = {} + + +def aesara_code(expr, cache=None, **kwargs): + """ + Convert a SymPy expression into a Aesara graph variable. + + Parameters + ========== + + expr : sympy.core.expr.Expr + SymPy expression object to convert. + + cache : dict + Cached Aesara variables (see :class:`AesaraPrinter.cache + `). Defaults to the module-level global cache. + + dtypes : dict + Passed to :meth:`.AesaraPrinter.doprint`. + + broadcastables : dict + Passed to :meth:`.AesaraPrinter.doprint`. + + Returns + ======= + + aesara.graph.basic.Variable + A variable corresponding to the expression's value in a Aesara symbolic + expression graph. + + """ + if not aesara: + raise ImportError("aesara is required for aesara_code") + + if cache is None: + cache = global_cache + + return AesaraPrinter(cache=cache, settings={}).doprint(expr, **kwargs) + + +def dim_handling(inputs, dim=None, dims=None, broadcastables=None): + r""" + Get value of ``broadcastables`` argument to :func:`.aesara_code` from + keyword arguments to :func:`.aesara_function`. + + Included for backwards compatibility. + + Parameters + ========== + + inputs + Sequence of input symbols. + + dim : int + Common number of dimensions for all inputs. Overrides other arguments + if given. + + dims : dict + Mapping from input symbols to number of dimensions. Overrides + ``broadcastables`` argument if given. + + broadcastables : dict + Explicit value of ``broadcastables`` argument to + :meth:`.AesaraPrinter.doprint`. If not None function will return this value unchanged. + + Returns + ======= + dict + Dictionary mapping elements of ``inputs`` to their "broadcastable" + values (tuple of ``bool``\ s). + """ + if dim is not None: + return {s: (False,) * dim for s in inputs} + + if dims is not None: + maxdim = max(dims.values()) + return { + s: (False,) * d + (True,) * (maxdim - d) + for s, d in dims.items() + } + + if broadcastables is not None: + return broadcastables + + return {} + + +def aesara_function(inputs, outputs, scalar=False, *, + dim=None, dims=None, broadcastables=None, **kwargs): + """ + Create a Aesara function from SymPy expressions. + + The inputs and outputs are converted to Aesara variables using + :func:`.aesara_code` and then passed to ``aesara.function``. + + Parameters + ========== + + inputs + Sequence of symbols which constitute the inputs of the function. + + outputs + Sequence of expressions which constitute the outputs(s) of the + function. The free symbols of each expression must be a subset of + ``inputs``. + + scalar : bool + Convert 0-dimensional arrays in output to scalars. This will return a + Python wrapper function around the Aesara function object. + + cache : dict + Cached Aesara variables (see :class:`AesaraPrinter.cache + `). Defaults to the module-level global cache. + + dtypes : dict + Passed to :meth:`.AesaraPrinter.doprint`. + + broadcastables : dict + Passed to :meth:`.AesaraPrinter.doprint`. + + dims : dict + Alternative to ``broadcastables`` argument. Mapping from elements of + ``inputs`` to integers indicating the dimension of their associated + arrays/tensors. Overrides ``broadcastables`` argument if given. + + dim : int + Another alternative to the ``broadcastables`` argument. Common number of + dimensions to use for all arrays/tensors. + ``aesara_function([x, y], [...], dim=2)`` is equivalent to using + ``broadcastables={x: (False, False), y: (False, False)}``. + + Returns + ======= + callable + A callable object which takes values of ``inputs`` as positional + arguments and returns an output array for each of the expressions + in ``outputs``. If ``outputs`` is a single expression the function will + return a Numpy array, if it is a list of multiple expressions the + function will return a list of arrays. See description of the ``squeeze`` + argument above for the behavior when a single output is passed in a list. + The returned object will either be an instance of + ``aesara.compile.function.types.Function`` or a Python wrapper + function around one. In both cases, the returned value will have a + ``aesara_function`` attribute which points to the return value of + ``aesara.function``. + + Examples + ======== + + >>> from sympy.abc import x, y, z + >>> from sympy.printing.aesaracode import aesara_function + + A simple function with one input and one output: + + >>> f1 = aesara_function([x], [x**2 - 1], scalar=True) + >>> f1(3) + 8.0 + + A function with multiple inputs and one output: + + >>> f2 = aesara_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True) + >>> f2(3, 4, 2) + 5.0 + + A function with multiple inputs and multiple outputs: + + >>> f3 = aesara_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True) + >>> f3(2, 3) + [13.0, -5.0] + + See also + ======== + + dim_handling + + """ + if not aesara: + raise ImportError("Aesara is required for aesara_function") + + # Pop off non-aesara keyword args + cache = kwargs.pop('cache', {}) + dtypes = kwargs.pop('dtypes', {}) + + broadcastables = dim_handling( + inputs, dim=dim, dims=dims, broadcastables=broadcastables, + ) + + # Print inputs/outputs + code = partial(aesara_code, cache=cache, dtypes=dtypes, + broadcastables=broadcastables) + tinputs = list(map(code, inputs)) + toutputs = list(map(code, outputs)) + + #fix constant expressions as variables + toutputs = [output if isinstance(output, aesara.graph.basic.Variable) else aet.as_tensor_variable(output) for output in toutputs] + + if len(toutputs) == 1: + toutputs = toutputs[0] + + # Compile aesara func + func = aesara.function(tinputs, toutputs, **kwargs) + + is_0d = [len(o.variable.broadcastable) == 0 for o in func.outputs] + + # No wrapper required + if not scalar or not any(is_0d): + func.aesara_function = func + return func + + # Create wrapper to convert 0-dimensional outputs to scalars + def wrapper(*args): + out = func(*args) + # out can be array(1.0) or [array(1.0), array(2.0)] + + if is_sequence(out): + return [o[()] if is_0d[i] else o for i, o in enumerate(out)] + else: + return out[()] + + wrapper.__wrapped__ = func + wrapper.__doc__ = func.__doc__ + wrapper.aesara_function = func + return wrapper diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/c.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/c.py new file mode 100644 index 0000000000000000000000000000000000000000..0921dbf5556bd8ef49a1b0468e2a765ed20b486c --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/c.py @@ -0,0 +1,747 @@ +""" +C code printer + +The C89CodePrinter & C99CodePrinter converts single SymPy expressions into +single C expressions, using the functions defined in math.h where possible. + +A complete code generator, which uses ccode extensively, can be found in +sympy.utilities.codegen. The codegen module can be used to generate complete +source code files that are compilable without further modifications. + + +""" + +from __future__ import annotations +from typing import Any + +from functools import wraps +from itertools import chain + +from sympy.core import S +from sympy.core.numbers import equal_valued +from sympy.codegen.ast import ( + Assignment, Pointer, Variable, Declaration, Type, + real, complex_, integer, bool_, float32, float64, float80, + complex64, complex128, intc, value_const, pointer_const, + int8, int16, int32, int64, uint8, uint16, uint32, uint64, untyped, + none +) +from sympy.printing.codeprinter import CodePrinter, requires +from sympy.printing.precedence import precedence, PRECEDENCE +from sympy.sets.fancysets import Range + +# These are defined in the other file so we can avoid importing sympy.codegen +# from the top-level 'import sympy'. Export them here as well. +from sympy.printing.codeprinter import ccode, print_ccode # noqa:F401 + +# dictionary mapping SymPy function to (argument_conditions, C_function). +# Used in C89CodePrinter._print_Function(self) +known_functions_C89 = { + "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")], + "sin": "sin", + "cos": "cos", + "tan": "tan", + "asin": "asin", + "acos": "acos", + "atan": "atan", + "atan2": "atan2", + "exp": "exp", + "log": "log", + "sinh": "sinh", + "cosh": "cosh", + "tanh": "tanh", + "floor": "floor", + "ceiling": "ceil", + "sqrt": "sqrt", # To enable automatic rewrites +} + +known_functions_C99 = dict(known_functions_C89, **{ + 'exp2': 'exp2', + 'expm1': 'expm1', + 'log10': 'log10', + 'log2': 'log2', + 'log1p': 'log1p', + 'Cbrt': 'cbrt', + 'hypot': 'hypot', + 'fma': 'fma', + 'loggamma': 'lgamma', + 'erfc': 'erfc', + 'Max': 'fmax', + 'Min': 'fmin', + "asinh": "asinh", + "acosh": "acosh", + "atanh": "atanh", + "erf": "erf", + "gamma": "tgamma", +}) + +# These are the core reserved words in the C language. Taken from: +# https://en.cppreference.com/w/c/keyword + +reserved_words = [ + 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do', + 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int', + 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static', + 'struct', 'entry', # never standardized, we'll leave it here anyway + 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while' +] + +reserved_words_c99 = ['inline', 'restrict'] + +def get_math_macros(): + """ Returns a dictionary with math-related macros from math.h/cmath + + Note that these macros are not strictly required by the C/C++-standard. + For MSVC they are enabled by defining "_USE_MATH_DEFINES" (preferably + via a compilation flag). + + Returns + ======= + + Dictionary mapping SymPy expressions to strings (macro names) + + """ + from sympy.codegen.cfunctions import log2, Sqrt + from sympy.functions.elementary.exponential import log + from sympy.functions.elementary.miscellaneous import sqrt + + return { + S.Exp1: 'M_E', + log2(S.Exp1): 'M_LOG2E', + 1/log(2): 'M_LOG2E', + log(2): 'M_LN2', + log(10): 'M_LN10', + S.Pi: 'M_PI', + S.Pi/2: 'M_PI_2', + S.Pi/4: 'M_PI_4', + 1/S.Pi: 'M_1_PI', + 2/S.Pi: 'M_2_PI', + 2/sqrt(S.Pi): 'M_2_SQRTPI', + 2/Sqrt(S.Pi): 'M_2_SQRTPI', + sqrt(2): 'M_SQRT2', + Sqrt(2): 'M_SQRT2', + 1/sqrt(2): 'M_SQRT1_2', + 1/Sqrt(2): 'M_SQRT1_2' + } + + +def _as_macro_if_defined(meth): + """ Decorator for printer methods + + When a Printer's method is decorated using this decorator the expressions printed + will first be looked for in the attribute ``math_macros``, and if present it will + print the macro name in ``math_macros`` followed by a type suffix for the type + ``real``. e.g. printing ``sympy.pi`` would print ``M_PIl`` if real is mapped to float80. + + """ + @wraps(meth) + def _meth_wrapper(self, expr, **kwargs): + if expr in self.math_macros: + return '%s%s' % (self.math_macros[expr], self._get_math_macro_suffix(real)) + else: + return meth(self, expr, **kwargs) + + return _meth_wrapper + + +class C89CodePrinter(CodePrinter): + """A printer to convert Python expressions to strings of C code""" + printmethod = "_ccode" + language = "C" + standard = "C89" + reserved_words = set(reserved_words) + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'precision': 17, + 'user_functions': {}, + 'human': True, + 'allow_unknown_functions': False, + 'contract': True, + 'dereference': set(), + 'error_on_reserved': False, + 'reserved_word_suffix': '_', + } + + type_aliases = { + real: float64, + complex_: complex128, + integer: intc + } + + type_mappings: dict[Type, Any] = { + real: 'double', + intc: 'int', + float32: 'float', + float64: 'double', + integer: 'int', + bool_: 'bool', + int8: 'int8_t', + int16: 'int16_t', + int32: 'int32_t', + int64: 'int64_t', + uint8: 'int8_t', + uint16: 'int16_t', + uint32: 'int32_t', + uint64: 'int64_t', + } + + type_headers = { + bool_: {'stdbool.h'}, + int8: {'stdint.h'}, + int16: {'stdint.h'}, + int32: {'stdint.h'}, + int64: {'stdint.h'}, + uint8: {'stdint.h'}, + uint16: {'stdint.h'}, + uint32: {'stdint.h'}, + uint64: {'stdint.h'}, + } + + # Macros needed to be defined when using a Type + type_macros: dict[Type, tuple[str, ...]] = {} + + type_func_suffixes = { + float32: 'f', + float64: '', + float80: 'l' + } + + type_literal_suffixes = { + float32: 'F', + float64: '', + float80: 'L' + } + + type_math_macro_suffixes = { + float80: 'l' + } + + math_macros = None + + _ns = '' # namespace, C++ uses 'std::' + # known_functions-dict to copy + _kf: dict[str, Any] = known_functions_C89 + + def __init__(self, settings=None): + settings = settings or {} + if self.math_macros is None: + self.math_macros = settings.pop('math_macros', get_math_macros()) + self.type_aliases = dict(chain(self.type_aliases.items(), + settings.pop('type_aliases', {}).items())) + self.type_mappings = dict(chain(self.type_mappings.items(), + settings.pop('type_mappings', {}).items())) + self.type_headers = dict(chain(self.type_headers.items(), + settings.pop('type_headers', {}).items())) + self.type_macros = dict(chain(self.type_macros.items(), + settings.pop('type_macros', {}).items())) + self.type_func_suffixes = dict(chain(self.type_func_suffixes.items(), + settings.pop('type_func_suffixes', {}).items())) + self.type_literal_suffixes = dict(chain(self.type_literal_suffixes.items(), + settings.pop('type_literal_suffixes', {}).items())) + self.type_math_macro_suffixes = dict(chain(self.type_math_macro_suffixes.items(), + settings.pop('type_math_macro_suffixes', {}).items())) + super().__init__(settings) + self.known_functions = dict(self._kf, **settings.get('user_functions', {})) + self._dereference = set(settings.get('dereference', [])) + self.headers = set() + self.libraries = set() + self.macros = set() + + def _rate_index_position(self, p): + return p*5 + + def _get_statement(self, codestring): + """ Get code string as a statement - i.e. ending with a semicolon. """ + return codestring if codestring.endswith(';') else codestring + ';' + + def _get_comment(self, text): + return "/* {} */".format(text) + + def _declare_number_const(self, name, value): + type_ = self.type_aliases[real] + var = Variable(name, type=type_, value=value.evalf(type_.decimal_dig), attrs={value_const}) + decl = Declaration(var) + return self._get_statement(self._print(decl)) + + def _format_code(self, lines): + return self.indent_code(lines) + + def _traverse_matrix_indices(self, mat): + rows, cols = mat.shape + return ((i, j) for i in range(rows) for j in range(cols)) + + @_as_macro_if_defined + def _print_Mul(self, expr, **kwargs): + return super()._print_Mul(expr, **kwargs) + + @_as_macro_if_defined + def _print_Pow(self, expr): + if "Pow" in self.known_functions: + return self._print_Function(expr) + PREC = precedence(expr) + suffix = self._get_func_suffix(real) + if equal_valued(expr.exp, -1): + literal_suffix = self._get_literal_suffix(real) + return '1.0%s/%s' % (literal_suffix, self.parenthesize(expr.base, PREC)) + elif equal_valued(expr.exp, 0.5): + return '%ssqrt%s(%s)' % (self._ns, suffix, self._print(expr.base)) + elif expr.exp == S.One/3 and self.standard != 'C89': + return '%scbrt%s(%s)' % (self._ns, suffix, self._print(expr.base)) + else: + return '%spow%s(%s, %s)' % (self._ns, suffix, self._print(expr.base), + self._print(expr.exp)) + + def _print_Mod(self, expr): + num, den = expr.args + if num.is_integer and den.is_integer: + PREC = precedence(expr) + snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args] + # % is remainder (same sign as numerator), not modulo (same sign as + # denominator), in C. Hence, % only works as modulo if both numbers + # have the same sign + if (num.is_nonnegative and den.is_nonnegative or + num.is_nonpositive and den.is_nonpositive): + return f"{snum} % {sden}" + return f"(({snum} % {sden}) + {sden}) % {sden}" + # Not guaranteed integer + return self._print_math_func(expr, known='fmod') + + def _print_Rational(self, expr): + p, q = int(expr.p), int(expr.q) + suffix = self._get_literal_suffix(real) + return '%d.0%s/%d.0%s' % (p, suffix, q, suffix) + + def _print_Indexed(self, expr): + # calculate index for 1d array + offset = getattr(expr.base, 'offset', S.Zero) + strides = getattr(expr.base, 'strides', None) + indices = expr.indices + + if strides is None or isinstance(strides, str): + dims = expr.shape + shift = S.One + temp = () + if strides == 'C' or strides is None: + traversal = reversed(range(expr.rank)) + indices = indices[::-1] + elif strides == 'F': + traversal = range(expr.rank) + + for i in traversal: + temp += (shift,) + shift *= dims[i] + strides = temp + flat_index = sum([x[0]*x[1] for x in zip(indices, strides)]) + offset + return "%s[%s]" % (self._print(expr.base.label), + self._print(flat_index)) + + def _print_Idx(self, expr): + return self._print(expr.label) + + @_as_macro_if_defined + def _print_NumberSymbol(self, expr): + return super()._print_NumberSymbol(expr) + + def _print_Infinity(self, expr): + return 'HUGE_VAL' + + def _print_NegativeInfinity(self, expr): + return '-HUGE_VAL' + + def _print_Piecewise(self, expr): + if expr.args[-1].cond != True: + # We need the last conditional to be a True, otherwise the resulting + # function may not return a result. + raise ValueError("All Piecewise expressions must contain an " + "(expr, True) statement to be used as a default " + "condition. Without one, the generated " + "expression may not evaluate to anything under " + "some condition.") + lines = [] + if expr.has(Assignment): + for i, (e, c) in enumerate(expr.args): + if i == 0: + lines.append("if (%s) {" % self._print(c)) + elif i == len(expr.args) - 1 and c == True: + lines.append("else {") + else: + lines.append("else if (%s) {" % self._print(c)) + code0 = self._print(e) + lines.append(code0) + lines.append("}") + return "\n".join(lines) + else: + # The piecewise was used in an expression, need to do inline + # operators. This has the downside that inline operators will + # not work for statements that span multiple lines (Matrix or + # Indexed expressions). + ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), + self._print(e)) + for e, c in expr.args[:-1]] + last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr) + return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)]) + + def _print_ITE(self, expr): + from sympy.functions import Piecewise + return self._print(expr.rewrite(Piecewise, deep=False)) + + def _print_MatrixElement(self, expr): + return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"], + strict=True), expr.j + expr.i*expr.parent.shape[1]) + + def _print_Symbol(self, expr): + name = super()._print_Symbol(expr) + if expr in self._settings['dereference']: + return '(*{})'.format(name) + else: + return name + + def _print_Relational(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + op = expr.rel_op + return "{} {} {}".format(lhs_code, op, rhs_code) + + def _print_For(self, expr): + target = self._print(expr.target) + if isinstance(expr.iterable, Range): + start, stop, step = expr.iterable.args + else: + raise NotImplementedError("Only iterable currently supported is Range") + body = self._print(expr.body) + return ('for ({target} = {start}; {target} < {stop}; {target} += ' + '{step}) {{\n{body}\n}}').format(target=target, start=start, + stop=stop, step=step, body=body) + + def _print_sign(self, func): + return '((({0}) > 0) - (({0}) < 0))'.format(self._print(func.args[0])) + + def _print_Max(self, expr): + if "Max" in self.known_functions: + return self._print_Function(expr) + def inner_print_max(args): # The more natural abstraction of creating + if len(args) == 1: # and printing smaller Max objects is slow + return self._print(args[0]) # when there are many arguments. + half = len(args) // 2 + return "((%(a)s > %(b)s) ? %(a)s : %(b)s)" % { + 'a': inner_print_max(args[:half]), + 'b': inner_print_max(args[half:]) + } + return inner_print_max(expr.args) + + def _print_Min(self, expr): + if "Min" in self.known_functions: + return self._print_Function(expr) + def inner_print_min(args): # The more natural abstraction of creating + if len(args) == 1: # and printing smaller Min objects is slow + return self._print(args[0]) # when there are many arguments. + half = len(args) // 2 + return "((%(a)s < %(b)s) ? %(a)s : %(b)s)" % { + 'a': inner_print_min(args[:half]), + 'b': inner_print_min(args[half:]) + } + return inner_print_min(expr.args) + + def indent_code(self, code): + """Accepts a string of code or a list of code lines""" + + if isinstance(code, str): + code_lines = self.indent_code(code.splitlines(True)) + return ''.join(code_lines) + + tab = " " + inc_token = ('{', '(', '{\n', '(\n') + dec_token = ('}', ')') + + code = [line.lstrip(' \t') for line in code] + + increase = [int(any(map(line.endswith, inc_token))) for line in code] + decrease = [int(any(map(line.startswith, dec_token))) for line in code] + + pretty = [] + level = 0 + for n, line in enumerate(code): + if line in ('', '\n'): + pretty.append(line) + continue + level -= decrease[n] + pretty.append("%s%s" % (tab*level, line)) + level += increase[n] + return pretty + + def _get_func_suffix(self, type_): + return self.type_func_suffixes[self.type_aliases.get(type_, type_)] + + def _get_literal_suffix(self, type_): + return self.type_literal_suffixes[self.type_aliases.get(type_, type_)] + + def _get_math_macro_suffix(self, type_): + alias = self.type_aliases.get(type_, type_) + dflt = self.type_math_macro_suffixes.get(alias, '') + return self.type_math_macro_suffixes.get(type_, dflt) + + def _print_Tuple(self, expr): + return '{'+', '.join(self._print(e) for e in expr)+'}' + + _print_List = _print_Tuple + + def _print_Type(self, type_): + self.headers.update(self.type_headers.get(type_, set())) + self.macros.update(self.type_macros.get(type_, set())) + return self._print(self.type_mappings.get(type_, type_.name)) + + def _print_Declaration(self, decl): + from sympy.codegen.cnodes import restrict + var = decl.variable + val = var.value + if var.type == untyped: + raise ValueError("C does not support untyped variables") + + if isinstance(var, Pointer): + result = '{vc}{t} *{pc} {r}{s}'.format( + vc='const ' if value_const in var.attrs else '', + t=self._print(var.type), + pc=' const' if pointer_const in var.attrs else '', + r='restrict ' if restrict in var.attrs else '', + s=self._print(var.symbol) + ) + elif isinstance(var, Variable): + result = '{vc}{t} {s}'.format( + vc='const ' if value_const in var.attrs else '', + t=self._print(var.type), + s=self._print(var.symbol) + ) + else: + raise NotImplementedError("Unknown type of var: %s" % type(var)) + if val != None: # Must be "!= None", cannot be "is not None" + result += ' = %s' % self._print(val) + return result + + def _print_Float(self, flt): + type_ = self.type_aliases.get(real, real) + self.macros.update(self.type_macros.get(type_, set())) + suffix = self._get_literal_suffix(type_) + num = str(flt.evalf(type_.decimal_dig)) + if 'e' not in num and '.' not in num: + num += '.0' + num_parts = num.split('e') + num_parts[0] = num_parts[0].rstrip('0') + if num_parts[0].endswith('.'): + num_parts[0] += '0' + return 'e'.join(num_parts) + suffix + + @requires(headers={'stdbool.h'}) + def _print_BooleanTrue(self, expr): + return 'true' + + @requires(headers={'stdbool.h'}) + def _print_BooleanFalse(self, expr): + return 'false' + + def _print_Element(self, elem): + if elem.strides == None: # Must be "== None", cannot be "is None" + if elem.offset != None: # Must be "!= None", cannot be "is not None" + raise ValueError("Expected strides when offset is given") + idxs = ']['.join((self._print(arg) for arg in elem.indices)) + else: + global_idx = sum([i*s for i, s in zip(elem.indices, elem.strides)]) + if elem.offset != None: # Must be "!= None", cannot be "is not None" + global_idx += elem.offset + idxs = self._print(global_idx) + + return "{symb}[{idxs}]".format( + symb=self._print(elem.symbol), + idxs=idxs + ) + + def _print_CodeBlock(self, expr): + """ Elements of code blocks printed as statements. """ + return '\n'.join([self._get_statement(self._print(i)) for i in expr.args]) + + def _print_While(self, expr): + return 'while ({condition}) {{\n{body}\n}}'.format(**expr.kwargs( + apply=lambda arg: self._print(arg))) + + def _print_Scope(self, expr): + return '{\n%s\n}' % self._print_CodeBlock(expr.body) + + @requires(headers={'stdio.h'}) + def _print_Print(self, expr): + return 'printf({fmt}, {pargs})'.format( + fmt=self._print(expr.format_string), + pargs=', '.join((self._print(arg) for arg in expr.print_args)) + ) + + def _print_FunctionPrototype(self, expr): + pars = ', '.join((self._print(Declaration(arg)) for arg in expr.parameters)) + return "%s %s(%s)" % ( + tuple((self._print(arg) for arg in (expr.return_type, expr.name))) + (pars,) + ) + + def _print_FunctionDefinition(self, expr): + return "%s%s" % (self._print_FunctionPrototype(expr), + self._print_Scope(expr)) + + def _print_Return(self, expr): + arg, = expr.args + return 'return %s' % self._print(arg) + + def _print_CommaOperator(self, expr): + return '(%s)' % ', '.join((self._print(arg) for arg in expr.args)) + + def _print_Label(self, expr): + if expr.body == none: + return '%s:' % str(expr.name) + if len(expr.body.args) == 1: + return '%s:\n%s' % (str(expr.name), self._print_CodeBlock(expr.body)) + return '%s:\n{\n%s\n}' % (str(expr.name), self._print_CodeBlock(expr.body)) + + def _print_goto(self, expr): + return 'goto %s' % expr.label.name + + def _print_PreIncrement(self, expr): + arg, = expr.args + return '++(%s)' % self._print(arg) + + def _print_PostIncrement(self, expr): + arg, = expr.args + return '(%s)++' % self._print(arg) + + def _print_PreDecrement(self, expr): + arg, = expr.args + return '--(%s)' % self._print(arg) + + def _print_PostDecrement(self, expr): + arg, = expr.args + return '(%s)--' % self._print(arg) + + def _print_struct(self, expr): + return "%(keyword)s %(name)s {\n%(lines)s}" % { + "keyword": expr.__class__.__name__, "name": expr.name, "lines": ';\n'.join( + [self._print(decl) for decl in expr.declarations] + ['']) + } + + def _print_BreakToken(self, _): + return 'break' + + def _print_ContinueToken(self, _): + return 'continue' + + _print_union = _print_struct + +class C99CodePrinter(C89CodePrinter): + standard = 'C99' + reserved_words = set(reserved_words + reserved_words_c99) + type_mappings=dict(chain(C89CodePrinter.type_mappings.items(), { + complex64: 'float complex', + complex128: 'double complex', + }.items())) + type_headers = dict(chain(C89CodePrinter.type_headers.items(), { + complex64: {'complex.h'}, + complex128: {'complex.h'} + }.items())) + + # known_functions-dict to copy + _kf: dict[str, Any] = known_functions_C99 + + # functions with versions with 'f' and 'l' suffixes: + _prec_funcs = ('fabs fmod remainder remquo fma fmax fmin fdim nan exp exp2' + ' expm1 log log10 log2 log1p pow sqrt cbrt hypot sin cos tan' + ' asin acos atan atan2 sinh cosh tanh asinh acosh atanh erf' + ' erfc tgamma lgamma ceil floor trunc round nearbyint rint' + ' frexp ldexp modf scalbn ilogb logb nextafter copysign').split() + + def _print_Infinity(self, expr): + return 'INFINITY' + + def _print_NegativeInfinity(self, expr): + return '-INFINITY' + + def _print_NaN(self, expr): + return 'NAN' + + # tgamma was already covered by 'known_functions' dict + + @requires(headers={'math.h'}, libraries={'m'}) + @_as_macro_if_defined + def _print_math_func(self, expr, nest=False, known=None): + if known is None: + known = self.known_functions[expr.__class__.__name__] + if not isinstance(known, str): + for cb, name in known: + if cb(*expr.args): + known = name + break + else: + raise ValueError("No matching printer") + try: + return known(self, *expr.args) + except TypeError: + suffix = self._get_func_suffix(real) if self._ns + known in self._prec_funcs else '' + + if nest: + args = self._print(expr.args[0]) + if len(expr.args) > 1: + paren_pile = '' + for curr_arg in expr.args[1:-1]: + paren_pile += ')' + args += ', {ns}{name}{suffix}({next}'.format( + ns=self._ns, + name=known, + suffix=suffix, + next = self._print(curr_arg) + ) + args += ', %s%s' % ( + self._print(expr.func(expr.args[-1])), + paren_pile + ) + else: + args = ', '.join((self._print(arg) for arg in expr.args)) + return '{ns}{name}{suffix}({args})'.format( + ns=self._ns, + name=known, + suffix=suffix, + args=args + ) + + def _print_Max(self, expr): + return self._print_math_func(expr, nest=True) + + def _print_Min(self, expr): + return self._print_math_func(expr, nest=True) + + def _get_loop_opening_ending(self, indices): + open_lines = [] + close_lines = [] + loopstart = "for (int %(var)s=%(start)s; %(var)s<%(end)s; %(var)s++){" # C99 + for i in indices: + # C arrays start at 0 and end at dimension-1 + open_lines.append(loopstart % { + 'var': self._print(i.label), + 'start': self._print(i.lower), + 'end': self._print(i.upper + 1)}) + close_lines.append("}") + return open_lines, close_lines + + +for k in ('Abs Sqrt exp exp2 expm1 log log10 log2 log1p Cbrt hypot fma' + ' loggamma sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh ' + 'atanh erf erfc loggamma gamma ceiling floor').split(): + setattr(C99CodePrinter, '_print_%s' % k, C99CodePrinter._print_math_func) + + +class C11CodePrinter(C99CodePrinter): + + @requires(headers={'stdalign.h'}) + def _print_alignof(self, expr): + arg, = expr.args + return 'alignof(%s)' % self._print(arg) + + +c_code_printers = { + 'c89': C89CodePrinter, + 'c99': C99CodePrinter, + 'c11': C11CodePrinter +} diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/codeprinter.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/codeprinter.py new file mode 100644 index 0000000000000000000000000000000000000000..951910a202f1da24f0a2df243a20793f262f1e53 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/codeprinter.py @@ -0,0 +1,875 @@ +from __future__ import annotations +from typing import Any + +from functools import wraps + +from sympy.core import Add, Mul, Pow, S, sympify, Float +from sympy.core.basic import Basic +from sympy.core.expr import UnevaluatedExpr +from sympy.core.function import Lambda +from sympy.core.mul import _keep_coeff +from sympy.core.sorting import default_sort_key +from sympy.core.symbol import Symbol +from sympy.functions.elementary.complexes import re +from sympy.printing.str import StrPrinter +from sympy.printing.precedence import precedence, PRECEDENCE + + +class requires: + """ Decorator for registering requirements on print methods. """ + def __init__(self, **kwargs): + self._req = kwargs + + def __call__(self, method): + def _method_wrapper(self_, *args, **kwargs): + for k, v in self._req.items(): + getattr(self_, k).update(v) + return method(self_, *args, **kwargs) + return wraps(method)(_method_wrapper) + + +class AssignmentError(Exception): + """ + Raised if an assignment variable for a loop is missing. + """ + pass + + +def _convert_python_lists(arg): + if isinstance(arg, list): + from sympy.codegen.abstract_nodes import List + return List(*(_convert_python_lists(e) for e in arg)) + elif isinstance(arg, tuple): + return tuple(_convert_python_lists(e) for e in arg) + else: + return arg + + +class CodePrinter(StrPrinter): + """ + The base class for code-printing subclasses. + """ + + _operators = { + 'and': '&&', + 'or': '||', + 'not': '!', + } + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'error_on_reserved': False, + 'reserved_word_suffix': '_', + 'human': True, + 'inline': False, + 'allow_unknown_functions': False, + } + + # Functions which are "simple" to rewrite to other functions that + # may be supported + # function_to_rewrite : (function_to_rewrite_to, iterable_with_other_functions_required) + _rewriteable_functions = { + 'cot': ('tan', []), + 'csc': ('sin', []), + 'sec': ('cos', []), + 'acot': ('atan', []), + 'acsc': ('asin', []), + 'asec': ('acos', []), + 'coth': ('exp', []), + 'csch': ('exp', []), + 'sech': ('exp', []), + 'acoth': ('log', []), + 'acsch': ('log', []), + 'asech': ('log', []), + 'catalan': ('gamma', []), + 'fibonacci': ('sqrt', []), + 'lucas': ('sqrt', []), + 'beta': ('gamma', []), + 'sinc': ('sin', ['Piecewise']), + 'Mod': ('floor', []), + 'factorial': ('gamma', []), + 'factorial2': ('gamma', ['Piecewise']), + 'subfactorial': ('uppergamma', []), + 'RisingFactorial': ('gamma', ['Piecewise']), + 'FallingFactorial': ('gamma', ['Piecewise']), + 'binomial': ('gamma', []), + 'frac': ('floor', []), + 'Max': ('Piecewise', []), + 'Min': ('Piecewise', []), + 'Heaviside': ('Piecewise', []), + 'erf2': ('erf', []), + 'erfc': ('erf', []), + 'Li': ('li', []), + 'Ei': ('li', []), + 'dirichlet_eta': ('zeta', []), + 'riemann_xi': ('zeta', ['gamma']), + } + + def __init__(self, settings=None): + + super().__init__(settings=settings) + if not hasattr(self, 'reserved_words'): + self.reserved_words = set() + + def _handle_UnevaluatedExpr(self, expr): + return expr.replace(re, lambda arg: arg if isinstance( + arg, UnevaluatedExpr) and arg.args[0].is_real else re(arg)) + + def doprint(self, expr, assign_to=None): + """ + Print the expression as code. + + Parameters + ---------- + expr : Expression + The expression to be printed. + + assign_to : Symbol, string, MatrixSymbol, list of strings or Symbols (optional) + If provided, the printed code will set the expression to a variable or multiple variables + with the name or names given in ``assign_to``. + """ + from sympy.matrices.expressions.matexpr import MatrixSymbol + from sympy.codegen.ast import CodeBlock, Assignment + + def _handle_assign_to(expr, assign_to): + if assign_to is None: + return sympify(expr) + if isinstance(assign_to, (list, tuple)): + if len(expr) != len(assign_to): + raise ValueError('Failed to assign an expression of length {} to {} variables'.format(len(expr), len(assign_to))) + return CodeBlock(*[_handle_assign_to(lhs, rhs) for lhs, rhs in zip(expr, assign_to)]) + if isinstance(assign_to, str): + if expr.is_Matrix: + assign_to = MatrixSymbol(assign_to, *expr.shape) + else: + assign_to = Symbol(assign_to) + elif not isinstance(assign_to, Basic): + raise TypeError("{} cannot assign to object of type {}".format( + type(self).__name__, type(assign_to))) + return Assignment(assign_to, expr) + + expr = _convert_python_lists(expr) + expr = _handle_assign_to(expr, assign_to) + + # Remove re(...) nodes due to UnevaluatedExpr.is_real always is None: + expr = self._handle_UnevaluatedExpr(expr) + + # keep a set of expressions that are not strictly translatable to Code + # and number constants that must be declared and initialized + self._not_supported = set() + self._number_symbols = set() + + lines = self._print(expr).splitlines() + + # format the output + if self._settings["human"]: + frontlines = [] + if self._not_supported: + frontlines.append(self._get_comment( + "Not supported in {}:".format(self.language))) + for expr in sorted(self._not_supported, key=str): + frontlines.append(self._get_comment(type(expr).__name__)) + for name, value in sorted(self._number_symbols, key=str): + frontlines.append(self._declare_number_const(name, value)) + lines = frontlines + lines + lines = self._format_code(lines) + result = "\n".join(lines) + else: + lines = self._format_code(lines) + num_syms = {(k, self._print(v)) for k, v in self._number_symbols} + result = (num_syms, self._not_supported, "\n".join(lines)) + self._not_supported = set() + self._number_symbols = set() + return result + + def _doprint_loops(self, expr, assign_to=None): + # Here we print an expression that contains Indexed objects, they + # correspond to arrays in the generated code. The low-level implementation + # involves looping over array elements and possibly storing results in temporary + # variables or accumulate it in the assign_to object. + + if self._settings.get('contract', True): + from sympy.tensor import get_contraction_structure + # Setup loops over non-dummy indices -- all terms need these + indices = self._get_expression_indices(expr, assign_to) + # Setup loops over dummy indices -- each term needs separate treatment + dummies = get_contraction_structure(expr) + else: + indices = [] + dummies = {None: (expr,)} + openloop, closeloop = self._get_loop_opening_ending(indices) + + # terms with no summations first + if None in dummies: + text = StrPrinter.doprint(self, Add(*dummies[None])) + else: + # If all terms have summations we must initialize array to Zero + text = StrPrinter.doprint(self, 0) + + # skip redundant assignments (where lhs == rhs) + lhs_printed = self._print(assign_to) + lines = [] + if text != lhs_printed: + lines.extend(openloop) + if assign_to is not None: + text = self._get_statement("%s = %s" % (lhs_printed, text)) + lines.append(text) + lines.extend(closeloop) + + # then terms with summations + for d in dummies: + if isinstance(d, tuple): + indices = self._sort_optimized(d, expr) + openloop_d, closeloop_d = self._get_loop_opening_ending( + indices) + + for term in dummies[d]: + if term in dummies and not ([list(f.keys()) for f in dummies[term]] + == [[None] for f in dummies[term]]): + # If one factor in the term has it's own internal + # contractions, those must be computed first. + # (temporary variables?) + raise NotImplementedError( + "FIXME: no support for contractions in factor yet") + else: + + # We need the lhs expression as an accumulator for + # the loops, i.e + # + # for (int d=0; d < dim; d++){ + # lhs[] = lhs[] + term[][d] + # } ^.................. the accumulator + # + # We check if the expression already contains the + # lhs, and raise an exception if it does, as that + # syntax is currently undefined. FIXME: What would be + # a good interpretation? + if assign_to is None: + raise AssignmentError( + "need assignment variable for loops") + if term.has(assign_to): + raise ValueError("FIXME: lhs present in rhs,\ + this is undefined in CodePrinter") + + lines.extend(openloop) + lines.extend(openloop_d) + text = "%s = %s" % (lhs_printed, StrPrinter.doprint( + self, assign_to + term)) + lines.append(self._get_statement(text)) + lines.extend(closeloop_d) + lines.extend(closeloop) + + return "\n".join(lines) + + def _get_expression_indices(self, expr, assign_to): + from sympy.tensor import get_indices + rinds, junk = get_indices(expr) + linds, junk = get_indices(assign_to) + + # support broadcast of scalar + if linds and not rinds: + rinds = linds + if rinds != linds: + raise ValueError("lhs indices must match non-dummy" + " rhs indices in %s" % expr) + + return self._sort_optimized(rinds, assign_to) + + def _sort_optimized(self, indices, expr): + + from sympy.tensor.indexed import Indexed + + if not indices: + return [] + + # determine optimized loop order by giving a score to each index + # the index with the highest score are put in the innermost loop. + score_table = {} + for i in indices: + score_table[i] = 0 + + arrays = expr.atoms(Indexed) + for arr in arrays: + for p, ind in enumerate(arr.indices): + try: + score_table[ind] += self._rate_index_position(p) + except KeyError: + pass + + return sorted(indices, key=lambda x: score_table[x]) + + def _rate_index_position(self, p): + """function to calculate score based on position among indices + + This method is used to sort loops in an optimized order, see + CodePrinter._sort_optimized() + """ + raise NotImplementedError("This function must be implemented by " + "subclass of CodePrinter.") + + def _get_statement(self, codestring): + """Formats a codestring with the proper line ending.""" + raise NotImplementedError("This function must be implemented by " + "subclass of CodePrinter.") + + def _get_comment(self, text): + """Formats a text string as a comment.""" + raise NotImplementedError("This function must be implemented by " + "subclass of CodePrinter.") + + def _declare_number_const(self, name, value): + """Declare a numeric constant at the top of a function""" + raise NotImplementedError("This function must be implemented by " + "subclass of CodePrinter.") + + def _format_code(self, lines): + """Take in a list of lines of code, and format them accordingly. + + This may include indenting, wrapping long lines, etc...""" + raise NotImplementedError("This function must be implemented by " + "subclass of CodePrinter.") + + def _get_loop_opening_ending(self, indices): + """Returns a tuple (open_lines, close_lines) containing lists + of codelines""" + raise NotImplementedError("This function must be implemented by " + "subclass of CodePrinter.") + + def _print_Dummy(self, expr): + if expr.name.startswith('Dummy_'): + return '_' + expr.name + else: + return '%s_%d' % (expr.name, expr.dummy_index) + + def _print_CodeBlock(self, expr): + return '\n'.join([self._print(i) for i in expr.args]) + + def _print_String(self, string): + return str(string) + + def _print_QuotedString(self, arg): + return '"%s"' % arg.text + + def _print_Comment(self, string): + return self._get_comment(str(string)) + + def _print_Assignment(self, expr): + from sympy.codegen.ast import Assignment + from sympy.functions.elementary.piecewise import Piecewise + from sympy.matrices.expressions.matexpr import MatrixSymbol + from sympy.tensor.indexed import IndexedBase + lhs = expr.lhs + rhs = expr.rhs + # We special case assignments that take multiple lines + if isinstance(expr.rhs, Piecewise): + # Here we modify Piecewise so each expression is now + # an Assignment, and then continue on the print. + expressions = [] + conditions = [] + for (e, c) in rhs.args: + expressions.append(Assignment(lhs, e)) + conditions.append(c) + temp = Piecewise(*zip(expressions, conditions)) + return self._print(temp) + elif isinstance(lhs, MatrixSymbol): + # Here we form an Assignment for each element in the array, + # printing each one. + lines = [] + for (i, j) in self._traverse_matrix_indices(lhs): + temp = Assignment(lhs[i, j], rhs[i, j]) + code0 = self._print(temp) + lines.append(code0) + return "\n".join(lines) + elif self._settings.get("contract", False) and (lhs.has(IndexedBase) or + rhs.has(IndexedBase)): + # Here we check if there is looping to be done, and if so + # print the required loops. + return self._doprint_loops(rhs, lhs) + else: + lhs_code = self._print(lhs) + rhs_code = self._print(rhs) + return self._get_statement("%s = %s" % (lhs_code, rhs_code)) + + def _print_AugmentedAssignment(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + return self._get_statement("{} {} {}".format( + *(self._print(arg) for arg in [lhs_code, expr.op, rhs_code]))) + + def _print_FunctionCall(self, expr): + return '%s(%s)' % ( + expr.name, + ', '.join((self._print(arg) for arg in expr.function_args))) + + def _print_Variable(self, expr): + return self._print(expr.symbol) + + def _print_Symbol(self, expr): + + name = super()._print_Symbol(expr) + + if name in self.reserved_words: + if self._settings['error_on_reserved']: + msg = ('This expression includes the symbol "{}" which is a ' + 'reserved keyword in this language.') + raise ValueError(msg.format(name)) + return name + self._settings['reserved_word_suffix'] + else: + return name + + def _can_print(self, name): + """ Check if function ``name`` is either a known function or has its own + printing method. Used to check if rewriting is possible.""" + return name in self.known_functions or getattr(self, '_print_{}'.format(name), False) + + def _print_Function(self, expr): + if expr.func.__name__ in self.known_functions: + cond_func = self.known_functions[expr.func.__name__] + if isinstance(cond_func, str): + return "%s(%s)" % (cond_func, self.stringify(expr.args, ", ")) + else: + for cond, func in cond_func: + if cond(*expr.args): + break + if func is not None: + try: + return func(*[self.parenthesize(item, 0) for item in expr.args]) + except TypeError: + return "%s(%s)" % (func, self.stringify(expr.args, ", ")) + elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda): + # inlined function + return self._print(expr._imp_(*expr.args)) + elif expr.func.__name__ in self._rewriteable_functions: + # Simple rewrite to supported function possible + target_f, required_fs = self._rewriteable_functions[expr.func.__name__] + if self._can_print(target_f) and all(self._can_print(f) for f in required_fs): + return self._print(expr.rewrite(target_f)) + if expr.is_Function and self._settings.get('allow_unknown_functions', False): + return '%s(%s)' % (self._print(expr.func), ', '.join(map(self._print, expr.args))) + else: + return self._print_not_supported(expr) + + _print_Expr = _print_Function + + # Don't inherit the str-printer method for Heaviside to the code printers + _print_Heaviside = None + + def _print_NumberSymbol(self, expr): + if self._settings.get("inline", False): + return self._print(Float(expr.evalf(self._settings["precision"]))) + else: + # A Number symbol that is not implemented here or with _printmethod + # is registered and evaluated + self._number_symbols.add((expr, + Float(expr.evalf(self._settings["precision"])))) + return str(expr) + + def _print_Catalan(self, expr): + return self._print_NumberSymbol(expr) + def _print_EulerGamma(self, expr): + return self._print_NumberSymbol(expr) + def _print_GoldenRatio(self, expr): + return self._print_NumberSymbol(expr) + def _print_TribonacciConstant(self, expr): + return self._print_NumberSymbol(expr) + def _print_Exp1(self, expr): + return self._print_NumberSymbol(expr) + def _print_Pi(self, expr): + return self._print_NumberSymbol(expr) + + def _print_And(self, expr): + PREC = precedence(expr) + return (" %s " % self._operators['and']).join(self.parenthesize(a, PREC) + for a in sorted(expr.args, key=default_sort_key)) + + def _print_Or(self, expr): + PREC = precedence(expr) + return (" %s " % self._operators['or']).join(self.parenthesize(a, PREC) + for a in sorted(expr.args, key=default_sort_key)) + + def _print_Xor(self, expr): + if self._operators.get('xor') is None: + return self._print(expr.to_nnf()) + PREC = precedence(expr) + return (" %s " % self._operators['xor']).join(self.parenthesize(a, PREC) + for a in expr.args) + + def _print_Equivalent(self, expr): + if self._operators.get('equivalent') is None: + return self._print(expr.to_nnf()) + PREC = precedence(expr) + return (" %s " % self._operators['equivalent']).join(self.parenthesize(a, PREC) + for a in expr.args) + + def _print_Not(self, expr): + PREC = precedence(expr) + return self._operators['not'] + self.parenthesize(expr.args[0], PREC) + + def _print_BooleanFunction(self, expr): + return self._print(expr.to_nnf()) + + def _print_Mul(self, expr): + + prec = precedence(expr) + + c, e = expr.as_coeff_Mul() + if c < 0: + expr = _keep_coeff(-c, e) + sign = "-" + else: + sign = "" + + a = [] # items in the numerator + b = [] # items that are in the denominator (if any) + + pow_paren = [] # Will collect all pow with more than one base element and exp = -1 + + if self.order not in ('old', 'none'): + args = expr.as_ordered_factors() + else: + # use make_args in case expr was something like -x -> x + args = Mul.make_args(expr) + + # Gather args for numerator/denominator + for item in args: + if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative: + if item.exp != -1: + b.append(Pow(item.base, -item.exp, evaluate=False)) + else: + if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160 + pow_paren.append(item) + b.append(Pow(item.base, -item.exp)) + else: + a.append(item) + + a = a or [S.One] + + if len(a) == 1 and sign == "-": + # Unary minus does not have a SymPy class, and hence there's no + # precedence weight associated with it, Python's unary minus has + # an operator precedence between multiplication and exponentiation, + # so we use this to compute a weight. + a_str = [self.parenthesize(a[0], 0.5*(PRECEDENCE["Pow"]+PRECEDENCE["Mul"]))] + else: + a_str = [self.parenthesize(x, prec) for x in a] + b_str = [self.parenthesize(x, prec) for x in b] + + # To parenthesize Pow with exp = -1 and having more than one Symbol + for item in pow_paren: + if item.base in b: + b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] + + if not b: + return sign + '*'.join(a_str) + elif len(b) == 1: + return sign + '*'.join(a_str) + "/" + b_str[0] + else: + return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str) + + def _print_not_supported(self, expr): + try: + self._not_supported.add(expr) + except TypeError: + # not hashable + pass + return self.emptyPrinter(expr) + + # The following can not be simply translated into C or Fortran + _print_Basic = _print_not_supported + _print_ComplexInfinity = _print_not_supported + _print_Derivative = _print_not_supported + _print_ExprCondPair = _print_not_supported + _print_GeometryEntity = _print_not_supported + _print_Infinity = _print_not_supported + _print_Integral = _print_not_supported + _print_Interval = _print_not_supported + _print_AccumulationBounds = _print_not_supported + _print_Limit = _print_not_supported + _print_MatrixBase = _print_not_supported + _print_DeferredVector = _print_not_supported + _print_NaN = _print_not_supported + _print_NegativeInfinity = _print_not_supported + _print_Order = _print_not_supported + _print_RootOf = _print_not_supported + _print_RootsOf = _print_not_supported + _print_RootSum = _print_not_supported + _print_Uniform = _print_not_supported + _print_Unit = _print_not_supported + _print_Wild = _print_not_supported + _print_WildFunction = _print_not_supported + _print_Relational = _print_not_supported + + +# Code printer functions. These are included in this file so that they can be +# imported in the top-level __init__.py without importing the sympy.codegen +# module. + +def ccode(expr, assign_to=None, standard='c99', **settings): + """Converts an expr to a string of c code + + Parameters + ========== + + expr : Expr + A SymPy expression to be converted. + assign_to : optional + When given, the argument is used as the name of the variable to which + the expression is assigned. Can be a string, ``Symbol``, + ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of + line-wrapping, or for expressions that generate multi-line statements. + standard : str, optional + String specifying the standard. If your compiler supports a more modern + standard you may set this to 'c99' to allow the printer to use more math + functions. [default='c89']. + precision : integer, optional + The precision for numbers such as pi [default=17]. + user_functions : dict, optional + A dictionary where the keys are string representations of either + ``FunctionClass`` or ``UndefinedFunction`` instances and the values + are their desired C string representations. Alternatively, the + dictionary value can be a list of tuples i.e. [(argument_test, + cfunction_string)] or [(argument_test, cfunction_formater)]. See below + for examples. + dereference : iterable, optional + An iterable of symbols that should be dereferenced in the printed code + expression. These would be values passed by address to the function. + For example, if ``dereference=[a]``, the resulting code would print + ``(*a)`` instead of ``a``. + human : bool, optional + If True, the result is a single string that may contain some constant + declarations for the number symbols. If False, the same information is + returned in a tuple of (symbols_to_declare, not_supported_functions, + code_text). [default=True]. + contract: bool, optional + If True, ``Indexed`` instances are assumed to obey tensor contraction + rules and the corresponding nested loops over indices are generated. + Setting contract=False will not generate loops, instead the user is + responsible to provide values for the indices in the code. + [default=True]. + + Examples + ======== + + >>> from sympy import ccode, symbols, Rational, sin, ceiling, Abs, Function + >>> x, tau = symbols("x, tau") + >>> expr = (2*tau)**Rational(7, 2) + >>> ccode(expr) + '8*M_SQRT2*pow(tau, 7.0/2.0)' + >>> ccode(expr, math_macros={}) + '8*sqrt(2)*pow(tau, 7.0/2.0)' + >>> ccode(sin(x), assign_to="s") + 's = sin(x);' + >>> from sympy.codegen.ast import real, float80 + >>> ccode(expr, type_aliases={real: float80}) + '8*M_SQRT2l*powl(tau, 7.0L/2.0L)' + + Simple custom printing can be defined for certain types by passing a + dictionary of {"type" : "function"} to the ``user_functions`` kwarg. + Alternatively, the dictionary value can be a list of tuples i.e. + [(argument_test, cfunction_string)]. + + >>> custom_functions = { + ... "ceiling": "CEIL", + ... "Abs": [(lambda x: not x.is_integer, "fabs"), + ... (lambda x: x.is_integer, "ABS")], + ... "func": "f" + ... } + >>> func = Function('func') + >>> ccode(func(Abs(x) + ceiling(x)), standard='C89', user_functions=custom_functions) + 'f(fabs(x) + CEIL(x))' + + or if the C-function takes a subset of the original arguments: + + >>> ccode(2**x + 3**x, standard='C99', user_functions={'Pow': [ + ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e), + ... (lambda b, e: b != 2, 'pow')]}) + 'exp2(x) + pow(3, x)' + + ``Piecewise`` expressions are converted into conditionals. If an + ``assign_to`` variable is provided an if statement is created, otherwise + the ternary operator is used. Note that if the ``Piecewise`` lacks a + default term, represented by ``(expr, True)`` then an error will be thrown. + This is to prevent generating an expression that may not evaluate to + anything. + + >>> from sympy import Piecewise + >>> expr = Piecewise((x + 1, x > 0), (x, True)) + >>> print(ccode(expr, tau, standard='C89')) + if (x > 0) { + tau = x + 1; + } + else { + tau = x; + } + + Support for loops is provided through ``Indexed`` types. With + ``contract=True`` these expressions will be turned into loops, whereas + ``contract=False`` will just print the assignment expression that should be + looped over: + + >>> from sympy import Eq, IndexedBase, Idx + >>> len_y = 5 + >>> y = IndexedBase('y', shape=(len_y,)) + >>> t = IndexedBase('t', shape=(len_y,)) + >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) + >>> i = Idx('i', len_y-1) + >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) + >>> ccode(e.rhs, assign_to=e.lhs, contract=False, standard='C89') + 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' + + Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions + must be provided to ``assign_to``. Note that any expression that can be + generated normally can also exist inside a Matrix: + + >>> from sympy import Matrix, MatrixSymbol + >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) + >>> A = MatrixSymbol('A', 3, 1) + >>> print(ccode(mat, A, standard='C89')) + A[0] = pow(x, 2); + if (x > 0) { + A[1] = x + 1; + } + else { + A[1] = x; + } + A[2] = sin(x); + """ + from sympy.printing.c import c_code_printers + return c_code_printers[standard.lower()](settings).doprint(expr, assign_to) + +def print_ccode(expr, **settings): + """Prints C representation of the given expression.""" + print(ccode(expr, **settings)) + +def fcode(expr, assign_to=None, **settings): + """Converts an expr to a string of fortran code + + Parameters + ========== + + expr : Expr + A SymPy expression to be converted. + assign_to : optional + When given, the argument is used as the name of the variable to which + the expression is assigned. Can be a string, ``Symbol``, + ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of + line-wrapping, or for expressions that generate multi-line statements. + precision : integer, optional + DEPRECATED. Use type_mappings instead. The precision for numbers such + as pi [default=17]. + user_functions : dict, optional + A dictionary where keys are ``FunctionClass`` instances and values are + their string representations. Alternatively, the dictionary value can + be a list of tuples i.e. [(argument_test, cfunction_string)]. See below + for examples. + human : bool, optional + If True, the result is a single string that may contain some constant + declarations for the number symbols. If False, the same information is + returned in a tuple of (symbols_to_declare, not_supported_functions, + code_text). [default=True]. + contract: bool, optional + If True, ``Indexed`` instances are assumed to obey tensor contraction + rules and the corresponding nested loops over indices are generated. + Setting contract=False will not generate loops, instead the user is + responsible to provide values for the indices in the code. + [default=True]. + source_format : optional + The source format can be either 'fixed' or 'free'. [default='fixed'] + standard : integer, optional + The Fortran standard to be followed. This is specified as an integer. + Acceptable standards are 66, 77, 90, 95, 2003, and 2008. Default is 77. + Note that currently the only distinction internally is between + standards before 95, and those 95 and after. This may change later as + more features are added. + name_mangling : bool, optional + If True, then the variables that would become identical in + case-insensitive Fortran are mangled by appending different number + of ``_`` at the end. If False, SymPy Will not interfere with naming of + variables. [default=True] + + Examples + ======== + + >>> from sympy import fcode, symbols, Rational, sin, ceiling, floor + >>> x, tau = symbols("x, tau") + >>> fcode((2*tau)**Rational(7, 2)) + ' 8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)' + >>> fcode(sin(x), assign_to="s") + ' s = sin(x)' + + Custom printing can be defined for certain types by passing a dictionary of + "type" : "function" to the ``user_functions`` kwarg. Alternatively, the + dictionary value can be a list of tuples i.e. [(argument_test, + cfunction_string)]. + + >>> custom_functions = { + ... "ceiling": "CEIL", + ... "floor": [(lambda x: not x.is_integer, "FLOOR1"), + ... (lambda x: x.is_integer, "FLOOR2")] + ... } + >>> fcode(floor(x) + ceiling(x), user_functions=custom_functions) + ' CEIL(x) + FLOOR1(x)' + + ``Piecewise`` expressions are converted into conditionals. If an + ``assign_to`` variable is provided an if statement is created, otherwise + the ternary operator is used. Note that if the ``Piecewise`` lacks a + default term, represented by ``(expr, True)`` then an error will be thrown. + This is to prevent generating an expression that may not evaluate to + anything. + + >>> from sympy import Piecewise + >>> expr = Piecewise((x + 1, x > 0), (x, True)) + >>> print(fcode(expr, tau)) + if (x > 0) then + tau = x + 1 + else + tau = x + end if + + Support for loops is provided through ``Indexed`` types. With + ``contract=True`` these expressions will be turned into loops, whereas + ``contract=False`` will just print the assignment expression that should be + looped over: + + >>> from sympy import Eq, IndexedBase, Idx + >>> len_y = 5 + >>> y = IndexedBase('y', shape=(len_y,)) + >>> t = IndexedBase('t', shape=(len_y,)) + >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) + >>> i = Idx('i', len_y-1) + >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) + >>> fcode(e.rhs, assign_to=e.lhs, contract=False) + ' Dy(i) = (y(i + 1) - y(i))/(t(i + 1) - t(i))' + + Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions + must be provided to ``assign_to``. Note that any expression that can be + generated normally can also exist inside a Matrix: + + >>> from sympy import Matrix, MatrixSymbol + >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) + >>> A = MatrixSymbol('A', 3, 1) + >>> print(fcode(mat, A)) + A(1, 1) = x**2 + if (x > 0) then + A(2, 1) = x + 1 + else + A(2, 1) = x + end if + A(3, 1) = sin(x) + """ + from sympy.printing.fortran import FCodePrinter + return FCodePrinter(settings).doprint(expr, assign_to) + + +def print_fcode(expr, **settings): + """Prints the Fortran representation of the given expression. + + See fcode for the meaning of the optional arguments. + """ + print(fcode(expr, **settings)) + +def cxxcode(expr, assign_to=None, standard='c++11', **settings): + """ C++ equivalent of :func:`~.ccode`. """ + from sympy.printing.cxx import cxx_code_printers + return cxx_code_printers[standard.lower()](settings).doprint(expr, assign_to) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/conventions.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/conventions.py new file mode 100644 index 0000000000000000000000000000000000000000..3eda9c1a54aef5dd5090debf98dc74bba72f9405 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/conventions.py @@ -0,0 +1,88 @@ +""" +A few practical conventions common to all printers. +""" + +import re + +from collections.abc import Iterable +from sympy.core.function import Derivative + +_name_with_digits_p = re.compile(r'^([^\W\d_]+)(\d+)$', re.U) + + +def split_super_sub(text): + """Split a symbol name into a name, superscripts and subscripts + + The first part of the symbol name is considered to be its actual + 'name', followed by super- and subscripts. Each superscript is + preceded with a "^" character or by "__". Each subscript is preceded + by a "_" character. The three return values are the actual name, a + list with superscripts and a list with subscripts. + + Examples + ======== + + >>> from sympy.printing.conventions import split_super_sub + >>> split_super_sub('a_x^1') + ('a', ['1'], ['x']) + >>> split_super_sub('var_sub1__sup_sub2') + ('var', ['sup'], ['sub1', 'sub2']) + + """ + if not text: + return text, [], [] + + pos = 0 + name = None + supers = [] + subs = [] + while pos < len(text): + start = pos + 1 + if text[pos:pos + 2] == "__": + start += 1 + pos_hat = text.find("^", start) + if pos_hat < 0: + pos_hat = len(text) + pos_usc = text.find("_", start) + if pos_usc < 0: + pos_usc = len(text) + pos_next = min(pos_hat, pos_usc) + part = text[pos:pos_next] + pos = pos_next + if name is None: + name = part + elif part.startswith("^"): + supers.append(part[1:]) + elif part.startswith("__"): + supers.append(part[2:]) + elif part.startswith("_"): + subs.append(part[1:]) + else: + raise RuntimeError("This should never happen.") + + # Make a little exception when a name ends with digits, i.e. treat them + # as a subscript too. + m = _name_with_digits_p.match(name) + if m: + name, sub = m.groups() + subs.insert(0, sub) + + return name, supers, subs + + +def requires_partial(expr): + """Return whether a partial derivative symbol is required for printing + + This requires checking how many free variables there are, + filtering out the ones that are integers. Some expressions do not have + free variables. In that case, check its variable list explicitly to + get the context of the expression. + """ + + if isinstance(expr, Derivative): + return requires_partial(expr.expr) + + if not isinstance(expr.free_symbols, Iterable): + return len(set(expr.variables)) > 1 + + return sum(not s.is_integer for s in expr.free_symbols) > 1 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/cxx.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/cxx.py new file mode 100644 index 0000000000000000000000000000000000000000..cd5d281a9028e66e57bf37d7054afe2c48f25754 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/cxx.py @@ -0,0 +1,169 @@ +""" +C++ code printer +""" + +from itertools import chain +from sympy.codegen.ast import Type, none +from .c import C89CodePrinter, C99CodePrinter + +# These are defined in the other file so we can avoid importing sympy.codegen +# from the top-level 'import sympy'. Export them here as well. +from sympy.printing.codeprinter import cxxcode # noqa:F401 + +# from https://en.cppreference.com/w/cpp/keyword +reserved = { + 'C++98': [ + 'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor', 'bool', 'break', + 'case', 'catch,', 'char', 'class', 'compl', 'const', 'const_cast', + 'continue', 'default', 'delete', 'do', 'double', 'dynamic_cast', + 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float', + 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable', + 'namespace', 'new', 'not', 'not_eq', 'operator', 'or', 'or_eq', + 'private', 'protected', 'public', 'register', 'reinterpret_cast', + 'return', 'short', 'signed', 'sizeof', 'static', 'static_cast', + 'struct', 'switch', 'template', 'this', 'throw', 'true', 'try', + 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', + 'virtual', 'void', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq' + ] +} + +reserved['C++11'] = reserved['C++98'][:] + [ + 'alignas', 'alignof', 'char16_t', 'char32_t', 'constexpr', 'decltype', + 'noexcept', 'nullptr', 'static_assert', 'thread_local' +] +reserved['C++17'] = reserved['C++11'][:] +reserved['C++17'].remove('register') +# TM TS: atomic_cancel, atomic_commit, atomic_noexcept, synchronized +# concepts TS: concept, requires +# module TS: import, module + + +_math_functions = { + 'C++98': { + 'Mod': 'fmod', + 'ceiling': 'ceil', + }, + 'C++11': { + 'gamma': 'tgamma', + }, + 'C++17': { + 'beta': 'beta', + 'Ei': 'expint', + 'zeta': 'riemann_zeta', + } +} + +# from https://en.cppreference.com/w/cpp/header/cmath +for k in ('Abs', 'exp', 'log', 'log10', 'sqrt', 'sin', 'cos', 'tan', # 'Pow' + 'asin', 'acos', 'atan', 'atan2', 'sinh', 'cosh', 'tanh', 'floor'): + _math_functions['C++98'][k] = k.lower() + + +for k in ('asinh', 'acosh', 'atanh', 'erf', 'erfc'): + _math_functions['C++11'][k] = k.lower() + + +def _attach_print_method(cls, sympy_name, func_name): + meth_name = '_print_%s' % sympy_name + if hasattr(cls, meth_name): + raise ValueError("Edit method (or subclass) instead of overwriting.") + def _print_method(self, expr): + return '{}{}({})'.format(self._ns, func_name, ', '.join(map(self._print, expr.args))) + _print_method.__doc__ = "Prints code for %s" % k + setattr(cls, meth_name, _print_method) + + +def _attach_print_methods(cls, cont): + for sympy_name, cxx_name in cont[cls.standard].items(): + _attach_print_method(cls, sympy_name, cxx_name) + + +class _CXXCodePrinterBase: + printmethod = "_cxxcode" + language = 'C++' + _ns = 'std::' # namespace + + def __init__(self, settings=None): + super().__init__(settings or {}) + + def _print_Max(self, expr): + from sympy.functions.elementary.miscellaneous import Max + if len(expr.args) == 1: + return self._print(expr.args[0]) + return "%smax(%s, %s)" % (self._ns, self._print(expr.args[0]), + self._print(Max(*expr.args[1:]))) + + def _print_Min(self, expr): + from sympy.functions.elementary.miscellaneous import Min + if len(expr.args) == 1: + return self._print(expr.args[0]) + return "%smin(%s, %s)" % (self._ns, self._print(expr.args[0]), + self._print(Min(*expr.args[1:]))) + + def _print_using(self, expr): + if expr.alias == none: + return 'using %s' % expr.type + else: + raise ValueError("C++98 does not support type aliases") + + +class CXX98CodePrinter(_CXXCodePrinterBase, C89CodePrinter): + standard = 'C++98' + reserved_words = set(reserved['C++98']) + + +# _attach_print_methods(CXX98CodePrinter, _math_functions) + + +class CXX11CodePrinter(_CXXCodePrinterBase, C99CodePrinter): + standard = 'C++11' + reserved_words = set(reserved['C++11']) + type_mappings = dict(chain( + CXX98CodePrinter.type_mappings.items(), + { + Type('int8'): ('int8_t', {'cstdint'}), + Type('int16'): ('int16_t', {'cstdint'}), + Type('int32'): ('int32_t', {'cstdint'}), + Type('int64'): ('int64_t', {'cstdint'}), + Type('uint8'): ('uint8_t', {'cstdint'}), + Type('uint16'): ('uint16_t', {'cstdint'}), + Type('uint32'): ('uint32_t', {'cstdint'}), + Type('uint64'): ('uint64_t', {'cstdint'}), + Type('complex64'): ('std::complex', {'complex'}), + Type('complex128'): ('std::complex', {'complex'}), + Type('bool'): ('bool', None), + }.items() + )) + + def _print_using(self, expr): + if expr.alias == none: + return super()._print_using(expr) + else: + return 'using %(alias)s = %(type)s' % expr.kwargs(apply=self._print) + +# _attach_print_methods(CXX11CodePrinter, _math_functions) + + +class CXX17CodePrinter(_CXXCodePrinterBase, C99CodePrinter): + standard = 'C++17' + reserved_words = set(reserved['C++17']) + + _kf = dict(C99CodePrinter._kf, **_math_functions['C++17']) + + def _print_beta(self, expr): + return self._print_math_func(expr) + + def _print_Ei(self, expr): + return self._print_math_func(expr) + + def _print_zeta(self, expr): + return self._print_math_func(expr) + + +# _attach_print_methods(CXX17CodePrinter, _math_functions) + +cxx_code_printers = { + 'c++98': CXX98CodePrinter, + 'c++11': CXX11CodePrinter, + 'c++17': CXX17CodePrinter +} diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/defaults.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..77a88d353fed4bd70496456ddd03cc429a4ba5e7 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/defaults.py @@ -0,0 +1,5 @@ +from sympy.core._print_helpers import Printable + +# alias for compatibility +Printable.__module__ = __name__ +DefaultPrinting = Printable diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/dot.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/dot.py new file mode 100644 index 0000000000000000000000000000000000000000..c968fee389c16108b757b8fcad531ac6fa4ddb2f --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/dot.py @@ -0,0 +1,294 @@ +from sympy.core.basic import Basic +from sympy.core.expr import Expr +from sympy.core.symbol import Symbol +from sympy.core.numbers import Integer, Rational, Float +from sympy.printing.repr import srepr + +__all__ = ['dotprint'] + +default_styles = ( + (Basic, {'color': 'blue', 'shape': 'ellipse'}), + (Expr, {'color': 'black'}) +) + +slotClasses = (Symbol, Integer, Rational, Float) +def purestr(x, with_args=False): + """A string that follows ```obj = type(obj)(*obj.args)``` exactly. + + Parameters + ========== + + with_args : boolean, optional + If ``True``, there will be a second argument for the return + value, which is a tuple containing ``purestr`` applied to each + of the subnodes. + + If ``False``, there will not be a second argument for the + return. + + Default is ``False`` + + Examples + ======== + + >>> from sympy import Float, Symbol, MatrixSymbol + >>> from sympy import Integer # noqa: F401 + >>> from sympy.core.symbol import Str # noqa: F401 + >>> from sympy.printing.dot import purestr + + Applying ``purestr`` for basic symbolic object: + >>> code = purestr(Symbol('x')) + >>> code + "Symbol('x')" + >>> eval(code) == Symbol('x') + True + + For basic numeric object: + >>> purestr(Float(2)) + "Float('2.0', precision=53)" + + For matrix symbol: + >>> code = purestr(MatrixSymbol('x', 2, 2)) + >>> code + "MatrixSymbol(Str('x'), Integer(2), Integer(2))" + >>> eval(code) == MatrixSymbol('x', 2, 2) + True + + With ``with_args=True``: + >>> purestr(Float(2), with_args=True) + ("Float('2.0', precision=53)", ()) + >>> purestr(MatrixSymbol('x', 2, 2), with_args=True) + ("MatrixSymbol(Str('x'), Integer(2), Integer(2))", + ("Str('x')", 'Integer(2)', 'Integer(2)')) + """ + sargs = () + if not isinstance(x, Basic): + rv = str(x) + elif not x.args: + rv = srepr(x) + else: + args = x.args + sargs = tuple(map(purestr, args)) + rv = "%s(%s)"%(type(x).__name__, ', '.join(sargs)) + if with_args: + rv = rv, sargs + return rv + + +def styleof(expr, styles=default_styles): + """ Merge style dictionaries in order + + Examples + ======== + + >>> from sympy import Symbol, Basic, Expr, S + >>> from sympy.printing.dot import styleof + >>> styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}), + ... (Expr, {'color': 'black'})] + + >>> styleof(Basic(S(1)), styles) + {'color': 'blue', 'shape': 'ellipse'} + + >>> x = Symbol('x') + >>> styleof(x + 1, styles) # this is an Expr + {'color': 'black', 'shape': 'ellipse'} + """ + style = {} + for typ, sty in styles: + if isinstance(expr, typ): + style.update(sty) + return style + + +def attrprint(d, delimiter=', '): + """ Print a dictionary of attributes + + Examples + ======== + + >>> from sympy.printing.dot import attrprint + >>> print(attrprint({'color': 'blue', 'shape': 'ellipse'})) + "color"="blue", "shape"="ellipse" + """ + return delimiter.join('"%s"="%s"'%item for item in sorted(d.items())) + + +def dotnode(expr, styles=default_styles, labelfunc=str, pos=(), repeat=True): + """ String defining a node + + Examples + ======== + + >>> from sympy.printing.dot import dotnode + >>> from sympy.abc import x + >>> print(dotnode(x)) + "Symbol('x')_()" ["color"="black", "label"="x", "shape"="ellipse"]; + """ + style = styleof(expr, styles) + + if isinstance(expr, Basic) and not expr.is_Atom: + label = str(expr.__class__.__name__) + else: + label = labelfunc(expr) + style['label'] = label + expr_str = purestr(expr) + if repeat: + expr_str += '_%s' % str(pos) + return '"%s" [%s];' % (expr_str, attrprint(style)) + + +def dotedges(expr, atom=lambda x: not isinstance(x, Basic), pos=(), repeat=True): + """ List of strings for all expr->expr.arg pairs + + See the docstring of dotprint for explanations of the options. + + Examples + ======== + + >>> from sympy.printing.dot import dotedges + >>> from sympy.abc import x + >>> for e in dotedges(x+2): + ... print(e) + "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)"; + "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)"; + """ + if atom(expr): + return [] + else: + expr_str, arg_strs = purestr(expr, with_args=True) + if repeat: + expr_str += '_%s' % str(pos) + arg_strs = ['%s_%s' % (a, str(pos + (i,))) + for i, a in enumerate(arg_strs)] + return ['"%s" -> "%s";' % (expr_str, a) for a in arg_strs] + +template = \ +"""digraph{ + +# Graph style +%(graphstyle)s + +######### +# Nodes # +######### + +%(nodes)s + +######### +# Edges # +######### + +%(edges)s +}""" + +_graphstyle = {'rankdir': 'TD', 'ordering': 'out'} + +def dotprint(expr, + styles=default_styles, atom=lambda x: not isinstance(x, Basic), + maxdepth=None, repeat=True, labelfunc=str, **kwargs): + """DOT description of a SymPy expression tree + + Parameters + ========== + + styles : list of lists composed of (Class, mapping), optional + Styles for different classes. + + The default is + + .. code-block:: python + + ( + (Basic, {'color': 'blue', 'shape': 'ellipse'}), + (Expr, {'color': 'black'}) + ) + + atom : function, optional + Function used to determine if an arg is an atom. + + A good choice is ``lambda x: not x.args``. + + The default is ``lambda x: not isinstance(x, Basic)``. + + maxdepth : integer, optional + The maximum depth. + + The default is ``None``, meaning no limit. + + repeat : boolean, optional + Whether to use different nodes for common subexpressions. + + The default is ``True``. + + For example, for ``x + x*y`` with ``repeat=True``, it will have + two nodes for ``x``; with ``repeat=False``, it will have one + node. + + .. warning:: + Even if a node appears twice in the same object like ``x`` in + ``Pow(x, x)``, it will still only appear once. + Hence, with ``repeat=False``, the number of arrows out of an + object might not equal the number of args it has. + + labelfunc : function, optional + A function to create a label for a given leaf node. + + The default is ``str``. + + Another good option is ``srepr``. + + For example with ``str``, the leaf nodes of ``x + 1`` are labeled, + ``x`` and ``1``. With ``srepr``, they are labeled ``Symbol('x')`` + and ``Integer(1)``. + + **kwargs : optional + Additional keyword arguments are included as styles for the graph. + + Examples + ======== + + >>> from sympy import dotprint + >>> from sympy.abc import x + >>> print(dotprint(x+2)) # doctest: +NORMALIZE_WHITESPACE + digraph{ + + # Graph style + "ordering"="out" + "rankdir"="TD" + + ######### + # Nodes # + ######### + + "Add(Integer(2), Symbol('x'))_()" ["color"="black", "label"="Add", "shape"="ellipse"]; + "Integer(2)_(0,)" ["color"="black", "label"="2", "shape"="ellipse"]; + "Symbol('x')_(1,)" ["color"="black", "label"="x", "shape"="ellipse"]; + + ######### + # Edges # + ######### + + "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)"; + "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)"; + } + + """ + # repeat works by adding a signature tuple to the end of each node for its + # position in the graph. For example, for expr = Add(x, Pow(x, 2)), the x in the + # Pow will have the tuple (1, 0), meaning it is expr.args[1].args[0]. + graphstyle = _graphstyle.copy() + graphstyle.update(kwargs) + + nodes = [] + edges = [] + def traverse(e, depth, pos=()): + nodes.append(dotnode(e, styles, labelfunc=labelfunc, pos=pos, repeat=repeat)) + if maxdepth and depth >= maxdepth: + return + edges.extend(dotedges(e, atom=atom, pos=pos, repeat=repeat)) + [traverse(arg, depth+1, pos + (i,)) for i, arg in enumerate(e.args) if not atom(arg)] + traverse(expr, 0) + + return template%{'graphstyle': attrprint(graphstyle, delimiter='\n'), + 'nodes': '\n'.join(nodes), + 'edges': '\n'.join(edges)} diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/fortran.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/fortran.py new file mode 100644 index 0000000000000000000000000000000000000000..184116648bbb774c7d0215c56197b13ce848803d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/fortran.py @@ -0,0 +1,782 @@ +""" +Fortran code printer + +The FCodePrinter converts single SymPy expressions into single Fortran +expressions, using the functions defined in the Fortran 77 standard where +possible. Some useful pointers to Fortran can be found on wikipedia: + +https://en.wikipedia.org/wiki/Fortran + +Most of the code below is based on the "Professional Programmer\'s Guide to +Fortran77" by Clive G. Page: + +https://www.star.le.ac.uk/~cgp/prof77.html + +Fortran is a case-insensitive language. This might cause trouble because +SymPy is case sensitive. So, fcode adds underscores to variable names when +it is necessary to make them different for Fortran. +""" + +from __future__ import annotations +from typing import Any + +from collections import defaultdict +from itertools import chain +import string + +from sympy.codegen.ast import ( + Assignment, Declaration, Pointer, value_const, + float32, float64, float80, complex64, complex128, int8, int16, int32, + int64, intc, real, integer, bool_, complex_ +) +from sympy.codegen.fnodes import ( + allocatable, isign, dsign, cmplx, merge, literal_dp, elemental, pure, + intent_in, intent_out, intent_inout +) +from sympy.core import S, Add, N, Float, Symbol +from sympy.core.function import Function +from sympy.core.numbers import equal_valued +from sympy.core.relational import Eq +from sympy.sets import Range +from sympy.printing.codeprinter import CodePrinter +from sympy.printing.precedence import precedence, PRECEDENCE +from sympy.printing.printer import printer_context + +# These are defined in the other file so we can avoid importing sympy.codegen +# from the top-level 'import sympy'. Export them here as well. +from sympy.printing.codeprinter import fcode, print_fcode # noqa:F401 + +known_functions = { + "sin": "sin", + "cos": "cos", + "tan": "tan", + "asin": "asin", + "acos": "acos", + "atan": "atan", + "atan2": "atan2", + "sinh": "sinh", + "cosh": "cosh", + "tanh": "tanh", + "log": "log", + "exp": "exp", + "erf": "erf", + "Abs": "abs", + "conjugate": "conjg", + "Max": "max", + "Min": "min", +} + + +class FCodePrinter(CodePrinter): + """A printer to convert SymPy expressions to strings of Fortran code""" + printmethod = "_fcode" + language = "Fortran" + + type_aliases = { + integer: int32, + real: float64, + complex_: complex128, + } + + type_mappings = { + intc: 'integer(c_int)', + float32: 'real*4', # real(kind(0.e0)) + float64: 'real*8', # real(kind(0.d0)) + float80: 'real*10', # real(kind(????)) + complex64: 'complex*8', + complex128: 'complex*16', + int8: 'integer*1', + int16: 'integer*2', + int32: 'integer*4', + int64: 'integer*8', + bool_: 'logical' + } + + type_modules = { + intc: {'iso_c_binding': 'c_int'} + } + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'precision': 17, + 'user_functions': {}, + 'human': True, + 'allow_unknown_functions': False, + 'source_format': 'fixed', + 'contract': True, + 'standard': 77, + 'name_mangling': True, + } + + _operators = { + 'and': '.and.', + 'or': '.or.', + 'xor': '.neqv.', + 'equivalent': '.eqv.', + 'not': '.not. ', + } + + _relationals = { + '!=': '/=', + } + + def __init__(self, settings=None): + if not settings: + settings = {} + self.mangled_symbols = {} # Dict showing mapping of all words + self.used_name = [] + self.type_aliases = dict(chain(self.type_aliases.items(), + settings.pop('type_aliases', {}).items())) + self.type_mappings = dict(chain(self.type_mappings.items(), + settings.pop('type_mappings', {}).items())) + super().__init__(settings) + self.known_functions = dict(known_functions) + userfuncs = settings.get('user_functions', {}) + self.known_functions.update(userfuncs) + # leading columns depend on fixed or free format + standards = {66, 77, 90, 95, 2003, 2008} + if self._settings['standard'] not in standards: + raise ValueError("Unknown Fortran standard: %s" % self._settings[ + 'standard']) + self.module_uses = defaultdict(set) # e.g.: use iso_c_binding, only: c_int + + @property + def _lead(self): + if self._settings['source_format'] == 'fixed': + return {'code': " ", 'cont': " @ ", 'comment': "C "} + elif self._settings['source_format'] == 'free': + return {'code': "", 'cont': " ", 'comment': "! "} + else: + raise ValueError("Unknown source format: %s" % self._settings['source_format']) + + def _print_Symbol(self, expr): + if self._settings['name_mangling'] == True: + if expr not in self.mangled_symbols: + name = expr.name + while name.lower() in self.used_name: + name += '_' + self.used_name.append(name.lower()) + if name == expr.name: + self.mangled_symbols[expr] = expr + else: + self.mangled_symbols[expr] = Symbol(name) + + expr = expr.xreplace(self.mangled_symbols) + + name = super()._print_Symbol(expr) + return name + + def _rate_index_position(self, p): + return -p*5 + + def _get_statement(self, codestring): + return codestring + + def _get_comment(self, text): + return "! {}".format(text) + + def _declare_number_const(self, name, value): + return "parameter ({} = {})".format(name, self._print(value)) + + def _print_NumberSymbol(self, expr): + # A Number symbol that is not implemented here or with _printmethod + # is registered and evaluated + self._number_symbols.add((expr, Float(expr.evalf(self._settings['precision'])))) + return str(expr) + + def _format_code(self, lines): + return self._wrap_fortran(self.indent_code(lines)) + + def _traverse_matrix_indices(self, mat): + rows, cols = mat.shape + return ((i, j) for j in range(cols) for i in range(rows)) + + def _get_loop_opening_ending(self, indices): + open_lines = [] + close_lines = [] + for i in indices: + # fortran arrays start at 1 and end at dimension + var, start, stop = map(self._print, + [i.label, i.lower + 1, i.upper + 1]) + open_lines.append("do %s = %s, %s" % (var, start, stop)) + close_lines.append("end do") + return open_lines, close_lines + + def _print_sign(self, expr): + from sympy.functions.elementary.complexes import Abs + arg, = expr.args + if arg.is_integer: + new_expr = merge(0, isign(1, arg), Eq(arg, 0)) + elif (arg.is_complex or arg.is_infinite): + new_expr = merge(cmplx(literal_dp(0), literal_dp(0)), arg/Abs(arg), Eq(Abs(arg), literal_dp(0))) + else: + new_expr = merge(literal_dp(0), dsign(literal_dp(1), arg), Eq(arg, literal_dp(0))) + return self._print(new_expr) + + + def _print_Piecewise(self, expr): + if expr.args[-1].cond != True: + # We need the last conditional to be a True, otherwise the resulting + # function may not return a result. + raise ValueError("All Piecewise expressions must contain an " + "(expr, True) statement to be used as a default " + "condition. Without one, the generated " + "expression may not evaluate to anything under " + "some condition.") + lines = [] + if expr.has(Assignment): + for i, (e, c) in enumerate(expr.args): + if i == 0: + lines.append("if (%s) then" % self._print(c)) + elif i == len(expr.args) - 1 and c == True: + lines.append("else") + else: + lines.append("else if (%s) then" % self._print(c)) + lines.append(self._print(e)) + lines.append("end if") + return "\n".join(lines) + elif self._settings["standard"] >= 95: + # Only supported in F95 and newer: + # The piecewise was used in an expression, need to do inline + # operators. This has the downside that inline operators will + # not work for statements that span multiple lines (Matrix or + # Indexed expressions). + pattern = "merge({T}, {F}, {COND})" + code = self._print(expr.args[-1].expr) + terms = list(expr.args[:-1]) + while terms: + e, c = terms.pop() + expr = self._print(e) + cond = self._print(c) + code = pattern.format(T=expr, F=code, COND=cond) + return code + else: + # `merge` is not supported prior to F95 + raise NotImplementedError("Using Piecewise as an expression using " + "inline operators is not supported in " + "standards earlier than Fortran95.") + + def _print_MatrixElement(self, expr): + return "{}({}, {})".format(self.parenthesize(expr.parent, + PRECEDENCE["Atom"], strict=True), expr.i + 1, expr.j + 1) + + def _print_Add(self, expr): + # purpose: print complex numbers nicely in Fortran. + # collect the purely real and purely imaginary parts: + pure_real = [] + pure_imaginary = [] + mixed = [] + for arg in expr.args: + if arg.is_number and arg.is_real: + pure_real.append(arg) + elif arg.is_number and arg.is_imaginary: + pure_imaginary.append(arg) + else: + mixed.append(arg) + if pure_imaginary: + if mixed: + PREC = precedence(expr) + term = Add(*mixed) + t = self._print(term) + if t.startswith('-'): + sign = "-" + t = t[1:] + else: + sign = "+" + if precedence(term) < PREC: + t = "(%s)" % t + + return "cmplx(%s,%s) %s %s" % ( + self._print(Add(*pure_real)), + self._print(-S.ImaginaryUnit*Add(*pure_imaginary)), + sign, t, + ) + else: + return "cmplx(%s,%s)" % ( + self._print(Add(*pure_real)), + self._print(-S.ImaginaryUnit*Add(*pure_imaginary)), + ) + else: + return CodePrinter._print_Add(self, expr) + + def _print_Function(self, expr): + # All constant function args are evaluated as floats + prec = self._settings['precision'] + args = [N(a, prec) for a in expr.args] + eval_expr = expr.func(*args) + if not isinstance(eval_expr, Function): + return self._print(eval_expr) + else: + return CodePrinter._print_Function(self, expr.func(*args)) + + def _print_Mod(self, expr): + # NOTE : Fortran has the functions mod() and modulo(). modulo() behaves + # the same wrt to the sign of the arguments as Python and SymPy's + # modulus computations (% and Mod()) but is not available in Fortran 66 + # or Fortran 77, thus we raise an error. + if self._settings['standard'] in [66, 77]: + msg = ("Python % operator and SymPy's Mod() function are not " + "supported by Fortran 66 or 77 standards.") + raise NotImplementedError(msg) + else: + x, y = expr.args + return " modulo({}, {})".format(self._print(x), self._print(y)) + + def _print_ImaginaryUnit(self, expr): + # purpose: print complex numbers nicely in Fortran. + return "cmplx(0,1)" + + def _print_int(self, expr): + return str(expr) + + def _print_Mul(self, expr): + # purpose: print complex numbers nicely in Fortran. + if expr.is_number and expr.is_imaginary: + return "cmplx(0,%s)" % ( + self._print(-S.ImaginaryUnit*expr) + ) + else: + return CodePrinter._print_Mul(self, expr) + + def _print_Pow(self, expr): + PREC = precedence(expr) + if equal_valued(expr.exp, -1): + return '%s/%s' % ( + self._print(literal_dp(1)), + self.parenthesize(expr.base, PREC) + ) + elif equal_valued(expr.exp, 0.5): + if expr.base.is_integer: + # Fortran intrinsic sqrt() does not accept integer argument + if expr.base.is_Number: + return 'sqrt(%s.0d0)' % self._print(expr.base) + else: + return 'sqrt(dble(%s))' % self._print(expr.base) + else: + return 'sqrt(%s)' % self._print(expr.base) + else: + return CodePrinter._print_Pow(self, expr) + + def _print_Rational(self, expr): + p, q = int(expr.p), int(expr.q) + return "%d.0d0/%d.0d0" % (p, q) + + def _print_Float(self, expr): + printed = CodePrinter._print_Float(self, expr) + e = printed.find('e') + if e > -1: + return "%sd%s" % (printed[:e], printed[e + 1:]) + return "%sd0" % printed + + def _print_Relational(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + op = expr.rel_op + op = op if op not in self._relationals else self._relationals[op] + return "{} {} {}".format(lhs_code, op, rhs_code) + + def _print_Indexed(self, expr): + inds = [ self._print(i) for i in expr.indices ] + return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds)) + + def _print_Idx(self, expr): + return self._print(expr.label) + + def _print_AugmentedAssignment(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + return self._get_statement("{0} = {0} {1} {2}".format( + self._print(lhs_code), self._print(expr.binop), self._print(rhs_code))) + + def _print_sum_(self, sm): + params = self._print(sm.array) + if sm.dim != None: # Must use '!= None', cannot use 'is not None' + params += ', ' + self._print(sm.dim) + if sm.mask != None: # Must use '!= None', cannot use 'is not None' + params += ', mask=' + self._print(sm.mask) + return '%s(%s)' % (sm.__class__.__name__.rstrip('_'), params) + + def _print_product_(self, prod): + return self._print_sum_(prod) + + def _print_Do(self, do): + excl = ['concurrent'] + if do.step == 1: + excl.append('step') + step = '' + else: + step = ', {step}' + + return ( + 'do {concurrent}{counter} = {first}, {last}'+step+'\n' + '{body}\n' + 'end do\n' + ).format( + concurrent='concurrent ' if do.concurrent else '', + **do.kwargs(apply=lambda arg: self._print(arg), exclude=excl) + ) + + def _print_ImpliedDoLoop(self, idl): + step = '' if idl.step == 1 else ', {step}' + return ('({expr}, {counter} = {first}, {last}'+step+')').format( + **idl.kwargs(apply=lambda arg: self._print(arg)) + ) + + def _print_For(self, expr): + target = self._print(expr.target) + if isinstance(expr.iterable, Range): + start, stop, step = expr.iterable.args + else: + raise NotImplementedError("Only iterable currently supported is Range") + body = self._print(expr.body) + return ('do {target} = {start}, {stop}, {step}\n' + '{body}\n' + 'end do').format(target=target, start=start, stop=stop - 1, + step=step, body=body) + + def _print_Type(self, type_): + type_ = self.type_aliases.get(type_, type_) + type_str = self.type_mappings.get(type_, type_.name) + module_uses = self.type_modules.get(type_) + if module_uses: + for k, v in module_uses: + self.module_uses[k].add(v) + return type_str + + def _print_Element(self, elem): + return '{symbol}({idxs})'.format( + symbol=self._print(elem.symbol), + idxs=', '.join((self._print(arg) for arg in elem.indices)) + ) + + def _print_Extent(self, ext): + return str(ext) + + def _print_Declaration(self, expr): + var = expr.variable + val = var.value + dim = var.attr_params('dimension') + intents = [intent in var.attrs for intent in (intent_in, intent_out, intent_inout)] + if intents.count(True) == 0: + intent = '' + elif intents.count(True) == 1: + intent = ', intent(%s)' % ['in', 'out', 'inout'][intents.index(True)] + else: + raise ValueError("Multiple intents specified for %s" % self) + + if isinstance(var, Pointer): + raise NotImplementedError("Pointers are not available by default in Fortran.") + if self._settings["standard"] >= 90: + result = '{t}{vc}{dim}{intent}{alloc} :: {s}'.format( + t=self._print(var.type), + vc=', parameter' if value_const in var.attrs else '', + dim=', dimension(%s)' % ', '.join((self._print(arg) for arg in dim)) if dim else '', + intent=intent, + alloc=', allocatable' if allocatable in var.attrs else '', + s=self._print(var.symbol) + ) + if val != None: # Must be "!= None", cannot be "is not None" + result += ' = %s' % self._print(val) + else: + if value_const in var.attrs or val: + raise NotImplementedError("F77 init./parameter statem. req. multiple lines.") + result = ' '.join((self._print(arg) for arg in [var.type, var.symbol])) + + return result + + + def _print_Infinity(self, expr): + return '(huge(%s) + 1)' % self._print(literal_dp(0)) + + def _print_While(self, expr): + return 'do while ({condition})\n{body}\nend do'.format(**expr.kwargs( + apply=lambda arg: self._print(arg))) + + def _print_BooleanTrue(self, expr): + return '.true.' + + def _print_BooleanFalse(self, expr): + return '.false.' + + def _pad_leading_columns(self, lines): + result = [] + for line in lines: + if line.startswith('!'): + result.append(self._lead['comment'] + line[1:].lstrip()) + else: + result.append(self._lead['code'] + line) + return result + + def _wrap_fortran(self, lines): + """Wrap long Fortran lines + + Argument: + lines -- a list of lines (without \\n character) + + A comment line is split at white space. Code lines are split with a more + complex rule to give nice results. + """ + # routine to find split point in a code line + my_alnum = set("_+-." + string.digits + string.ascii_letters) + my_white = set(" \t()") + + def split_pos_code(line, endpos): + if len(line) <= endpos: + return len(line) + pos = endpos + split = lambda pos: \ + (line[pos] in my_alnum and line[pos - 1] not in my_alnum) or \ + (line[pos] not in my_alnum and line[pos - 1] in my_alnum) or \ + (line[pos] in my_white and line[pos - 1] not in my_white) or \ + (line[pos] not in my_white and line[pos - 1] in my_white) + while not split(pos): + pos -= 1 + if pos == 0: + return endpos + return pos + # split line by line and add the split lines to result + result = [] + if self._settings['source_format'] == 'free': + trailing = ' &' + else: + trailing = '' + for line in lines: + if line.startswith(self._lead['comment']): + # comment line + if len(line) > 72: + pos = line.rfind(" ", 6, 72) + if pos == -1: + pos = 72 + hunk = line[:pos] + line = line[pos:].lstrip() + result.append(hunk) + while line: + pos = line.rfind(" ", 0, 66) + if pos == -1 or len(line) < 66: + pos = 66 + hunk = line[:pos] + line = line[pos:].lstrip() + result.append("%s%s" % (self._lead['comment'], hunk)) + else: + result.append(line) + elif line.startswith(self._lead['code']): + # code line + pos = split_pos_code(line, 72) + hunk = line[:pos].rstrip() + line = line[pos:].lstrip() + if line: + hunk += trailing + result.append(hunk) + while line: + pos = split_pos_code(line, 65) + hunk = line[:pos].rstrip() + line = line[pos:].lstrip() + if line: + hunk += trailing + result.append("%s%s" % (self._lead['cont'], hunk)) + else: + result.append(line) + return result + + def indent_code(self, code): + """Accepts a string of code or a list of code lines""" + if isinstance(code, str): + code_lines = self.indent_code(code.splitlines(True)) + return ''.join(code_lines) + + free = self._settings['source_format'] == 'free' + code = [ line.lstrip(' \t') for line in code ] + + inc_keyword = ('do ', 'if(', 'if ', 'do\n', 'else', 'program', 'interface') + dec_keyword = ('end do', 'enddo', 'end if', 'endif', 'else', 'end program', 'end interface') + + increase = [ int(any(map(line.startswith, inc_keyword))) + for line in code ] + decrease = [ int(any(map(line.startswith, dec_keyword))) + for line in code ] + continuation = [ int(any(map(line.endswith, ['&', '&\n']))) + for line in code ] + + level = 0 + cont_padding = 0 + tabwidth = 3 + new_code = [] + for i, line in enumerate(code): + if line in ('', '\n'): + new_code.append(line) + continue + level -= decrease[i] + + if free: + padding = " "*(level*tabwidth + cont_padding) + else: + padding = " "*level*tabwidth + + line = "%s%s" % (padding, line) + if not free: + line = self._pad_leading_columns([line])[0] + + new_code.append(line) + + if continuation[i]: + cont_padding = 2*tabwidth + else: + cont_padding = 0 + level += increase[i] + + if not free: + return self._wrap_fortran(new_code) + return new_code + + def _print_GoTo(self, goto): + if goto.expr: # computed goto + return "go to ({labels}), {expr}".format( + labels=', '.join((self._print(arg) for arg in goto.labels)), + expr=self._print(goto.expr) + ) + else: + lbl, = goto.labels + return "go to %s" % self._print(lbl) + + def _print_Program(self, prog): + return ( + "program {name}\n" + "{body}\n" + "end program\n" + ).format(**prog.kwargs(apply=lambda arg: self._print(arg))) + + def _print_Module(self, mod): + return ( + "module {name}\n" + "{declarations}\n" + "\ncontains\n\n" + "{definitions}\n" + "end module\n" + ).format(**mod.kwargs(apply=lambda arg: self._print(arg))) + + def _print_Stream(self, strm): + if strm.name == 'stdout' and self._settings["standard"] >= 2003: + self.module_uses['iso_c_binding'].add('stdint=>input_unit') + return 'input_unit' + elif strm.name == 'stderr' and self._settings["standard"] >= 2003: + self.module_uses['iso_c_binding'].add('stdint=>error_unit') + return 'error_unit' + else: + if strm.name == 'stdout': + return '*' + else: + return strm.name + + def _print_Print(self, ps): + if ps.format_string != None: # Must be '!= None', cannot be 'is not None' + fmt = self._print(ps.format_string) + else: + fmt = "*" + return "print {fmt}, {iolist}".format(fmt=fmt, iolist=', '.join( + (self._print(arg) for arg in ps.print_args))) + + def _print_Return(self, rs): + arg, = rs.args + return "{result_name} = {arg}".format( + result_name=self._context.get('result_name', 'sympy_result'), + arg=self._print(arg) + ) + + def _print_FortranReturn(self, frs): + arg, = frs.args + if arg: + return 'return %s' % self._print(arg) + else: + return 'return' + + def _head(self, entity, fp, **kwargs): + bind_C_params = fp.attr_params('bind_C') + if bind_C_params is None: + bind = '' + else: + bind = ' bind(C, name="%s")' % bind_C_params[0] if bind_C_params else ' bind(C)' + result_name = self._settings.get('result_name', None) + return ( + "{entity}{name}({arg_names}){result}{bind}\n" + "{arg_declarations}" + ).format( + entity=entity, + name=self._print(fp.name), + arg_names=', '.join([self._print(arg.symbol) for arg in fp.parameters]), + result=(' result(%s)' % result_name) if result_name else '', + bind=bind, + arg_declarations='\n'.join((self._print(Declaration(arg)) for arg in fp.parameters)) + ) + + def _print_FunctionPrototype(self, fp): + entity = "{} function ".format(self._print(fp.return_type)) + return ( + "interface\n" + "{function_head}\n" + "end function\n" + "end interface" + ).format(function_head=self._head(entity, fp)) + + def _print_FunctionDefinition(self, fd): + if elemental in fd.attrs: + prefix = 'elemental ' + elif pure in fd.attrs: + prefix = 'pure ' + else: + prefix = '' + + entity = "{} function ".format(self._print(fd.return_type)) + with printer_context(self, result_name=fd.name): + return ( + "{prefix}{function_head}\n" + "{body}\n" + "end function\n" + ).format( + prefix=prefix, + function_head=self._head(entity, fd), + body=self._print(fd.body) + ) + + def _print_Subroutine(self, sub): + return ( + '{subroutine_head}\n' + '{body}\n' + 'end subroutine\n' + ).format( + subroutine_head=self._head('subroutine ', sub), + body=self._print(sub.body) + ) + + def _print_SubroutineCall(self, scall): + return 'call {name}({args})'.format( + name=self._print(scall.name), + args=', '.join((self._print(arg) for arg in scall.subroutine_args)) + ) + + def _print_use_rename(self, rnm): + return "%s => %s" % tuple((self._print(arg) for arg in rnm.args)) + + def _print_use(self, use): + result = 'use %s' % self._print(use.namespace) + if use.rename != None: # Must be '!= None', cannot be 'is not None' + result += ', ' + ', '.join([self._print(rnm) for rnm in use.rename]) + if use.only != None: # Must be '!= None', cannot be 'is not None' + result += ', only: ' + ', '.join([self._print(nly) for nly in use.only]) + return result + + def _print_BreakToken(self, _): + return 'exit' + + def _print_ContinueToken(self, _): + return 'cycle' + + def _print_ArrayConstructor(self, ac): + fmtstr = "[%s]" if self._settings["standard"] >= 2003 else '(/%s/)' + return fmtstr % ', '.join((self._print(arg) for arg in ac.elements)) + + def _print_ArrayElement(self, elem): + return '{symbol}({idxs})'.format( + symbol=self._print(elem.name), + idxs=', '.join((self._print(arg) for arg in elem.indices)) + ) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/glsl.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/glsl.py new file mode 100644 index 0000000000000000000000000000000000000000..70669ccefc089bba868f2cdd5d9cba0034f4ec7a --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/glsl.py @@ -0,0 +1,557 @@ +from __future__ import annotations + +from sympy.core import Basic, S +from sympy.core.function import Lambda +from sympy.core.numbers import equal_valued +from sympy.printing.codeprinter import CodePrinter +from sympy.printing.precedence import precedence +from functools import reduce + +known_functions = { + 'Abs': 'abs', + 'sin': 'sin', + 'cos': 'cos', + 'tan': 'tan', + 'acos': 'acos', + 'asin': 'asin', + 'atan': 'atan', + 'atan2': 'atan', + 'ceiling': 'ceil', + 'floor': 'floor', + 'sign': 'sign', + 'exp': 'exp', + 'log': 'log', + 'add': 'add', + 'sub': 'sub', + 'mul': 'mul', + 'pow': 'pow' +} + +class GLSLPrinter(CodePrinter): + """ + Rudimentary, generic GLSL printing tools. + + Additional settings: + 'use_operators': Boolean (should the printer use operators for +,-,*, or functions?) + """ + _not_supported: set[Basic] = set() + printmethod = "_glsl" + language = "GLSL" + + _default_settings = { + 'use_operators': True, + 'zero': 0, + 'mat_nested': False, + 'mat_separator': ',\n', + 'mat_transpose': False, + 'array_type': 'float', + 'glsl_types': True, + + 'order': None, + 'full_prec': 'auto', + 'precision': 9, + 'user_functions': {}, + 'human': True, + 'allow_unknown_functions': False, + 'contract': True, + 'error_on_reserved': False, + 'reserved_word_suffix': '_', + } + + def __init__(self, settings={}): + CodePrinter.__init__(self, settings) + self.known_functions = dict(known_functions) + userfuncs = settings.get('user_functions', {}) + self.known_functions.update(userfuncs) + + def _rate_index_position(self, p): + return p*5 + + def _get_statement(self, codestring): + return "%s;" % codestring + + def _get_comment(self, text): + return "// {}".format(text) + + def _declare_number_const(self, name, value): + return "float {} = {};".format(name, value) + + def _format_code(self, lines): + return self.indent_code(lines) + + def indent_code(self, code): + """Accepts a string of code or a list of code lines""" + + if isinstance(code, str): + code_lines = self.indent_code(code.splitlines(True)) + return ''.join(code_lines) + + tab = " " + inc_token = ('{', '(', '{\n', '(\n') + dec_token = ('}', ')') + + code = [line.lstrip(' \t') for line in code] + + increase = [int(any(map(line.endswith, inc_token))) for line in code] + decrease = [int(any(map(line.startswith, dec_token))) for line in code] + + pretty = [] + level = 0 + for n, line in enumerate(code): + if line in ('', '\n'): + pretty.append(line) + continue + level -= decrease[n] + pretty.append("%s%s" % (tab*level, line)) + level += increase[n] + return pretty + + def _print_MatrixBase(self, mat): + mat_separator = self._settings['mat_separator'] + mat_transpose = self._settings['mat_transpose'] + column_vector = (mat.rows == 1) if mat_transpose else (mat.cols == 1) + A = mat.transpose() if mat_transpose != column_vector else mat + + glsl_types = self._settings['glsl_types'] + array_type = self._settings['array_type'] + array_size = A.cols*A.rows + array_constructor = "{}[{}]".format(array_type, array_size) + + if A.cols == 1: + return self._print(A[0]); + if A.rows <= 4 and A.cols <= 4 and glsl_types: + if A.rows == 1: + return "vec{}{}".format( + A.cols, A.table(self,rowstart='(',rowend=')') + ) + elif A.rows == A.cols: + return "mat{}({})".format( + A.rows, A.table(self,rowsep=', ', + rowstart='',rowend='') + ) + else: + return "mat{}x{}({})".format( + A.cols, A.rows, + A.table(self,rowsep=', ', + rowstart='',rowend='') + ) + elif S.One in A.shape: + return "{}({})".format( + array_constructor, + A.table(self,rowsep=mat_separator,rowstart='',rowend='') + ) + elif not self._settings['mat_nested']: + return "{}(\n{}\n) /* a {}x{} matrix */".format( + array_constructor, + A.table(self,rowsep=mat_separator,rowstart='',rowend=''), + A.rows, A.cols + ) + elif self._settings['mat_nested']: + return "{}[{}][{}](\n{}\n)".format( + array_type, A.rows, A.cols, + A.table(self,rowsep=mat_separator,rowstart='float[](',rowend=')') + ) + + def _print_SparseRepMatrix(self, mat): + # do not allow sparse matrices to be made dense + return self._print_not_supported(mat) + + def _traverse_matrix_indices(self, mat): + mat_transpose = self._settings['mat_transpose'] + if mat_transpose: + rows,cols = mat.shape + else: + cols,rows = mat.shape + return ((i, j) for i in range(cols) for j in range(rows)) + + def _print_MatrixElement(self, expr): + # print('begin _print_MatrixElement') + nest = self._settings['mat_nested']; + glsl_types = self._settings['glsl_types']; + mat_transpose = self._settings['mat_transpose']; + if mat_transpose: + cols,rows = expr.parent.shape + i,j = expr.j,expr.i + else: + rows,cols = expr.parent.shape + i,j = expr.i,expr.j + pnt = self._print(expr.parent) + if glsl_types and ((rows <= 4 and cols <=4) or nest): + return "{}[{}][{}]".format(pnt, i, j) + else: + return "{}[{}]".format(pnt, i + j*rows) + + def _print_list(self, expr): + l = ', '.join(self._print(item) for item in expr) + glsl_types = self._settings['glsl_types'] + array_type = self._settings['array_type'] + array_size = len(expr) + array_constructor = '{}[{}]'.format(array_type, array_size) + + if array_size <= 4 and glsl_types: + return 'vec{}({})'.format(array_size, l) + else: + return '{}({})'.format(array_constructor, l) + + _print_tuple = _print_list + _print_Tuple = _print_list + + def _get_loop_opening_ending(self, indices): + open_lines = [] + close_lines = [] + loopstart = "for (int %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){" + for i in indices: + # GLSL arrays start at 0 and end at dimension-1 + open_lines.append(loopstart % { + 'varble': self._print(i.label), + 'start': self._print(i.lower), + 'end': self._print(i.upper + 1)}) + close_lines.append("}") + return open_lines, close_lines + + def _print_Function_with_args(self, func, func_args): + if func in self.known_functions: + cond_func = self.known_functions[func] + func = None + if isinstance(cond_func, str): + func = cond_func + else: + for cond, func in cond_func: + if cond(func_args): + break + if func is not None: + try: + return func(*[self.parenthesize(item, 0) for item in func_args]) + except TypeError: + return '{}({})'.format(func, self.stringify(func_args, ", ")) + elif isinstance(func, Lambda): + # inlined function + return self._print(func(*func_args)) + else: + return self._print_not_supported(func) + + def _print_Piecewise(self, expr): + from sympy.codegen.ast import Assignment + if expr.args[-1].cond != True: + # We need the last conditional to be a True, otherwise the resulting + # function may not return a result. + raise ValueError("All Piecewise expressions must contain an " + "(expr, True) statement to be used as a default " + "condition. Without one, the generated " + "expression may not evaluate to anything under " + "some condition.") + lines = [] + if expr.has(Assignment): + for i, (e, c) in enumerate(expr.args): + if i == 0: + lines.append("if (%s) {" % self._print(c)) + elif i == len(expr.args) - 1 and c == True: + lines.append("else {") + else: + lines.append("else if (%s) {" % self._print(c)) + code0 = self._print(e) + lines.append(code0) + lines.append("}") + return "\n".join(lines) + else: + # The piecewise was used in an expression, need to do inline + # operators. This has the downside that inline operators will + # not work for statements that span multiple lines (Matrix or + # Indexed expressions). + ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), + self._print(e)) + for e, c in expr.args[:-1]] + last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr) + return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)]) + + def _print_Idx(self, expr): + return self._print(expr.label) + + def _print_Indexed(self, expr): + # calculate index for 1d array + dims = expr.shape + elem = S.Zero + offset = S.One + for i in reversed(range(expr.rank)): + elem += expr.indices[i]*offset + offset *= dims[i] + return "{}[{}]".format( + self._print(expr.base.label), + self._print(elem) + ) + + def _print_Pow(self, expr): + PREC = precedence(expr) + if equal_valued(expr.exp, -1): + return '1.0/%s' % (self.parenthesize(expr.base, PREC)) + elif equal_valued(expr.exp, 0.5): + return 'sqrt(%s)' % self._print(expr.base) + else: + try: + e = self._print(float(expr.exp)) + except TypeError: + e = self._print(expr.exp) + return self._print_Function_with_args('pow', ( + self._print(expr.base), + e + )) + + def _print_int(self, expr): + return str(float(expr)) + + def _print_Rational(self, expr): + return "{}.0/{}.0".format(expr.p, expr.q) + + def _print_Relational(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + op = expr.rel_op + return "{} {} {}".format(lhs_code, op, rhs_code) + + def _print_Add(self, expr, order=None): + if self._settings['use_operators']: + return CodePrinter._print_Add(self, expr, order=order) + + terms = expr.as_ordered_terms() + + def partition(p,l): + return reduce(lambda x, y: (x[0]+[y], x[1]) if p(y) else (x[0], x[1]+[y]), l, ([], [])) + def add(a,b): + return self._print_Function_with_args('add', (a, b)) + # return self.known_functions['add']+'(%s, %s)' % (a,b) + neg, pos = partition(lambda arg: arg.could_extract_minus_sign(), terms) + if pos: + s = pos = reduce(lambda a,b: add(a,b), (self._print(t) for t in pos)) + else: + s = pos = self._print(self._settings['zero']) + + if neg: + # sum the absolute values of the negative terms + neg = reduce(lambda a,b: add(a,b), (self._print(-n) for n in neg)) + # then subtract them from the positive terms + s = self._print_Function_with_args('sub', (pos,neg)) + # s = self.known_functions['sub']+'(%s, %s)' % (pos,neg) + return s + + def _print_Mul(self, expr, **kwargs): + if self._settings['use_operators']: + return CodePrinter._print_Mul(self, expr, **kwargs) + terms = expr.as_ordered_factors() + def mul(a,b): + # return self.known_functions['mul']+'(%s, %s)' % (a,b) + return self._print_Function_with_args('mul', (a,b)) + + s = reduce(lambda a,b: mul(a,b), (self._print(t) for t in terms)) + return s + +def glsl_code(expr,assign_to=None,**settings): + """Converts an expr to a string of GLSL code + + Parameters + ========== + + expr : Expr + A SymPy expression to be converted. + assign_to : optional + When given, the argument is used for naming the variable or variables + to which the expression is assigned. Can be a string, ``Symbol``, + ``MatrixSymbol`` or ``Indexed`` type object. In cases where ``expr`` + would be printed as an array, a list of string or ``Symbol`` objects + can also be passed. + + This is helpful in case of line-wrapping, or for expressions that + generate multi-line statements. It can also be used to spread an array-like + expression into multiple assignments. + use_operators: bool, optional + If set to False, then *,/,+,- operators will be replaced with functions + mul, add, and sub, which must be implemented by the user, e.g. for + implementing non-standard rings or emulated quad/octal precision. + [default=True] + glsl_types: bool, optional + Set this argument to ``False`` in order to avoid using the ``vec`` and ``mat`` + types. The printer will instead use arrays (or nested arrays). + [default=True] + mat_nested: bool, optional + GLSL version 4.3 and above support nested arrays (arrays of arrays). Set this to ``True`` + to render matrices as nested arrays. + [default=False] + mat_separator: str, optional + By default, matrices are rendered with newlines using this separator, + making them easier to read, but less compact. By removing the newline + this option can be used to make them more vertically compact. + [default=',\n'] + mat_transpose: bool, optional + GLSL's matrix multiplication implementation assumes column-major indexing. + By default, this printer ignores that convention. Setting this option to + ``True`` transposes all matrix output. + [default=False] + array_type: str, optional + The GLSL array constructor type. + [default='float'] + precision : integer, optional + The precision for numbers such as pi [default=15]. + user_functions : dict, optional + A dictionary where keys are ``FunctionClass`` instances and values are + their string representations. Alternatively, the dictionary value can + be a list of tuples i.e. [(argument_test, js_function_string)]. See + below for examples. + human : bool, optional + If True, the result is a single string that may contain some constant + declarations for the number symbols. If False, the same information is + returned in a tuple of (symbols_to_declare, not_supported_functions, + code_text). [default=True]. + contract: bool, optional + If True, ``Indexed`` instances are assumed to obey tensor contraction + rules and the corresponding nested loops over indices are generated. + Setting contract=False will not generate loops, instead the user is + responsible to provide values for the indices in the code. + [default=True]. + + Examples + ======== + + >>> from sympy import glsl_code, symbols, Rational, sin, ceiling, Abs + >>> x, tau = symbols("x, tau") + >>> glsl_code((2*tau)**Rational(7, 2)) + '8*sqrt(2)*pow(tau, 3.5)' + >>> glsl_code(sin(x), assign_to="float y") + 'float y = sin(x);' + + Various GLSL types are supported: + >>> from sympy import Matrix, glsl_code + >>> glsl_code(Matrix([1,2,3])) + 'vec3(1, 2, 3)' + + >>> glsl_code(Matrix([[1, 2],[3, 4]])) + 'mat2(1, 2, 3, 4)' + + Pass ``mat_transpose = True`` to switch to column-major indexing: + >>> glsl_code(Matrix([[1, 2],[3, 4]]), mat_transpose = True) + 'mat2(1, 3, 2, 4)' + + By default, larger matrices get collapsed into float arrays: + >>> print(glsl_code( Matrix([[1,2,3,4,5],[6,7,8,9,10]]) )) + float[10]( + 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10 + ) /* a 2x5 matrix */ + + The type of array constructor used to print GLSL arrays can be controlled + via the ``array_type`` parameter: + >>> glsl_code(Matrix([1,2,3,4,5]), array_type='int') + 'int[5](1, 2, 3, 4, 5)' + + Passing a list of strings or ``symbols`` to the ``assign_to`` parameter will yield + a multi-line assignment for each item in an array-like expression: + >>> x_struct_members = symbols('x.a x.b x.c x.d') + >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=x_struct_members)) + x.a = 1; + x.b = 2; + x.c = 3; + x.d = 4; + + This could be useful in cases where it's desirable to modify members of a + GLSL ``Struct``. It could also be used to spread items from an array-like + expression into various miscellaneous assignments: + >>> misc_assignments = ('x[0]', 'x[1]', 'float y', 'float z') + >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=misc_assignments)) + x[0] = 1; + x[1] = 2; + float y = 3; + float z = 4; + + Passing ``mat_nested = True`` instead prints out nested float arrays, which are + supported in GLSL 4.3 and above. + >>> mat = Matrix([ + ... [ 0, 1, 2], + ... [ 3, 4, 5], + ... [ 6, 7, 8], + ... [ 9, 10, 11], + ... [12, 13, 14]]) + >>> print(glsl_code( mat, mat_nested = True )) + float[5][3]( + float[]( 0, 1, 2), + float[]( 3, 4, 5), + float[]( 6, 7, 8), + float[]( 9, 10, 11), + float[](12, 13, 14) + ) + + + + Custom printing can be defined for certain types by passing a dictionary of + "type" : "function" to the ``user_functions`` kwarg. Alternatively, the + dictionary value can be a list of tuples i.e. [(argument_test, + js_function_string)]. + + >>> custom_functions = { + ... "ceiling": "CEIL", + ... "Abs": [(lambda x: not x.is_integer, "fabs"), + ... (lambda x: x.is_integer, "ABS")] + ... } + >>> glsl_code(Abs(x) + ceiling(x), user_functions=custom_functions) + 'fabs(x) + CEIL(x)' + + If further control is needed, addition, subtraction, multiplication and + division operators can be replaced with ``add``, ``sub``, and ``mul`` + functions. This is done by passing ``use_operators = False``: + + >>> x,y,z = symbols('x,y,z') + >>> glsl_code(x*(y+z), use_operators = False) + 'mul(x, add(y, z))' + >>> glsl_code(x*(y+z*(x-y)**z), use_operators = False) + 'mul(x, add(y, mul(z, pow(sub(x, y), z))))' + + ``Piecewise`` expressions are converted into conditionals. If an + ``assign_to`` variable is provided an if statement is created, otherwise + the ternary operator is used. Note that if the ``Piecewise`` lacks a + default term, represented by ``(expr, True)`` then an error will be thrown. + This is to prevent generating an expression that may not evaluate to + anything. + + >>> from sympy import Piecewise + >>> expr = Piecewise((x + 1, x > 0), (x, True)) + >>> print(glsl_code(expr, tau)) + if (x > 0) { + tau = x + 1; + } + else { + tau = x; + } + + Support for loops is provided through ``Indexed`` types. With + ``contract=True`` these expressions will be turned into loops, whereas + ``contract=False`` will just print the assignment expression that should be + looped over: + + >>> from sympy import Eq, IndexedBase, Idx + >>> len_y = 5 + >>> y = IndexedBase('y', shape=(len_y,)) + >>> t = IndexedBase('t', shape=(len_y,)) + >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) + >>> i = Idx('i', len_y-1) + >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) + >>> glsl_code(e.rhs, assign_to=e.lhs, contract=False) + 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' + + >>> from sympy import Matrix, MatrixSymbol + >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) + >>> A = MatrixSymbol('A', 3, 1) + >>> print(glsl_code(mat, A)) + A[0][0] = pow(x, 2.0); + if (x > 0) { + A[1][0] = x + 1; + } + else { + A[1][0] = x; + } + A[2][0] = sin(x); + """ + return GLSLPrinter(settings).doprint(expr,assign_to) + +def print_glsl(expr, **settings): + """Prints the GLSL representation of the given expression. + + See GLSLPrinter init function for settings. + """ + print(glsl_code(expr, **settings)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/gtk.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/gtk.py new file mode 100644 index 0000000000000000000000000000000000000000..4123d7231c730bbde28e33f441470c28b21c78d0 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/gtk.py @@ -0,0 +1,16 @@ +from sympy.printing.mathml import mathml +from sympy.utilities.mathml import c2p +import tempfile +import subprocess + + +def print_gtk(x, start_viewer=True): + """Print to Gtkmathview, a gtk widget capable of rendering MathML. + + Needs libgtkmathview-bin""" + with tempfile.NamedTemporaryFile('w') as file: + file.write(c2p(mathml(x), simple=True)) + file.flush() + + if start_viewer: + subprocess.check_call(('mathmlviewer', file.name)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/jscode.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/jscode.py new file mode 100644 index 0000000000000000000000000000000000000000..b214cbce3962ab085de48b17d2d4faac3dd01231 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/jscode.py @@ -0,0 +1,339 @@ +""" +Javascript code printer + +The JavascriptCodePrinter converts single SymPy expressions into single +Javascript expressions, using the functions defined in the Javascript +Math object where possible. + +""" + +from __future__ import annotations +from typing import Any + +from sympy.core import S +from sympy.core.numbers import equal_valued +from sympy.printing.codeprinter import CodePrinter +from sympy.printing.precedence import precedence, PRECEDENCE + + +# dictionary mapping SymPy function to (argument_conditions, Javascript_function). +# Used in JavascriptCodePrinter._print_Function(self) +known_functions = { + 'Abs': 'Math.abs', + 'acos': 'Math.acos', + 'acosh': 'Math.acosh', + 'asin': 'Math.asin', + 'asinh': 'Math.asinh', + 'atan': 'Math.atan', + 'atan2': 'Math.atan2', + 'atanh': 'Math.atanh', + 'ceiling': 'Math.ceil', + 'cos': 'Math.cos', + 'cosh': 'Math.cosh', + 'exp': 'Math.exp', + 'floor': 'Math.floor', + 'log': 'Math.log', + 'Max': 'Math.max', + 'Min': 'Math.min', + 'sign': 'Math.sign', + 'sin': 'Math.sin', + 'sinh': 'Math.sinh', + 'tan': 'Math.tan', + 'tanh': 'Math.tanh', +} + + +class JavascriptCodePrinter(CodePrinter): + """"A Printer to convert Python expressions to strings of JavaScript code + """ + printmethod = '_javascript' + language = 'JavaScript' + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'precision': 17, + 'user_functions': {}, + 'human': True, + 'allow_unknown_functions': False, + 'contract': True, + } + + def __init__(self, settings={}): + CodePrinter.__init__(self, settings) + self.known_functions = dict(known_functions) + userfuncs = settings.get('user_functions', {}) + self.known_functions.update(userfuncs) + + def _rate_index_position(self, p): + return p*5 + + def _get_statement(self, codestring): + return "%s;" % codestring + + def _get_comment(self, text): + return "// {}".format(text) + + def _declare_number_const(self, name, value): + return "var {} = {};".format(name, value.evalf(self._settings['precision'])) + + def _format_code(self, lines): + return self.indent_code(lines) + + def _traverse_matrix_indices(self, mat): + rows, cols = mat.shape + return ((i, j) for i in range(rows) for j in range(cols)) + + def _get_loop_opening_ending(self, indices): + open_lines = [] + close_lines = [] + loopstart = "for (var %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){" + for i in indices: + # Javascript arrays start at 0 and end at dimension-1 + open_lines.append(loopstart % { + 'varble': self._print(i.label), + 'start': self._print(i.lower), + 'end': self._print(i.upper + 1)}) + close_lines.append("}") + return open_lines, close_lines + + def _print_Pow(self, expr): + PREC = precedence(expr) + if equal_valued(expr.exp, -1): + return '1/%s' % (self.parenthesize(expr.base, PREC)) + elif equal_valued(expr.exp, 0.5): + return 'Math.sqrt(%s)' % self._print(expr.base) + elif expr.exp == S.One/3: + return 'Math.cbrt(%s)' % self._print(expr.base) + else: + return 'Math.pow(%s, %s)' % (self._print(expr.base), + self._print(expr.exp)) + + def _print_Rational(self, expr): + p, q = int(expr.p), int(expr.q) + return '%d/%d' % (p, q) + + def _print_Mod(self, expr): + num, den = expr.args + PREC = precedence(expr) + snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args] + # % is remainder (same sign as numerator), not modulo (same sign as + # denominator), in js. Hence, % only works as modulo if both numbers + # have the same sign + if (num.is_nonnegative and den.is_nonnegative or + num.is_nonpositive and den.is_nonpositive): + return f"{snum} % {sden}" + return f"(({snum} % {sden}) + {sden}) % {sden}" + + def _print_Relational(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + op = expr.rel_op + return "{} {} {}".format(lhs_code, op, rhs_code) + + def _print_Indexed(self, expr): + # calculate index for 1d array + dims = expr.shape + elem = S.Zero + offset = S.One + for i in reversed(range(expr.rank)): + elem += expr.indices[i]*offset + offset *= dims[i] + return "%s[%s]" % (self._print(expr.base.label), self._print(elem)) + + def _print_Idx(self, expr): + return self._print(expr.label) + + def _print_Exp1(self, expr): + return "Math.E" + + def _print_Pi(self, expr): + return 'Math.PI' + + def _print_Infinity(self, expr): + return 'Number.POSITIVE_INFINITY' + + def _print_NegativeInfinity(self, expr): + return 'Number.NEGATIVE_INFINITY' + + def _print_Piecewise(self, expr): + from sympy.codegen.ast import Assignment + if expr.args[-1].cond != True: + # We need the last conditional to be a True, otherwise the resulting + # function may not return a result. + raise ValueError("All Piecewise expressions must contain an " + "(expr, True) statement to be used as a default " + "condition. Without one, the generated " + "expression may not evaluate to anything under " + "some condition.") + lines = [] + if expr.has(Assignment): + for i, (e, c) in enumerate(expr.args): + if i == 0: + lines.append("if (%s) {" % self._print(c)) + elif i == len(expr.args) - 1 and c == True: + lines.append("else {") + else: + lines.append("else if (%s) {" % self._print(c)) + code0 = self._print(e) + lines.append(code0) + lines.append("}") + return "\n".join(lines) + else: + # The piecewise was used in an expression, need to do inline + # operators. This has the downside that inline operators will + # not work for statements that span multiple lines (Matrix or + # Indexed expressions). + ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e)) + for e, c in expr.args[:-1]] + last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr) + return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)]) + + def _print_MatrixElement(self, expr): + return "{}[{}]".format(self.parenthesize(expr.parent, + PRECEDENCE["Atom"], strict=True), + expr.j + expr.i*expr.parent.shape[1]) + + def indent_code(self, code): + """Accepts a string of code or a list of code lines""" + + if isinstance(code, str): + code_lines = self.indent_code(code.splitlines(True)) + return ''.join(code_lines) + + tab = " " + inc_token = ('{', '(', '{\n', '(\n') + dec_token = ('}', ')') + + code = [ line.lstrip(' \t') for line in code ] + + increase = [ int(any(map(line.endswith, inc_token))) for line in code ] + decrease = [ int(any(map(line.startswith, dec_token))) + for line in code ] + + pretty = [] + level = 0 + for n, line in enumerate(code): + if line in ('', '\n'): + pretty.append(line) + continue + level -= decrease[n] + pretty.append("%s%s" % (tab*level, line)) + level += increase[n] + return pretty + + +def jscode(expr, assign_to=None, **settings): + """Converts an expr to a string of javascript code + + Parameters + ========== + + expr : Expr + A SymPy expression to be converted. + assign_to : optional + When given, the argument is used as the name of the variable to which + the expression is assigned. Can be a string, ``Symbol``, + ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of + line-wrapping, or for expressions that generate multi-line statements. + precision : integer, optional + The precision for numbers such as pi [default=15]. + user_functions : dict, optional + A dictionary where keys are ``FunctionClass`` instances and values are + their string representations. Alternatively, the dictionary value can + be a list of tuples i.e. [(argument_test, js_function_string)]. See + below for examples. + human : bool, optional + If True, the result is a single string that may contain some constant + declarations for the number symbols. If False, the same information is + returned in a tuple of (symbols_to_declare, not_supported_functions, + code_text). [default=True]. + contract: bool, optional + If True, ``Indexed`` instances are assumed to obey tensor contraction + rules and the corresponding nested loops over indices are generated. + Setting contract=False will not generate loops, instead the user is + responsible to provide values for the indices in the code. + [default=True]. + + Examples + ======== + + >>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs + >>> x, tau = symbols("x, tau") + >>> jscode((2*tau)**Rational(7, 2)) + '8*Math.sqrt(2)*Math.pow(tau, 7/2)' + >>> jscode(sin(x), assign_to="s") + 's = Math.sin(x);' + + Custom printing can be defined for certain types by passing a dictionary of + "type" : "function" to the ``user_functions`` kwarg. Alternatively, the + dictionary value can be a list of tuples i.e. [(argument_test, + js_function_string)]. + + >>> custom_functions = { + ... "ceiling": "CEIL", + ... "Abs": [(lambda x: not x.is_integer, "fabs"), + ... (lambda x: x.is_integer, "ABS")] + ... } + >>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions) + 'fabs(x) + CEIL(x)' + + ``Piecewise`` expressions are converted into conditionals. If an + ``assign_to`` variable is provided an if statement is created, otherwise + the ternary operator is used. Note that if the ``Piecewise`` lacks a + default term, represented by ``(expr, True)`` then an error will be thrown. + This is to prevent generating an expression that may not evaluate to + anything. + + >>> from sympy import Piecewise + >>> expr = Piecewise((x + 1, x > 0), (x, True)) + >>> print(jscode(expr, tau)) + if (x > 0) { + tau = x + 1; + } + else { + tau = x; + } + + Support for loops is provided through ``Indexed`` types. With + ``contract=True`` these expressions will be turned into loops, whereas + ``contract=False`` will just print the assignment expression that should be + looped over: + + >>> from sympy import Eq, IndexedBase, Idx + >>> len_y = 5 + >>> y = IndexedBase('y', shape=(len_y,)) + >>> t = IndexedBase('t', shape=(len_y,)) + >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) + >>> i = Idx('i', len_y-1) + >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) + >>> jscode(e.rhs, assign_to=e.lhs, contract=False) + 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' + + Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions + must be provided to ``assign_to``. Note that any expression that can be + generated normally can also exist inside a Matrix: + + >>> from sympy import Matrix, MatrixSymbol + >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) + >>> A = MatrixSymbol('A', 3, 1) + >>> print(jscode(mat, A)) + A[0] = Math.pow(x, 2); + if (x > 0) { + A[1] = x + 1; + } + else { + A[1] = x; + } + A[2] = Math.sin(x); + """ + + return JavascriptCodePrinter(settings).doprint(expr, assign_to) + + +def print_jscode(expr, **settings): + """Prints the Javascript representation of the given expression. + + See jscode for the meaning of the optional arguments. + """ + print(jscode(expr, **settings)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/julia.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/julia.py new file mode 100644 index 0000000000000000000000000000000000000000..da12681f270356959185d87aca3f7614c64def6f --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/julia.py @@ -0,0 +1,658 @@ +""" +Julia code printer + +The `JuliaCodePrinter` converts SymPy expressions into Julia expressions. + +A complete code generator, which uses `julia_code` extensively, can be found +in `sympy.utilities.codegen`. The `codegen` module can be used to generate +complete source code files. + +""" + +from __future__ import annotations +from typing import Any + +from sympy.core import Mul, Pow, S, Rational +from sympy.core.mul import _keep_coeff +from sympy.core.numbers import equal_valued +from sympy.printing.codeprinter import CodePrinter +from sympy.printing.precedence import precedence, PRECEDENCE +from re import search + +# List of known functions. First, those that have the same name in +# SymPy and Julia. This is almost certainly incomplete! +known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc", + "asin", "acos", "atan", "acot", "asec", "acsc", + "sinh", "cosh", "tanh", "coth", "sech", "csch", + "asinh", "acosh", "atanh", "acoth", "asech", "acsch", + "sinc", "atan2", "sign", "floor", "log", "exp", + "cbrt", "sqrt", "erf", "erfc", "erfi", + "factorial", "gamma", "digamma", "trigamma", + "polygamma", "beta", + "airyai", "airyaiprime", "airybi", "airybiprime", + "besselj", "bessely", "besseli", "besselk", + "erfinv", "erfcinv"] +# These functions have different names ("SymPy": "Julia"), more +# generally a mapping to (argument_conditions, julia_function). +known_fcns_src2 = { + "Abs": "abs", + "ceiling": "ceil", + "conjugate": "conj", + "hankel1": "hankelh1", + "hankel2": "hankelh2", + "im": "imag", + "re": "real" +} + + +class JuliaCodePrinter(CodePrinter): + """ + A printer to convert expressions to strings of Julia code. + """ + printmethod = "_julia" + language = "Julia" + + _operators = { + 'and': '&&', + 'or': '||', + 'not': '!', + } + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'precision': 17, + 'user_functions': {}, + 'human': True, + 'allow_unknown_functions': False, + 'contract': True, + 'inline': True, + } + # Note: contract is for expressing tensors as loops (if True), or just + # assignment (if False). FIXME: this should be looked a more carefully + # for Julia. + + def __init__(self, settings={}): + super().__init__(settings) + self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1)) + self.known_functions.update(dict(known_fcns_src2)) + userfuncs = settings.get('user_functions', {}) + self.known_functions.update(userfuncs) + + + def _rate_index_position(self, p): + return p*5 + + + def _get_statement(self, codestring): + return "%s" % codestring + + + def _get_comment(self, text): + return "# {}".format(text) + + + def _declare_number_const(self, name, value): + return "const {} = {}".format(name, value) + + + def _format_code(self, lines): + return self.indent_code(lines) + + + def _traverse_matrix_indices(self, mat): + # Julia uses Fortran order (column-major) + rows, cols = mat.shape + return ((i, j) for j in range(cols) for i in range(rows)) + + + def _get_loop_opening_ending(self, indices): + open_lines = [] + close_lines = [] + for i in indices: + # Julia arrays start at 1 and end at dimension + var, start, stop = map(self._print, + [i.label, i.lower + 1, i.upper + 1]) + open_lines.append("for %s = %s:%s" % (var, start, stop)) + close_lines.append("end") + return open_lines, close_lines + + + def _print_Mul(self, expr): + # print complex numbers nicely in Julia + if (expr.is_number and expr.is_imaginary and + expr.as_coeff_Mul()[0].is_integer): + return "%sim" % self._print(-S.ImaginaryUnit*expr) + + # cribbed from str.py + prec = precedence(expr) + + c, e = expr.as_coeff_Mul() + if c < 0: + expr = _keep_coeff(-c, e) + sign = "-" + else: + sign = "" + + a = [] # items in the numerator + b = [] # items that are in the denominator (if any) + + pow_paren = [] # Will collect all pow with more than one base element and exp = -1 + + if self.order not in ('old', 'none'): + args = expr.as_ordered_factors() + else: + # use make_args in case expr was something like -x -> x + args = Mul.make_args(expr) + + # Gather args for numerator/denominator + for item in args: + if (item.is_commutative and item.is_Pow and item.exp.is_Rational + and item.exp.is_negative): + if item.exp != -1: + b.append(Pow(item.base, -item.exp, evaluate=False)) + else: + if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160 + pow_paren.append(item) + b.append(Pow(item.base, -item.exp)) + elif item.is_Rational and item is not S.Infinity and item.p == 1: + # Save the Rational type in julia Unless the numerator is 1. + # For example: + # julia_code(Rational(3, 7)*x) --> (3 // 7) * x + # julia_code(x/3) --> x / 3 but not x * (1 // 3) + b.append(Rational(item.q)) + else: + a.append(item) + + a = a or [S.One] + + a_str = [self.parenthesize(x, prec) for x in a] + b_str = [self.parenthesize(x, prec) for x in b] + + # To parenthesize Pow with exp = -1 and having more than one Symbol + for item in pow_paren: + if item.base in b: + b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] + + # from here it differs from str.py to deal with "*" and ".*" + def multjoin(a, a_str): + # here we probably are assuming the constants will come first + r = a_str[0] + for i in range(1, len(a)): + mulsym = '*' if a[i-1].is_number else '.*' + r = "%s %s %s" % (r, mulsym, a_str[i]) + return r + + if not b: + return sign + multjoin(a, a_str) + elif len(b) == 1: + divsym = '/' if b[0].is_number else './' + return "%s %s %s" % (sign+multjoin(a, a_str), divsym, b_str[0]) + else: + divsym = '/' if all(bi.is_number for bi in b) else './' + return "%s %s (%s)" % (sign + multjoin(a, a_str), divsym, multjoin(b, b_str)) + + def _print_Relational(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + op = expr.rel_op + return "{} {} {}".format(lhs_code, op, rhs_code) + + def _print_Pow(self, expr): + powsymbol = '^' if all(x.is_number for x in expr.args) else '.^' + + PREC = precedence(expr) + + if equal_valued(expr.exp, 0.5): + return "sqrt(%s)" % self._print(expr.base) + + if expr.is_commutative: + if equal_valued(expr.exp, -0.5): + sym = '/' if expr.base.is_number else './' + return "1 %s sqrt(%s)" % (sym, self._print(expr.base)) + if equal_valued(expr.exp, -1): + sym = '/' if expr.base.is_number else './' + return "1 %s %s" % (sym, self.parenthesize(expr.base, PREC)) + + return '%s %s %s' % (self.parenthesize(expr.base, PREC), powsymbol, + self.parenthesize(expr.exp, PREC)) + + + def _print_MatPow(self, expr): + PREC = precedence(expr) + return '%s ^ %s' % (self.parenthesize(expr.base, PREC), + self.parenthesize(expr.exp, PREC)) + + + def _print_Pi(self, expr): + if self._settings["inline"]: + return "pi" + else: + return super()._print_NumberSymbol(expr) + + + def _print_ImaginaryUnit(self, expr): + return "im" + + + def _print_Exp1(self, expr): + if self._settings["inline"]: + return "e" + else: + return super()._print_NumberSymbol(expr) + + + def _print_EulerGamma(self, expr): + if self._settings["inline"]: + return "eulergamma" + else: + return super()._print_NumberSymbol(expr) + + + def _print_Catalan(self, expr): + if self._settings["inline"]: + return "catalan" + else: + return super()._print_NumberSymbol(expr) + + + def _print_GoldenRatio(self, expr): + if self._settings["inline"]: + return "golden" + else: + return super()._print_NumberSymbol(expr) + + + def _print_Assignment(self, expr): + from sympy.codegen.ast import Assignment + from sympy.functions.elementary.piecewise import Piecewise + from sympy.tensor.indexed import IndexedBase + # Copied from codeprinter, but remove special MatrixSymbol treatment + lhs = expr.lhs + rhs = expr.rhs + # We special case assignments that take multiple lines + if not self._settings["inline"] and isinstance(expr.rhs, Piecewise): + # Here we modify Piecewise so each expression is now + # an Assignment, and then continue on the print. + expressions = [] + conditions = [] + for (e, c) in rhs.args: + expressions.append(Assignment(lhs, e)) + conditions.append(c) + temp = Piecewise(*zip(expressions, conditions)) + return self._print(temp) + if self._settings["contract"] and (lhs.has(IndexedBase) or + rhs.has(IndexedBase)): + # Here we check if there is looping to be done, and if so + # print the required loops. + return self._doprint_loops(rhs, lhs) + else: + lhs_code = self._print(lhs) + rhs_code = self._print(rhs) + return self._get_statement("%s = %s" % (lhs_code, rhs_code)) + + + def _print_Infinity(self, expr): + return 'Inf' + + + def _print_NegativeInfinity(self, expr): + return '-Inf' + + + def _print_NaN(self, expr): + return 'NaN' + + + def _print_list(self, expr): + return 'Any[' + ', '.join(self._print(a) for a in expr) + ']' + + + def _print_tuple(self, expr): + if len(expr) == 1: + return "(%s,)" % self._print(expr[0]) + else: + return "(%s)" % self.stringify(expr, ", ") + _print_Tuple = _print_tuple + + + def _print_BooleanTrue(self, expr): + return "true" + + + def _print_BooleanFalse(self, expr): + return "false" + + + def _print_bool(self, expr): + return str(expr).lower() + + + # Could generate quadrature code for definite Integrals? + #_print_Integral = _print_not_supported + + + def _print_MatrixBase(self, A): + # Handle zero dimensions: + if S.Zero in A.shape: + return 'zeros(%s, %s)' % (A.rows, A.cols) + elif (A.rows, A.cols) == (1, 1): + return "[%s]" % A[0, 0] + elif A.rows == 1: + return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ') + elif A.cols == 1: + # note .table would unnecessarily equispace the rows + return "[%s]" % ", ".join([self._print(a) for a in A]) + return "[%s]" % A.table(self, rowstart='', rowend='', + rowsep=';\n', colsep=' ') + + + def _print_SparseRepMatrix(self, A): + from sympy.matrices import Matrix + L = A.col_list(); + # make row vectors of the indices and entries + I = Matrix([k[0] + 1 for k in L]) + J = Matrix([k[1] + 1 for k in L]) + AIJ = Matrix([k[2] for k in L]) + return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J), + self._print(AIJ), A.rows, A.cols) + + + def _print_MatrixElement(self, expr): + return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + + '[%s,%s]' % (expr.i + 1, expr.j + 1) + + + def _print_MatrixSlice(self, expr): + def strslice(x, lim): + l = x[0] + 1 + h = x[1] + step = x[2] + lstr = self._print(l) + hstr = 'end' if h == lim else self._print(h) + if step == 1: + if l == 1 and h == lim: + return ':' + if l == h: + return lstr + else: + return lstr + ':' + hstr + else: + return ':'.join((lstr, self._print(step), hstr)) + return (self._print(expr.parent) + '[' + + strslice(expr.rowslice, expr.parent.shape[0]) + ',' + + strslice(expr.colslice, expr.parent.shape[1]) + ']') + + + def _print_Indexed(self, expr): + inds = [ self._print(i) for i in expr.indices ] + return "%s[%s]" % (self._print(expr.base.label), ",".join(inds)) + + + def _print_Idx(self, expr): + return self._print(expr.label) + + + def _print_Identity(self, expr): + return "eye(%s)" % self._print(expr.shape[0]) + + def _print_HadamardProduct(self, expr): + return ' .* '.join([self.parenthesize(arg, precedence(expr)) + for arg in expr.args]) + + def _print_HadamardPower(self, expr): + PREC = precedence(expr) + return '.**'.join([ + self.parenthesize(expr.base, PREC), + self.parenthesize(expr.exp, PREC) + ]) + + def _print_Rational(self, expr): + if expr.q == 1: + return str(expr.p) + return "%s // %s" % (expr.p, expr.q) + + # Note: as of 2022, Julia doesn't have spherical Bessel functions + def _print_jn(self, expr): + from sympy.functions import sqrt, besselj + x = expr.argument + expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x) + return self._print(expr2) + + + def _print_yn(self, expr): + from sympy.functions import sqrt, bessely + x = expr.argument + expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x) + return self._print(expr2) + + + def _print_Piecewise(self, expr): + if expr.args[-1].cond != True: + # We need the last conditional to be a True, otherwise the resulting + # function may not return a result. + raise ValueError("All Piecewise expressions must contain an " + "(expr, True) statement to be used as a default " + "condition. Without one, the generated " + "expression may not evaluate to anything under " + "some condition.") + lines = [] + if self._settings["inline"]: + # Express each (cond, expr) pair in a nested Horner form: + # (condition) .* (expr) + (not cond) .* () + # Expressions that result in multiple statements won't work here. + ecpairs = ["({}) ? ({}) :".format + (self._print(c), self._print(e)) + for e, c in expr.args[:-1]] + elast = " (%s)" % self._print(expr.args[-1].expr) + pw = "\n".join(ecpairs) + elast + # Note: current need these outer brackets for 2*pw. Would be + # nicer to teach parenthesize() to do this for us when needed! + return "(" + pw + ")" + else: + for i, (e, c) in enumerate(expr.args): + if i == 0: + lines.append("if (%s)" % self._print(c)) + elif i == len(expr.args) - 1 and c == True: + lines.append("else") + else: + lines.append("elseif (%s)" % self._print(c)) + code0 = self._print(e) + lines.append(code0) + if i == len(expr.args) - 1: + lines.append("end") + return "\n".join(lines) + + def _print_MatMul(self, expr): + c, m = expr.as_coeff_mmul() + + sign = "" + if c.is_number: + re, im = c.as_real_imag() + if im.is_zero and re.is_negative: + expr = _keep_coeff(-c, m) + sign = "-" + elif re.is_zero and im.is_negative: + expr = _keep_coeff(-c, m) + sign = "-" + + return sign + ' * '.join( + (self.parenthesize(arg, precedence(expr)) for arg in expr.args) + ) + + + def indent_code(self, code): + """Accepts a string of code or a list of code lines""" + + # code mostly copied from ccode + if isinstance(code, str): + code_lines = self.indent_code(code.splitlines(True)) + return ''.join(code_lines) + + tab = " " + inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ') + dec_regex = ('^end$', '^elseif ', '^else$') + + # pre-strip left-space from the code + code = [ line.lstrip(' \t') for line in code ] + + increase = [ int(any(search(re, line) for re in inc_regex)) + for line in code ] + decrease = [ int(any(search(re, line) for re in dec_regex)) + for line in code ] + + pretty = [] + level = 0 + for n, line in enumerate(code): + if line in ('', '\n'): + pretty.append(line) + continue + level -= decrease[n] + pretty.append("%s%s" % (tab*level, line)) + level += increase[n] + return pretty + + +def julia_code(expr, assign_to=None, **settings): + r"""Converts `expr` to a string of Julia code. + + Parameters + ========== + + expr : Expr + A SymPy expression to be converted. + assign_to : optional + When given, the argument is used as the name of the variable to which + the expression is assigned. Can be a string, ``Symbol``, + ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for + expressions that generate multi-line statements. + precision : integer, optional + The precision for numbers such as pi [default=16]. + user_functions : dict, optional + A dictionary where keys are ``FunctionClass`` instances and values are + their string representations. Alternatively, the dictionary value can + be a list of tuples i.e. [(argument_test, cfunction_string)]. See + below for examples. + human : bool, optional + If True, the result is a single string that may contain some constant + declarations for the number symbols. If False, the same information is + returned in a tuple of (symbols_to_declare, not_supported_functions, + code_text). [default=True]. + contract: bool, optional + If True, ``Indexed`` instances are assumed to obey tensor contraction + rules and the corresponding nested loops over indices are generated. + Setting contract=False will not generate loops, instead the user is + responsible to provide values for the indices in the code. + [default=True]. + inline: bool, optional + If True, we try to create single-statement code instead of multiple + statements. [default=True]. + + Examples + ======== + + >>> from sympy import julia_code, symbols, sin, pi + >>> x = symbols('x') + >>> julia_code(sin(x).series(x).removeO()) + 'x .^ 5 / 120 - x .^ 3 / 6 + x' + + >>> from sympy import Rational, ceiling + >>> x, y, tau = symbols("x, y, tau") + >>> julia_code((2*tau)**Rational(7, 2)) + '8 * sqrt(2) * tau .^ (7 // 2)' + + Note that element-wise (Hadamard) operations are used by default between + symbols. This is because its possible in Julia to write "vectorized" + code. It is harmless if the values are scalars. + + >>> julia_code(sin(pi*x*y), assign_to="s") + 's = sin(pi * x .* y)' + + If you need a matrix product "*" or matrix power "^", you can specify the + symbol as a ``MatrixSymbol``. + + >>> from sympy import Symbol, MatrixSymbol + >>> n = Symbol('n', integer=True, positive=True) + >>> A = MatrixSymbol('A', n, n) + >>> julia_code(3*pi*A**3) + '(3 * pi) * A ^ 3' + + This class uses several rules to decide which symbol to use a product. + Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*". + A HadamardProduct can be used to specify componentwise multiplication ".*" + of two MatrixSymbols. There is currently there is no easy way to specify + scalar symbols, so sometimes the code might have some minor cosmetic + issues. For example, suppose x and y are scalars and A is a Matrix, then + while a human programmer might write "(x^2*y)*A^3", we generate: + + >>> julia_code(x**2*y*A**3) + '(x .^ 2 .* y) * A ^ 3' + + Matrices are supported using Julia inline notation. When using + ``assign_to`` with matrices, the name can be specified either as a string + or as a ``MatrixSymbol``. The dimensions must align in the latter case. + + >>> from sympy import Matrix, MatrixSymbol + >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) + >>> julia_code(mat, assign_to='A') + 'A = [x .^ 2 sin(x) ceil(x)]' + + ``Piecewise`` expressions are implemented with logical masking by default. + Alternatively, you can pass "inline=False" to use if-else conditionals. + Note that if the ``Piecewise`` lacks a default term, represented by + ``(expr, True)`` then an error will be thrown. This is to prevent + generating an expression that may not evaluate to anything. + + >>> from sympy import Piecewise + >>> pw = Piecewise((x + 1, x > 0), (x, True)) + >>> julia_code(pw, assign_to=tau) + 'tau = ((x > 0) ? (x + 1) : (x))' + + Note that any expression that can be generated normally can also exist + inside a Matrix: + + >>> mat = Matrix([[x**2, pw, sin(x)]]) + >>> julia_code(mat, assign_to='A') + 'A = [x .^ 2 ((x > 0) ? (x + 1) : (x)) sin(x)]' + + Custom printing can be defined for certain types by passing a dictionary of + "type" : "function" to the ``user_functions`` kwarg. Alternatively, the + dictionary value can be a list of tuples i.e., [(argument_test, + cfunction_string)]. This can be used to call a custom Julia function. + + >>> from sympy import Function + >>> f = Function('f') + >>> g = Function('g') + >>> custom_functions = { + ... "f": "existing_julia_fcn", + ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), + ... (lambda x: not x.is_Matrix, "my_fcn")] + ... } + >>> mat = Matrix([[1, x]]) + >>> julia_code(f(x) + g(x) + g(mat), user_functions=custom_functions) + 'existing_julia_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])' + + Support for loops is provided through ``Indexed`` types. With + ``contract=True`` these expressions will be turned into loops, whereas + ``contract=False`` will just print the assignment expression that should be + looped over: + + >>> from sympy import Eq, IndexedBase, Idx + >>> len_y = 5 + >>> y = IndexedBase('y', shape=(len_y,)) + >>> t = IndexedBase('t', shape=(len_y,)) + >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) + >>> i = Idx('i', len_y-1) + >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) + >>> julia_code(e.rhs, assign_to=e.lhs, contract=False) + 'Dy[i] = (y[i + 1] - y[i]) ./ (t[i + 1] - t[i])' + """ + return JuliaCodePrinter(settings).doprint(expr, assign_to) + + +def print_julia_code(expr, **settings): + """Prints the Julia representation of the given expression. + + See `julia_code` for the meaning of the optional arguments. + """ + print(julia_code(expr, **settings)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/lambdarepr.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/lambdarepr.py new file mode 100644 index 0000000000000000000000000000000000000000..87fa0988d138d54d68ab8aef1bbc0f27b243b472 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/lambdarepr.py @@ -0,0 +1,251 @@ +from .pycode import ( + PythonCodePrinter, + MpmathPrinter, +) +from .numpy import NumPyPrinter # NumPyPrinter is imported for backward compatibility +from sympy.core.sorting import default_sort_key + + +__all__ = [ + 'PythonCodePrinter', + 'MpmathPrinter', # MpmathPrinter is published for backward compatibility + 'NumPyPrinter', + 'LambdaPrinter', + 'NumPyPrinter', + 'IntervalPrinter', + 'lambdarepr', +] + + +class LambdaPrinter(PythonCodePrinter): + """ + This printer converts expressions into strings that can be used by + lambdify. + """ + printmethod = "_lambdacode" + + + def _print_And(self, expr): + result = ['('] + for arg in sorted(expr.args, key=default_sort_key): + result.extend(['(', self._print(arg), ')']) + result.append(' and ') + result = result[:-1] + result.append(')') + return ''.join(result) + + def _print_Or(self, expr): + result = ['('] + for arg in sorted(expr.args, key=default_sort_key): + result.extend(['(', self._print(arg), ')']) + result.append(' or ') + result = result[:-1] + result.append(')') + return ''.join(result) + + def _print_Not(self, expr): + result = ['(', 'not (', self._print(expr.args[0]), '))'] + return ''.join(result) + + def _print_BooleanTrue(self, expr): + return "True" + + def _print_BooleanFalse(self, expr): + return "False" + + def _print_ITE(self, expr): + result = [ + '((', self._print(expr.args[1]), + ') if (', self._print(expr.args[0]), + ') else (', self._print(expr.args[2]), '))' + ] + return ''.join(result) + + def _print_NumberSymbol(self, expr): + return str(expr) + + def _print_Pow(self, expr, **kwargs): + # XXX Temporary workaround. Should Python math printer be + # isolated from PythonCodePrinter? + return super(PythonCodePrinter, self)._print_Pow(expr, **kwargs) + + +# numexpr works by altering the string passed to numexpr.evaluate +# rather than by populating a namespace. Thus a special printer... +class NumExprPrinter(LambdaPrinter): + # key, value pairs correspond to SymPy name and numexpr name + # functions not appearing in this dict will raise a TypeError + printmethod = "_numexprcode" + + _numexpr_functions = { + 'sin' : 'sin', + 'cos' : 'cos', + 'tan' : 'tan', + 'asin': 'arcsin', + 'acos': 'arccos', + 'atan': 'arctan', + 'atan2' : 'arctan2', + 'sinh' : 'sinh', + 'cosh' : 'cosh', + 'tanh' : 'tanh', + 'asinh': 'arcsinh', + 'acosh': 'arccosh', + 'atanh': 'arctanh', + 'ln' : 'log', + 'log': 'log', + 'exp': 'exp', + 'sqrt' : 'sqrt', + 'Abs' : 'abs', + 'conjugate' : 'conj', + 'im' : 'imag', + 're' : 'real', + 'where' : 'where', + 'complex' : 'complex', + 'contains' : 'contains', + } + + module = 'numexpr' + + def _print_ImaginaryUnit(self, expr): + return '1j' + + def _print_seq(self, seq, delimiter=', '): + # simplified _print_seq taken from pretty.py + s = [self._print(item) for item in seq] + if s: + return delimiter.join(s) + else: + return "" + + def _print_Function(self, e): + func_name = e.func.__name__ + + nstr = self._numexpr_functions.get(func_name, None) + if nstr is None: + # check for implemented_function + if hasattr(e, '_imp_'): + return "(%s)" % self._print(e._imp_(*e.args)) + else: + raise TypeError("numexpr does not support function '%s'" % + func_name) + return "%s(%s)" % (nstr, self._print_seq(e.args)) + + def _print_Piecewise(self, expr): + "Piecewise function printer" + exprs = [self._print(arg.expr) for arg in expr.args] + conds = [self._print(arg.cond) for arg in expr.args] + # If [default_value, True] is a (expr, cond) sequence in a Piecewise object + # it will behave the same as passing the 'default' kwarg to select() + # *as long as* it is the last element in expr.args. + # If this is not the case, it may be triggered prematurely. + ans = [] + parenthesis_count = 0 + is_last_cond_True = False + for cond, expr in zip(conds, exprs): + if cond == 'True': + ans.append(expr) + is_last_cond_True = True + break + else: + ans.append('where(%s, %s, ' % (cond, expr)) + parenthesis_count += 1 + if not is_last_cond_True: + # See https://github.com/pydata/numexpr/issues/298 + # + # simplest way to put a nan but raises + # 'RuntimeWarning: invalid value encountered in log' + # + # There are other ways to do this such as + # + # >>> import numexpr as ne + # >>> nan = float('nan') + # >>> ne.evaluate('where(x < 0, -1, nan)', {'x': [-1, 2, 3], 'nan':nan}) + # array([-1., nan, nan]) + # + # That needs to be handled in the lambdified function though rather + # than here in the printer. + ans.append('log(-1)') + return ''.join(ans) + ')' * parenthesis_count + + def _print_ITE(self, expr): + from sympy.functions.elementary.piecewise import Piecewise + return self._print(expr.rewrite(Piecewise)) + + def blacklisted(self, expr): + raise TypeError("numexpr cannot be used with %s" % + expr.__class__.__name__) + + # blacklist all Matrix printing + _print_SparseRepMatrix = \ + _print_MutableSparseMatrix = \ + _print_ImmutableSparseMatrix = \ + _print_Matrix = \ + _print_DenseMatrix = \ + _print_MutableDenseMatrix = \ + _print_ImmutableMatrix = \ + _print_ImmutableDenseMatrix = \ + blacklisted + # blacklist some Python expressions + _print_list = \ + _print_tuple = \ + _print_Tuple = \ + _print_dict = \ + _print_Dict = \ + blacklisted + + def _print_NumExprEvaluate(self, expr): + evaluate = self._module_format(self.module +".evaluate") + return "%s('%s', truediv=True)" % (evaluate, self._print(expr.expr)) + + def doprint(self, expr): + from sympy.codegen.ast import CodegenAST + from sympy.codegen.pynodes import NumExprEvaluate + if not isinstance(expr, CodegenAST): + expr = NumExprEvaluate(expr) + return super().doprint(expr) + + def _print_Return(self, expr): + from sympy.codegen.pynodes import NumExprEvaluate + r, = expr.args + if not isinstance(r, NumExprEvaluate): + expr = expr.func(NumExprEvaluate(r)) + return super()._print_Return(expr) + + def _print_Assignment(self, expr): + from sympy.codegen.pynodes import NumExprEvaluate + lhs, rhs, *args = expr.args + if not isinstance(rhs, NumExprEvaluate): + expr = expr.func(lhs, NumExprEvaluate(rhs), *args) + return super()._print_Assignment(expr) + + def _print_CodeBlock(self, expr): + from sympy.codegen.ast import CodegenAST + from sympy.codegen.pynodes import NumExprEvaluate + args = [ arg if isinstance(arg, CodegenAST) else NumExprEvaluate(arg) for arg in expr.args ] + return super()._print_CodeBlock(self, expr.func(*args)) + + +class IntervalPrinter(MpmathPrinter, LambdaPrinter): + """Use ``lambda`` printer but print numbers as ``mpi`` intervals. """ + + def _print_Integer(self, expr): + return "mpi('%s')" % super(PythonCodePrinter, self)._print_Integer(expr) + + def _print_Rational(self, expr): + return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr) + + def _print_Half(self, expr): + return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr) + + def _print_Pow(self, expr): + return super(MpmathPrinter, self)._print_Pow(expr, rational=True) + + +for k in NumExprPrinter._numexpr_functions: + setattr(NumExprPrinter, '_print_%s' % k, NumExprPrinter._print_Function) + +def lambdarepr(expr, **settings): + """ + Returns a string usable for lambdifying. + """ + return LambdaPrinter(settings).doprint(expr) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/latex.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/latex.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2a9a6efade243c93b6cf9f950b514aad5cd224 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/latex.py @@ -0,0 +1,3277 @@ +""" +A Printer which converts an expression into its LaTeX equivalent. +""" +from __future__ import annotations +from typing import Any, Callable, TYPE_CHECKING + +import itertools + +from sympy.core import Add, Float, Mod, Mul, Number, S, Symbol, Expr +from sympy.core.alphabets import greeks +from sympy.core.containers import Tuple +from sympy.core.function import Function, AppliedUndef, Derivative +from sympy.core.operations import AssocOp +from sympy.core.power import Pow +from sympy.core.sorting import default_sort_key +from sympy.core.sympify import SympifyError +from sympy.logic.boolalg import true, BooleanTrue, BooleanFalse +from sympy.tensor.array import NDimArray + +# sympy.printing imports +from sympy.printing.precedence import precedence_traditional +from sympy.printing.printer import Printer, print_function +from sympy.printing.conventions import split_super_sub, requires_partial +from sympy.printing.precedence import precedence, PRECEDENCE + +from mpmath.libmp.libmpf import prec_to_dps, to_str as mlib_to_str + +from sympy.utilities.iterables import has_variety, sift + +import re + +if TYPE_CHECKING: + from sympy.vector.basisdependent import BasisDependent + +# Hand-picked functions which can be used directly in both LaTeX and MathJax +# Complete list at +# https://docs.mathjax.org/en/latest/tex.html#supported-latex-commands +# This variable only contains those functions which SymPy uses. +accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan', + 'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec', + 'csc', 'cot', 'coth', 're', 'im', 'frac', 'root', + 'arg', + ] + +tex_greek_dictionary = { + 'Alpha': r'\mathrm{A}', + 'Beta': r'\mathrm{B}', + 'Gamma': r'\Gamma', + 'Delta': r'\Delta', + 'Epsilon': r'\mathrm{E}', + 'Zeta': r'\mathrm{Z}', + 'Eta': r'\mathrm{H}', + 'Theta': r'\Theta', + 'Iota': r'\mathrm{I}', + 'Kappa': r'\mathrm{K}', + 'Lambda': r'\Lambda', + 'Mu': r'\mathrm{M}', + 'Nu': r'\mathrm{N}', + 'Xi': r'\Xi', + 'omicron': 'o', + 'Omicron': r'\mathrm{O}', + 'Pi': r'\Pi', + 'Rho': r'\mathrm{P}', + 'Sigma': r'\Sigma', + 'Tau': r'\mathrm{T}', + 'Upsilon': r'\Upsilon', + 'Phi': r'\Phi', + 'Chi': r'\mathrm{X}', + 'Psi': r'\Psi', + 'Omega': r'\Omega', + 'lamda': r'\lambda', + 'Lamda': r'\Lambda', + 'khi': r'\chi', + 'Khi': r'\mathrm{X}', + 'varepsilon': r'\varepsilon', + 'varkappa': r'\varkappa', + 'varphi': r'\varphi', + 'varpi': r'\varpi', + 'varrho': r'\varrho', + 'varsigma': r'\varsigma', + 'vartheta': r'\vartheta', +} + +other_symbols = {'aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar', + 'hslash', 'mho', 'wp'} + +# Variable name modifiers +modifier_dict: dict[str, Callable[[str], str]] = { + # Accents + 'mathring': lambda s: r'\mathring{'+s+r'}', + 'ddddot': lambda s: r'\ddddot{'+s+r'}', + 'dddot': lambda s: r'\dddot{'+s+r'}', + 'ddot': lambda s: r'\ddot{'+s+r'}', + 'dot': lambda s: r'\dot{'+s+r'}', + 'check': lambda s: r'\check{'+s+r'}', + 'breve': lambda s: r'\breve{'+s+r'}', + 'acute': lambda s: r'\acute{'+s+r'}', + 'grave': lambda s: r'\grave{'+s+r'}', + 'tilde': lambda s: r'\tilde{'+s+r'}', + 'hat': lambda s: r'\hat{'+s+r'}', + 'bar': lambda s: r'\bar{'+s+r'}', + 'vec': lambda s: r'\vec{'+s+r'}', + 'prime': lambda s: "{"+s+"}'", + 'prm': lambda s: "{"+s+"}'", + # Faces + 'bold': lambda s: r'\boldsymbol{'+s+r'}', + 'bm': lambda s: r'\boldsymbol{'+s+r'}', + 'cal': lambda s: r'\mathcal{'+s+r'}', + 'scr': lambda s: r'\mathscr{'+s+r'}', + 'frak': lambda s: r'\mathfrak{'+s+r'}', + # Brackets + 'norm': lambda s: r'\left\|{'+s+r'}\right\|', + 'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle', + 'abs': lambda s: r'\left|{'+s+r'}\right|', + 'mag': lambda s: r'\left|{'+s+r'}\right|', +} + +greek_letters_set = frozenset(greeks) + +_between_two_numbers_p = ( + re.compile(r'[0-9][} ]*$'), # search + re.compile(r'[0-9]'), # match +) + + +def latex_escape(s: str) -> str: + """ + Escape a string such that latex interprets it as plaintext. + + We cannot use verbatim easily with mathjax, so escaping is easier. + Rules from https://tex.stackexchange.com/a/34586/41112. + """ + s = s.replace('\\', r'\textbackslash') + for c in '&%$#_{}': + s = s.replace(c, '\\' + c) + s = s.replace('~', r'\textasciitilde') + s = s.replace('^', r'\textasciicircum') + return s + + +class LatexPrinter(Printer): + printmethod = "_latex" + + _default_settings: dict[str, Any] = { + "full_prec": False, + "fold_frac_powers": False, + "fold_func_brackets": False, + "fold_short_frac": None, + "inv_trig_style": "abbreviated", + "itex": False, + "ln_notation": False, + "long_frac_ratio": None, + "mat_delim": "[", + "mat_str": None, + "mode": "plain", + "mul_symbol": None, + "order": None, + "symbol_names": {}, + "root_notation": True, + "mat_symbol_style": "plain", + "imaginary_unit": "i", + "gothic_re_im": False, + "decimal_separator": "period", + "perm_cyclic": True, + "parenthesize_super": True, + "min": None, + "max": None, + "diff_operator": "d", + } + + def __init__(self, settings=None): + Printer.__init__(self, settings) + + if 'mode' in self._settings: + valid_modes = ['inline', 'plain', 'equation', + 'equation*'] + if self._settings['mode'] not in valid_modes: + raise ValueError("'mode' must be one of 'inline', 'plain', " + "'equation' or 'equation*'") + + if self._settings['fold_short_frac'] is None and \ + self._settings['mode'] == 'inline': + self._settings['fold_short_frac'] = True + + mul_symbol_table = { + None: r" ", + "ldot": r" \,.\, ", + "dot": r" \cdot ", + "times": r" \times " + } + try: + self._settings['mul_symbol_latex'] = \ + mul_symbol_table[self._settings['mul_symbol']] + except KeyError: + self._settings['mul_symbol_latex'] = \ + self._settings['mul_symbol'] + try: + self._settings['mul_symbol_latex_numbers'] = \ + mul_symbol_table[self._settings['mul_symbol'] or 'dot'] + except KeyError: + if (self._settings['mul_symbol'].strip() in + ['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']): + self._settings['mul_symbol_latex_numbers'] = \ + mul_symbol_table['dot'] + else: + self._settings['mul_symbol_latex_numbers'] = \ + self._settings['mul_symbol'] + + self._delim_dict = {'(': ')', '[': ']'} + + imaginary_unit_table = { + None: r"i", + "i": r"i", + "ri": r"\mathrm{i}", + "ti": r"\text{i}", + "j": r"j", + "rj": r"\mathrm{j}", + "tj": r"\text{j}", + } + imag_unit = self._settings['imaginary_unit'] + self._settings['imaginary_unit_latex'] = imaginary_unit_table.get(imag_unit, imag_unit) + + diff_operator_table = { + None: r"d", + "d": r"d", + "rd": r"\mathrm{d}", + "td": r"\text{d}", + } + diff_operator = self._settings['diff_operator'] + self._settings["diff_operator_latex"] = diff_operator_table.get(diff_operator, diff_operator) + + def _add_parens(self, s) -> str: + return r"\left({}\right)".format(s) + + # TODO: merge this with the above, which requires a lot of test changes + def _add_parens_lspace(self, s) -> str: + return r"\left( {}\right)".format(s) + + def parenthesize(self, item, level, is_neg=False, strict=False) -> str: + prec_val = precedence_traditional(item) + if is_neg and strict: + return self._add_parens(self._print(item)) + + if (prec_val < level) or ((not strict) and prec_val <= level): + return self._add_parens(self._print(item)) + else: + return self._print(item) + + def parenthesize_super(self, s): + """ + Protect superscripts in s + + If the parenthesize_super option is set, protect with parentheses, else + wrap in braces. + """ + if "^" in s: + if self._settings['parenthesize_super']: + return self._add_parens(s) + else: + return "{{{}}}".format(s) + return s + + def doprint(self, expr) -> str: + tex = Printer.doprint(self, expr) + + if self._settings['mode'] == 'plain': + return tex + elif self._settings['mode'] == 'inline': + return r"$%s$" % tex + elif self._settings['itex']: + return r"$$%s$$" % tex + else: + env_str = self._settings['mode'] + return r"\begin{%s}%s\end{%s}" % (env_str, tex, env_str) + + def _needs_brackets(self, expr) -> bool: + """ + Returns True if the expression needs to be wrapped in brackets when + printed, False otherwise. For example: a + b => True; a => False; + 10 => False; -10 => True. + """ + return not ((expr.is_Integer and expr.is_nonnegative) + or (expr.is_Atom and (expr is not S.NegativeOne + and expr.is_Rational is False))) + + def _needs_function_brackets(self, expr) -> bool: + """ + Returns True if the expression needs to be wrapped in brackets when + passed as an argument to a function, False otherwise. This is a more + liberal version of _needs_brackets, in that many expressions which need + to be wrapped in brackets when added/subtracted/raised to a power do + not need them when passed to a function. Such an example is a*b. + """ + if not self._needs_brackets(expr): + return False + else: + # Muls of the form a*b*c... can be folded + if expr.is_Mul and not self._mul_is_clean(expr): + return True + # Pows which don't need brackets can be folded + elif expr.is_Pow and not self._pow_is_clean(expr): + return True + # Add and Function always need brackets + elif expr.is_Add or expr.is_Function: + return True + else: + return False + + def _needs_mul_brackets(self, expr, first=False, last=False) -> bool: + """ + Returns True if the expression needs to be wrapped in brackets when + printed as part of a Mul, False otherwise. This is True for Add, + but also for some container objects that would not need brackets + when appearing last in a Mul, e.g. an Integral. ``last=True`` + specifies that this expr is the last to appear in a Mul. + ``first=True`` specifies that this expr is the first to appear in + a Mul. + """ + from sympy.concrete.products import Product + from sympy.concrete.summations import Sum + from sympy.integrals.integrals import Integral + + if expr.is_Mul: + if not first and expr.could_extract_minus_sign(): + return True + elif precedence_traditional(expr) < PRECEDENCE["Mul"]: + return True + elif expr.is_Relational: + return True + if expr.is_Piecewise: + return True + if any(expr.has(x) for x in (Mod,)): + return True + if (not last and + any(expr.has(x) for x in (Integral, Product, Sum))): + return True + + return False + + def _needs_add_brackets(self, expr) -> bool: + """ + Returns True if the expression needs to be wrapped in brackets when + printed as part of an Add, False otherwise. This is False for most + things. + """ + if expr.is_Relational: + return True + if any(expr.has(x) for x in (Mod,)): + return True + if expr.is_Add: + return True + return False + + def _mul_is_clean(self, expr) -> bool: + for arg in expr.args: + if arg.is_Function: + return False + return True + + def _pow_is_clean(self, expr) -> bool: + return not self._needs_brackets(expr.base) + + def _do_exponent(self, expr: str, exp): + if exp is not None: + return r"\left(%s\right)^{%s}" % (expr, exp) + else: + return expr + + def _print_Basic(self, expr): + name = self._deal_with_super_sub(expr.__class__.__name__) + if expr.args: + ls = [self._print(o) for o in expr.args] + s = r"\operatorname{{{}}}\left({}\right)" + return s.format(name, ", ".join(ls)) + else: + return r"\text{{{}}}".format(name) + + def _print_bool(self, e: bool | BooleanTrue | BooleanFalse): + return r"\text{%s}" % e + + _print_BooleanTrue = _print_bool + _print_BooleanFalse = _print_bool + + def _print_NoneType(self, e): + return r"\text{%s}" % e + + def _print_Add(self, expr, order=None): + terms = self._as_ordered_terms(expr, order=order) + + tex = "" + for i, term in enumerate(terms): + if i == 0: + pass + elif term.could_extract_minus_sign(): + tex += " - " + term = -term + else: + tex += " + " + term_tex = self._print(term) + if self._needs_add_brackets(term): + term_tex = r"\left(%s\right)" % term_tex + tex += term_tex + + return tex + + def _print_Cycle(self, expr): + from sympy.combinatorics.permutations import Permutation + if expr.size == 0: + return r"\left( \right)" + expr = Permutation(expr) + expr_perm = expr.cyclic_form + siz = expr.size + if expr.array_form[-1] == siz - 1: + expr_perm = expr_perm + [[siz - 1]] + term_tex = '' + for i in expr_perm: + term_tex += str(i).replace(',', r"\;") + term_tex = term_tex.replace('[', r"\left( ") + term_tex = term_tex.replace(']', r"\right)") + return term_tex + + def _print_Permutation(self, expr): + from sympy.combinatorics.permutations import Permutation + from sympy.utilities.exceptions import sympy_deprecation_warning + + perm_cyclic = Permutation.print_cyclic + if perm_cyclic is not None: + sympy_deprecation_warning( + f""" + Setting Permutation.print_cyclic is deprecated. Instead use + init_printing(perm_cyclic={perm_cyclic}). + """, + deprecated_since_version="1.6", + active_deprecations_target="deprecated-permutation-print_cyclic", + stacklevel=8, + ) + else: + perm_cyclic = self._settings.get("perm_cyclic", True) + + if perm_cyclic: + return self._print_Cycle(expr) + + if expr.size == 0: + return r"\left( \right)" + + lower = [self._print(arg) for arg in expr.array_form] + upper = [self._print(arg) for arg in range(len(lower))] + + row1 = " & ".join(upper) + row2 = " & ".join(lower) + mat = r" \\ ".join((row1, row2)) + return r"\begin{pmatrix} %s \end{pmatrix}" % mat + + + def _print_AppliedPermutation(self, expr): + perm, var = expr.args + return r"\sigma_{%s}(%s)" % (self._print(perm), self._print(var)) + + def _print_Float(self, expr): + # Based off of that in StrPrinter + dps = prec_to_dps(expr._prec) + strip = False if self._settings['full_prec'] else True + low = self._settings["min"] if "min" in self._settings else None + high = self._settings["max"] if "max" in self._settings else None + str_real = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) + + # Must always have a mul symbol (as 2.5 10^{20} just looks odd) + # thus we use the number separator + separator = self._settings['mul_symbol_latex_numbers'] + + if 'e' in str_real: + (mant, exp) = str_real.split('e') + + if exp[0] == '+': + exp = exp[1:] + if self._settings['decimal_separator'] == 'comma': + mant = mant.replace('.','{,}') + + return r"%s%s10^{%s}" % (mant, separator, exp) + elif str_real == "+inf": + return r"\infty" + elif str_real == "-inf": + return r"- \infty" + else: + if self._settings['decimal_separator'] == 'comma': + str_real = str_real.replace('.','{,}') + return str_real + + def _print_Cross(self, expr): + vec1 = expr._expr1 + vec2 = expr._expr2 + return r"%s \times %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']), + self.parenthesize(vec2, PRECEDENCE['Mul'])) + + def _print_Curl(self, expr): + vec = expr._expr + return r"\nabla\times %s" % self.parenthesize(vec, PRECEDENCE['Mul']) + + def _print_Divergence(self, expr): + vec = expr._expr + return r"\nabla\cdot %s" % self.parenthesize(vec, PRECEDENCE['Mul']) + + def _print_Dot(self, expr): + vec1 = expr._expr1 + vec2 = expr._expr2 + return r"%s \cdot %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']), + self.parenthesize(vec2, PRECEDENCE['Mul'])) + + def _print_Gradient(self, expr): + func = expr._expr + return r"\nabla %s" % self.parenthesize(func, PRECEDENCE['Mul']) + + def _print_Laplacian(self, expr): + func = expr._expr + return r"\Delta %s" % self.parenthesize(func, PRECEDENCE['Mul']) + + def _print_Mul(self, expr: Expr): + from sympy.simplify import fraction + separator: str = self._settings['mul_symbol_latex'] + numbersep: str = self._settings['mul_symbol_latex_numbers'] + + def convert(expr) -> str: + if not expr.is_Mul: + return str(self._print(expr)) + else: + if self.order not in ('old', 'none'): + args = expr.as_ordered_factors() + else: + args = list(expr.args) + + # If there are quantities or prefixes, append them at the back. + units, nonunits = sift(args, lambda x: (hasattr(x, "_scale_factor") or hasattr(x, "is_physical_constant")) or + (isinstance(x, Pow) and + hasattr(x.base, "is_physical_constant")), binary=True) + prefixes, units = sift(units, lambda x: hasattr(x, "_scale_factor"), binary=True) + return convert_args(nonunits + prefixes + units) + + def convert_args(args) -> str: + _tex = last_term_tex = "" + + for i, term in enumerate(args): + term_tex = self._print(term) + if not (hasattr(term, "_scale_factor") or hasattr(term, "is_physical_constant")): + if self._needs_mul_brackets(term, first=(i == 0), + last=(i == len(args) - 1)): + term_tex = r"\left(%s\right)" % term_tex + + if _between_two_numbers_p[0].search(last_term_tex) and \ + _between_two_numbers_p[1].match(str(term)): + # between two numbers + _tex += numbersep + elif _tex: + _tex += separator + elif _tex: + _tex += separator + + _tex += term_tex + last_term_tex = term_tex + return _tex + + # Check for unevaluated Mul. In this case we need to make sure the + # identities are visible, multiple Rational factors are not combined + # etc so we display in a straight-forward form that fully preserves all + # args and their order. + # XXX: _print_Pow calls this routine with instances of Pow... + if isinstance(expr, Mul): + args = expr.args + if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]): + return convert_args(args) + + include_parens = False + if expr.could_extract_minus_sign(): + expr = -expr + tex = "- " + if expr.is_Add: + tex += "(" + include_parens = True + else: + tex = "" + + numer, denom = fraction(expr, exact=True) + + if denom is S.One and Pow(1, -1, evaluate=False) not in expr.args: + # use the original expression here, since fraction() may have + # altered it when producing numer and denom + tex += convert(expr) + + else: + snumer = convert(numer) + sdenom = convert(denom) + ldenom = len(sdenom.split()) + ratio = self._settings['long_frac_ratio'] + if self._settings['fold_short_frac'] and ldenom <= 2 and \ + "^" not in sdenom: + # handle short fractions + if self._needs_mul_brackets(numer, last=False): + tex += r"\left(%s\right) / %s" % (snumer, sdenom) + else: + tex += r"%s / %s" % (snumer, sdenom) + elif ratio is not None and \ + len(snumer.split()) > ratio*ldenom: + # handle long fractions + if self._needs_mul_brackets(numer, last=True): + tex += r"\frac{1}{%s}%s\left(%s\right)" \ + % (sdenom, separator, snumer) + elif numer.is_Mul: + # split a long numerator + a = S.One + b = S.One + for x in numer.args: + if self._needs_mul_brackets(x, last=False) or \ + len(convert(a*x).split()) > ratio*ldenom or \ + (b.is_commutative is x.is_commutative is False): + b *= x + else: + a *= x + if self._needs_mul_brackets(b, last=True): + tex += r"\frac{%s}{%s}%s\left(%s\right)" \ + % (convert(a), sdenom, separator, convert(b)) + else: + tex += r"\frac{%s}{%s}%s%s" \ + % (convert(a), sdenom, separator, convert(b)) + else: + tex += r"\frac{1}{%s}%s%s" % (sdenom, separator, snumer) + else: + tex += r"\frac{%s}{%s}" % (snumer, sdenom) + + if include_parens: + tex += ")" + return tex + + def _print_AlgebraicNumber(self, expr): + if expr.is_aliased: + return self._print(expr.as_poly().as_expr()) + else: + return self._print(expr.as_expr()) + + def _print_PrimeIdeal(self, expr): + p = self._print(expr.p) + if expr.is_inert: + return rf'\left({p}\right)' + alpha = self._print(expr.alpha.as_expr()) + return rf'\left({p}, {alpha}\right)' + + def _print_Pow(self, expr: Pow): + # Treat x**Rational(1,n) as special case + if expr.exp.is_Rational: + p: int = expr.exp.p # type: ignore + q: int = expr.exp.q # type: ignore + if abs(p) == 1 and q != 1 and self._settings['root_notation']: + base = self._print(expr.base) + if q == 2: + tex = r"\sqrt{%s}" % base + elif self._settings['itex']: + tex = r"\root{%d}{%s}" % (q, base) + else: + tex = r"\sqrt[%d]{%s}" % (q, base) + if expr.exp.is_negative: + return r"\frac{1}{%s}" % tex + else: + return tex + elif self._settings['fold_frac_powers'] and q != 1: + base = self.parenthesize(expr.base, PRECEDENCE['Pow']) + # issue #12886: add parentheses for superscripts raised to powers + if expr.base.is_Symbol: + base = self.parenthesize_super(base) + if expr.base.is_Function: + return self._print(expr.base, exp="%s/%s" % (p, q)) + return r"%s^{%s/%s}" % (base, p, q) + elif expr.exp.is_negative and expr.base.is_commutative: + # special case for 1^(-x), issue 9216 + if expr.base == 1: + return r"%s^{%s}" % (expr.base, expr.exp) + # special case for (1/x)^(-y) and (-1/-x)^(-y), issue 20252 + if expr.base.is_Rational: + base_p: int = expr.base.p # type: ignore + base_q: int = expr.base.q # type: ignore + if base_p * base_q == abs(base_q): + if expr.exp == -1: + return r"\frac{1}{\frac{%s}{%s}}" % (base_p, base_q) + else: + return r"\frac{1}{(\frac{%s}{%s})^{%s}}" % (base_p, base_q, abs(expr.exp)) + # things like 1/x + return self._print_Mul(expr) + if expr.base.is_Function: + return self._print(expr.base, exp=self._print(expr.exp)) + tex = r"%s^{%s}" + return self._helper_print_standard_power(expr, tex) + + def _helper_print_standard_power(self, expr, template: str) -> str: + exp = self._print(expr.exp) + # issue #12886: add parentheses around superscripts raised + # to powers + base = self.parenthesize(expr.base, PRECEDENCE['Pow']) + if expr.base.is_Symbol: + base = self.parenthesize_super(base) + elif (isinstance(expr.base, Derivative) + and base.startswith(r'\left(') + and re.match(r'\\left\(\\d?d?dot', base) + and base.endswith(r'\right)')): + # don't use parentheses around dotted derivative + base = base[6: -7] # remove outermost added parens + return template % (base, exp) + + def _print_UnevaluatedExpr(self, expr): + return self._print(expr.args[0]) + + def _print_Sum(self, expr): + if len(expr.limits) == 1: + tex = r"\sum_{%s=%s}^{%s} " % \ + tuple([self._print(i) for i in expr.limits[0]]) + else: + def _format_ineq(l): + return r"%s \leq %s \leq %s" % \ + tuple([self._print(s) for s in (l[1], l[0], l[2])]) + + tex = r"\sum_{\substack{%s}} " % \ + str.join('\\\\', [_format_ineq(l) for l in expr.limits]) + + if isinstance(expr.function, Add): + tex += r"\left(%s\right)" % self._print(expr.function) + else: + tex += self._print(expr.function) + + return tex + + def _print_Product(self, expr): + if len(expr.limits) == 1: + tex = r"\prod_{%s=%s}^{%s} " % \ + tuple([self._print(i) for i in expr.limits[0]]) + else: + def _format_ineq(l): + return r"%s \leq %s \leq %s" % \ + tuple([self._print(s) for s in (l[1], l[0], l[2])]) + + tex = r"\prod_{\substack{%s}} " % \ + str.join('\\\\', [_format_ineq(l) for l in expr.limits]) + + if isinstance(expr.function, Add): + tex += r"\left(%s\right)" % self._print(expr.function) + else: + tex += self._print(expr.function) + + return tex + + def _print_BasisDependent(self, expr: 'BasisDependent'): + from sympy.vector import Vector + + o1: list[str] = [] + if expr == expr.zero: + return expr.zero._latex_form + if isinstance(expr, Vector): + items = expr.separate().items() + else: + items = [(0, expr)] + + for system, vect in items: + inneritems = list(vect.components.items()) + inneritems.sort(key=lambda x: x[0].__str__()) + for k, v in inneritems: + if v == 1: + o1.append(' + ' + k._latex_form) + elif v == -1: + o1.append(' - ' + k._latex_form) + else: + arg_str = r'\left(' + self._print(v) + r'\right)' + o1.append(' + ' + arg_str + k._latex_form) + + outstr = (''.join(o1)) + if outstr[1] != '-': + outstr = outstr[3:] + else: + outstr = outstr[1:] + return outstr + + def _print_Indexed(self, expr): + tex_base = self._print(expr.base) + tex = '{'+tex_base+'}'+'_{%s}' % ','.join( + map(self._print, expr.indices)) + return tex + + def _print_IndexedBase(self, expr): + return self._print(expr.label) + + def _print_Idx(self, expr): + label = self._print(expr.label) + if expr.upper is not None: + upper = self._print(expr.upper) + if expr.lower is not None: + lower = self._print(expr.lower) + else: + lower = self._print(S.Zero) + interval = '{lower}\\mathrel{{..}}\\nobreak {upper}'.format( + lower = lower, upper = upper) + return '{{{label}}}_{{{interval}}}'.format( + label = label, interval = interval) + #if no bounds are defined this just prints the label + return label + + def _print_Derivative(self, expr): + if requires_partial(expr.expr): + diff_symbol = r'\partial' + else: + diff_symbol = self._settings["diff_operator_latex"] + + tex = "" + dim = 0 + for x, num in reversed(expr.variable_count): + dim += num + if num == 1: + tex += r"%s %s" % (diff_symbol, self._print(x)) + else: + tex += r"%s %s^{%s}" % (diff_symbol, + self.parenthesize_super(self._print(x)), + self._print(num)) + + if dim == 1: + tex = r"\frac{%s}{%s}" % (diff_symbol, tex) + else: + tex = r"\frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex) + + if any(i.could_extract_minus_sign() for i in expr.args): + return r"%s %s" % (tex, self.parenthesize(expr.expr, + PRECEDENCE["Mul"], + is_neg=True, + strict=True)) + + return r"%s %s" % (tex, self.parenthesize(expr.expr, + PRECEDENCE["Mul"], + is_neg=False, + strict=True)) + + def _print_Subs(self, subs): + expr, old, new = subs.args + latex_expr = self._print(expr) + latex_old = (self._print(e) for e in old) + latex_new = (self._print(e) for e in new) + latex_subs = r'\\ '.join( + e[0] + '=' + e[1] for e in zip(latex_old, latex_new)) + return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr, + latex_subs) + + def _print_Integral(self, expr): + tex, symbols = "", [] + diff_symbol = self._settings["diff_operator_latex"] + + # Only up to \iiiint exists + if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits): + # Use len(expr.limits)-1 so that syntax highlighters don't think + # \" is an escaped quote + tex = r"\i" + "i"*(len(expr.limits) - 1) + "nt" + symbols = [r"\, %s%s" % (diff_symbol, self._print(symbol[0])) + for symbol in expr.limits] + + else: + for lim in reversed(expr.limits): + symbol = lim[0] + tex += r"\int" + + if len(lim) > 1: + if self._settings['mode'] != 'inline' \ + and not self._settings['itex']: + tex += r"\limits" + + if len(lim) == 3: + tex += "_{%s}^{%s}" % (self._print(lim[1]), + self._print(lim[2])) + if len(lim) == 2: + tex += "^{%s}" % (self._print(lim[1])) + + symbols.insert(0, r"\, %s%s" % (diff_symbol, self._print(symbol))) + + return r"%s %s%s" % (tex, self.parenthesize(expr.function, + PRECEDENCE["Mul"], + is_neg=any(i.could_extract_minus_sign() for i in expr.args), + strict=True), + "".join(symbols)) + + def _print_Limit(self, expr): + e, z, z0, dir = expr.args + + tex = r"\lim_{%s \to " % self._print(z) + if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity): + tex += r"%s}" % self._print(z0) + else: + tex += r"%s^%s}" % (self._print(z0), self._print(dir)) + + if isinstance(e, AssocOp): + return r"%s\left(%s\right)" % (tex, self._print(e)) + else: + return r"%s %s" % (tex, self._print(e)) + + def _hprint_Function(self, func: str) -> str: + r''' + Logic to decide how to render a function to latex + - if it is a recognized latex name, use the appropriate latex command + - if it is a single letter, excluding sub- and superscripts, just use that letter + - if it is a longer name, then put \operatorname{} around it and be + mindful of undercores in the name + ''' + func = self._deal_with_super_sub(func) + superscriptidx = func.find("^") + subscriptidx = func.find("_") + if func in accepted_latex_functions: + name = r"\%s" % func + elif len(func) == 1 or func.startswith('\\') or subscriptidx == 1 or superscriptidx == 1: + name = func + else: + if superscriptidx > 0 and subscriptidx > 0: + name = r"\operatorname{%s}%s" %( + func[:min(subscriptidx,superscriptidx)], + func[min(subscriptidx,superscriptidx):]) + elif superscriptidx > 0: + name = r"\operatorname{%s}%s" %( + func[:superscriptidx], + func[superscriptidx:]) + elif subscriptidx > 0: + name = r"\operatorname{%s}%s" %( + func[:subscriptidx], + func[subscriptidx:]) + else: + name = r"\operatorname{%s}" % func + return name + + def _print_Function(self, expr: Function, exp=None) -> str: + r''' + Render functions to LaTeX, handling functions that LaTeX knows about + e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...). + For single-letter function names, render them as regular LaTeX math + symbols. For multi-letter function names that LaTeX does not know + about, (e.g., Li, sech) use \operatorname{} so that the function name + is rendered in Roman font and LaTeX handles spacing properly. + + expr is the expression involving the function + exp is an exponent + ''' + func = expr.func.__name__ + if hasattr(self, '_print_' + func) and \ + not isinstance(expr, AppliedUndef): + return getattr(self, '_print_' + func)(expr, exp) + else: + args = [str(self._print(arg)) for arg in expr.args] + # How inverse trig functions should be displayed, formats are: + # abbreviated: asin, full: arcsin, power: sin^-1 + inv_trig_style = self._settings['inv_trig_style'] + # If we are dealing with a power-style inverse trig function + inv_trig_power_case = False + # If it is applicable to fold the argument brackets + can_fold_brackets = self._settings['fold_func_brackets'] and \ + len(args) == 1 and \ + not self._needs_function_brackets(expr.args[0]) + + inv_trig_table = [ + "asin", "acos", "atan", + "acsc", "asec", "acot", + "asinh", "acosh", "atanh", + "acsch", "asech", "acoth", + ] + + # If the function is an inverse trig function, handle the style + if func in inv_trig_table: + if inv_trig_style == "abbreviated": + pass + elif inv_trig_style == "full": + func = ("ar" if func[-1] == "h" else "arc") + func[1:] + elif inv_trig_style == "power": + func = func[1:] + inv_trig_power_case = True + + # Can never fold brackets if we're raised to a power + if exp is not None: + can_fold_brackets = False + + if inv_trig_power_case: + if func in accepted_latex_functions: + name = r"\%s^{-1}" % func + else: + name = r"\operatorname{%s}^{-1}" % func + elif exp is not None: + func_tex = self._hprint_Function(func) + func_tex = self.parenthesize_super(func_tex) + name = r'%s^{%s}' % (func_tex, exp) + else: + name = self._hprint_Function(func) + + if can_fold_brackets: + if func in accepted_latex_functions: + # Wrap argument safely to avoid parse-time conflicts + # with the function name itself + name += r" {%s}" + else: + name += r"%s" + else: + name += r"{\left(%s \right)}" + + if inv_trig_power_case and exp is not None: + name += r"^{%s}" % exp + + return name % ",".join(args) + + def _print_UndefinedFunction(self, expr): + return self._hprint_Function(str(expr)) + + def _print_ElementwiseApplyFunction(self, expr): + return r"{%s}_{\circ}\left({%s}\right)" % ( + self._print(expr.function), + self._print(expr.expr), + ) + + @property + def _special_function_classes(self): + from sympy.functions.special.tensor_functions import KroneckerDelta + from sympy.functions.special.gamma_functions import gamma, lowergamma + from sympy.functions.special.beta_functions import beta + from sympy.functions.special.delta_functions import DiracDelta + from sympy.functions.special.error_functions import Chi + return {KroneckerDelta: r'\delta', + gamma: r'\Gamma', + lowergamma: r'\gamma', + beta: r'\operatorname{B}', + DiracDelta: r'\delta', + Chi: r'\operatorname{Chi}'} + + def _print_FunctionClass(self, expr): + for cls in self._special_function_classes: + if issubclass(expr, cls) and expr.__name__ == cls.__name__: + return self._special_function_classes[cls] + return self._hprint_Function(str(expr)) + + def _print_Lambda(self, expr): + symbols, expr = expr.args + + if len(symbols) == 1: + symbols = self._print(symbols[0]) + else: + symbols = self._print(tuple(symbols)) + + tex = r"\left( %s \mapsto %s \right)" % (symbols, self._print(expr)) + + return tex + + def _print_IdentityFunction(self, expr): + return r"\left( x \mapsto x \right)" + + def _hprint_variadic_function(self, expr, exp=None) -> str: + args = sorted(expr.args, key=default_sort_key) + texargs = [r"%s" % self._print(symbol) for symbol in args] + tex = r"\%s\left(%s\right)" % (str(expr.func).lower(), + ", ".join(texargs)) + if exp is not None: + return r"%s^{%s}" % (tex, exp) + else: + return tex + + _print_Min = _print_Max = _hprint_variadic_function + + def _print_floor(self, expr, exp=None): + tex = r"\left\lfloor{%s}\right\rfloor" % self._print(expr.args[0]) + + if exp is not None: + return r"%s^{%s}" % (tex, exp) + else: + return tex + + def _print_ceiling(self, expr, exp=None): + tex = r"\left\lceil{%s}\right\rceil" % self._print(expr.args[0]) + + if exp is not None: + return r"%s^{%s}" % (tex, exp) + else: + return tex + + def _print_log(self, expr, exp=None): + if not self._settings["ln_notation"]: + tex = r"\log{\left(%s \right)}" % self._print(expr.args[0]) + else: + tex = r"\ln{\left(%s \right)}" % self._print(expr.args[0]) + + if exp is not None: + return r"%s^{%s}" % (tex, exp) + else: + return tex + + def _print_Abs(self, expr, exp=None): + tex = r"\left|{%s}\right|" % self._print(expr.args[0]) + + if exp is not None: + return r"%s^{%s}" % (tex, exp) + else: + return tex + + def _print_re(self, expr, exp=None): + if self._settings['gothic_re_im']: + tex = r"\Re{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom']) + else: + tex = r"\operatorname{{re}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom'])) + + return self._do_exponent(tex, exp) + + def _print_im(self, expr, exp=None): + if self._settings['gothic_re_im']: + tex = r"\Im{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom']) + else: + tex = r"\operatorname{{im}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom'])) + + return self._do_exponent(tex, exp) + + def _print_Not(self, e): + from sympy.logic.boolalg import (Equivalent, Implies) + if isinstance(e.args[0], Equivalent): + return self._print_Equivalent(e.args[0], r"\not\Leftrightarrow") + if isinstance(e.args[0], Implies): + return self._print_Implies(e.args[0], r"\not\Rightarrow") + if (e.args[0].is_Boolean): + return r"\neg \left(%s\right)" % self._print(e.args[0]) + else: + return r"\neg %s" % self._print(e.args[0]) + + def _print_LogOp(self, args, char): + arg = args[0] + if arg.is_Boolean and not arg.is_Not: + tex = r"\left(%s\right)" % self._print(arg) + else: + tex = r"%s" % self._print(arg) + + for arg in args[1:]: + if arg.is_Boolean and not arg.is_Not: + tex += r" %s \left(%s\right)" % (char, self._print(arg)) + else: + tex += r" %s %s" % (char, self._print(arg)) + + return tex + + def _print_And(self, e): + args = sorted(e.args, key=default_sort_key) + return self._print_LogOp(args, r"\wedge") + + def _print_Or(self, e): + args = sorted(e.args, key=default_sort_key) + return self._print_LogOp(args, r"\vee") + + def _print_Xor(self, e): + args = sorted(e.args, key=default_sort_key) + return self._print_LogOp(args, r"\veebar") + + def _print_Implies(self, e, altchar=None): + return self._print_LogOp(e.args, altchar or r"\Rightarrow") + + def _print_Equivalent(self, e, altchar=None): + args = sorted(e.args, key=default_sort_key) + return self._print_LogOp(args, altchar or r"\Leftrightarrow") + + def _print_conjugate(self, expr, exp=None): + tex = r"\overline{%s}" % self._print(expr.args[0]) + + if exp is not None: + return r"%s^{%s}" % (tex, exp) + else: + return tex + + def _print_polar_lift(self, expr, exp=None): + func = r"\operatorname{polar\_lift}" + arg = r"{\left(%s \right)}" % self._print(expr.args[0]) + + if exp is not None: + return r"%s^{%s}%s" % (func, exp, arg) + else: + return r"%s%s" % (func, arg) + + def _print_ExpBase(self, expr, exp=None): + # TODO should exp_polar be printed differently? + # what about exp_polar(0), exp_polar(1)? + tex = r"e^{%s}" % self._print(expr.args[0]) + return self._do_exponent(tex, exp) + + def _print_Exp1(self, expr, exp=None): + return "e" + + def _print_elliptic_k(self, expr, exp=None): + tex = r"\left(%s\right)" % self._print(expr.args[0]) + if exp is not None: + return r"K^{%s}%s" % (exp, tex) + else: + return r"K%s" % tex + + def _print_elliptic_f(self, expr, exp=None): + tex = r"\left(%s\middle| %s\right)" % \ + (self._print(expr.args[0]), self._print(expr.args[1])) + if exp is not None: + return r"F^{%s}%s" % (exp, tex) + else: + return r"F%s" % tex + + def _print_elliptic_e(self, expr, exp=None): + if len(expr.args) == 2: + tex = r"\left(%s\middle| %s\right)" % \ + (self._print(expr.args[0]), self._print(expr.args[1])) + else: + tex = r"\left(%s\right)" % self._print(expr.args[0]) + if exp is not None: + return r"E^{%s}%s" % (exp, tex) + else: + return r"E%s" % tex + + def _print_elliptic_pi(self, expr, exp=None): + if len(expr.args) == 3: + tex = r"\left(%s; %s\middle| %s\right)" % \ + (self._print(expr.args[0]), self._print(expr.args[1]), + self._print(expr.args[2])) + else: + tex = r"\left(%s\middle| %s\right)" % \ + (self._print(expr.args[0]), self._print(expr.args[1])) + if exp is not None: + return r"\Pi^{%s}%s" % (exp, tex) + else: + return r"\Pi%s" % tex + + def _print_beta(self, expr, exp=None): + x = expr.args[0] + # Deal with unevaluated single argument beta + y = expr.args[0] if len(expr.args) == 1 else expr.args[1] + tex = rf"\left({x}, {y}\right)" + + if exp is not None: + return r"\operatorname{B}^{%s}%s" % (exp, tex) + else: + return r"\operatorname{B}%s" % tex + + def _print_betainc(self, expr, exp=None, operator='B'): + largs = [self._print(arg) for arg in expr.args] + tex = r"\left(%s, %s\right)" % (largs[0], largs[1]) + + if exp is not None: + return r"\operatorname{%s}_{(%s, %s)}^{%s}%s" % (operator, largs[2], largs[3], exp, tex) + else: + return r"\operatorname{%s}_{(%s, %s)}%s" % (operator, largs[2], largs[3], tex) + + def _print_betainc_regularized(self, expr, exp=None): + return self._print_betainc(expr, exp, operator='I') + + def _print_uppergamma(self, expr, exp=None): + tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]), + self._print(expr.args[1])) + + if exp is not None: + return r"\Gamma^{%s}%s" % (exp, tex) + else: + return r"\Gamma%s" % tex + + def _print_lowergamma(self, expr, exp=None): + tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]), + self._print(expr.args[1])) + + if exp is not None: + return r"\gamma^{%s}%s" % (exp, tex) + else: + return r"\gamma%s" % tex + + def _hprint_one_arg_func(self, expr, exp=None) -> str: + tex = r"\left(%s\right)" % self._print(expr.args[0]) + + if exp is not None: + return r"%s^{%s}%s" % (self._print(expr.func), exp, tex) + else: + return r"%s%s" % (self._print(expr.func), tex) + + _print_gamma = _hprint_one_arg_func + + def _print_Chi(self, expr, exp=None): + tex = r"\left(%s\right)" % self._print(expr.args[0]) + + if exp is not None: + return r"\operatorname{Chi}^{%s}%s" % (exp, tex) + else: + return r"\operatorname{Chi}%s" % tex + + def _print_expint(self, expr, exp=None): + tex = r"\left(%s\right)" % self._print(expr.args[1]) + nu = self._print(expr.args[0]) + + if exp is not None: + return r"\operatorname{E}_{%s}^{%s}%s" % (nu, exp, tex) + else: + return r"\operatorname{E}_{%s}%s" % (nu, tex) + + def _print_fresnels(self, expr, exp=None): + tex = r"\left(%s\right)" % self._print(expr.args[0]) + + if exp is not None: + return r"S^{%s}%s" % (exp, tex) + else: + return r"S%s" % tex + + def _print_fresnelc(self, expr, exp=None): + tex = r"\left(%s\right)" % self._print(expr.args[0]) + + if exp is not None: + return r"C^{%s}%s" % (exp, tex) + else: + return r"C%s" % tex + + def _print_subfactorial(self, expr, exp=None): + tex = r"!%s" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) + + if exp is not None: + return r"\left(%s\right)^{%s}" % (tex, exp) + else: + return tex + + def _print_factorial(self, expr, exp=None): + tex = r"%s!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) + + if exp is not None: + return r"%s^{%s}" % (tex, exp) + else: + return tex + + def _print_factorial2(self, expr, exp=None): + tex = r"%s!!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) + + if exp is not None: + return r"%s^{%s}" % (tex, exp) + else: + return tex + + def _print_binomial(self, expr, exp=None): + tex = r"{\binom{%s}{%s}}" % (self._print(expr.args[0]), + self._print(expr.args[1])) + + if exp is not None: + return r"%s^{%s}" % (tex, exp) + else: + return tex + + def _print_RisingFactorial(self, expr, exp=None): + n, k = expr.args + base = r"%s" % self.parenthesize(n, PRECEDENCE['Func']) + + tex = r"{%s}^{\left(%s\right)}" % (base, self._print(k)) + + return self._do_exponent(tex, exp) + + def _print_FallingFactorial(self, expr, exp=None): + n, k = expr.args + sub = r"%s" % self.parenthesize(k, PRECEDENCE['Func']) + + tex = r"{\left(%s\right)}_{%s}" % (self._print(n), sub) + + return self._do_exponent(tex, exp) + + def _hprint_BesselBase(self, expr, exp, sym: str) -> str: + tex = r"%s" % (sym) + + need_exp = False + if exp is not None: + if tex.find('^') == -1: + tex = r"%s^{%s}" % (tex, exp) + else: + need_exp = True + + tex = r"%s_{%s}\left(%s\right)" % (tex, self._print(expr.order), + self._print(expr.argument)) + + if need_exp: + tex = self._do_exponent(tex, exp) + return tex + + def _hprint_vec(self, vec) -> str: + if not vec: + return "" + s = "" + for i in vec[:-1]: + s += "%s, " % self._print(i) + s += self._print(vec[-1]) + return s + + def _print_besselj(self, expr, exp=None): + return self._hprint_BesselBase(expr, exp, 'J') + + def _print_besseli(self, expr, exp=None): + return self._hprint_BesselBase(expr, exp, 'I') + + def _print_besselk(self, expr, exp=None): + return self._hprint_BesselBase(expr, exp, 'K') + + def _print_bessely(self, expr, exp=None): + return self._hprint_BesselBase(expr, exp, 'Y') + + def _print_yn(self, expr, exp=None): + return self._hprint_BesselBase(expr, exp, 'y') + + def _print_jn(self, expr, exp=None): + return self._hprint_BesselBase(expr, exp, 'j') + + def _print_hankel1(self, expr, exp=None): + return self._hprint_BesselBase(expr, exp, 'H^{(1)}') + + def _print_hankel2(self, expr, exp=None): + return self._hprint_BesselBase(expr, exp, 'H^{(2)}') + + def _print_hn1(self, expr, exp=None): + return self._hprint_BesselBase(expr, exp, 'h^{(1)}') + + def _print_hn2(self, expr, exp=None): + return self._hprint_BesselBase(expr, exp, 'h^{(2)}') + + def _hprint_airy(self, expr, exp=None, notation="") -> str: + tex = r"\left(%s\right)" % self._print(expr.args[0]) + + if exp is not None: + return r"%s^{%s}%s" % (notation, exp, tex) + else: + return r"%s%s" % (notation, tex) + + def _hprint_airy_prime(self, expr, exp=None, notation="") -> str: + tex = r"\left(%s\right)" % self._print(expr.args[0]) + + if exp is not None: + return r"{%s^\prime}^{%s}%s" % (notation, exp, tex) + else: + return r"%s^\prime%s" % (notation, tex) + + def _print_airyai(self, expr, exp=None): + return self._hprint_airy(expr, exp, 'Ai') + + def _print_airybi(self, expr, exp=None): + return self._hprint_airy(expr, exp, 'Bi') + + def _print_airyaiprime(self, expr, exp=None): + return self._hprint_airy_prime(expr, exp, 'Ai') + + def _print_airybiprime(self, expr, exp=None): + return self._hprint_airy_prime(expr, exp, 'Bi') + + def _print_hyper(self, expr, exp=None): + tex = r"{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}" \ + r"\middle| {%s} \right)}" % \ + (self._print(len(expr.ap)), self._print(len(expr.bq)), + self._hprint_vec(expr.ap), self._hprint_vec(expr.bq), + self._print(expr.argument)) + + if exp is not None: + tex = r"{%s}^{%s}" % (tex, exp) + return tex + + def _print_meijerg(self, expr, exp=None): + tex = r"{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\" \ + r"%s & %s \end{matrix} \middle| {%s} \right)}" % \ + (self._print(len(expr.ap)), self._print(len(expr.bq)), + self._print(len(expr.bm)), self._print(len(expr.an)), + self._hprint_vec(expr.an), self._hprint_vec(expr.aother), + self._hprint_vec(expr.bm), self._hprint_vec(expr.bother), + self._print(expr.argument)) + + if exp is not None: + tex = r"{%s}^{%s}" % (tex, exp) + return tex + + def _print_dirichlet_eta(self, expr, exp=None): + tex = r"\left(%s\right)" % self._print(expr.args[0]) + if exp is not None: + return r"\eta^{%s}%s" % (exp, tex) + return r"\eta%s" % tex + + def _print_zeta(self, expr, exp=None): + if len(expr.args) == 2: + tex = r"\left(%s, %s\right)" % tuple(map(self._print, expr.args)) + else: + tex = r"\left(%s\right)" % self._print(expr.args[0]) + if exp is not None: + return r"\zeta^{%s}%s" % (exp, tex) + return r"\zeta%s" % tex + + def _print_stieltjes(self, expr, exp=None): + if len(expr.args) == 2: + tex = r"_{%s}\left(%s\right)" % tuple(map(self._print, expr.args)) + else: + tex = r"_{%s}" % self._print(expr.args[0]) + if exp is not None: + return r"\gamma%s^{%s}" % (tex, exp) + return r"\gamma%s" % tex + + def _print_lerchphi(self, expr, exp=None): + tex = r"\left(%s, %s, %s\right)" % tuple(map(self._print, expr.args)) + if exp is None: + return r"\Phi%s" % tex + return r"\Phi^{%s}%s" % (exp, tex) + + def _print_polylog(self, expr, exp=None): + s, z = map(self._print, expr.args) + tex = r"\left(%s\right)" % z + if exp is None: + return r"\operatorname{Li}_{%s}%s" % (s, tex) + return r"\operatorname{Li}_{%s}^{%s}%s" % (s, exp, tex) + + def _print_jacobi(self, expr, exp=None): + n, a, b, x = map(self._print, expr.args) + tex = r"P_{%s}^{\left(%s,%s\right)}\left(%s\right)" % (n, a, b, x) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def _print_gegenbauer(self, expr, exp=None): + n, a, x = map(self._print, expr.args) + tex = r"C_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def _print_chebyshevt(self, expr, exp=None): + n, x = map(self._print, expr.args) + tex = r"T_{%s}\left(%s\right)" % (n, x) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def _print_chebyshevu(self, expr, exp=None): + n, x = map(self._print, expr.args) + tex = r"U_{%s}\left(%s\right)" % (n, x) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def _print_legendre(self, expr, exp=None): + n, x = map(self._print, expr.args) + tex = r"P_{%s}\left(%s\right)" % (n, x) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def _print_assoc_legendre(self, expr, exp=None): + n, a, x = map(self._print, expr.args) + tex = r"P_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def _print_hermite(self, expr, exp=None): + n, x = map(self._print, expr.args) + tex = r"H_{%s}\left(%s\right)" % (n, x) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def _print_laguerre(self, expr, exp=None): + n, x = map(self._print, expr.args) + tex = r"L_{%s}\left(%s\right)" % (n, x) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def _print_assoc_laguerre(self, expr, exp=None): + n, a, x = map(self._print, expr.args) + tex = r"L_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def _print_Ynm(self, expr, exp=None): + n, m, theta, phi = map(self._print, expr.args) + tex = r"Y_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def _print_Znm(self, expr, exp=None): + n, m, theta, phi = map(self._print, expr.args) + tex = r"Z_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi) + if exp is not None: + tex = r"\left(" + tex + r"\right)^{%s}" % (exp) + return tex + + def __print_mathieu_functions(self, character, args, prime=False, exp=None): + a, q, z = map(self._print, args) + sup = r"^{\prime}" if prime else "" + exp = "" if not exp else "^{%s}" % exp + return r"%s%s\left(%s, %s, %s\right)%s" % (character, sup, a, q, z, exp) + + def _print_mathieuc(self, expr, exp=None): + return self.__print_mathieu_functions("C", expr.args, exp=exp) + + def _print_mathieus(self, expr, exp=None): + return self.__print_mathieu_functions("S", expr.args, exp=exp) + + def _print_mathieucprime(self, expr, exp=None): + return self.__print_mathieu_functions("C", expr.args, prime=True, exp=exp) + + def _print_mathieusprime(self, expr, exp=None): + return self.__print_mathieu_functions("S", expr.args, prime=True, exp=exp) + + def _print_Rational(self, expr): + if expr.q != 1: + sign = "" + p = expr.p + if expr.p < 0: + sign = "- " + p = -p + if self._settings['fold_short_frac']: + return r"%s%d / %d" % (sign, p, expr.q) + return r"%s\frac{%d}{%d}" % (sign, p, expr.q) + else: + return self._print(expr.p) + + def _print_Order(self, expr): + s = self._print(expr.expr) + if expr.point and any(p != S.Zero for p in expr.point) or \ + len(expr.variables) > 1: + s += '; ' + if len(expr.variables) > 1: + s += self._print(expr.variables) + elif expr.variables: + s += self._print(expr.variables[0]) + s += r'\rightarrow ' + if len(expr.point) > 1: + s += self._print(expr.point) + else: + s += self._print(expr.point[0]) + return r"O\left(%s\right)" % s + + def _print_Symbol(self, expr: Symbol, style='plain'): + name: str = self._settings['symbol_names'].get(expr) + if name is not None: + return name + + return self._deal_with_super_sub(expr.name, style=style) + + _print_RandomSymbol = _print_Symbol + + def _deal_with_super_sub(self, string: str, style='plain') -> str: + if '{' in string: + name, supers, subs = string, [], [] + else: + name, supers, subs = split_super_sub(string) + + name = translate(name) + supers = [translate(sup) for sup in supers] + subs = [translate(sub) for sub in subs] + + # apply the style only to the name + if style == 'bold': + name = "\\mathbf{{{}}}".format(name) + + # glue all items together: + if supers: + name += "^{%s}" % " ".join(supers) + if subs: + name += "_{%s}" % " ".join(subs) + + return name + + def _print_Relational(self, expr): + if self._settings['itex']: + gt = r"\gt" + lt = r"\lt" + else: + gt = ">" + lt = "<" + + charmap = { + "==": "=", + ">": gt, + "<": lt, + ">=": r"\geq", + "<=": r"\leq", + "!=": r"\neq", + } + + return "%s %s %s" % (self._print(expr.lhs), + charmap[expr.rel_op], self._print(expr.rhs)) + + def _print_Piecewise(self, expr): + ecpairs = [r"%s & \text{for}\: %s" % (self._print(e), self._print(c)) + for e, c in expr.args[:-1]] + if expr.args[-1].cond == true: + ecpairs.append(r"%s & \text{otherwise}" % + self._print(expr.args[-1].expr)) + else: + ecpairs.append(r"%s & \text{for}\: %s" % + (self._print(expr.args[-1].expr), + self._print(expr.args[-1].cond))) + tex = r"\begin{cases} %s \end{cases}" + return tex % r" \\".join(ecpairs) + + def _print_matrix_contents(self, expr): + lines = [] + + for line in range(expr.rows): # horrible, should be 'rows' + lines.append(" & ".join([self._print(i) for i in expr[line, :]])) + + mat_str = self._settings['mat_str'] + if mat_str is None: + if self._settings['mode'] == 'inline': + mat_str = 'smallmatrix' + else: + if (expr.cols <= 10) is True: + mat_str = 'matrix' + else: + mat_str = 'array' + + out_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}' + out_str = out_str.replace('%MATSTR%', mat_str) + if mat_str == 'array': + out_str = out_str.replace('%s', '{' + 'c'*expr.cols + '}%s') + return out_str % r"\\".join(lines) + + def _print_MatrixBase(self, expr): + out_str = self._print_matrix_contents(expr) + if self._settings['mat_delim']: + left_delim = self._settings['mat_delim'] + right_delim = self._delim_dict[left_delim] + out_str = r'\left' + left_delim + out_str + \ + r'\right' + right_delim + return out_str + + def _print_MatrixElement(self, expr): + return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True)\ + + '_{%s, %s}' % (self._print(expr.i), self._print(expr.j)) + + def _print_MatrixSlice(self, expr): + def latexslice(x, dim): + x = list(x) + if x[2] == 1: + del x[2] + if x[0] == 0: + x[0] = None + if x[1] == dim: + x[1] = None + return ':'.join(self._print(xi) if xi is not None else '' for xi in x) + return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' + + latexslice(expr.rowslice, expr.parent.rows) + ', ' + + latexslice(expr.colslice, expr.parent.cols) + r'\right]') + + def _print_BlockMatrix(self, expr): + return self._print(expr.blocks) + + def _print_Transpose(self, expr): + mat = expr.arg + from sympy.matrices import MatrixSymbol, BlockMatrix + if (not isinstance(mat, MatrixSymbol) and + not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr): + return r"\left(%s\right)^{T}" % self._print(mat) + else: + s = self.parenthesize(mat, precedence_traditional(expr), True) + if '^' in s: + return r"\left(%s\right)^{T}" % s + else: + return "%s^{T}" % s + + def _print_Trace(self, expr): + mat = expr.arg + return r"\operatorname{tr}\left(%s \right)" % self._print(mat) + + def _print_Adjoint(self, expr): + mat = expr.arg + from sympy.matrices import MatrixSymbol, BlockMatrix + if (not isinstance(mat, MatrixSymbol) and + not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr): + return r"\left(%s\right)^{\dagger}" % self._print(mat) + else: + s = self.parenthesize(mat, precedence_traditional(expr), True) + if '^' in s: + return r"\left(%s\right)^{\dagger}" % s + else: + return r"%s^{\dagger}" % s + + def _print_MatMul(self, expr): + from sympy import MatMul + + # Parenthesize nested MatMul but not other types of Mul objects: + parens = lambda x: self._print(x) if isinstance(x, Mul) and not isinstance(x, MatMul) else \ + self.parenthesize(x, precedence_traditional(expr), False) + + args = list(expr.args) + if expr.could_extract_minus_sign(): + if args[0] == -1: + args = args[1:] + else: + args[0] = -args[0] + return '- ' + ' '.join(map(parens, args)) + else: + return ' '.join(map(parens, args)) + + def _print_Determinant(self, expr): + mat = expr.arg + if mat.is_MatrixExpr: + from sympy.matrices.expressions.blockmatrix import BlockMatrix + if isinstance(mat, BlockMatrix): + return r"\left|{%s}\right|" % self._print_matrix_contents(mat.blocks) + return r"\left|{%s}\right|" % self._print(mat) + return r"\left|{%s}\right|" % self._print_matrix_contents(mat) + + + def _print_Mod(self, expr, exp=None): + if exp is not None: + return r'\left(%s \bmod %s\right)^{%s}' % \ + (self.parenthesize(expr.args[0], PRECEDENCE['Mul'], + strict=True), + self.parenthesize(expr.args[1], PRECEDENCE['Mul'], + strict=True), + exp) + return r'%s \bmod %s' % (self.parenthesize(expr.args[0], + PRECEDENCE['Mul'], + strict=True), + self.parenthesize(expr.args[1], + PRECEDENCE['Mul'], + strict=True)) + + def _print_HadamardProduct(self, expr): + args = expr.args + prec = PRECEDENCE['Pow'] + parens = self.parenthesize + + return r' \circ '.join( + (parens(arg, prec, strict=True) for arg in args)) + + def _print_HadamardPower(self, expr): + if precedence_traditional(expr.exp) < PRECEDENCE["Mul"]: + template = r"%s^{\circ \left({%s}\right)}" + else: + template = r"%s^{\circ {%s}}" + return self._helper_print_standard_power(expr, template) + + def _print_KroneckerProduct(self, expr): + args = expr.args + prec = PRECEDENCE['Pow'] + parens = self.parenthesize + + return r' \otimes '.join( + (parens(arg, prec, strict=True) for arg in args)) + + def _print_MatPow(self, expr): + base, exp = expr.base, expr.exp + from sympy.matrices import MatrixSymbol + if not isinstance(base, MatrixSymbol) and base.is_MatrixExpr: + return "\\left(%s\\right)^{%s}" % (self._print(base), + self._print(exp)) + else: + base_str = self._print(base) + if '^' in base_str: + return r"\left(%s\right)^{%s}" % (base_str, self._print(exp)) + else: + return "%s^{%s}" % (base_str, self._print(exp)) + + def _print_MatrixSymbol(self, expr): + return self._print_Symbol(expr, style=self._settings[ + 'mat_symbol_style']) + + def _print_ZeroMatrix(self, Z): + return "0" if self._settings[ + 'mat_symbol_style'] == 'plain' else r"\mathbf{0}" + + def _print_OneMatrix(self, O): + return "1" if self._settings[ + 'mat_symbol_style'] == 'plain' else r"\mathbf{1}" + + def _print_Identity(self, I): + return r"\mathbb{I}" if self._settings[ + 'mat_symbol_style'] == 'plain' else r"\mathbf{I}" + + def _print_PermutationMatrix(self, P): + perm_str = self._print(P.args[0]) + return "P_{%s}" % perm_str + + def _print_NDimArray(self, expr: NDimArray): + + if expr.rank() == 0: + return self._print(expr[()]) + + mat_str = self._settings['mat_str'] + if mat_str is None: + if self._settings['mode'] == 'inline': + mat_str = 'smallmatrix' + else: + if (expr.rank() == 0) or (expr.shape[-1] <= 10): + mat_str = 'matrix' + else: + mat_str = 'array' + block_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}' + block_str = block_str.replace('%MATSTR%', mat_str) + if mat_str == 'array': + block_str= block_str.replace('%s','{}%s') + if self._settings['mat_delim']: + left_delim: str = self._settings['mat_delim'] + right_delim = self._delim_dict[left_delim] + block_str = r'\left' + left_delim + block_str + \ + r'\right' + right_delim + + if expr.rank() == 0: + return block_str % "" + + level_str: list[list[str]] = [[] for i in range(expr.rank() + 1)] + shape_ranges = [list(range(i)) for i in expr.shape] + for outer_i in itertools.product(*shape_ranges): + level_str[-1].append(self._print(expr[outer_i])) + even = True + for back_outer_i in range(expr.rank()-1, -1, -1): + if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]: + break + if even: + level_str[back_outer_i].append( + r" & ".join(level_str[back_outer_i+1])) + else: + level_str[back_outer_i].append( + block_str % (r"\\".join(level_str[back_outer_i+1]))) + if len(level_str[back_outer_i+1]) == 1: + level_str[back_outer_i][-1] = r"\left[" + \ + level_str[back_outer_i][-1] + r"\right]" + even = not even + level_str[back_outer_i+1] = [] + + out_str = level_str[0][0] + + if expr.rank() % 2 == 1: + out_str = block_str % out_str + + return out_str + + def _printer_tensor_indices(self, name, indices, index_map: dict): + out_str = self._print(name) + last_valence = None + prev_map = None + for index in indices: + new_valence = index.is_up + if ((index in index_map) or prev_map) and \ + last_valence == new_valence: + out_str += "," + if last_valence != new_valence: + if last_valence is not None: + out_str += "}" + if index.is_up: + out_str += "{}^{" + else: + out_str += "{}_{" + out_str += self._print(index.args[0]) + if index in index_map: + out_str += "=" + out_str += self._print(index_map[index]) + prev_map = True + else: + prev_map = False + last_valence = new_valence + if last_valence is not None: + out_str += "}" + return out_str + + def _print_Tensor(self, expr): + name = expr.args[0].args[0] + indices = expr.get_indices() + return self._printer_tensor_indices(name, indices, {}) + + def _print_TensorElement(self, expr): + name = expr.expr.args[0].args[0] + indices = expr.expr.get_indices() + index_map = expr.index_map + return self._printer_tensor_indices(name, indices, index_map) + + def _print_TensMul(self, expr): + # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" + sign, args = expr._get_args_for_traditional_printer() + return sign + "".join( + [self.parenthesize(arg, precedence(expr)) for arg in args] + ) + + def _print_TensAdd(self, expr): + a = [] + args = expr.args + for x in args: + a.append(self.parenthesize(x, precedence(expr))) + a.sort() + s = ' + '.join(a) + s = s.replace('+ -', '- ') + return s + + def _print_TensorIndex(self, expr): + return "{}%s{%s}" % ( + "^" if expr.is_up else "_", + self._print(expr.args[0]) + ) + + def _print_PartialDerivative(self, expr): + if len(expr.variables) == 1: + return r"\frac{\partial}{\partial {%s}}{%s}" % ( + self._print(expr.variables[0]), + self.parenthesize(expr.expr, PRECEDENCE["Mul"], False) + ) + else: + return r"\frac{\partial^{%s}}{%s}{%s}" % ( + len(expr.variables), + " ".join([r"\partial {%s}" % self._print(i) for i in expr.variables]), + self.parenthesize(expr.expr, PRECEDENCE["Mul"], False) + ) + + def _print_ArraySymbol(self, expr): + return self._print(expr.name) + + def _print_ArrayElement(self, expr): + return "{{%s}_{%s}}" % ( + self.parenthesize(expr.name, PRECEDENCE["Func"], True), + ", ".join([f"{self._print(i)}" for i in expr.indices])) + + def _print_UniversalSet(self, expr): + return r"\mathbb{U}" + + def _print_frac(self, expr, exp=None): + if exp is None: + return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0]) + else: + return r"\operatorname{frac}{\left(%s\right)}^{%s}" % ( + self._print(expr.args[0]), exp) + + def _print_tuple(self, expr): + if self._settings['decimal_separator'] == 'comma': + sep = ";" + elif self._settings['decimal_separator'] == 'period': + sep = "," + else: + raise ValueError('Unknown Decimal Separator') + + if len(expr) == 1: + # 1-tuple needs a trailing separator + return self._add_parens_lspace(self._print(expr[0]) + sep) + else: + return self._add_parens_lspace( + (sep + r" \ ").join([self._print(i) for i in expr])) + + def _print_TensorProduct(self, expr): + elements = [self._print(a) for a in expr.args] + return r' \otimes '.join(elements) + + def _print_WedgeProduct(self, expr): + elements = [self._print(a) for a in expr.args] + return r' \wedge '.join(elements) + + def _print_Tuple(self, expr): + return self._print_tuple(expr) + + def _print_list(self, expr): + if self._settings['decimal_separator'] == 'comma': + return r"\left[ %s\right]" % \ + r"; \ ".join([self._print(i) for i in expr]) + elif self._settings['decimal_separator'] == 'period': + return r"\left[ %s\right]" % \ + r", \ ".join([self._print(i) for i in expr]) + else: + raise ValueError('Unknown Decimal Separator') + + + def _print_dict(self, d): + keys = sorted(d.keys(), key=default_sort_key) + items = [] + + for key in keys: + val = d[key] + items.append("%s : %s" % (self._print(key), self._print(val))) + + return r"\left\{ %s\right\}" % r", \ ".join(items) + + def _print_Dict(self, expr): + return self._print_dict(expr) + + def _print_DiracDelta(self, expr, exp=None): + if len(expr.args) == 1 or expr.args[1] == 0: + tex = r"\delta\left(%s\right)" % self._print(expr.args[0]) + else: + tex = r"\delta^{\left( %s \right)}\left( %s \right)" % ( + self._print(expr.args[1]), self._print(expr.args[0])) + if exp: + tex = r"\left(%s\right)^{%s}" % (tex, exp) + return tex + + def _print_SingularityFunction(self, expr, exp=None): + shift = self._print(expr.args[0] - expr.args[1]) + power = self._print(expr.args[2]) + tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power) + if exp is not None: + tex = r"{\left({\langle %s \rangle}^{%s}\right)}^{%s}" % (shift, power, exp) + return tex + + def _print_Heaviside(self, expr, exp=None): + pargs = ', '.join(self._print(arg) for arg in expr.pargs) + tex = r"\theta\left(%s\right)" % pargs + if exp: + tex = r"\left(%s\right)^{%s}" % (tex, exp) + return tex + + def _print_KroneckerDelta(self, expr, exp=None): + i = self._print(expr.args[0]) + j = self._print(expr.args[1]) + if expr.args[0].is_Atom and expr.args[1].is_Atom: + tex = r'\delta_{%s %s}' % (i, j) + else: + tex = r'\delta_{%s, %s}' % (i, j) + if exp is not None: + tex = r'\left(%s\right)^{%s}' % (tex, exp) + return tex + + def _print_LeviCivita(self, expr, exp=None): + indices = map(self._print, expr.args) + if all(x.is_Atom for x in expr.args): + tex = r'\varepsilon_{%s}' % " ".join(indices) + else: + tex = r'\varepsilon_{%s}' % ", ".join(indices) + if exp: + tex = r'\left(%s\right)^{%s}' % (tex, exp) + return tex + + def _print_RandomDomain(self, d): + if hasattr(d, 'as_boolean'): + return '\\text{Domain: }' + self._print(d.as_boolean()) + elif hasattr(d, 'set'): + return ('\\text{Domain: }' + self._print(d.symbols) + ' \\in ' + + self._print(d.set)) + elif hasattr(d, 'symbols'): + return '\\text{Domain on }' + self._print(d.symbols) + else: + return self._print(None) + + def _print_FiniteSet(self, s): + items = sorted(s.args, key=default_sort_key) + return self._print_set(items) + + def _print_set(self, s): + items = sorted(s, key=default_sort_key) + if self._settings['decimal_separator'] == 'comma': + items = "; ".join(map(self._print, items)) + elif self._settings['decimal_separator'] == 'period': + items = ", ".join(map(self._print, items)) + else: + raise ValueError('Unknown Decimal Separator') + return r"\left\{%s\right\}" % items + + + _print_frozenset = _print_set + + def _print_Range(self, s): + def _print_symbolic_range(): + # Symbolic Range that cannot be resolved + if s.args[0] == 0: + if s.args[2] == 1: + cont = self._print(s.args[1]) + else: + cont = ", ".join(self._print(arg) for arg in s.args) + else: + if s.args[2] == 1: + cont = ", ".join(self._print(arg) for arg in s.args[:2]) + else: + cont = ", ".join(self._print(arg) for arg in s.args) + + return(f"\\text{{Range}}\\left({cont}\\right)") + + dots = object() + + if s.start.is_infinite and s.stop.is_infinite: + if s.step.is_positive: + printset = dots, -1, 0, 1, dots + else: + printset = dots, 1, 0, -1, dots + elif s.start.is_infinite: + printset = dots, s[-1] - s.step, s[-1] + elif s.stop.is_infinite: + it = iter(s) + printset = next(it), next(it), dots + elif s.is_empty is not None: + if (s.size < 4) == True: + printset = tuple(s) + elif s.is_iterable: + it = iter(s) + printset = next(it), next(it), dots, s[-1] + else: + return _print_symbolic_range() + else: + return _print_symbolic_range() + return (r"\left\{" + + r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) + + r"\right\}") + + def __print_number_polynomial(self, expr, letter, exp=None): + if len(expr.args) == 2: + if exp is not None: + return r"%s_{%s}^{%s}\left(%s\right)" % (letter, + self._print(expr.args[0]), exp, + self._print(expr.args[1])) + return r"%s_{%s}\left(%s\right)" % (letter, + self._print(expr.args[0]), self._print(expr.args[1])) + + tex = r"%s_{%s}" % (letter, self._print(expr.args[0])) + if exp is not None: + tex = r"%s^{%s}" % (tex, exp) + return tex + + def _print_bernoulli(self, expr, exp=None): + return self.__print_number_polynomial(expr, "B", exp) + + def _print_genocchi(self, expr, exp=None): + return self.__print_number_polynomial(expr, "G", exp) + + def _print_bell(self, expr, exp=None): + if len(expr.args) == 3: + tex1 = r"B_{%s, %s}" % (self._print(expr.args[0]), + self._print(expr.args[1])) + tex2 = r"\left(%s\right)" % r", ".join(self._print(el) for + el in expr.args[2]) + if exp is not None: + tex = r"%s^{%s}%s" % (tex1, exp, tex2) + else: + tex = tex1 + tex2 + return tex + return self.__print_number_polynomial(expr, "B", exp) + + def _print_fibonacci(self, expr, exp=None): + return self.__print_number_polynomial(expr, "F", exp) + + def _print_lucas(self, expr, exp=None): + tex = r"L_{%s}" % self._print(expr.args[0]) + if exp is not None: + tex = r"%s^{%s}" % (tex, exp) + return tex + + def _print_tribonacci(self, expr, exp=None): + return self.__print_number_polynomial(expr, "T", exp) + + def _print_SeqFormula(self, s): + dots = object() + if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0: + return r"\left\{%s\right\}_{%s=%s}^{%s}" % ( + self._print(s.formula), + self._print(s.variables[0]), + self._print(s.start), + self._print(s.stop) + ) + if s.start is S.NegativeInfinity: + stop = s.stop + printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2), + s.coeff(stop - 1), s.coeff(stop)) + elif s.stop is S.Infinity or s.length > 4: + printset = s[:4] + printset.append(dots) + else: + printset = tuple(s) + + return (r"\left[" + + r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) + + r"\right]") + + _print_SeqPer = _print_SeqFormula + _print_SeqAdd = _print_SeqFormula + _print_SeqMul = _print_SeqFormula + + def _print_Interval(self, i): + if i.start == i.end: + return r"\left\{%s\right\}" % self._print(i.start) + + else: + if i.left_open: + left = '(' + else: + left = '[' + + if i.right_open: + right = ')' + else: + right = ']' + + return r"\left%s%s, %s\right%s" % \ + (left, self._print(i.start), self._print(i.end), right) + + def _print_AccumulationBounds(self, i): + return r"\left\langle %s, %s\right\rangle" % \ + (self._print(i.min), self._print(i.max)) + + def _print_Union(self, u): + prec = precedence_traditional(u) + args_str = [self.parenthesize(i, prec) for i in u.args] + return r" \cup ".join(args_str) + + def _print_Complement(self, u): + prec = precedence_traditional(u) + args_str = [self.parenthesize(i, prec) for i in u.args] + return r" \setminus ".join(args_str) + + def _print_Intersection(self, u): + prec = precedence_traditional(u) + args_str = [self.parenthesize(i, prec) for i in u.args] + return r" \cap ".join(args_str) + + def _print_SymmetricDifference(self, u): + prec = precedence_traditional(u) + args_str = [self.parenthesize(i, prec) for i in u.args] + return r" \triangle ".join(args_str) + + def _print_ProductSet(self, p): + prec = precedence_traditional(p) + if len(p.sets) >= 1 and not has_variety(p.sets): + return self.parenthesize(p.sets[0], prec) + "^{%d}" % len(p.sets) + return r" \times ".join( + self.parenthesize(set, prec) for set in p.sets) + + def _print_EmptySet(self, e): + return r"\emptyset" + + def _print_Naturals(self, n): + return r"\mathbb{N}" + + def _print_Naturals0(self, n): + return r"\mathbb{N}_0" + + def _print_Integers(self, i): + return r"\mathbb{Z}" + + def _print_Rationals(self, i): + return r"\mathbb{Q}" + + def _print_Reals(self, i): + return r"\mathbb{R}" + + def _print_Complexes(self, i): + return r"\mathbb{C}" + + def _print_ImageSet(self, s): + expr = s.lamda.expr + sig = s.lamda.signature + xys = ((self._print(x), self._print(y)) for x, y in zip(sig, s.base_sets)) + xinys = r", ".join(r"%s \in %s" % xy for xy in xys) + return r"\left\{%s\; \middle|\; %s\right\}" % (self._print(expr), xinys) + + def _print_ConditionSet(self, s): + vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)]) + if s.base_set is S.UniversalSet: + return r"\left\{%s\; \middle|\; %s \right\}" % \ + (vars_print, self._print(s.condition)) + + return r"\left\{%s\; \middle|\; %s \in %s \wedge %s \right\}" % ( + vars_print, + vars_print, + self._print(s.base_set), + self._print(s.condition)) + + def _print_PowerSet(self, expr): + arg_print = self._print(expr.args[0]) + return r"\mathcal{{P}}\left({}\right)".format(arg_print) + + def _print_ComplexRegion(self, s): + vars_print = ', '.join([self._print(var) for var in s.variables]) + return r"\left\{%s\; \middle|\; %s \in %s \right\}" % ( + self._print(s.expr), + vars_print, + self._print(s.sets)) + + def _print_Contains(self, e): + return r"%s \in %s" % tuple(self._print(a) for a in e.args) + + def _print_FourierSeries(self, s): + if s.an.formula is S.Zero and s.bn.formula is S.Zero: + return self._print(s.a0) + return self._print_Add(s.truncate()) + r' + \ldots' + + def _print_FormalPowerSeries(self, s): + return self._print_Add(s.infinite) + + def _print_FiniteField(self, expr): + return r"\mathbb{F}_{%s}" % expr.mod + + def _print_IntegerRing(self, expr): + return r"\mathbb{Z}" + + def _print_RationalField(self, expr): + return r"\mathbb{Q}" + + def _print_RealField(self, expr): + return r"\mathbb{R}" + + def _print_ComplexField(self, expr): + return r"\mathbb{C}" + + def _print_PolynomialRing(self, expr): + domain = self._print(expr.domain) + symbols = ", ".join(map(self._print, expr.symbols)) + return r"%s\left[%s\right]" % (domain, symbols) + + def _print_FractionField(self, expr): + domain = self._print(expr.domain) + symbols = ", ".join(map(self._print, expr.symbols)) + return r"%s\left(%s\right)" % (domain, symbols) + + def _print_PolynomialRingBase(self, expr): + domain = self._print(expr.domain) + symbols = ", ".join(map(self._print, expr.symbols)) + inv = "" + if not expr.is_Poly: + inv = r"S_<^{-1}" + return r"%s%s\left[%s\right]" % (inv, domain, symbols) + + def _print_Poly(self, poly): + cls = poly.__class__.__name__ + terms = [] + for monom, coeff in poly.terms(): + s_monom = '' + for i, exp in enumerate(monom): + if exp > 0: + if exp == 1: + s_monom += self._print(poly.gens[i]) + else: + s_monom += self._print(pow(poly.gens[i], exp)) + + if coeff.is_Add: + if s_monom: + s_coeff = r"\left(%s\right)" % self._print(coeff) + else: + s_coeff = self._print(coeff) + else: + if s_monom: + if coeff is S.One: + terms.extend(['+', s_monom]) + continue + + if coeff is S.NegativeOne: + terms.extend(['-', s_monom]) + continue + + s_coeff = self._print(coeff) + + if not s_monom: + s_term = s_coeff + else: + s_term = s_coeff + " " + s_monom + + if s_term.startswith('-'): + terms.extend(['-', s_term[1:]]) + else: + terms.extend(['+', s_term]) + + if terms[0] in ('-', '+'): + modifier = terms.pop(0) + + if modifier == '-': + terms[0] = '-' + terms[0] + + expr = ' '.join(terms) + gens = list(map(self._print, poly.gens)) + domain = "domain=%s" % self._print(poly.get_domain()) + + args = ", ".join([expr] + gens + [domain]) + if cls in accepted_latex_functions: + tex = r"\%s {\left(%s \right)}" % (cls, args) + else: + tex = r"\operatorname{%s}{\left( %s \right)}" % (cls, args) + + return tex + + def _print_ComplexRootOf(self, root): + cls = root.__class__.__name__ + if cls == "ComplexRootOf": + cls = "CRootOf" + expr = self._print(root.expr) + index = root.index + if cls in accepted_latex_functions: + return r"\%s {\left(%s, %d\right)}" % (cls, expr, index) + else: + return r"\operatorname{%s} {\left(%s, %d\right)}" % (cls, expr, + index) + + def _print_RootSum(self, expr): + cls = expr.__class__.__name__ + args = [self._print(expr.expr)] + + if expr.fun is not S.IdentityFunction: + args.append(self._print(expr.fun)) + + if cls in accepted_latex_functions: + return r"\%s {\left(%s\right)}" % (cls, ", ".join(args)) + else: + return r"\operatorname{%s} {\left(%s\right)}" % (cls, + ", ".join(args)) + + def _print_OrdinalOmega(self, expr): + return r"\omega" + + def _print_OmegaPower(self, expr): + exp, mul = expr.args + if mul != 1: + if exp != 1: + return r"{} \omega^{{{}}}".format(mul, exp) + else: + return r"{} \omega".format(mul) + else: + if exp != 1: + return r"\omega^{{{}}}".format(exp) + else: + return r"\omega" + + def _print_Ordinal(self, expr): + return " + ".join([self._print(arg) for arg in expr.args]) + + def _print_PolyElement(self, poly): + mul_symbol = self._settings['mul_symbol_latex'] + return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol) + + def _print_FracElement(self, frac): + if frac.denom == 1: + return self._print(frac.numer) + else: + numer = self._print(frac.numer) + denom = self._print(frac.denom) + return r"\frac{%s}{%s}" % (numer, denom) + + def _print_euler(self, expr, exp=None): + m, x = (expr.args[0], None) if len(expr.args) == 1 else expr.args + tex = r"E_{%s}" % self._print(m) + if exp is not None: + tex = r"%s^{%s}" % (tex, exp) + if x is not None: + tex = r"%s\left(%s\right)" % (tex, self._print(x)) + return tex + + def _print_catalan(self, expr, exp=None): + tex = r"C_{%s}" % self._print(expr.args[0]) + if exp is not None: + tex = r"%s^{%s}" % (tex, exp) + return tex + + def _print_UnifiedTransform(self, expr, s, inverse=False): + return r"\mathcal{{{}}}{}_{{{}}}\left[{}\right]\left({}\right)".format(s, '^{-1}' if inverse else '', self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2])) + + def _print_MellinTransform(self, expr): + return self._print_UnifiedTransform(expr, 'M') + + def _print_InverseMellinTransform(self, expr): + return self._print_UnifiedTransform(expr, 'M', True) + + def _print_LaplaceTransform(self, expr): + return self._print_UnifiedTransform(expr, 'L') + + def _print_InverseLaplaceTransform(self, expr): + return self._print_UnifiedTransform(expr, 'L', True) + + def _print_FourierTransform(self, expr): + return self._print_UnifiedTransform(expr, 'F') + + def _print_InverseFourierTransform(self, expr): + return self._print_UnifiedTransform(expr, 'F', True) + + def _print_SineTransform(self, expr): + return self._print_UnifiedTransform(expr, 'SIN') + + def _print_InverseSineTransform(self, expr): + return self._print_UnifiedTransform(expr, 'SIN', True) + + def _print_CosineTransform(self, expr): + return self._print_UnifiedTransform(expr, 'COS') + + def _print_InverseCosineTransform(self, expr): + return self._print_UnifiedTransform(expr, 'COS', True) + + def _print_DMP(self, p): + try: + if p.ring is not None: + # TODO incorporate order + return self._print(p.ring.to_sympy(p)) + except SympifyError: + pass + return self._print(repr(p)) + + def _print_DMF(self, p): + return self._print_DMP(p) + + def _print_Object(self, object): + return self._print(Symbol(object.name)) + + def _print_LambertW(self, expr, exp=None): + arg0 = self._print(expr.args[0]) + exp = r"^{%s}" % (exp,) if exp is not None else "" + if len(expr.args) == 1: + result = r"W%s\left(%s\right)" % (exp, arg0) + else: + arg1 = self._print(expr.args[1]) + result = "W{0}_{{{1}}}\\left({2}\\right)".format(exp, arg1, arg0) + return result + + def _print_Expectation(self, expr): + return r"\operatorname{{E}}\left[{}\right]".format(self._print(expr.args[0])) + + def _print_Variance(self, expr): + return r"\operatorname{{Var}}\left({}\right)".format(self._print(expr.args[0])) + + def _print_Covariance(self, expr): + return r"\operatorname{{Cov}}\left({}\right)".format(", ".join(self._print(arg) for arg in expr.args)) + + def _print_Probability(self, expr): + return r"\operatorname{{P}}\left({}\right)".format(self._print(expr.args[0])) + + def _print_Morphism(self, morphism): + domain = self._print(morphism.domain) + codomain = self._print(morphism.codomain) + return "%s\\rightarrow %s" % (domain, codomain) + + def _print_TransferFunction(self, expr): + num, den = self._print(expr.num), self._print(expr.den) + return r"\frac{%s}{%s}" % (num, den) + + def _print_Series(self, expr): + args = list(expr.args) + parens = lambda x: self.parenthesize(x, precedence_traditional(expr), + False) + return ' '.join(map(parens, args)) + + def _print_MIMOSeries(self, expr): + from sympy.physics.control.lti import MIMOParallel + args = list(expr.args)[::-1] + parens = lambda x: self.parenthesize(x, precedence_traditional(expr), + False) if isinstance(x, MIMOParallel) else self._print(x) + return r"\cdot".join(map(parens, args)) + + def _print_Parallel(self, expr): + return ' + '.join(map(self._print, expr.args)) + + def _print_MIMOParallel(self, expr): + return ' + '.join(map(self._print, expr.args)) + + def _print_Feedback(self, expr): + from sympy.physics.control import TransferFunction, Series + + num, tf = expr.sys1, TransferFunction(1, 1, expr.var) + num_arg_list = list(num.args) if isinstance(num, Series) else [num] + den_arg_list = list(expr.sys2.args) if \ + isinstance(expr.sys2, Series) else [expr.sys2] + den_term_1 = tf + + if isinstance(num, Series) and isinstance(expr.sys2, Series): + den_term_2 = Series(*num_arg_list, *den_arg_list) + elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction): + if expr.sys2 == tf: + den_term_2 = Series(*num_arg_list) + else: + den_term_2 = tf, Series(*num_arg_list, expr.sys2) + elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series): + if num == tf: + den_term_2 = Series(*den_arg_list) + else: + den_term_2 = Series(num, *den_arg_list) + else: + if num == tf: + den_term_2 = Series(*den_arg_list) + elif expr.sys2 == tf: + den_term_2 = Series(*num_arg_list) + else: + den_term_2 = Series(*num_arg_list, *den_arg_list) + + numer = self._print(num) + denom_1 = self._print(den_term_1) + denom_2 = self._print(den_term_2) + _sign = "+" if expr.sign == -1 else "-" + + return r"\frac{%s}{%s %s %s}" % (numer, denom_1, _sign, denom_2) + + def _print_MIMOFeedback(self, expr): + from sympy.physics.control import MIMOSeries + inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1)) + sys1 = self._print(expr.sys1) + _sign = "+" if expr.sign == -1 else "-" + return r"\left(I_{\tau} %s %s\right)^{-1} \cdot %s" % (_sign, inv_mat, sys1) + + def _print_TransferFunctionMatrix(self, expr): + mat = self._print(expr._expr_mat) + return r"%s_\tau" % mat + + def _print_DFT(self, expr): + return r"\text{{{}}}_{{{}}}".format(expr.__class__.__name__, expr.n) + _print_IDFT = _print_DFT + + def _print_NamedMorphism(self, morphism): + pretty_name = self._print(Symbol(morphism.name)) + pretty_morphism = self._print_Morphism(morphism) + return "%s:%s" % (pretty_name, pretty_morphism) + + def _print_IdentityMorphism(self, morphism): + from sympy.categories import NamedMorphism + return self._print_NamedMorphism(NamedMorphism( + morphism.domain, morphism.codomain, "id")) + + def _print_CompositeMorphism(self, morphism): + # All components of the morphism have names and it is thus + # possible to build the name of the composite. + component_names_list = [self._print(Symbol(component.name)) for + component in morphism.components] + component_names_list.reverse() + component_names = "\\circ ".join(component_names_list) + ":" + + pretty_morphism = self._print_Morphism(morphism) + return component_names + pretty_morphism + + def _print_Category(self, morphism): + return r"\mathbf{{{}}}".format(self._print(Symbol(morphism.name))) + + def _print_Diagram(self, diagram): + if not diagram.premises: + # This is an empty diagram. + return self._print(S.EmptySet) + + latex_result = self._print(diagram.premises) + if diagram.conclusions: + latex_result += "\\Longrightarrow %s" % \ + self._print(diagram.conclusions) + + return latex_result + + def _print_DiagramGrid(self, grid): + latex_result = "\\begin{array}{%s}\n" % ("c" * grid.width) + + for i in range(grid.height): + for j in range(grid.width): + if grid[i, j]: + latex_result += latex(grid[i, j]) + latex_result += " " + if j != grid.width - 1: + latex_result += "& " + + if i != grid.height - 1: + latex_result += "\\\\" + latex_result += "\n" + + latex_result += "\\end{array}\n" + return latex_result + + def _print_FreeModule(self, M): + return '{{{}}}^{{{}}}'.format(self._print(M.ring), self._print(M.rank)) + + def _print_FreeModuleElement(self, m): + # Print as row vector for convenience, for now. + return r"\left[ {} \right]".format(",".join( + '{' + self._print(x) + '}' for x in m)) + + def _print_SubModule(self, m): + return r"\left\langle {} \right\rangle".format(",".join( + '{' + self._print(x) + '}' for x in m.gens)) + + def _print_ModuleImplementedIdeal(self, m): + return r"\left\langle {} \right\rangle".format(",".join( + '{' + self._print(x) + '}' for [x] in m._module.gens)) + + def _print_Quaternion(self, expr): + # TODO: This expression is potentially confusing, + # shall we print it as `Quaternion( ... )`? + s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) + for i in expr.args] + a = [s[0]] + [i+" "+j for i, j in zip(s[1:], "ijk")] + return " + ".join(a) + + def _print_QuotientRing(self, R): + # TODO nicer fractions for few generators... + return r"\frac{{{}}}{{{}}}".format(self._print(R.ring), + self._print(R.base_ideal)) + + def _print_QuotientRingElement(self, x): + return r"{{{}}} + {{{}}}".format(self._print(x.data), + self._print(x.ring.base_ideal)) + + def _print_QuotientModuleElement(self, m): + return r"{{{}}} + {{{}}}".format(self._print(m.data), + self._print(m.module.killed_module)) + + def _print_QuotientModule(self, M): + # TODO nicer fractions for few generators... + return r"\frac{{{}}}{{{}}}".format(self._print(M.base), + self._print(M.killed_module)) + + def _print_MatrixHomomorphism(self, h): + return r"{{{}}} : {{{}}} \to {{{}}}".format(self._print(h._sympy_matrix()), + self._print(h.domain), self._print(h.codomain)) + + def _print_Manifold(self, manifold): + string = manifold.name.name + if '{' in string: + name, supers, subs = string, [], [] + else: + name, supers, subs = split_super_sub(string) + + name = translate(name) + supers = [translate(sup) for sup in supers] + subs = [translate(sub) for sub in subs] + + name = r'\text{%s}' % name + if supers: + name += "^{%s}" % " ".join(supers) + if subs: + name += "_{%s}" % " ".join(subs) + + return name + + def _print_Patch(self, patch): + return r'\text{%s}_{%s}' % (self._print(patch.name), self._print(patch.manifold)) + + def _print_CoordSystem(self, coordsys): + return r'\text{%s}^{\text{%s}}_{%s}' % ( + self._print(coordsys.name), self._print(coordsys.patch.name), self._print(coordsys.manifold) + ) + + def _print_CovarDerivativeOp(self, cvd): + return r'\mathbb{\nabla}_{%s}' % self._print(cvd._wrt) + + def _print_BaseScalarField(self, field): + string = field._coord_sys.symbols[field._index].name + return r'\mathbf{{{}}}'.format(self._print(Symbol(string))) + + def _print_BaseVectorField(self, field): + string = field._coord_sys.symbols[field._index].name + return r'\partial_{{{}}}'.format(self._print(Symbol(string))) + + def _print_Differential(self, diff): + field = diff._form_field + if hasattr(field, '_coord_sys'): + string = field._coord_sys.symbols[field._index].name + return r'\operatorname{{d}}{}'.format(self._print(Symbol(string))) + else: + string = self._print(field) + return r'\operatorname{{d}}\left({}\right)'.format(string) + + def _print_Tr(self, p): + # TODO: Handle indices + contents = self._print(p.args[0]) + return r'\operatorname{{tr}}\left({}\right)'.format(contents) + + def _print_totient(self, expr, exp=None): + if exp is not None: + return r'\left(\phi\left(%s\right)\right)^{%s}' % \ + (self._print(expr.args[0]), exp) + return r'\phi\left(%s\right)' % self._print(expr.args[0]) + + def _print_reduced_totient(self, expr, exp=None): + if exp is not None: + return r'\left(\lambda\left(%s\right)\right)^{%s}' % \ + (self._print(expr.args[0]), exp) + return r'\lambda\left(%s\right)' % self._print(expr.args[0]) + + def _print_divisor_sigma(self, expr, exp=None): + if len(expr.args) == 2: + tex = r"_%s\left(%s\right)" % tuple(map(self._print, + (expr.args[1], expr.args[0]))) + else: + tex = r"\left(%s\right)" % self._print(expr.args[0]) + if exp is not None: + return r"\sigma^{%s}%s" % (exp, tex) + return r"\sigma%s" % tex + + def _print_udivisor_sigma(self, expr, exp=None): + if len(expr.args) == 2: + tex = r"_%s\left(%s\right)" % tuple(map(self._print, + (expr.args[1], expr.args[0]))) + else: + tex = r"\left(%s\right)" % self._print(expr.args[0]) + if exp is not None: + return r"\sigma^*^{%s}%s" % (exp, tex) + return r"\sigma^*%s" % tex + + def _print_primenu(self, expr, exp=None): + if exp is not None: + return r'\left(\nu\left(%s\right)\right)^{%s}' % \ + (self._print(expr.args[0]), exp) + return r'\nu\left(%s\right)' % self._print(expr.args[0]) + + def _print_primeomega(self, expr, exp=None): + if exp is not None: + return r'\left(\Omega\left(%s\right)\right)^{%s}' % \ + (self._print(expr.args[0]), exp) + return r'\Omega\left(%s\right)' % self._print(expr.args[0]) + + def _print_Str(self, s): + return str(s.name) + + def _print_float(self, expr): + return self._print(Float(expr)) + + def _print_int(self, expr): + return str(expr) + + def _print_mpz(self, expr): + return str(expr) + + def _print_mpq(self, expr): + return str(expr) + + def _print_Predicate(self, expr): + return r"\operatorname{{Q}}_{{\text{{{}}}}}".format(latex_escape(str(expr.name))) + + def _print_AppliedPredicate(self, expr): + pred = expr.function + args = expr.arguments + pred_latex = self._print(pred) + args_latex = ', '.join([self._print(a) for a in args]) + return '%s(%s)' % (pred_latex, args_latex) + + def emptyPrinter(self, expr): + # default to just printing as monospace, like would normally be shown + s = super().emptyPrinter(expr) + + return r"\mathtt{\text{%s}}" % latex_escape(s) + + +def translate(s: str) -> str: + r''' + Check for a modifier ending the string. If present, convert the + modifier to latex and translate the rest recursively. + + Given a description of a Greek letter or other special character, + return the appropriate latex. + + Let everything else pass as given. + + >>> from sympy.printing.latex import translate + >>> translate('alphahatdotprime') + "{\\dot{\\hat{\\alpha}}}'" + ''' + # Process the rest + tex = tex_greek_dictionary.get(s) + if tex: + return tex + elif s.lower() in greek_letters_set: + return "\\" + s.lower() + elif s in other_symbols: + return "\\" + s + else: + # Process modifiers, if any, and recurse + for key in sorted(modifier_dict.keys(), key=len, reverse=True): + if s.lower().endswith(key) and len(s) > len(key): + return modifier_dict[key](translate(s[:-len(key)])) + return s + + + +@print_function(LatexPrinter) +def latex(expr, **settings): + r"""Convert the given expression to LaTeX string representation. + + Parameters + ========== + full_prec: boolean, optional + If set to True, a floating point number is printed with full precision. + fold_frac_powers : boolean, optional + Emit ``^{p/q}`` instead of ``^{\frac{p}{q}}`` for fractional powers. + fold_func_brackets : boolean, optional + Fold function brackets where applicable. + fold_short_frac : boolean, optional + Emit ``p / q`` instead of ``\frac{p}{q}`` when the denominator is + simple enough (at most two terms and no powers). The default value is + ``True`` for inline mode, ``False`` otherwise. + inv_trig_style : string, optional + How inverse trig functions should be displayed. Can be one of + ``'abbreviated'``, ``'full'``, or ``'power'``. Defaults to + ``'abbreviated'``. + itex : boolean, optional + Specifies if itex-specific syntax is used, including emitting + ``$$...$$``. + ln_notation : boolean, optional + If set to ``True``, ``\ln`` is used instead of default ``\log``. + long_frac_ratio : float or None, optional + The allowed ratio of the width of the numerator to the width of the + denominator before the printer breaks off long fractions. If ``None`` + (the default value), long fractions are not broken up. + mat_delim : string, optional + The delimiter to wrap around matrices. Can be one of ``'['``, ``'('``, + or the empty string ``''``. Defaults to ``'['``. + mat_str : string, optional + Which matrix environment string to emit. ``'smallmatrix'``, + ``'matrix'``, ``'array'``, etc. Defaults to ``'smallmatrix'`` for + inline mode, ``'matrix'`` for matrices of no more than 10 columns, and + ``'array'`` otherwise. + mode: string, optional + Specifies how the generated code will be delimited. ``mode`` can be one + of ``'plain'``, ``'inline'``, ``'equation'`` or ``'equation*'``. If + ``mode`` is set to ``'plain'``, then the resulting code will not be + delimited at all (this is the default). If ``mode`` is set to + ``'inline'`` then inline LaTeX ``$...$`` will be used. If ``mode`` is + set to ``'equation'`` or ``'equation*'``, the resulting code will be + enclosed in the ``equation`` or ``equation*`` environment (remember to + import ``amsmath`` for ``equation*``), unless the ``itex`` option is + set. In the latter case, the ``$$...$$`` syntax is used. + mul_symbol : string or None, optional + The symbol to use for multiplication. Can be one of ``None``, + ``'ldot'``, ``'dot'``, or ``'times'``. + order: string, optional + Any of the supported monomial orderings (currently ``'lex'``, + ``'grlex'``, or ``'grevlex'``), ``'old'``, and ``'none'``. This + parameter does nothing for `~.Mul` objects. Setting order to ``'old'`` + uses the compatibility ordering for ``~.Add`` defined in Printer. For + very large expressions, set the ``order`` keyword to ``'none'`` if + speed is a concern. + symbol_names : dictionary of strings mapped to symbols, optional + Dictionary of symbols and the custom strings they should be emitted as. + root_notation : boolean, optional + If set to ``False``, exponents of the form 1/n are printed in fractonal + form. Default is ``True``, to print exponent in root form. + mat_symbol_style : string, optional + Can be either ``'plain'`` (default) or ``'bold'``. If set to + ``'bold'``, a `~.MatrixSymbol` A will be printed as ``\mathbf{A}``, + otherwise as ``A``. + imaginary_unit : string, optional + String to use for the imaginary unit. Defined options are ``'i'`` + (default) and ``'j'``. Adding ``r`` or ``t`` in front gives ``\mathrm`` + or ``\text``, so ``'ri'`` leads to ``\mathrm{i}`` which gives + `\mathrm{i}`. + gothic_re_im : boolean, optional + If set to ``True``, `\Re` and `\Im` is used for ``re`` and ``im``, respectively. + The default is ``False`` leading to `\operatorname{re}` and `\operatorname{im}`. + decimal_separator : string, optional + Specifies what separator to use to separate the whole and fractional parts of a + floating point number as in `2.5` for the default, ``period`` or `2{,}5` + when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon + separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when + ``comma`` is chosen and [1,2,3] for when ``period`` is chosen. + parenthesize_super : boolean, optional + If set to ``False``, superscripted expressions will not be parenthesized when + powered. Default is ``True``, which parenthesizes the expression when powered. + min: Integer or None, optional + Sets the lower bound for the exponent to print floating point numbers in + fixed-point format. + max: Integer or None, optional + Sets the upper bound for the exponent to print floating point numbers in + fixed-point format. + diff_operator: string, optional + String to use for differential operator. Default is ``'d'``, to print in italic + form. ``'rd'``, ``'td'`` are shortcuts for ``\mathrm{d}`` and ``\text{d}``. + + Notes + ===== + + Not using a print statement for printing, results in double backslashes for + latex commands since that's the way Python escapes backslashes in strings. + + >>> from sympy import latex, Rational + >>> from sympy.abc import tau + >>> latex((2*tau)**Rational(7,2)) + '8 \\sqrt{2} \\tau^{\\frac{7}{2}}' + >>> print(latex((2*tau)**Rational(7,2))) + 8 \sqrt{2} \tau^{\frac{7}{2}} + + Examples + ======== + + >>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log + >>> from sympy.abc import x, y, mu, r, tau + + Basic usage: + + >>> print(latex((2*tau)**Rational(7,2))) + 8 \sqrt{2} \tau^{\frac{7}{2}} + + ``mode`` and ``itex`` options: + + >>> print(latex((2*mu)**Rational(7,2), mode='plain')) + 8 \sqrt{2} \mu^{\frac{7}{2}} + >>> print(latex((2*tau)**Rational(7,2), mode='inline')) + $8 \sqrt{2} \tau^{7 / 2}$ + >>> print(latex((2*mu)**Rational(7,2), mode='equation*')) + \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*} + >>> print(latex((2*mu)**Rational(7,2), mode='equation')) + \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation} + >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) + $$8 \sqrt{2} \mu^{\frac{7}{2}}$$ + >>> print(latex((2*mu)**Rational(7,2), mode='plain')) + 8 \sqrt{2} \mu^{\frac{7}{2}} + >>> print(latex((2*tau)**Rational(7,2), mode='inline')) + $8 \sqrt{2} \tau^{7 / 2}$ + >>> print(latex((2*mu)**Rational(7,2), mode='equation*')) + \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*} + >>> print(latex((2*mu)**Rational(7,2), mode='equation')) + \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation} + >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) + $$8 \sqrt{2} \mu^{\frac{7}{2}}$$ + + Fraction options: + + >>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True)) + 8 \sqrt{2} \tau^{7/2} + >>> print(latex((2*tau)**sin(Rational(7,2)))) + \left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}} + >>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True)) + \left(2 \tau\right)^{\sin {\frac{7}{2}}} + >>> print(latex(3*x**2/y)) + \frac{3 x^{2}}{y} + >>> print(latex(3*x**2/y, fold_short_frac=True)) + 3 x^{2} / y + >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2)) + \frac{\int r\, dr}{2 \pi} + >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0)) + \frac{1}{2 \pi} \int r\, dr + + Multiplication options: + + >>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times")) + \left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}} + + Trig options: + + >>> print(latex(asin(Rational(7,2)))) + \operatorname{asin}{\left(\frac{7}{2} \right)} + >>> print(latex(asin(Rational(7,2)), inv_trig_style="full")) + \arcsin{\left(\frac{7}{2} \right)} + >>> print(latex(asin(Rational(7,2)), inv_trig_style="power")) + \sin^{-1}{\left(\frac{7}{2} \right)} + + Matrix options: + + >>> print(latex(Matrix(2, 1, [x, y]))) + \left[\begin{matrix}x\\y\end{matrix}\right] + >>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array")) + \left[\begin{array}{c}x\\y\end{array}\right] + >>> print(latex(Matrix(2, 1, [x, y]), mat_delim="(")) + \left(\begin{matrix}x\\y\end{matrix}\right) + + Custom printing of symbols: + + >>> print(latex(x**2, symbol_names={x: 'x_i'})) + x_i^{2} + + Logarithms: + + >>> print(latex(log(10))) + \log{\left(10 \right)} + >>> print(latex(log(10), ln_notation=True)) + \ln{\left(10 \right)} + + ``latex()`` also supports the builtin container types :class:`list`, + :class:`tuple`, and :class:`dict`: + + >>> print(latex([2/x, y], mode='inline')) + $\left[ 2 / x, \ y\right]$ + + Unsupported types are rendered as monospaced plaintext: + + >>> print(latex(int)) + \mathtt{\text{}} + >>> print(latex("plain % text")) + \mathtt{\text{plain \% text}} + + See :ref:`printer_method_example` for an example of how to override + this behavior for your own types by implementing ``_latex``. + + .. versionchanged:: 1.7.0 + Unsupported types no longer have their ``str`` representation treated as valid latex. + + """ + return LatexPrinter(settings).doprint(expr) + + +def print_latex(expr, **settings): + """Prints LaTeX representation of the given expression. Takes the same + settings as ``latex()``.""" + + print(latex(expr, **settings)) + + +def multiline_latex(lhs, rhs, terms_per_line=1, environment="align*", use_dots=False, **settings): + r""" + This function generates a LaTeX equation with a multiline right-hand side + in an ``align*``, ``eqnarray`` or ``IEEEeqnarray`` environment. + + Parameters + ========== + + lhs : Expr + Left-hand side of equation + + rhs : Expr + Right-hand side of equation + + terms_per_line : integer, optional + Number of terms per line to print. Default is 1. + + environment : "string", optional + Which LaTeX wnvironment to use for the output. Options are "align*" + (default), "eqnarray", and "IEEEeqnarray". + + use_dots : boolean, optional + If ``True``, ``\\dots`` is added to the end of each line. Default is ``False``. + + Examples + ======== + + >>> from sympy import multiline_latex, symbols, sin, cos, exp, log, I + >>> x, y, alpha = symbols('x y alpha') + >>> expr = sin(alpha*y) + exp(I*alpha) - cos(log(y)) + >>> print(multiline_latex(x, expr)) + \begin{align*} + x = & e^{i \alpha} \\ + & + \sin{\left(\alpha y \right)} \\ + & - \cos{\left(\log{\left(y \right)} \right)} + \end{align*} + + Using at most two terms per line: + >>> print(multiline_latex(x, expr, 2)) + \begin{align*} + x = & e^{i \alpha} + \sin{\left(\alpha y \right)} \\ + & - \cos{\left(\log{\left(y \right)} \right)} + \end{align*} + + Using ``eqnarray`` and dots: + >>> print(multiline_latex(x, expr, terms_per_line=2, environment="eqnarray", use_dots=True)) + \begin{eqnarray} + x & = & e^{i \alpha} + \sin{\left(\alpha y \right)} \dots\nonumber\\ + & & - \cos{\left(\log{\left(y \right)} \right)} + \end{eqnarray} + + Using ``IEEEeqnarray``: + >>> print(multiline_latex(x, expr, environment="IEEEeqnarray")) + \begin{IEEEeqnarray}{rCl} + x & = & e^{i \alpha} \nonumber\\ + & & + \sin{\left(\alpha y \right)} \nonumber\\ + & & - \cos{\left(\log{\left(y \right)} \right)} + \end{IEEEeqnarray} + + Notes + ===== + + All optional parameters from ``latex`` can also be used. + + """ + + # Based on code from https://github.com/sympy/sympy/issues/3001 + l = LatexPrinter(**settings) + if environment == "eqnarray": + result = r'\begin{eqnarray}' + '\n' + first_term = '& = &' + nonumber = r'\nonumber' + end_term = '\n\\end{eqnarray}' + doubleet = True + elif environment == "IEEEeqnarray": + result = r'\begin{IEEEeqnarray}{rCl}' + '\n' + first_term = '& = &' + nonumber = r'\nonumber' + end_term = '\n\\end{IEEEeqnarray}' + doubleet = True + elif environment == "align*": + result = r'\begin{align*}' + '\n' + first_term = '= &' + nonumber = '' + end_term = '\n\\end{align*}' + doubleet = False + else: + raise ValueError("Unknown environment: {}".format(environment)) + dots = '' + if use_dots: + dots=r'\dots' + terms = rhs.as_ordered_terms() + n_terms = len(terms) + term_count = 1 + for i in range(n_terms): + term = terms[i] + term_start = '' + term_end = '' + sign = '+' + if term_count > terms_per_line: + if doubleet: + term_start = '& & ' + else: + term_start = '& ' + term_count = 1 + if term_count == terms_per_line: + # End of line + if i < n_terms-1: + # There are terms remaining + term_end = dots + nonumber + r'\\' + '\n' + else: + term_end = '' + + if term.as_ordered_factors()[0] == -1: + term = -1*term + sign = r'-' + if i == 0: # beginning + if sign == '+': + sign = '' + result += r'{:s} {:s}{:s} {:s} {:s}'.format(l.doprint(lhs), + first_term, sign, l.doprint(term), term_end) + else: + result += r'{:s}{:s} {:s} {:s}'.format(term_start, sign, + l.doprint(term), term_end) + term_count += 1 + result += end_term + return result diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/llvmjitcode.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/llvmjitcode.py new file mode 100644 index 0000000000000000000000000000000000000000..5bba1003c87ccd8204619c9a878c612f741d9a96 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/llvmjitcode.py @@ -0,0 +1,489 @@ +''' +Use llvmlite to create executable functions from SymPy expressions + +This module requires llvmlite (https://github.com/numba/llvmlite). +''' + +import ctypes + +from sympy.external import import_module +from sympy.printing.printer import Printer +from sympy.core.singleton import S +from sympy.tensor.indexed import IndexedBase +from sympy.utilities.decorator import doctest_depends_on + +llvmlite = import_module('llvmlite') +if llvmlite: + ll = import_module('llvmlite.ir').ir + llvm = import_module('llvmlite.binding').binding + llvm.initialize() + llvm.initialize_native_target() + llvm.initialize_native_asmprinter() + + +__doctest_requires__ = {('llvm_callable'): ['llvmlite']} + + +class LLVMJitPrinter(Printer): + '''Convert expressions to LLVM IR''' + def __init__(self, module, builder, fn, *args, **kwargs): + self.func_arg_map = kwargs.pop("func_arg_map", {}) + if not llvmlite: + raise ImportError("llvmlite is required for LLVMJITPrinter") + super().__init__(*args, **kwargs) + self.fp_type = ll.DoubleType() + self.module = module + self.builder = builder + self.fn = fn + self.ext_fn = {} # keep track of wrappers to external functions + self.tmp_var = {} + + def _add_tmp_var(self, name, value): + self.tmp_var[name] = value + + def _print_Number(self, n): + return ll.Constant(self.fp_type, float(n)) + + def _print_Integer(self, expr): + return ll.Constant(self.fp_type, float(expr.p)) + + def _print_Symbol(self, s): + val = self.tmp_var.get(s) + if not val: + # look up parameter with name s + val = self.func_arg_map.get(s) + if not val: + raise LookupError("Symbol not found: %s" % s) + return val + + def _print_Pow(self, expr): + base0 = self._print(expr.base) + if expr.exp == S.NegativeOne: + return self.builder.fdiv(ll.Constant(self.fp_type, 1.0), base0) + if expr.exp == S.Half: + fn = self.ext_fn.get("sqrt") + if not fn: + fn_type = ll.FunctionType(self.fp_type, [self.fp_type]) + fn = ll.Function(self.module, fn_type, "sqrt") + self.ext_fn["sqrt"] = fn + return self.builder.call(fn, [base0], "sqrt") + if expr.exp == 2: + return self.builder.fmul(base0, base0) + + exp0 = self._print(expr.exp) + fn = self.ext_fn.get("pow") + if not fn: + fn_type = ll.FunctionType(self.fp_type, [self.fp_type, self.fp_type]) + fn = ll.Function(self.module, fn_type, "pow") + self.ext_fn["pow"] = fn + return self.builder.call(fn, [base0, exp0], "pow") + + def _print_Mul(self, expr): + nodes = [self._print(a) for a in expr.args] + e = nodes[0] + for node in nodes[1:]: + e = self.builder.fmul(e, node) + return e + + def _print_Add(self, expr): + nodes = [self._print(a) for a in expr.args] + e = nodes[0] + for node in nodes[1:]: + e = self.builder.fadd(e, node) + return e + + # TODO - assumes all called functions take one double precision argument. + # Should have a list of math library functions to validate this. + def _print_Function(self, expr): + name = expr.func.__name__ + e0 = self._print(expr.args[0]) + fn = self.ext_fn.get(name) + if not fn: + fn_type = ll.FunctionType(self.fp_type, [self.fp_type]) + fn = ll.Function(self.module, fn_type, name) + self.ext_fn[name] = fn + return self.builder.call(fn, [e0], name) + + def emptyPrinter(self, expr): + raise TypeError("Unsupported type for LLVM JIT conversion: %s" + % type(expr)) + + +# Used when parameters are passed by array. Often used in callbacks to +# handle a variable number of parameters. +class LLVMJitCallbackPrinter(LLVMJitPrinter): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def _print_Indexed(self, expr): + array, idx = self.func_arg_map[expr.base] + offset = int(expr.indices[0].evalf()) + array_ptr = self.builder.gep(array, [ll.Constant(ll.IntType(32), offset)]) + fp_array_ptr = self.builder.bitcast(array_ptr, ll.PointerType(self.fp_type)) + value = self.builder.load(fp_array_ptr) + return value + + def _print_Symbol(self, s): + val = self.tmp_var.get(s) + if val: + return val + + array, idx = self.func_arg_map.get(s, [None, 0]) + if not array: + raise LookupError("Symbol not found: %s" % s) + array_ptr = self.builder.gep(array, [ll.Constant(ll.IntType(32), idx)]) + fp_array_ptr = self.builder.bitcast(array_ptr, + ll.PointerType(self.fp_type)) + value = self.builder.load(fp_array_ptr) + return value + + +# ensure lifetime of the execution engine persists (else call to compiled +# function will seg fault) +exe_engines = [] + +# ensure names for generated functions are unique +link_names = set() +current_link_suffix = 0 + + +class LLVMJitCode: + def __init__(self, signature): + self.signature = signature + self.fp_type = ll.DoubleType() + self.module = ll.Module('mod1') + self.fn = None + self.llvm_arg_types = [] + self.llvm_ret_type = self.fp_type + self.param_dict = {} # map symbol name to LLVM function argument + self.link_name = '' + + def _from_ctype(self, ctype): + if ctype == ctypes.c_int: + return ll.IntType(32) + if ctype == ctypes.c_double: + return self.fp_type + if ctype == ctypes.POINTER(ctypes.c_double): + return ll.PointerType(self.fp_type) + if ctype == ctypes.c_void_p: + return ll.PointerType(ll.IntType(32)) + if ctype == ctypes.py_object: + return ll.PointerType(ll.IntType(32)) + + print("Unhandled ctype = %s" % str(ctype)) + + def _create_args(self, func_args): + """Create types for function arguments""" + self.llvm_ret_type = self._from_ctype(self.signature.ret_type) + self.llvm_arg_types = \ + [self._from_ctype(a) for a in self.signature.arg_ctypes] + + def _create_function_base(self): + """Create function with name and type signature""" + global link_names, current_link_suffix + default_link_name = 'jit_func' + current_link_suffix += 1 + self.link_name = default_link_name + str(current_link_suffix) + link_names.add(self.link_name) + + fn_type = ll.FunctionType(self.llvm_ret_type, self.llvm_arg_types) + self.fn = ll.Function(self.module, fn_type, name=self.link_name) + + def _create_param_dict(self, func_args): + """Mapping of symbolic values to function arguments""" + for i, a in enumerate(func_args): + self.fn.args[i].name = str(a) + self.param_dict[a] = self.fn.args[i] + + def _create_function(self, expr): + """Create function body and return LLVM IR""" + bb_entry = self.fn.append_basic_block('entry') + builder = ll.IRBuilder(bb_entry) + + lj = LLVMJitPrinter(self.module, builder, self.fn, + func_arg_map=self.param_dict) + + ret = self._convert_expr(lj, expr) + lj.builder.ret(self._wrap_return(lj, ret)) + + strmod = str(self.module) + return strmod + + def _wrap_return(self, lj, vals): + # Return a single double if there is one return value, + # else return a tuple of doubles. + + # Don't wrap return value in this case + if self.signature.ret_type == ctypes.c_double: + return vals[0] + + # Use this instead of a real PyObject* + void_ptr = ll.PointerType(ll.IntType(32)) + + # Create a wrapped double: PyObject* PyFloat_FromDouble(double v) + wrap_type = ll.FunctionType(void_ptr, [self.fp_type]) + wrap_fn = ll.Function(lj.module, wrap_type, "PyFloat_FromDouble") + + wrapped_vals = [lj.builder.call(wrap_fn, [v]) for v in vals] + if len(vals) == 1: + final_val = wrapped_vals[0] + else: + # Create a tuple: PyObject* PyTuple_Pack(Py_ssize_t n, ...) + + # This should be Py_ssize_t + tuple_arg_types = [ll.IntType(32)] + + tuple_arg_types.extend([void_ptr]*len(vals)) + tuple_type = ll.FunctionType(void_ptr, tuple_arg_types) + tuple_fn = ll.Function(lj.module, tuple_type, "PyTuple_Pack") + + tuple_args = [ll.Constant(ll.IntType(32), len(wrapped_vals))] + tuple_args.extend(wrapped_vals) + + final_val = lj.builder.call(tuple_fn, tuple_args) + + return final_val + + def _convert_expr(self, lj, expr): + try: + # Match CSE return data structure. + if len(expr) == 2: + tmp_exprs = expr[0] + final_exprs = expr[1] + if len(final_exprs) != 1 and self.signature.ret_type == ctypes.c_double: + raise NotImplementedError("Return of multiple expressions not supported for this callback") + for name, e in tmp_exprs: + val = lj._print(e) + lj._add_tmp_var(name, val) + except TypeError: + final_exprs = [expr] + + vals = [lj._print(e) for e in final_exprs] + + return vals + + def _compile_function(self, strmod): + global exe_engines + llmod = llvm.parse_assembly(strmod) + + pmb = llvm.create_pass_manager_builder() + pmb.opt_level = 2 + pass_manager = llvm.create_module_pass_manager() + pmb.populate(pass_manager) + + pass_manager.run(llmod) + + target_machine = \ + llvm.Target.from_default_triple().create_target_machine() + exe_eng = llvm.create_mcjit_compiler(llmod, target_machine) + exe_eng.finalize_object() + exe_engines.append(exe_eng) + + if False: + print("Assembly") + print(target_machine.emit_assembly(llmod)) + + fptr = exe_eng.get_function_address(self.link_name) + + return fptr + + +class LLVMJitCodeCallback(LLVMJitCode): + def __init__(self, signature): + super().__init__(signature) + + def _create_param_dict(self, func_args): + for i, a in enumerate(func_args): + if isinstance(a, IndexedBase): + self.param_dict[a] = (self.fn.args[i], i) + self.fn.args[i].name = str(a) + else: + self.param_dict[a] = (self.fn.args[self.signature.input_arg], + i) + + def _create_function(self, expr): + """Create function body and return LLVM IR""" + bb_entry = self.fn.append_basic_block('entry') + builder = ll.IRBuilder(bb_entry) + + lj = LLVMJitCallbackPrinter(self.module, builder, self.fn, + func_arg_map=self.param_dict) + + ret = self._convert_expr(lj, expr) + + if self.signature.ret_arg: + output_fp_ptr = builder.bitcast(self.fn.args[self.signature.ret_arg], + ll.PointerType(self.fp_type)) + for i, val in enumerate(ret): + index = ll.Constant(ll.IntType(32), i) + output_array_ptr = builder.gep(output_fp_ptr, [index]) + builder.store(val, output_array_ptr) + builder.ret(ll.Constant(ll.IntType(32), 0)) # return success + else: + lj.builder.ret(self._wrap_return(lj, ret)) + + strmod = str(self.module) + return strmod + + +class CodeSignature: + def __init__(self, ret_type): + self.ret_type = ret_type + self.arg_ctypes = [] + + # Input argument array element index + self.input_arg = 0 + + # For the case output value is referenced through a parameter rather + # than the return value + self.ret_arg = None + + +def _llvm_jit_code(args, expr, signature, callback_type): + """Create a native code function from a SymPy expression""" + if callback_type is None: + jit = LLVMJitCode(signature) + else: + jit = LLVMJitCodeCallback(signature) + + jit._create_args(args) + jit._create_function_base() + jit._create_param_dict(args) + strmod = jit._create_function(expr) + if False: + print("LLVM IR") + print(strmod) + fptr = jit._compile_function(strmod) + return fptr + + +@doctest_depends_on(modules=('llvmlite', 'scipy')) +def llvm_callable(args, expr, callback_type=None): + '''Compile function from a SymPy expression + + Expressions are evaluated using double precision arithmetic. + Some single argument math functions (exp, sin, cos, etc.) are supported + in expressions. + + Parameters + ========== + + args : List of Symbol + Arguments to the generated function. Usually the free symbols in + the expression. Currently each one is assumed to convert to + a double precision scalar. + expr : Expr, or (Replacements, Expr) as returned from 'cse' + Expression to compile. + callback_type : string + Create function with signature appropriate to use as a callback. + Currently supported: + 'scipy.integrate' + 'scipy.integrate.test' + 'cubature' + + Returns + ======= + + Compiled function that can evaluate the expression. + + Examples + ======== + + >>> import sympy.printing.llvmjitcode as jit + >>> from sympy.abc import a + >>> e = a*a + a + 1 + >>> e1 = jit.llvm_callable([a], e) + >>> e.subs(a, 1.1) # Evaluate via substitution + 3.31000000000000 + >>> e1(1.1) # Evaluate using JIT-compiled code + 3.3100000000000005 + + + Callbacks for integration functions can be JIT compiled. + >>> import sympy.printing.llvmjitcode as jit + >>> from sympy.abc import a + >>> from sympy import integrate + >>> from scipy.integrate import quad + >>> e = a*a + >>> e1 = jit.llvm_callable([a], e, callback_type='scipy.integrate') + >>> integrate(e, (a, 0.0, 2.0)) + 2.66666666666667 + >>> quad(e1, 0.0, 2.0)[0] + 2.66666666666667 + + The 'cubature' callback is for the Python wrapper around the + cubature package ( https://github.com/saullocastro/cubature ) + and ( http://ab-initio.mit.edu/wiki/index.php/Cubature ) + + There are two signatures for the SciPy integration callbacks. + The first ('scipy.integrate') is the function to be passed to the + integration routine, and will pass the signature checks. + The second ('scipy.integrate.test') is only useful for directly calling + the function using ctypes variables. It will not pass the signature checks + for scipy.integrate. + + The return value from the cse module can also be compiled. This + can improve the performance of the compiled function. If multiple + expressions are given to cse, the compiled function returns a tuple. + The 'cubature' callback handles multiple expressions (set `fdim` + to match in the integration call.) + >>> import sympy.printing.llvmjitcode as jit + >>> from sympy import cse + >>> from sympy.abc import x,y + >>> e1 = x*x + y*y + >>> e2 = 4*(x*x + y*y) + 8.0 + >>> after_cse = cse([e1,e2]) + >>> after_cse + ([(x0, x**2), (x1, y**2)], [x0 + x1, 4*x0 + 4*x1 + 8.0]) + >>> j1 = jit.llvm_callable([x,y], after_cse) + >>> j1(1.0, 2.0) + (5.0, 28.0) + ''' + + if not llvmlite: + raise ImportError("llvmlite is required for llvmjitcode") + + signature = CodeSignature(ctypes.py_object) + + arg_ctypes = [] + if callback_type is None: + for _ in args: + arg_ctype = ctypes.c_double + arg_ctypes.append(arg_ctype) + elif callback_type in ('scipy.integrate', 'scipy.integrate.test'): + signature.ret_type = ctypes.c_double + arg_ctypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_double)] + arg_ctypes_formal = [ctypes.c_int, ctypes.c_double] + signature.input_arg = 1 + elif callback_type == 'cubature': + arg_ctypes = [ctypes.c_int, + ctypes.POINTER(ctypes.c_double), + ctypes.c_void_p, + ctypes.c_int, + ctypes.POINTER(ctypes.c_double) + ] + signature.ret_type = ctypes.c_int + signature.input_arg = 1 + signature.ret_arg = 4 + else: + raise ValueError("Unknown callback type: %s" % callback_type) + + signature.arg_ctypes = arg_ctypes + + fptr = _llvm_jit_code(args, expr, signature, callback_type) + + if callback_type and callback_type == 'scipy.integrate': + arg_ctypes = arg_ctypes_formal + + # PYFUNCTYPE holds the GIL which is needed to prevent a segfault when + # calling PyFloat_FromDouble on Python 3.10. Probably it is better to use + # ctypes.c_double when returning a float rather than using ctypes.py_object + # and returning a PyFloat from inside the jitted function (i.e. let ctypes + # handle the conversion from double to PyFloat). + if signature.ret_type == ctypes.py_object: + FUNCTYPE = ctypes.PYFUNCTYPE + else: + FUNCTYPE = ctypes.CFUNCTYPE + + cfunc = FUNCTYPE(signature.ret_type, *arg_ctypes)(fptr) + return cfunc diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/maple.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/maple.py new file mode 100644 index 0000000000000000000000000000000000000000..16a17f3a9e1ffbe0d4101185a69c1408c4ae2bc9 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/maple.py @@ -0,0 +1,311 @@ +""" +Maple code printer + +The MapleCodePrinter converts single SymPy expressions into single +Maple expressions, using the functions defined in the Maple objects where possible. + + +FIXME: This module is still under actively developed. Some functions may be not completed. +""" + +from sympy.core import S +from sympy.core.numbers import Integer, IntegerConstant, equal_valued +from sympy.printing.codeprinter import CodePrinter +from sympy.printing.precedence import precedence, PRECEDENCE + +import sympy + +_known_func_same_name = ( + 'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinh', 'cosh', 'tanh', 'sech', + 'csch', 'coth', 'exp', 'floor', 'factorial', 'bernoulli', 'euler', + 'fibonacci', 'gcd', 'lcm', 'conjugate', 'Ci', 'Chi', 'Ei', 'Li', 'Si', 'Shi', + 'erf', 'erfc', 'harmonic', 'LambertW', + 'sqrt', # For automatic rewrites +) + +known_functions = { + # SymPy -> Maple + 'Abs': 'abs', + 'log': 'ln', + 'asin': 'arcsin', + 'acos': 'arccos', + 'atan': 'arctan', + 'asec': 'arcsec', + 'acsc': 'arccsc', + 'acot': 'arccot', + 'asinh': 'arcsinh', + 'acosh': 'arccosh', + 'atanh': 'arctanh', + 'asech': 'arcsech', + 'acsch': 'arccsch', + 'acoth': 'arccoth', + 'ceiling': 'ceil', + 'Max' : 'max', + 'Min' : 'min', + + 'factorial2': 'doublefactorial', + 'RisingFactorial': 'pochhammer', + 'besseli': 'BesselI', + 'besselj': 'BesselJ', + 'besselk': 'BesselK', + 'bessely': 'BesselY', + 'hankelh1': 'HankelH1', + 'hankelh2': 'HankelH2', + 'airyai': 'AiryAi', + 'airybi': 'AiryBi', + 'appellf1': 'AppellF1', + 'fresnelc': 'FresnelC', + 'fresnels': 'FresnelS', + 'lerchphi' : 'LerchPhi', +} + +for _func in _known_func_same_name: + known_functions[_func] = _func + +number_symbols = { + # SymPy -> Maple + S.Pi: 'Pi', + S.Exp1: 'exp(1)', + S.Catalan: 'Catalan', + S.EulerGamma: 'gamma', + S.GoldenRatio: '(1/2 + (1/2)*sqrt(5))' +} + +spec_relational_ops = { + # SymPy -> Maple + '==': '=', + '!=': '<>' +} + +not_supported_symbol = [ + S.ComplexInfinity +] + +class MapleCodePrinter(CodePrinter): + """ + Printer which converts a SymPy expression into a maple code. + """ + printmethod = "_maple" + language = "maple" + + _default_settings = { + 'order': None, + 'full_prec': 'auto', + 'human': True, + 'inline': True, + 'allow_unknown_functions': True, + } + + def __init__(self, settings=None): + if settings is None: + settings = {} + super().__init__(settings) + self.known_functions = dict(known_functions) + userfuncs = settings.get('user_functions', {}) + self.known_functions.update(userfuncs) + + def _get_statement(self, codestring): + return "%s;" % codestring + + def _get_comment(self, text): + return "# {}".format(text) + + def _declare_number_const(self, name, value): + return "{} := {};".format(name, + value.evalf(self._settings['precision'])) + + def _format_code(self, lines): + return lines + + def _print_tuple(self, expr): + return self._print(list(expr)) + + def _print_Tuple(self, expr): + return self._print(list(expr)) + + def _print_Assignment(self, expr): + lhs = self._print(expr.lhs) + rhs = self._print(expr.rhs) + return "{lhs} := {rhs}".format(lhs=lhs, rhs=rhs) + + def _print_Pow(self, expr, **kwargs): + PREC = precedence(expr) + if equal_valued(expr.exp, -1): + return '1/%s' % (self.parenthesize(expr.base, PREC)) + elif equal_valued(expr.exp, 0.5): + return 'sqrt(%s)' % self._print(expr.base) + elif equal_valued(expr.exp, -0.5): + return '1/sqrt(%s)' % self._print(expr.base) + else: + return '{base}^{exp}'.format( + base=self.parenthesize(expr.base, PREC), + exp=self.parenthesize(expr.exp, PREC)) + + def _print_Piecewise(self, expr): + if (expr.args[-1].cond is not True) and (expr.args[-1].cond != S.BooleanTrue): + # We need the last conditional to be a True, otherwise the resulting + # function may not return a result. + raise ValueError("All Piecewise expressions must contain an " + "(expr, True) statement to be used as a default " + "condition. Without one, the generated " + "expression may not evaluate to anything under " + "some condition.") + _coup_list = [ + ("{c}, {e}".format(c=self._print(c), + e=self._print(e)) if c is not True and c is not S.BooleanTrue else "{e}".format( + e=self._print(e))) + for e, c in expr.args] + _inbrace = ', '.join(_coup_list) + return 'piecewise({_inbrace})'.format(_inbrace=_inbrace) + + def _print_Rational(self, expr): + p, q = int(expr.p), int(expr.q) + return "{p}/{q}".format(p=str(p), q=str(q)) + + def _print_Relational(self, expr): + PREC=precedence(expr) + lhs_code = self.parenthesize(expr.lhs, PREC) + rhs_code = self.parenthesize(expr.rhs, PREC) + op = expr.rel_op + if op in spec_relational_ops: + op = spec_relational_ops[op] + return "{lhs} {rel_op} {rhs}".format(lhs=lhs_code, rel_op=op, rhs=rhs_code) + + def _print_NumberSymbol(self, expr): + return number_symbols[expr] + + def _print_NegativeInfinity(self, expr): + return '-infinity' + + def _print_Infinity(self, expr): + return 'infinity' + + def _print_Idx(self, expr): + return self._print(expr.label) + + def _print_BooleanTrue(self, expr): + return "true" + + def _print_BooleanFalse(self, expr): + return "false" + + def _print_bool(self, expr): + return 'true' if expr else 'false' + + def _print_NaN(self, expr): + return 'undefined' + + def _get_matrix(self, expr, sparse=False): + if S.Zero in expr.shape: + _strM = 'Matrix([], storage = {storage})'.format( + storage='sparse' if sparse else 'rectangular') + else: + _strM = 'Matrix({list}, storage = {storage})'.format( + list=self._print(expr.tolist()), + storage='sparse' if sparse else 'rectangular') + return _strM + + def _print_MatrixElement(self, expr): + return "{parent}[{i_maple}, {j_maple}]".format( + parent=self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True), + i_maple=self._print(expr.i + 1), + j_maple=self._print(expr.j + 1)) + + def _print_MatrixBase(self, expr): + return self._get_matrix(expr, sparse=False) + + def _print_SparseRepMatrix(self, expr): + return self._get_matrix(expr, sparse=True) + + def _print_Identity(self, expr): + if isinstance(expr.rows, (Integer, IntegerConstant)): + return self._print(sympy.SparseMatrix(expr)) + else: + return "Matrix({var_size}, shape = identity)".format(var_size=self._print(expr.rows)) + + def _print_MatMul(self, expr): + PREC=precedence(expr) + _fact_list = list(expr.args) + _const = None + if not isinstance(_fact_list[0], (sympy.MatrixBase, sympy.MatrixExpr, + sympy.MatrixSlice, sympy.MatrixSymbol)): + _const, _fact_list = _fact_list[0], _fact_list[1:] + + if _const is None or _const == 1: + return '.'.join(self.parenthesize(_m, PREC) for _m in _fact_list) + else: + return '{c}*{m}'.format(c=_const, m='.'.join(self.parenthesize(_m, PREC) for _m in _fact_list)) + + def _print_MatPow(self, expr): + # This function requires LinearAlgebra Function in Maple + return 'MatrixPower({A}, {n})'.format(A=self._print(expr.base), n=self._print(expr.exp)) + + def _print_HadamardProduct(self, expr): + PREC = precedence(expr) + _fact_list = list(expr.args) + return '*'.join(self.parenthesize(_m, PREC) for _m in _fact_list) + + def _print_Derivative(self, expr): + _f, (_var, _order) = expr.args + + if _order != 1: + _second_arg = '{var}${order}'.format(var=self._print(_var), + order=self._print(_order)) + else: + _second_arg = '{var}'.format(var=self._print(_var)) + return 'diff({func_expr}, {sec_arg})'.format(func_expr=self._print(_f), sec_arg=_second_arg) + + +def maple_code(expr, assign_to=None, **settings): + r"""Converts ``expr`` to a string of Maple code. + + Parameters + ========== + + expr : Expr + A SymPy expression to be converted. + assign_to : optional + When given, the argument is used as the name of the variable to which + the expression is assigned. Can be a string, ``Symbol``, + ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for + expressions that generate multi-line statements. + precision : integer, optional + The precision for numbers such as pi [default=16]. + user_functions : dict, optional + A dictionary where keys are ``FunctionClass`` instances and values are + their string representations. Alternatively, the dictionary value can + be a list of tuples i.e. [(argument_test, cfunction_string)]. See + below for examples. + human : bool, optional + If True, the result is a single string that may contain some constant + declarations for the number symbols. If False, the same information is + returned in a tuple of (symbols_to_declare, not_supported_functions, + code_text). [default=True]. + contract: bool, optional + If True, ``Indexed`` instances are assumed to obey tensor contraction + rules and the corresponding nested loops over indices are generated. + Setting contract=False will not generate loops, instead the user is + responsible to provide values for the indices in the code. + [default=True]. + inline: bool, optional + If True, we try to create single-statement code instead of multiple + statements. [default=True]. + + """ + return MapleCodePrinter(settings).doprint(expr, assign_to) + + +def print_maple_code(expr, **settings): + """Prints the Maple representation of the given expression. + + See :func:`maple_code` for the meaning of the optional arguments. + + Examples + ======== + + >>> from sympy import print_maple_code, symbols + >>> x, y = symbols('x y') + >>> print_maple_code(x, assign_to=y) + y := x + """ + print(maple_code(expr, **settings)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/mathematica.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/mathematica.py new file mode 100644 index 0000000000000000000000000000000000000000..7bfe445f3c92687ae1d80377c8944cf0828fbbf5 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/mathematica.py @@ -0,0 +1,354 @@ +""" +Mathematica code printer +""" + +from __future__ import annotations +from typing import Any + +from sympy.core import Basic, Expr, Float +from sympy.core.sorting import default_sort_key + +from sympy.printing.codeprinter import CodePrinter +from sympy.printing.precedence import precedence + +# Used in MCodePrinter._print_Function(self) +known_functions = { + "exp": [(lambda x: True, "Exp")], + "log": [(lambda x: True, "Log")], + "sin": [(lambda x: True, "Sin")], + "cos": [(lambda x: True, "Cos")], + "tan": [(lambda x: True, "Tan")], + "cot": [(lambda x: True, "Cot")], + "sec": [(lambda x: True, "Sec")], + "csc": [(lambda x: True, "Csc")], + "asin": [(lambda x: True, "ArcSin")], + "acos": [(lambda x: True, "ArcCos")], + "atan": [(lambda x: True, "ArcTan")], + "acot": [(lambda x: True, "ArcCot")], + "asec": [(lambda x: True, "ArcSec")], + "acsc": [(lambda x: True, "ArcCsc")], + "atan2": [(lambda *x: True, "ArcTan")], + "sinh": [(lambda x: True, "Sinh")], + "cosh": [(lambda x: True, "Cosh")], + "tanh": [(lambda x: True, "Tanh")], + "coth": [(lambda x: True, "Coth")], + "sech": [(lambda x: True, "Sech")], + "csch": [(lambda x: True, "Csch")], + "asinh": [(lambda x: True, "ArcSinh")], + "acosh": [(lambda x: True, "ArcCosh")], + "atanh": [(lambda x: True, "ArcTanh")], + "acoth": [(lambda x: True, "ArcCoth")], + "asech": [(lambda x: True, "ArcSech")], + "acsch": [(lambda x: True, "ArcCsch")], + "sinc": [(lambda x: True, "Sinc")], + "conjugate": [(lambda x: True, "Conjugate")], + "Max": [(lambda *x: True, "Max")], + "Min": [(lambda *x: True, "Min")], + "erf": [(lambda x: True, "Erf")], + "erf2": [(lambda *x: True, "Erf")], + "erfc": [(lambda x: True, "Erfc")], + "erfi": [(lambda x: True, "Erfi")], + "erfinv": [(lambda x: True, "InverseErf")], + "erfcinv": [(lambda x: True, "InverseErfc")], + "erf2inv": [(lambda *x: True, "InverseErf")], + "expint": [(lambda *x: True, "ExpIntegralE")], + "Ei": [(lambda x: True, "ExpIntegralEi")], + "fresnelc": [(lambda x: True, "FresnelC")], + "fresnels": [(lambda x: True, "FresnelS")], + "gamma": [(lambda x: True, "Gamma")], + "uppergamma": [(lambda *x: True, "Gamma")], + "polygamma": [(lambda *x: True, "PolyGamma")], + "loggamma": [(lambda x: True, "LogGamma")], + "beta": [(lambda *x: True, "Beta")], + "Ci": [(lambda x: True, "CosIntegral")], + "Si": [(lambda x: True, "SinIntegral")], + "Chi": [(lambda x: True, "CoshIntegral")], + "Shi": [(lambda x: True, "SinhIntegral")], + "li": [(lambda x: True, "LogIntegral")], + "factorial": [(lambda x: True, "Factorial")], + "factorial2": [(lambda x: True, "Factorial2")], + "subfactorial": [(lambda x: True, "Subfactorial")], + "catalan": [(lambda x: True, "CatalanNumber")], + "harmonic": [(lambda *x: True, "HarmonicNumber")], + "lucas": [(lambda x: True, "LucasL")], + "RisingFactorial": [(lambda *x: True, "Pochhammer")], + "FallingFactorial": [(lambda *x: True, "FactorialPower")], + "laguerre": [(lambda *x: True, "LaguerreL")], + "assoc_laguerre": [(lambda *x: True, "LaguerreL")], + "hermite": [(lambda *x: True, "HermiteH")], + "jacobi": [(lambda *x: True, "JacobiP")], + "gegenbauer": [(lambda *x: True, "GegenbauerC")], + "chebyshevt": [(lambda *x: True, "ChebyshevT")], + "chebyshevu": [(lambda *x: True, "ChebyshevU")], + "legendre": [(lambda *x: True, "LegendreP")], + "assoc_legendre": [(lambda *x: True, "LegendreP")], + "mathieuc": [(lambda *x: True, "MathieuC")], + "mathieus": [(lambda *x: True, "MathieuS")], + "mathieucprime": [(lambda *x: True, "MathieuCPrime")], + "mathieusprime": [(lambda *x: True, "MathieuSPrime")], + "stieltjes": [(lambda x: True, "StieltjesGamma")], + "elliptic_e": [(lambda *x: True, "EllipticE")], + "elliptic_f": [(lambda *x: True, "EllipticE")], + "elliptic_k": [(lambda x: True, "EllipticK")], + "elliptic_pi": [(lambda *x: True, "EllipticPi")], + "zeta": [(lambda *x: True, "Zeta")], + "dirichlet_eta": [(lambda x: True, "DirichletEta")], + "riemann_xi": [(lambda x: True, "RiemannXi")], + "besseli": [(lambda *x: True, "BesselI")], + "besselj": [(lambda *x: True, "BesselJ")], + "besselk": [(lambda *x: True, "BesselK")], + "bessely": [(lambda *x: True, "BesselY")], + "hankel1": [(lambda *x: True, "HankelH1")], + "hankel2": [(lambda *x: True, "HankelH2")], + "airyai": [(lambda x: True, "AiryAi")], + "airybi": [(lambda x: True, "AiryBi")], + "airyaiprime": [(lambda x: True, "AiryAiPrime")], + "airybiprime": [(lambda x: True, "AiryBiPrime")], + "polylog": [(lambda *x: True, "PolyLog")], + "lerchphi": [(lambda *x: True, "LerchPhi")], + "gcd": [(lambda *x: True, "GCD")], + "lcm": [(lambda *x: True, "LCM")], + "jn": [(lambda *x: True, "SphericalBesselJ")], + "yn": [(lambda *x: True, "SphericalBesselY")], + "hyper": [(lambda *x: True, "HypergeometricPFQ")], + "meijerg": [(lambda *x: True, "MeijerG")], + "appellf1": [(lambda *x: True, "AppellF1")], + "DiracDelta": [(lambda x: True, "DiracDelta")], + "Heaviside": [(lambda x: True, "HeavisideTheta")], + "KroneckerDelta": [(lambda *x: True, "KroneckerDelta")], + "sqrt": [(lambda x: True, "Sqrt")], # For automatic rewrites +} + + +class MCodePrinter(CodePrinter): + """A printer to convert Python expressions to + strings of the Wolfram's Mathematica code + """ + printmethod = "_mcode" + language = "Wolfram Language" + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'precision': 15, + 'user_functions': {}, + 'human': True, + 'allow_unknown_functions': False, + } + + _number_symbols: set[tuple[Expr, Float]] = set() + _not_supported: set[Basic] = set() + + def __init__(self, settings={}): + """Register function mappings supplied by user""" + CodePrinter.__init__(self, settings) + self.known_functions = dict(known_functions) + userfuncs = settings.get('user_functions', {}).copy() + for k, v in userfuncs.items(): + if not isinstance(v, list): + userfuncs[k] = [(lambda *x: True, v)] + self.known_functions.update(userfuncs) + + def _format_code(self, lines): + return lines + + def _print_Pow(self, expr): + PREC = precedence(expr) + return '%s^%s' % (self.parenthesize(expr.base, PREC), + self.parenthesize(expr.exp, PREC)) + + def _print_Mul(self, expr): + PREC = precedence(expr) + c, nc = expr.args_cnc() + res = super()._print_Mul(expr.func(*c)) + if nc: + res += '*' + res += '**'.join(self.parenthesize(a, PREC) for a in nc) + return res + + def _print_Relational(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + op = expr.rel_op + return "{} {} {}".format(lhs_code, op, rhs_code) + + # Primitive numbers + def _print_Zero(self, expr): + return '0' + + def _print_One(self, expr): + return '1' + + def _print_NegativeOne(self, expr): + return '-1' + + def _print_Half(self, expr): + return '1/2' + + def _print_ImaginaryUnit(self, expr): + return 'I' + + + # Infinity and invalid numbers + def _print_Infinity(self, expr): + return 'Infinity' + + def _print_NegativeInfinity(self, expr): + return '-Infinity' + + def _print_ComplexInfinity(self, expr): + return 'ComplexInfinity' + + def _print_NaN(self, expr): + return 'Indeterminate' + + + # Mathematical constants + def _print_Exp1(self, expr): + return 'E' + + def _print_Pi(self, expr): + return 'Pi' + + def _print_GoldenRatio(self, expr): + return 'GoldenRatio' + + def _print_TribonacciConstant(self, expr): + expanded = expr.expand(func=True) + PREC = precedence(expr) + return self.parenthesize(expanded, PREC) + + def _print_EulerGamma(self, expr): + return 'EulerGamma' + + def _print_Catalan(self, expr): + return 'Catalan' + + + def _print_list(self, expr): + return '{' + ', '.join(self.doprint(a) for a in expr) + '}' + _print_tuple = _print_list + _print_Tuple = _print_list + + def _print_ImmutableDenseMatrix(self, expr): + return self.doprint(expr.tolist()) + + def _print_ImmutableSparseMatrix(self, expr): + + def print_rule(pos, val): + return '{} -> {}'.format( + self.doprint((pos[0]+1, pos[1]+1)), self.doprint(val)) + + def print_data(): + items = sorted(expr.todok().items(), key=default_sort_key) + return '{' + \ + ', '.join(print_rule(k, v) for k, v in items) + \ + '}' + + def print_dims(): + return self.doprint(expr.shape) + + return 'SparseArray[{}, {}]'.format(print_data(), print_dims()) + + def _print_ImmutableDenseNDimArray(self, expr): + return self.doprint(expr.tolist()) + + def _print_ImmutableSparseNDimArray(self, expr): + def print_string_list(string_list): + return '{' + ', '.join(a for a in string_list) + '}' + + def to_mathematica_index(*args): + """Helper function to change Python style indexing to + Pathematica indexing. + + Python indexing (0, 1 ... n-1) + -> Mathematica indexing (1, 2 ... n) + """ + return tuple(i + 1 for i in args) + + def print_rule(pos, val): + """Helper function to print a rule of Mathematica""" + return '{} -> {}'.format(self.doprint(pos), self.doprint(val)) + + def print_data(): + """Helper function to print data part of Mathematica + sparse array. + + It uses the fourth notation ``SparseArray[data,{d1,d2,...}]`` + from + https://reference.wolfram.com/language/ref/SparseArray.html + + ``data`` must be formatted with rule. + """ + return print_string_list( + [print_rule( + to_mathematica_index(*(expr._get_tuple_index(key))), + value) + for key, value in sorted(expr._sparse_array.items())] + ) + + def print_dims(): + """Helper function to print dimensions part of Mathematica + sparse array. + + It uses the fourth notation ``SparseArray[data,{d1,d2,...}]`` + from + https://reference.wolfram.com/language/ref/SparseArray.html + """ + return self.doprint(expr.shape) + + return 'SparseArray[{}, {}]'.format(print_data(), print_dims()) + + def _print_Function(self, expr): + if expr.func.__name__ in self.known_functions: + cond_mfunc = self.known_functions[expr.func.__name__] + for cond, mfunc in cond_mfunc: + if cond(*expr.args): + return "%s[%s]" % (mfunc, self.stringify(expr.args, ", ")) + elif expr.func.__name__ in self._rewriteable_functions: + # Simple rewrite to supported function possible + target_f, required_fs = self._rewriteable_functions[expr.func.__name__] + if self._can_print(target_f) and all(self._can_print(f) for f in required_fs): + return self._print(expr.rewrite(target_f)) + return expr.func.__name__ + "[%s]" % self.stringify(expr.args, ", ") + + _print_MinMaxBase = _print_Function + + def _print_LambertW(self, expr): + if len(expr.args) == 1: + return "ProductLog[{}]".format(self._print(expr.args[0])) + return "ProductLog[{}, {}]".format( + self._print(expr.args[1]), self._print(expr.args[0])) + + def _print_Integral(self, expr): + if len(expr.variables) == 1 and not expr.limits[0][1:]: + args = [expr.args[0], expr.variables[0]] + else: + args = expr.args + return "Hold[Integrate[" + ', '.join(self.doprint(a) for a in args) + "]]" + + def _print_Sum(self, expr): + return "Hold[Sum[" + ', '.join(self.doprint(a) for a in expr.args) + "]]" + + def _print_Derivative(self, expr): + dexpr = expr.expr + dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count] + return "Hold[D[" + ', '.join(self.doprint(a) for a in [dexpr] + dvars) + "]]" + + + def _get_comment(self, text): + return "(* {} *)".format(text) + + +def mathematica_code(expr, **settings): + r"""Converts an expr to a string of the Wolfram Mathematica code + + Examples + ======== + + >>> from sympy import mathematica_code as mcode, symbols, sin + >>> x = symbols('x') + >>> mcode(sin(x).series(x).removeO()) + '(1/120)*x^5 - 1/6*x^3 + x' + """ + return MCodePrinter(settings).doprint(expr) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/mathml.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/mathml.py new file mode 100644 index 0000000000000000000000000000000000000000..16e269566c20b3034a9818e5c10f813b171a0d2e --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/mathml.py @@ -0,0 +1,2126 @@ +""" +A MathML printer. +""" + +from __future__ import annotations +from typing import Any + +from sympy.core.mul import Mul +from sympy.core.singleton import S +from sympy.core.sorting import default_sort_key +from sympy.core.sympify import sympify +from sympy.printing.conventions import split_super_sub, requires_partial +from sympy.printing.precedence import \ + precedence_traditional, PRECEDENCE, PRECEDENCE_TRADITIONAL +from sympy.printing.pretty.pretty_symbology import greek_unicode +from sympy.printing.printer import Printer, print_function + +from mpmath.libmp import prec_to_dps, repr_dps, to_str as mlib_to_str + + +class MathMLPrinterBase(Printer): + """Contains common code required for MathMLContentPrinter and + MathMLPresentationPrinter. + """ + + _default_settings: dict[str, Any] = { + "order": None, + "encoding": "utf-8", + "fold_frac_powers": False, + "fold_func_brackets": False, + "fold_short_frac": None, + "inv_trig_style": "abbreviated", + "ln_notation": False, + "long_frac_ratio": None, + "mat_delim": "[", + "mat_symbol_style": "plain", + "mul_symbol": None, + "root_notation": True, + "symbol_names": {}, + "mul_symbol_mathml_numbers": '·', + } + + def __init__(self, settings=None): + Printer.__init__(self, settings) + from xml.dom.minidom import Document, Text + + self.dom = Document() + + # Workaround to allow strings to remain unescaped + # Based on + # https://stackoverflow.com/questions/38015864/python-xml-dom-minidom-\ + # please-dont-escape-my-strings/38041194 + class RawText(Text): + def writexml(self, writer, indent='', addindent='', newl=''): + if self.data: + writer.write('{}{}{}'.format(indent, self.data, newl)) + + def createRawTextNode(data): + r = RawText() + r.data = data + r.ownerDocument = self.dom + return r + + self.dom.createTextNode = createRawTextNode + + def doprint(self, expr): + """ + Prints the expression as MathML. + """ + mathML = Printer._print(self, expr) + unistr = mathML.toxml() + xmlbstr = unistr.encode('ascii', 'xmlcharrefreplace') + res = xmlbstr.decode() + return res + + def apply_patch(self): + # Applying the patch of xml.dom.minidom bug + # Date: 2011-11-18 + # Description: http://ronrothman.com/public/leftbraned/xml-dom-minidom\ + # -toprettyxml-and-silly-whitespace/#best-solution + # Issue: https://bugs.python.org/issue4147 + # Patch: https://hg.python.org/cpython/rev/7262f8f276ff/ + + from xml.dom.minidom import Element, Text, Node, _write_data + + def writexml(self, writer, indent="", addindent="", newl=""): + # indent = current indentation + # addindent = indentation to add to higher levels + # newl = newline string + writer.write(indent + "<" + self.tagName) + + attrs = self._get_attributes() + a_names = list(attrs.keys()) + a_names.sort() + + for a_name in a_names: + writer.write(" %s=\"" % a_name) + _write_data(writer, attrs[a_name].value) + writer.write("\"") + if self.childNodes: + writer.write(">") + if (len(self.childNodes) == 1 and + self.childNodes[0].nodeType == Node.TEXT_NODE): + self.childNodes[0].writexml(writer, '', '', '') + else: + writer.write(newl) + for node in self.childNodes: + node.writexml( + writer, indent + addindent, addindent, newl) + writer.write(indent) + writer.write("%s" % (self.tagName, newl)) + else: + writer.write("/>%s" % (newl)) + self._Element_writexml_old = Element.writexml + Element.writexml = writexml + + def writexml(self, writer, indent="", addindent="", newl=""): + _write_data(writer, "%s%s%s" % (indent, self.data, newl)) + self._Text_writexml_old = Text.writexml + Text.writexml = writexml + + def restore_patch(self): + from xml.dom.minidom import Element, Text + Element.writexml = self._Element_writexml_old + Text.writexml = self._Text_writexml_old + + +class MathMLContentPrinter(MathMLPrinterBase): + """Prints an expression to the Content MathML markup language. + + References: https://www.w3.org/TR/MathML2/chapter4.html + """ + printmethod = "_mathml_content" + + def mathml_tag(self, e): + """Returns the MathML tag for an expression.""" + translate = { + 'Add': 'plus', + 'Mul': 'times', + 'Derivative': 'diff', + 'Number': 'cn', + 'int': 'cn', + 'Pow': 'power', + 'Max': 'max', + 'Min': 'min', + 'Abs': 'abs', + 'And': 'and', + 'Or': 'or', + 'Xor': 'xor', + 'Not': 'not', + 'Implies': 'implies', + 'Symbol': 'ci', + 'MatrixSymbol': 'ci', + 'RandomSymbol': 'ci', + 'Integral': 'int', + 'Sum': 'sum', + 'sin': 'sin', + 'cos': 'cos', + 'tan': 'tan', + 'cot': 'cot', + 'csc': 'csc', + 'sec': 'sec', + 'sinh': 'sinh', + 'cosh': 'cosh', + 'tanh': 'tanh', + 'coth': 'coth', + 'csch': 'csch', + 'sech': 'sech', + 'asin': 'arcsin', + 'asinh': 'arcsinh', + 'acos': 'arccos', + 'acosh': 'arccosh', + 'atan': 'arctan', + 'atanh': 'arctanh', + 'atan2': 'arctan', + 'acot': 'arccot', + 'acoth': 'arccoth', + 'asec': 'arcsec', + 'asech': 'arcsech', + 'acsc': 'arccsc', + 'acsch': 'arccsch', + 'log': 'ln', + 'Equality': 'eq', + 'Unequality': 'neq', + 'GreaterThan': 'geq', + 'LessThan': 'leq', + 'StrictGreaterThan': 'gt', + 'StrictLessThan': 'lt', + 'Union': 'union', + 'Intersection': 'intersect', + } + + for cls in e.__class__.__mro__: + n = cls.__name__ + if n in translate: + return translate[n] + # Not found in the MRO set + n = e.__class__.__name__ + return n.lower() + + def _print_Mul(self, expr): + + if expr.could_extract_minus_sign(): + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement('minus')) + x.appendChild(self._print_Mul(-expr)) + return x + + from sympy.simplify import fraction + numer, denom = fraction(expr) + + if denom is not S.One: + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement('divide')) + x.appendChild(self._print(numer)) + x.appendChild(self._print(denom)) + return x + + coeff, terms = expr.as_coeff_mul() + if coeff is S.One and len(terms) == 1: + # XXX since the negative coefficient has been handled, I don't + # think a coeff of 1 can remain + return self._print(terms[0]) + + if self.order != 'old': + terms = Mul._from_args(terms).as_ordered_factors() + + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement('times')) + if coeff != 1: + x.appendChild(self._print(coeff)) + for term in terms: + x.appendChild(self._print(term)) + return x + + def _print_Add(self, expr, order=None): + args = self._as_ordered_terms(expr, order=order) + lastProcessed = self._print(args[0]) + plusNodes = [] + for arg in args[1:]: + if arg.could_extract_minus_sign(): + # use minus + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement('minus')) + x.appendChild(lastProcessed) + x.appendChild(self._print(-arg)) + # invert expression since this is now minused + lastProcessed = x + if arg == args[-1]: + plusNodes.append(lastProcessed) + else: + plusNodes.append(lastProcessed) + lastProcessed = self._print(arg) + if arg == args[-1]: + plusNodes.append(self._print(arg)) + if len(plusNodes) == 1: + return lastProcessed + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement('plus')) + while plusNodes: + x.appendChild(plusNodes.pop(0)) + return x + + def _print_Piecewise(self, expr): + if expr.args[-1].cond != True: + # We need the last conditional to be a True, otherwise the resulting + # function may not return a result. + raise ValueError("All Piecewise expressions must contain an " + "(expr, True) statement to be used as a default " + "condition. Without one, the generated " + "expression may not evaluate to anything under " + "some condition.") + root = self.dom.createElement('piecewise') + for i, (e, c) in enumerate(expr.args): + if i == len(expr.args) - 1 and c == True: + piece = self.dom.createElement('otherwise') + piece.appendChild(self._print(e)) + else: + piece = self.dom.createElement('piece') + piece.appendChild(self._print(e)) + piece.appendChild(self._print(c)) + root.appendChild(piece) + return root + + def _print_MatrixBase(self, m): + x = self.dom.createElement('matrix') + for i in range(m.rows): + x_r = self.dom.createElement('matrixrow') + for j in range(m.cols): + x_r.appendChild(self._print(m[i, j])) + x.appendChild(x_r) + return x + + def _print_Rational(self, e): + if e.q == 1: + # don't divide + x = self.dom.createElement('cn') + x.appendChild(self.dom.createTextNode(str(e.p))) + return x + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement('divide')) + # numerator + xnum = self.dom.createElement('cn') + xnum.appendChild(self.dom.createTextNode(str(e.p))) + # denominator + xdenom = self.dom.createElement('cn') + xdenom.appendChild(self.dom.createTextNode(str(e.q))) + x.appendChild(xnum) + x.appendChild(xdenom) + return x + + def _print_Limit(self, e): + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement(self.mathml_tag(e))) + + x_1 = self.dom.createElement('bvar') + x_2 = self.dom.createElement('lowlimit') + x_1.appendChild(self._print(e.args[1])) + x_2.appendChild(self._print(e.args[2])) + + x.appendChild(x_1) + x.appendChild(x_2) + x.appendChild(self._print(e.args[0])) + return x + + def _print_ImaginaryUnit(self, e): + return self.dom.createElement('imaginaryi') + + def _print_EulerGamma(self, e): + return self.dom.createElement('eulergamma') + + def _print_GoldenRatio(self, e): + """We use unicode #x3c6 for Greek letter phi as defined here + https://www.w3.org/2003/entities/2007doc/isogrk1.html""" + x = self.dom.createElement('cn') + x.appendChild(self.dom.createTextNode("\N{GREEK SMALL LETTER PHI}")) + return x + + def _print_Exp1(self, e): + return self.dom.createElement('exponentiale') + + def _print_Pi(self, e): + return self.dom.createElement('pi') + + def _print_Infinity(self, e): + return self.dom.createElement('infinity') + + def _print_NaN(self, e): + return self.dom.createElement('notanumber') + + def _print_EmptySet(self, e): + return self.dom.createElement('emptyset') + + def _print_BooleanTrue(self, e): + return self.dom.createElement('true') + + def _print_BooleanFalse(self, e): + return self.dom.createElement('false') + + def _print_NegativeInfinity(self, e): + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement('minus')) + x.appendChild(self.dom.createElement('infinity')) + return x + + def _print_Integral(self, e): + def lime_recur(limits): + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement(self.mathml_tag(e))) + bvar_elem = self.dom.createElement('bvar') + bvar_elem.appendChild(self._print(limits[0][0])) + x.appendChild(bvar_elem) + + if len(limits[0]) == 3: + low_elem = self.dom.createElement('lowlimit') + low_elem.appendChild(self._print(limits[0][1])) + x.appendChild(low_elem) + up_elem = self.dom.createElement('uplimit') + up_elem.appendChild(self._print(limits[0][2])) + x.appendChild(up_elem) + if len(limits[0]) == 2: + up_elem = self.dom.createElement('uplimit') + up_elem.appendChild(self._print(limits[0][1])) + x.appendChild(up_elem) + if len(limits) == 1: + x.appendChild(self._print(e.function)) + else: + x.appendChild(lime_recur(limits[1:])) + return x + + limits = list(e.limits) + limits.reverse() + return lime_recur(limits) + + def _print_Sum(self, e): + # Printer can be shared because Sum and Integral have the + # same internal representation. + return self._print_Integral(e) + + def _print_Symbol(self, sym): + ci = self.dom.createElement(self.mathml_tag(sym)) + + def join(items): + if len(items) > 1: + mrow = self.dom.createElement('mml:mrow') + for i, item in enumerate(items): + if i > 0: + mo = self.dom.createElement('mml:mo') + mo.appendChild(self.dom.createTextNode(" ")) + mrow.appendChild(mo) + mi = self.dom.createElement('mml:mi') + mi.appendChild(self.dom.createTextNode(item)) + mrow.appendChild(mi) + return mrow + else: + mi = self.dom.createElement('mml:mi') + mi.appendChild(self.dom.createTextNode(items[0])) + return mi + + # translate name, supers and subs to unicode characters + def translate(s): + if s in greek_unicode: + return greek_unicode.get(s) + else: + return s + + name, supers, subs = split_super_sub(sym.name) + name = translate(name) + supers = [translate(sup) for sup in supers] + subs = [translate(sub) for sub in subs] + + mname = self.dom.createElement('mml:mi') + mname.appendChild(self.dom.createTextNode(name)) + if not supers: + if not subs: + ci.appendChild(self.dom.createTextNode(name)) + else: + msub = self.dom.createElement('mml:msub') + msub.appendChild(mname) + msub.appendChild(join(subs)) + ci.appendChild(msub) + else: + if not subs: + msup = self.dom.createElement('mml:msup') + msup.appendChild(mname) + msup.appendChild(join(supers)) + ci.appendChild(msup) + else: + msubsup = self.dom.createElement('mml:msubsup') + msubsup.appendChild(mname) + msubsup.appendChild(join(subs)) + msubsup.appendChild(join(supers)) + ci.appendChild(msubsup) + return ci + + _print_MatrixSymbol = _print_Symbol + _print_RandomSymbol = _print_Symbol + + def _print_Pow(self, e): + # Here we use root instead of power if the exponent is the reciprocal + # of an integer + if (self._settings['root_notation'] and e.exp.is_Rational + and e.exp.p == 1): + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement('root')) + if e.exp.q != 2: + xmldeg = self.dom.createElement('degree') + xmlcn = self.dom.createElement('cn') + xmlcn.appendChild(self.dom.createTextNode(str(e.exp.q))) + xmldeg.appendChild(xmlcn) + x.appendChild(xmldeg) + x.appendChild(self._print(e.base)) + return x + + x = self.dom.createElement('apply') + x_1 = self.dom.createElement(self.mathml_tag(e)) + x.appendChild(x_1) + x.appendChild(self._print(e.base)) + x.appendChild(self._print(e.exp)) + return x + + def _print_Number(self, e): + x = self.dom.createElement(self.mathml_tag(e)) + x.appendChild(self.dom.createTextNode(str(e))) + return x + + def _print_Float(self, e): + x = self.dom.createElement(self.mathml_tag(e)) + repr_e = mlib_to_str(e._mpf_, repr_dps(e._prec)) + x.appendChild(self.dom.createTextNode(repr_e)) + return x + + def _print_Derivative(self, e): + x = self.dom.createElement('apply') + diff_symbol = self.mathml_tag(e) + if requires_partial(e.expr): + diff_symbol = 'partialdiff' + x.appendChild(self.dom.createElement(diff_symbol)) + x_1 = self.dom.createElement('bvar') + + for sym, times in reversed(e.variable_count): + x_1.appendChild(self._print(sym)) + if times > 1: + degree = self.dom.createElement('degree') + degree.appendChild(self._print(sympify(times))) + x_1.appendChild(degree) + + x.appendChild(x_1) + x.appendChild(self._print(e.expr)) + return x + + def _print_Function(self, e): + x = self.dom.createElement("apply") + x.appendChild(self.dom.createElement(self.mathml_tag(e))) + for arg in e.args: + x.appendChild(self._print(arg)) + return x + + def _print_Basic(self, e): + x = self.dom.createElement(self.mathml_tag(e)) + for arg in e.args: + x.appendChild(self._print(arg)) + return x + + def _print_AssocOp(self, e): + x = self.dom.createElement('apply') + x_1 = self.dom.createElement(self.mathml_tag(e)) + x.appendChild(x_1) + for arg in e.args: + x.appendChild(self._print(arg)) + return x + + def _print_Relational(self, e): + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement(self.mathml_tag(e))) + x.appendChild(self._print(e.lhs)) + x.appendChild(self._print(e.rhs)) + return x + + def _print_list(self, seq): + """MathML reference for the element: + https://www.w3.org/TR/MathML2/chapter4.html#contm.list""" + dom_element = self.dom.createElement('list') + for item in seq: + dom_element.appendChild(self._print(item)) + return dom_element + + def _print_int(self, p): + dom_element = self.dom.createElement(self.mathml_tag(p)) + dom_element.appendChild(self.dom.createTextNode(str(p))) + return dom_element + + _print_Implies = _print_AssocOp + _print_Not = _print_AssocOp + _print_Xor = _print_AssocOp + + def _print_FiniteSet(self, e): + x = self.dom.createElement('set') + for arg in e.args: + x.appendChild(self._print(arg)) + return x + + def _print_Complement(self, e): + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement('setdiff')) + for arg in e.args: + x.appendChild(self._print(arg)) + return x + + def _print_ProductSet(self, e): + x = self.dom.createElement('apply') + x.appendChild(self.dom.createElement('cartesianproduct')) + for arg in e.args: + x.appendChild(self._print(arg)) + return x + + # XXX Symmetric difference is not supported for MathML content printers. + + +class MathMLPresentationPrinter(MathMLPrinterBase): + """Prints an expression to the Presentation MathML markup language. + + References: https://www.w3.org/TR/MathML2/chapter3.html + """ + printmethod = "_mathml_presentation" + + def mathml_tag(self, e): + """Returns the MathML tag for an expression.""" + translate = { + 'Number': 'mn', + 'Limit': '→', + 'Derivative': 'ⅆ', + 'int': 'mn', + 'Symbol': 'mi', + 'Integral': '∫', + 'Sum': '∑', + 'sin': 'sin', + 'cos': 'cos', + 'tan': 'tan', + 'cot': 'cot', + 'asin': 'arcsin', + 'asinh': 'arcsinh', + 'acos': 'arccos', + 'acosh': 'arccosh', + 'atan': 'arctan', + 'atanh': 'arctanh', + 'acot': 'arccot', + 'atan2': 'arctan', + 'Equality': '=', + 'Unequality': '≠', + 'GreaterThan': '≥', + 'LessThan': '≤', + 'StrictGreaterThan': '>', + 'StrictLessThan': '<', + 'lerchphi': 'Φ', + 'zeta': 'ζ', + 'dirichlet_eta': 'η', + 'elliptic_k': 'Κ', + 'lowergamma': 'γ', + 'uppergamma': 'Γ', + 'gamma': 'Γ', + 'totient': 'ϕ', + 'reduced_totient': 'λ', + 'primenu': 'ν', + 'primeomega': 'Ω', + 'fresnels': 'S', + 'fresnelc': 'C', + 'LambertW': 'W', + 'Heaviside': 'Θ', + 'BooleanTrue': 'True', + 'BooleanFalse': 'False', + 'NoneType': 'None', + 'mathieus': 'S', + 'mathieuc': 'C', + 'mathieusprime': 'S′', + 'mathieucprime': 'C′', + } + + def mul_symbol_selection(): + if (self._settings["mul_symbol"] is None or + self._settings["mul_symbol"] == 'None'): + return '⁢' + elif self._settings["mul_symbol"] == 'times': + return '×' + elif self._settings["mul_symbol"] == 'dot': + return '·' + elif self._settings["mul_symbol"] == 'ldot': + return '․' + elif not isinstance(self._settings["mul_symbol"], str): + raise TypeError + else: + return self._settings["mul_symbol"] + for cls in e.__class__.__mro__: + n = cls.__name__ + if n in translate: + return translate[n] + # Not found in the MRO set + if e.__class__.__name__ == "Mul": + return mul_symbol_selection() + n = e.__class__.__name__ + return n.lower() + + def parenthesize(self, item, level, strict=False): + prec_val = precedence_traditional(item) + if (prec_val < level) or ((not strict) and prec_val <= level): + brac = self.dom.createElement('mfenced') + brac.appendChild(self._print(item)) + return brac + else: + return self._print(item) + + def _print_Mul(self, expr): + + def multiply(expr, mrow): + from sympy.simplify import fraction + numer, denom = fraction(expr) + if denom is not S.One: + frac = self.dom.createElement('mfrac') + if self._settings["fold_short_frac"] and len(str(expr)) < 7: + frac.setAttribute('bevelled', 'true') + xnum = self._print(numer) + xden = self._print(denom) + frac.appendChild(xnum) + frac.appendChild(xden) + mrow.appendChild(frac) + return mrow + + coeff, terms = expr.as_coeff_mul() + if coeff is S.One and len(terms) == 1: + mrow.appendChild(self._print(terms[0])) + return mrow + if self.order != 'old': + terms = Mul._from_args(terms).as_ordered_factors() + + if coeff != 1: + x = self._print(coeff) + y = self.dom.createElement('mo') + y.appendChild(self.dom.createTextNode(self.mathml_tag(expr))) + mrow.appendChild(x) + mrow.appendChild(y) + for term in terms: + mrow.appendChild(self.parenthesize(term, PRECEDENCE['Mul'])) + if not term == terms[-1]: + y = self.dom.createElement('mo') + y.appendChild(self.dom.createTextNode(self.mathml_tag(expr))) + mrow.appendChild(y) + return mrow + mrow = self.dom.createElement('mrow') + if expr.could_extract_minus_sign(): + x = self.dom.createElement('mo') + x.appendChild(self.dom.createTextNode('-')) + mrow.appendChild(x) + mrow = multiply(-expr, mrow) + else: + mrow = multiply(expr, mrow) + + return mrow + + def _print_Add(self, expr, order=None): + mrow = self.dom.createElement('mrow') + args = self._as_ordered_terms(expr, order=order) + mrow.appendChild(self._print(args[0])) + for arg in args[1:]: + if arg.could_extract_minus_sign(): + # use minus + x = self.dom.createElement('mo') + x.appendChild(self.dom.createTextNode('-')) + y = self._print(-arg) + # invert expression since this is now minused + else: + x = self.dom.createElement('mo') + x.appendChild(self.dom.createTextNode('+')) + y = self._print(arg) + mrow.appendChild(x) + mrow.appendChild(y) + + return mrow + + def _print_MatrixBase(self, m): + table = self.dom.createElement('mtable') + for i in range(m.rows): + x = self.dom.createElement('mtr') + for j in range(m.cols): + y = self.dom.createElement('mtd') + y.appendChild(self._print(m[i, j])) + x.appendChild(y) + table.appendChild(x) + if self._settings["mat_delim"] == '': + return table + brac = self.dom.createElement('mfenced') + if self._settings["mat_delim"] == "[": + brac.setAttribute('close', ']') + brac.setAttribute('open', '[') + brac.appendChild(table) + return brac + + def _get_printed_Rational(self, e, folded=None): + if e.p < 0: + p = -e.p + else: + p = e.p + x = self.dom.createElement('mfrac') + if folded or self._settings["fold_short_frac"]: + x.setAttribute('bevelled', 'true') + x.appendChild(self._print(p)) + x.appendChild(self._print(e.q)) + if e.p < 0: + mrow = self.dom.createElement('mrow') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('-')) + mrow.appendChild(mo) + mrow.appendChild(x) + return mrow + else: + return x + + def _print_Rational(self, e): + if e.q == 1: + # don't divide + return self._print(e.p) + + return self._get_printed_Rational(e, self._settings["fold_short_frac"]) + + def _print_Limit(self, e): + mrow = self.dom.createElement('mrow') + munder = self.dom.createElement('munder') + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode('lim')) + + x = self.dom.createElement('mrow') + x_1 = self._print(e.args[1]) + arrow = self.dom.createElement('mo') + arrow.appendChild(self.dom.createTextNode(self.mathml_tag(e))) + x_2 = self._print(e.args[2]) + x.appendChild(x_1) + x.appendChild(arrow) + x.appendChild(x_2) + + munder.appendChild(mi) + munder.appendChild(x) + mrow.appendChild(munder) + mrow.appendChild(self._print(e.args[0])) + + return mrow + + def _print_ImaginaryUnit(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('ⅈ')) + return x + + def _print_GoldenRatio(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('Φ')) + return x + + def _print_Exp1(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('ⅇ')) + return x + + def _print_Pi(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('π')) + return x + + def _print_Infinity(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('∞')) + return x + + def _print_NegativeInfinity(self, e): + mrow = self.dom.createElement('mrow') + y = self.dom.createElement('mo') + y.appendChild(self.dom.createTextNode('-')) + x = self._print_Infinity(e) + mrow.appendChild(y) + mrow.appendChild(x) + return mrow + + def _print_HBar(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('ℏ')) + return x + + def _print_EulerGamma(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('γ')) + return x + + def _print_TribonacciConstant(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('TribonacciConstant')) + return x + + def _print_Dagger(self, e): + msup = self.dom.createElement('msup') + msup.appendChild(self._print(e.args[0])) + msup.appendChild(self.dom.createTextNode('†')) + return msup + + def _print_Contains(self, e): + mrow = self.dom.createElement('mrow') + mrow.appendChild(self._print(e.args[0])) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('∈')) + mrow.appendChild(mo) + mrow.appendChild(self._print(e.args[1])) + return mrow + + def _print_HilbertSpace(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('ℋ')) + return x + + def _print_ComplexSpace(self, e): + msup = self.dom.createElement('msup') + msup.appendChild(self.dom.createTextNode('𝒞')) + msup.appendChild(self._print(e.args[0])) + return msup + + def _print_FockSpace(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('ℱ')) + return x + + + def _print_Integral(self, expr): + intsymbols = {1: "∫", 2: "∬", 3: "∭"} + + mrow = self.dom.createElement('mrow') + if len(expr.limits) <= 3 and all(len(lim) == 1 for lim in expr.limits): + # Only up to three-integral signs exists + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode(intsymbols[len(expr.limits)])) + mrow.appendChild(mo) + else: + # Either more than three or limits provided + for lim in reversed(expr.limits): + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode(intsymbols[1])) + if len(lim) == 1: + mrow.appendChild(mo) + if len(lim) == 2: + msup = self.dom.createElement('msup') + msup.appendChild(mo) + msup.appendChild(self._print(lim[1])) + mrow.appendChild(msup) + if len(lim) == 3: + msubsup = self.dom.createElement('msubsup') + msubsup.appendChild(mo) + msubsup.appendChild(self._print(lim[1])) + msubsup.appendChild(self._print(lim[2])) + mrow.appendChild(msubsup) + # print function + mrow.appendChild(self.parenthesize(expr.function, PRECEDENCE["Mul"], + strict=True)) + # print integration variables + for lim in reversed(expr.limits): + d = self.dom.createElement('mo') + d.appendChild(self.dom.createTextNode('ⅆ')) + mrow.appendChild(d) + mrow.appendChild(self._print(lim[0])) + return mrow + + def _print_Sum(self, e): + limits = list(e.limits) + subsup = self.dom.createElement('munderover') + low_elem = self._print(limits[0][1]) + up_elem = self._print(limits[0][2]) + summand = self.dom.createElement('mo') + summand.appendChild(self.dom.createTextNode(self.mathml_tag(e))) + + low = self.dom.createElement('mrow') + var = self._print(limits[0][0]) + equal = self.dom.createElement('mo') + equal.appendChild(self.dom.createTextNode('=')) + low.appendChild(var) + low.appendChild(equal) + low.appendChild(low_elem) + + subsup.appendChild(summand) + subsup.appendChild(low) + subsup.appendChild(up_elem) + + mrow = self.dom.createElement('mrow') + mrow.appendChild(subsup) + if len(str(e.function)) == 1: + mrow.appendChild(self._print(e.function)) + else: + fence = self.dom.createElement('mfenced') + fence.appendChild(self._print(e.function)) + mrow.appendChild(fence) + + return mrow + + def _print_Symbol(self, sym, style='plain'): + def join(items): + if len(items) > 1: + mrow = self.dom.createElement('mrow') + for i, item in enumerate(items): + if i > 0: + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode(" ")) + mrow.appendChild(mo) + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode(item)) + mrow.appendChild(mi) + return mrow + else: + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode(items[0])) + return mi + + # translate name, supers and subs to unicode characters + def translate(s): + if s in greek_unicode: + return greek_unicode.get(s) + else: + return s + + name, supers, subs = split_super_sub(sym.name) + name = translate(name) + supers = [translate(sup) for sup in supers] + subs = [translate(sub) for sub in subs] + + mname = self.dom.createElement('mi') + mname.appendChild(self.dom.createTextNode(name)) + if len(supers) == 0: + if len(subs) == 0: + x = mname + else: + x = self.dom.createElement('msub') + x.appendChild(mname) + x.appendChild(join(subs)) + else: + if len(subs) == 0: + x = self.dom.createElement('msup') + x.appendChild(mname) + x.appendChild(join(supers)) + else: + x = self.dom.createElement('msubsup') + x.appendChild(mname) + x.appendChild(join(subs)) + x.appendChild(join(supers)) + # Set bold font? + if style == 'bold': + x.setAttribute('mathvariant', 'bold') + return x + + def _print_MatrixSymbol(self, sym): + return self._print_Symbol(sym, + style=self._settings['mat_symbol_style']) + + _print_RandomSymbol = _print_Symbol + + def _print_conjugate(self, expr): + enc = self.dom.createElement('menclose') + enc.setAttribute('notation', 'top') + enc.appendChild(self._print(expr.args[0])) + return enc + + def _print_operator_after(self, op, expr): + row = self.dom.createElement('mrow') + row.appendChild(self.parenthesize(expr, PRECEDENCE["Func"])) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode(op)) + row.appendChild(mo) + return row + + def _print_factorial(self, expr): + return self._print_operator_after('!', expr.args[0]) + + def _print_factorial2(self, expr): + return self._print_operator_after('!!', expr.args[0]) + + def _print_binomial(self, expr): + brac = self.dom.createElement('mfenced') + frac = self.dom.createElement('mfrac') + frac.setAttribute('linethickness', '0') + frac.appendChild(self._print(expr.args[0])) + frac.appendChild(self._print(expr.args[1])) + brac.appendChild(frac) + return brac + + def _print_Pow(self, e): + # Here we use root instead of power if the exponent is the + # reciprocal of an integer + if (e.exp.is_Rational and abs(e.exp.p) == 1 and e.exp.q != 1 and + self._settings['root_notation']): + if e.exp.q == 2: + x = self.dom.createElement('msqrt') + x.appendChild(self._print(e.base)) + if e.exp.q != 2: + x = self.dom.createElement('mroot') + x.appendChild(self._print(e.base)) + x.appendChild(self._print(e.exp.q)) + if e.exp.p == -1: + frac = self.dom.createElement('mfrac') + frac.appendChild(self._print(1)) + frac.appendChild(x) + return frac + else: + return x + + if e.exp.is_Rational and e.exp.q != 1: + if e.exp.is_negative: + top = self.dom.createElement('mfrac') + top.appendChild(self._print(1)) + x = self.dom.createElement('msup') + x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow'])) + x.appendChild(self._get_printed_Rational(-e.exp, + self._settings['fold_frac_powers'])) + top.appendChild(x) + return top + else: + x = self.dom.createElement('msup') + x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow'])) + x.appendChild(self._get_printed_Rational(e.exp, + self._settings['fold_frac_powers'])) + return x + + if e.exp.is_negative: + top = self.dom.createElement('mfrac') + top.appendChild(self._print(1)) + if e.exp == -1: + top.appendChild(self._print(e.base)) + else: + x = self.dom.createElement('msup') + x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow'])) + x.appendChild(self._print(-e.exp)) + top.appendChild(x) + return top + + x = self.dom.createElement('msup') + x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow'])) + x.appendChild(self._print(e.exp)) + return x + + def _print_Number(self, e): + x = self.dom.createElement(self.mathml_tag(e)) + x.appendChild(self.dom.createTextNode(str(e))) + return x + + def _print_AccumulationBounds(self, i): + brac = self.dom.createElement('mfenced') + brac.setAttribute('close', '\u27e9') + brac.setAttribute('open', '\u27e8') + brac.appendChild(self._print(i.min)) + brac.appendChild(self._print(i.max)) + return brac + + def _print_Derivative(self, e): + + if requires_partial(e.expr): + d = '∂' + else: + d = self.mathml_tag(e) + + # Determine denominator + m = self.dom.createElement('mrow') + dim = 0 # Total diff dimension, for numerator + for sym, num in reversed(e.variable_count): + dim += num + if num >= 2: + x = self.dom.createElement('msup') + xx = self.dom.createElement('mo') + xx.appendChild(self.dom.createTextNode(d)) + x.appendChild(xx) + x.appendChild(self._print(num)) + else: + x = self.dom.createElement('mo') + x.appendChild(self.dom.createTextNode(d)) + m.appendChild(x) + y = self._print(sym) + m.appendChild(y) + + mnum = self.dom.createElement('mrow') + if dim >= 2: + x = self.dom.createElement('msup') + xx = self.dom.createElement('mo') + xx.appendChild(self.dom.createTextNode(d)) + x.appendChild(xx) + x.appendChild(self._print(dim)) + else: + x = self.dom.createElement('mo') + x.appendChild(self.dom.createTextNode(d)) + + mnum.appendChild(x) + mrow = self.dom.createElement('mrow') + frac = self.dom.createElement('mfrac') + frac.appendChild(mnum) + frac.appendChild(m) + mrow.appendChild(frac) + + # Print function + mrow.appendChild(self._print(e.expr)) + + return mrow + + def _print_Function(self, e): + mrow = self.dom.createElement('mrow') + x = self.dom.createElement('mi') + if self.mathml_tag(e) == 'log' and self._settings["ln_notation"]: + x.appendChild(self.dom.createTextNode('ln')) + else: + x.appendChild(self.dom.createTextNode(self.mathml_tag(e))) + y = self.dom.createElement('mfenced') + for arg in e.args: + y.appendChild(self._print(arg)) + mrow.appendChild(x) + mrow.appendChild(y) + return mrow + + def _print_Float(self, expr): + # Based off of that in StrPrinter + dps = prec_to_dps(expr._prec) + str_real = mlib_to_str(expr._mpf_, dps, strip_zeros=True) + + # Must always have a mul symbol (as 2.5 10^{20} just looks odd) + # thus we use the number separator + separator = self._settings['mul_symbol_mathml_numbers'] + mrow = self.dom.createElement('mrow') + if 'e' in str_real: + (mant, exp) = str_real.split('e') + + if exp[0] == '+': + exp = exp[1:] + + mn = self.dom.createElement('mn') + mn.appendChild(self.dom.createTextNode(mant)) + mrow.appendChild(mn) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode(separator)) + mrow.appendChild(mo) + msup = self.dom.createElement('msup') + mn = self.dom.createElement('mn') + mn.appendChild(self.dom.createTextNode("10")) + msup.appendChild(mn) + mn = self.dom.createElement('mn') + mn.appendChild(self.dom.createTextNode(exp)) + msup.appendChild(mn) + mrow.appendChild(msup) + return mrow + elif str_real == "+inf": + return self._print_Infinity(None) + elif str_real == "-inf": + return self._print_NegativeInfinity(None) + else: + mn = self.dom.createElement('mn') + mn.appendChild(self.dom.createTextNode(str_real)) + return mn + + def _print_polylog(self, expr): + mrow = self.dom.createElement('mrow') + m = self.dom.createElement('msub') + + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode('Li')) + m.appendChild(mi) + m.appendChild(self._print(expr.args[0])) + mrow.appendChild(m) + brac = self.dom.createElement('mfenced') + brac.appendChild(self._print(expr.args[1])) + mrow.appendChild(brac) + return mrow + + def _print_Basic(self, e): + mrow = self.dom.createElement('mrow') + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode(self.mathml_tag(e))) + mrow.appendChild(mi) + brac = self.dom.createElement('mfenced') + for arg in e.args: + brac.appendChild(self._print(arg)) + mrow.appendChild(brac) + return mrow + + def _print_Tuple(self, e): + mrow = self.dom.createElement('mrow') + x = self.dom.createElement('mfenced') + for arg in e.args: + x.appendChild(self._print(arg)) + mrow.appendChild(x) + return mrow + + def _print_Interval(self, i): + mrow = self.dom.createElement('mrow') + brac = self.dom.createElement('mfenced') + if i.start == i.end: + # Most often, this type of Interval is converted to a FiniteSet + brac.setAttribute('close', '}') + brac.setAttribute('open', '{') + brac.appendChild(self._print(i.start)) + else: + if i.right_open: + brac.setAttribute('close', ')') + else: + brac.setAttribute('close', ']') + + if i.left_open: + brac.setAttribute('open', '(') + else: + brac.setAttribute('open', '[') + brac.appendChild(self._print(i.start)) + brac.appendChild(self._print(i.end)) + + mrow.appendChild(brac) + return mrow + + def _print_Abs(self, expr, exp=None): + mrow = self.dom.createElement('mrow') + x = self.dom.createElement('mfenced') + x.setAttribute('close', '|') + x.setAttribute('open', '|') + x.appendChild(self._print(expr.args[0])) + mrow.appendChild(x) + return mrow + + _print_Determinant = _print_Abs + + def _print_re_im(self, c, expr): + mrow = self.dom.createElement('mrow') + mi = self.dom.createElement('mi') + mi.setAttribute('mathvariant', 'fraktur') + mi.appendChild(self.dom.createTextNode(c)) + mrow.appendChild(mi) + brac = self.dom.createElement('mfenced') + brac.appendChild(self._print(expr)) + mrow.appendChild(brac) + return mrow + + def _print_re(self, expr, exp=None): + return self._print_re_im('R', expr.args[0]) + + def _print_im(self, expr, exp=None): + return self._print_re_im('I', expr.args[0]) + + def _print_AssocOp(self, e): + mrow = self.dom.createElement('mrow') + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode(self.mathml_tag(e))) + mrow.appendChild(mi) + for arg in e.args: + mrow.appendChild(self._print(arg)) + return mrow + + def _print_SetOp(self, expr, symbol, prec): + mrow = self.dom.createElement('mrow') + mrow.appendChild(self.parenthesize(expr.args[0], prec)) + for arg in expr.args[1:]: + x = self.dom.createElement('mo') + x.appendChild(self.dom.createTextNode(symbol)) + y = self.parenthesize(arg, prec) + mrow.appendChild(x) + mrow.appendChild(y) + return mrow + + def _print_Union(self, expr): + prec = PRECEDENCE_TRADITIONAL['Union'] + return self._print_SetOp(expr, '∪', prec) + + def _print_Intersection(self, expr): + prec = PRECEDENCE_TRADITIONAL['Intersection'] + return self._print_SetOp(expr, '∩', prec) + + def _print_Complement(self, expr): + prec = PRECEDENCE_TRADITIONAL['Complement'] + return self._print_SetOp(expr, '∖', prec) + + def _print_SymmetricDifference(self, expr): + prec = PRECEDENCE_TRADITIONAL['SymmetricDifference'] + return self._print_SetOp(expr, '∆', prec) + + def _print_ProductSet(self, expr): + prec = PRECEDENCE_TRADITIONAL['ProductSet'] + return self._print_SetOp(expr, '×', prec) + + def _print_FiniteSet(self, s): + return self._print_set(s.args) + + def _print_set(self, s): + items = sorted(s, key=default_sort_key) + brac = self.dom.createElement('mfenced') + brac.setAttribute('close', '}') + brac.setAttribute('open', '{') + for item in items: + brac.appendChild(self._print(item)) + return brac + + _print_frozenset = _print_set + + def _print_LogOp(self, args, symbol): + mrow = self.dom.createElement('mrow') + if args[0].is_Boolean and not args[0].is_Not: + brac = self.dom.createElement('mfenced') + brac.appendChild(self._print(args[0])) + mrow.appendChild(brac) + else: + mrow.appendChild(self._print(args[0])) + for arg in args[1:]: + x = self.dom.createElement('mo') + x.appendChild(self.dom.createTextNode(symbol)) + if arg.is_Boolean and not arg.is_Not: + y = self.dom.createElement('mfenced') + y.appendChild(self._print(arg)) + else: + y = self._print(arg) + mrow.appendChild(x) + mrow.appendChild(y) + return mrow + + def _print_BasisDependent(self, expr): + from sympy.vector import Vector + + if expr == expr.zero: + # Not clear if this is ever called + return self._print(expr.zero) + if isinstance(expr, Vector): + items = expr.separate().items() + else: + items = [(0, expr)] + + mrow = self.dom.createElement('mrow') + for system, vect in items: + inneritems = list(vect.components.items()) + inneritems.sort(key = lambda x:x[0].__str__()) + for i, (k, v) in enumerate(inneritems): + if v == 1: + if i: # No + for first item + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('+')) + mrow.appendChild(mo) + mrow.appendChild(self._print(k)) + elif v == -1: + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('-')) + mrow.appendChild(mo) + mrow.appendChild(self._print(k)) + else: + if i: # No + for first item + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('+')) + mrow.appendChild(mo) + mbrac = self.dom.createElement('mfenced') + mbrac.appendChild(self._print(v)) + mrow.appendChild(mbrac) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('⁢')) + mrow.appendChild(mo) + mrow.appendChild(self._print(k)) + return mrow + + + def _print_And(self, expr): + args = sorted(expr.args, key=default_sort_key) + return self._print_LogOp(args, '∧') + + def _print_Or(self, expr): + args = sorted(expr.args, key=default_sort_key) + return self._print_LogOp(args, '∨') + + def _print_Xor(self, expr): + args = sorted(expr.args, key=default_sort_key) + return self._print_LogOp(args, '⊻') + + def _print_Implies(self, expr): + return self._print_LogOp(expr.args, '⇒') + + def _print_Equivalent(self, expr): + args = sorted(expr.args, key=default_sort_key) + return self._print_LogOp(args, '⇔') + + def _print_Not(self, e): + mrow = self.dom.createElement('mrow') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('¬')) + mrow.appendChild(mo) + if (e.args[0].is_Boolean): + x = self.dom.createElement('mfenced') + x.appendChild(self._print(e.args[0])) + else: + x = self._print(e.args[0]) + mrow.appendChild(x) + return mrow + + def _print_bool(self, e): + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode(self.mathml_tag(e))) + return mi + + _print_BooleanTrue = _print_bool + _print_BooleanFalse = _print_bool + + def _print_NoneType(self, e): + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode(self.mathml_tag(e))) + return mi + + def _print_Range(self, s): + dots = "\u2026" + brac = self.dom.createElement('mfenced') + brac.setAttribute('close', '}') + brac.setAttribute('open', '{') + + if s.start.is_infinite and s.stop.is_infinite: + if s.step.is_positive: + printset = dots, -1, 0, 1, dots + else: + printset = dots, 1, 0, -1, dots + elif s.start.is_infinite: + printset = dots, s[-1] - s.step, s[-1] + elif s.stop.is_infinite: + it = iter(s) + printset = next(it), next(it), dots + elif len(s) > 4: + it = iter(s) + printset = next(it), next(it), dots, s[-1] + else: + printset = tuple(s) + + for el in printset: + if el == dots: + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode(dots)) + brac.appendChild(mi) + else: + brac.appendChild(self._print(el)) + + return brac + + def _hprint_variadic_function(self, expr): + args = sorted(expr.args, key=default_sort_key) + mrow = self.dom.createElement('mrow') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode((str(expr.func)).lower())) + mrow.appendChild(mo) + brac = self.dom.createElement('mfenced') + for symbol in args: + brac.appendChild(self._print(symbol)) + mrow.appendChild(brac) + return mrow + + _print_Min = _print_Max = _hprint_variadic_function + + def _print_exp(self, expr): + msup = self.dom.createElement('msup') + msup.appendChild(self._print_Exp1(None)) + msup.appendChild(self._print(expr.args[0])) + return msup + + def _print_Relational(self, e): + mrow = self.dom.createElement('mrow') + mrow.appendChild(self._print(e.lhs)) + x = self.dom.createElement('mo') + x.appendChild(self.dom.createTextNode(self.mathml_tag(e))) + mrow.appendChild(x) + mrow.appendChild(self._print(e.rhs)) + return mrow + + def _print_int(self, p): + dom_element = self.dom.createElement(self.mathml_tag(p)) + dom_element.appendChild(self.dom.createTextNode(str(p))) + return dom_element + + def _print_BaseScalar(self, e): + msub = self.dom.createElement('msub') + index, system = e._id + mi = self.dom.createElement('mi') + mi.setAttribute('mathvariant', 'bold') + mi.appendChild(self.dom.createTextNode(system._variable_names[index])) + msub.appendChild(mi) + mi = self.dom.createElement('mi') + mi.setAttribute('mathvariant', 'bold') + mi.appendChild(self.dom.createTextNode(system._name)) + msub.appendChild(mi) + return msub + + def _print_BaseVector(self, e): + msub = self.dom.createElement('msub') + index, system = e._id + mover = self.dom.createElement('mover') + mi = self.dom.createElement('mi') + mi.setAttribute('mathvariant', 'bold') + mi.appendChild(self.dom.createTextNode(system._vector_names[index])) + mover.appendChild(mi) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('^')) + mover.appendChild(mo) + msub.appendChild(mover) + mi = self.dom.createElement('mi') + mi.setAttribute('mathvariant', 'bold') + mi.appendChild(self.dom.createTextNode(system._name)) + msub.appendChild(mi) + return msub + + def _print_VectorZero(self, e): + mover = self.dom.createElement('mover') + mi = self.dom.createElement('mi') + mi.setAttribute('mathvariant', 'bold') + mi.appendChild(self.dom.createTextNode("0")) + mover.appendChild(mi) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('^')) + mover.appendChild(mo) + return mover + + def _print_Cross(self, expr): + mrow = self.dom.createElement('mrow') + vec1 = expr._expr1 + vec2 = expr._expr2 + mrow.appendChild(self.parenthesize(vec1, PRECEDENCE['Mul'])) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('×')) + mrow.appendChild(mo) + mrow.appendChild(self.parenthesize(vec2, PRECEDENCE['Mul'])) + return mrow + + def _print_Curl(self, expr): + mrow = self.dom.createElement('mrow') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('∇')) + mrow.appendChild(mo) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('×')) + mrow.appendChild(mo) + mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul'])) + return mrow + + def _print_Divergence(self, expr): + mrow = self.dom.createElement('mrow') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('∇')) + mrow.appendChild(mo) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('·')) + mrow.appendChild(mo) + mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul'])) + return mrow + + def _print_Dot(self, expr): + mrow = self.dom.createElement('mrow') + vec1 = expr._expr1 + vec2 = expr._expr2 + mrow.appendChild(self.parenthesize(vec1, PRECEDENCE['Mul'])) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('·')) + mrow.appendChild(mo) + mrow.appendChild(self.parenthesize(vec2, PRECEDENCE['Mul'])) + return mrow + + def _print_Gradient(self, expr): + mrow = self.dom.createElement('mrow') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('∇')) + mrow.appendChild(mo) + mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul'])) + return mrow + + def _print_Laplacian(self, expr): + mrow = self.dom.createElement('mrow') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('∆')) + mrow.appendChild(mo) + mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul'])) + return mrow + + def _print_Integers(self, e): + x = self.dom.createElement('mi') + x.setAttribute('mathvariant', 'normal') + x.appendChild(self.dom.createTextNode('ℤ')) + return x + + def _print_Complexes(self, e): + x = self.dom.createElement('mi') + x.setAttribute('mathvariant', 'normal') + x.appendChild(self.dom.createTextNode('ℂ')) + return x + + def _print_Reals(self, e): + x = self.dom.createElement('mi') + x.setAttribute('mathvariant', 'normal') + x.appendChild(self.dom.createTextNode('ℝ')) + return x + + def _print_Naturals(self, e): + x = self.dom.createElement('mi') + x.setAttribute('mathvariant', 'normal') + x.appendChild(self.dom.createTextNode('ℕ')) + return x + + def _print_Naturals0(self, e): + sub = self.dom.createElement('msub') + x = self.dom.createElement('mi') + x.setAttribute('mathvariant', 'normal') + x.appendChild(self.dom.createTextNode('ℕ')) + sub.appendChild(x) + sub.appendChild(self._print(S.Zero)) + return sub + + def _print_SingularityFunction(self, expr): + shift = expr.args[0] - expr.args[1] + power = expr.args[2] + sup = self.dom.createElement('msup') + brac = self.dom.createElement('mfenced') + brac.setAttribute('close', '\u27e9') + brac.setAttribute('open', '\u27e8') + brac.appendChild(self._print(shift)) + sup.appendChild(brac) + sup.appendChild(self._print(power)) + return sup + + def _print_NaN(self, e): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('NaN')) + return x + + def _print_number_function(self, e, name): + # Print name_arg[0] for one argument or name_arg[0](arg[1]) + # for more than one argument + sub = self.dom.createElement('msub') + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode(name)) + sub.appendChild(mi) + sub.appendChild(self._print(e.args[0])) + if len(e.args) == 1: + return sub + # TODO: copy-pasted from _print_Function: can we do better? + mrow = self.dom.createElement('mrow') + y = self.dom.createElement('mfenced') + for arg in e.args[1:]: + y.appendChild(self._print(arg)) + mrow.appendChild(sub) + mrow.appendChild(y) + return mrow + + def _print_bernoulli(self, e): + return self._print_number_function(e, 'B') + + _print_bell = _print_bernoulli + + def _print_catalan(self, e): + return self._print_number_function(e, 'C') + + def _print_euler(self, e): + return self._print_number_function(e, 'E') + + def _print_fibonacci(self, e): + return self._print_number_function(e, 'F') + + def _print_lucas(self, e): + return self._print_number_function(e, 'L') + + def _print_stieltjes(self, e): + return self._print_number_function(e, 'γ') + + def _print_tribonacci(self, e): + return self._print_number_function(e, 'T') + + def _print_ComplexInfinity(self, e): + x = self.dom.createElement('mover') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('∞')) + x.appendChild(mo) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('~')) + x.appendChild(mo) + return x + + def _print_EmptySet(self, e): + x = self.dom.createElement('mo') + x.appendChild(self.dom.createTextNode('∅')) + return x + + def _print_UniversalSet(self, e): + x = self.dom.createElement('mo') + x.appendChild(self.dom.createTextNode('𝕌')) + return x + + def _print_Adjoint(self, expr): + from sympy.matrices import MatrixSymbol + mat = expr.arg + sup = self.dom.createElement('msup') + if not isinstance(mat, MatrixSymbol): + brac = self.dom.createElement('mfenced') + brac.appendChild(self._print(mat)) + sup.appendChild(brac) + else: + sup.appendChild(self._print(mat)) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('†')) + sup.appendChild(mo) + return sup + + def _print_Transpose(self, expr): + from sympy.matrices import MatrixSymbol + mat = expr.arg + sup = self.dom.createElement('msup') + if not isinstance(mat, MatrixSymbol): + brac = self.dom.createElement('mfenced') + brac.appendChild(self._print(mat)) + sup.appendChild(brac) + else: + sup.appendChild(self._print(mat)) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('T')) + sup.appendChild(mo) + return sup + + def _print_Inverse(self, expr): + from sympy.matrices import MatrixSymbol + mat = expr.arg + sup = self.dom.createElement('msup') + if not isinstance(mat, MatrixSymbol): + brac = self.dom.createElement('mfenced') + brac.appendChild(self._print(mat)) + sup.appendChild(brac) + else: + sup.appendChild(self._print(mat)) + sup.appendChild(self._print(-1)) + return sup + + def _print_MatMul(self, expr): + from sympy.matrices.expressions.matmul import MatMul + + x = self.dom.createElement('mrow') + args = expr.args + if isinstance(args[0], Mul): + args = args[0].as_ordered_factors() + list(args[1:]) + else: + args = list(args) + + if isinstance(expr, MatMul) and expr.could_extract_minus_sign(): + if args[0] == -1: + args = args[1:] + else: + args[0] = -args[0] + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('-')) + x.appendChild(mo) + + for arg in args[:-1]: + x.appendChild(self.parenthesize(arg, precedence_traditional(expr), + False)) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('⁢')) + x.appendChild(mo) + x.appendChild(self.parenthesize(args[-1], precedence_traditional(expr), + False)) + return x + + def _print_MatPow(self, expr): + from sympy.matrices import MatrixSymbol + base, exp = expr.base, expr.exp + sup = self.dom.createElement('msup') + if not isinstance(base, MatrixSymbol): + brac = self.dom.createElement('mfenced') + brac.appendChild(self._print(base)) + sup.appendChild(brac) + else: + sup.appendChild(self._print(base)) + sup.appendChild(self._print(exp)) + return sup + + def _print_HadamardProduct(self, expr): + x = self.dom.createElement('mrow') + args = expr.args + for arg in args[:-1]: + x.appendChild( + self.parenthesize(arg, precedence_traditional(expr), False)) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('∘')) + x.appendChild(mo) + x.appendChild( + self.parenthesize(args[-1], precedence_traditional(expr), False)) + return x + + def _print_ZeroMatrix(self, Z): + x = self.dom.createElement('mn') + x.appendChild(self.dom.createTextNode('𝟘')) + return x + + def _print_OneMatrix(self, Z): + x = self.dom.createElement('mn') + x.appendChild(self.dom.createTextNode('𝟙')) + return x + + def _print_Identity(self, I): + x = self.dom.createElement('mi') + x.appendChild(self.dom.createTextNode('𝕀')) + return x + + def _print_floor(self, e): + mrow = self.dom.createElement('mrow') + x = self.dom.createElement('mfenced') + x.setAttribute('close', '\u230B') + x.setAttribute('open', '\u230A') + x.appendChild(self._print(e.args[0])) + mrow.appendChild(x) + return mrow + + def _print_ceiling(self, e): + mrow = self.dom.createElement('mrow') + x = self.dom.createElement('mfenced') + x.setAttribute('close', '\u2309') + x.setAttribute('open', '\u2308') + x.appendChild(self._print(e.args[0])) + mrow.appendChild(x) + return mrow + + def _print_Lambda(self, e): + x = self.dom.createElement('mfenced') + mrow = self.dom.createElement('mrow') + symbols = e.args[0] + if len(symbols) == 1: + symbols = self._print(symbols[0]) + else: + symbols = self._print(symbols) + mrow.appendChild(symbols) + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('↦')) + mrow.appendChild(mo) + mrow.appendChild(self._print(e.args[1])) + x.appendChild(mrow) + return x + + def _print_tuple(self, e): + x = self.dom.createElement('mfenced') + for i in e: + x.appendChild(self._print(i)) + return x + + def _print_IndexedBase(self, e): + return self._print(e.label) + + def _print_Indexed(self, e): + x = self.dom.createElement('msub') + x.appendChild(self._print(e.base)) + if len(e.indices) == 1: + x.appendChild(self._print(e.indices[0])) + return x + x.appendChild(self._print(e.indices)) + return x + + def _print_MatrixElement(self, e): + x = self.dom.createElement('msub') + x.appendChild(self.parenthesize(e.parent, PRECEDENCE["Atom"], strict = True)) + brac = self.dom.createElement('mfenced') + brac.setAttribute("close", "") + brac.setAttribute("open", "") + for i in e.indices: + brac.appendChild(self._print(i)) + x.appendChild(brac) + return x + + def _print_elliptic_f(self, e): + x = self.dom.createElement('mrow') + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode('𝖥')) + x.appendChild(mi) + y = self.dom.createElement('mfenced') + y.setAttribute("separators", "|") + for i in e.args: + y.appendChild(self._print(i)) + x.appendChild(y) + return x + + def _print_elliptic_e(self, e): + x = self.dom.createElement('mrow') + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode('𝖤')) + x.appendChild(mi) + y = self.dom.createElement('mfenced') + y.setAttribute("separators", "|") + for i in e.args: + y.appendChild(self._print(i)) + x.appendChild(y) + return x + + def _print_elliptic_pi(self, e): + x = self.dom.createElement('mrow') + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode('𝛱')) + x.appendChild(mi) + y = self.dom.createElement('mfenced') + if len(e.args) == 2: + y.setAttribute("separators", "|") + else: + y.setAttribute("separators", ";|") + for i in e.args: + y.appendChild(self._print(i)) + x.appendChild(y) + return x + + def _print_Ei(self, e): + x = self.dom.createElement('mrow') + mi = self.dom.createElement('mi') + mi.appendChild(self.dom.createTextNode('Ei')) + x.appendChild(mi) + x.appendChild(self._print(e.args)) + return x + + def _print_expint(self, e): + x = self.dom.createElement('mrow') + y = self.dom.createElement('msub') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('E')) + y.appendChild(mo) + y.appendChild(self._print(e.args[0])) + x.appendChild(y) + x.appendChild(self._print(e.args[1:])) + return x + + def _print_jacobi(self, e): + x = self.dom.createElement('mrow') + y = self.dom.createElement('msubsup') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('P')) + y.appendChild(mo) + y.appendChild(self._print(e.args[0])) + y.appendChild(self._print(e.args[1:3])) + x.appendChild(y) + x.appendChild(self._print(e.args[3:])) + return x + + def _print_gegenbauer(self, e): + x = self.dom.createElement('mrow') + y = self.dom.createElement('msubsup') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('C')) + y.appendChild(mo) + y.appendChild(self._print(e.args[0])) + y.appendChild(self._print(e.args[1:2])) + x.appendChild(y) + x.appendChild(self._print(e.args[2:])) + return x + + def _print_chebyshevt(self, e): + x = self.dom.createElement('mrow') + y = self.dom.createElement('msub') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('T')) + y.appendChild(mo) + y.appendChild(self._print(e.args[0])) + x.appendChild(y) + x.appendChild(self._print(e.args[1:])) + return x + + def _print_chebyshevu(self, e): + x = self.dom.createElement('mrow') + y = self.dom.createElement('msub') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('U')) + y.appendChild(mo) + y.appendChild(self._print(e.args[0])) + x.appendChild(y) + x.appendChild(self._print(e.args[1:])) + return x + + def _print_legendre(self, e): + x = self.dom.createElement('mrow') + y = self.dom.createElement('msub') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('P')) + y.appendChild(mo) + y.appendChild(self._print(e.args[0])) + x.appendChild(y) + x.appendChild(self._print(e.args[1:])) + return x + + def _print_assoc_legendre(self, e): + x = self.dom.createElement('mrow') + y = self.dom.createElement('msubsup') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('P')) + y.appendChild(mo) + y.appendChild(self._print(e.args[0])) + y.appendChild(self._print(e.args[1:2])) + x.appendChild(y) + x.appendChild(self._print(e.args[2:])) + return x + + def _print_laguerre(self, e): + x = self.dom.createElement('mrow') + y = self.dom.createElement('msub') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('L')) + y.appendChild(mo) + y.appendChild(self._print(e.args[0])) + x.appendChild(y) + x.appendChild(self._print(e.args[1:])) + return x + + def _print_assoc_laguerre(self, e): + x = self.dom.createElement('mrow') + y = self.dom.createElement('msubsup') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('L')) + y.appendChild(mo) + y.appendChild(self._print(e.args[0])) + y.appendChild(self._print(e.args[1:2])) + x.appendChild(y) + x.appendChild(self._print(e.args[2:])) + return x + + def _print_hermite(self, e): + x = self.dom.createElement('mrow') + y = self.dom.createElement('msub') + mo = self.dom.createElement('mo') + mo.appendChild(self.dom.createTextNode('H')) + y.appendChild(mo) + y.appendChild(self._print(e.args[0])) + x.appendChild(y) + x.appendChild(self._print(e.args[1:])) + return x + + +@print_function(MathMLPrinterBase) +def mathml(expr, printer='content', **settings): + """Returns the MathML representation of expr. If printer is presentation + then prints Presentation MathML else prints content MathML. + """ + if printer == 'presentation': + return MathMLPresentationPrinter(settings).doprint(expr) + else: + return MathMLContentPrinter(settings).doprint(expr) + + +def print_mathml(expr, printer='content', **settings): + """ + Prints a pretty representation of the MathML code for expr. If printer is + presentation then prints Presentation MathML else prints content MathML. + + Examples + ======== + + >>> ## + >>> from sympy import print_mathml + >>> from sympy.abc import x + >>> print_mathml(x+1) #doctest: +NORMALIZE_WHITESPACE + + + x + 1 + + >>> print_mathml(x+1, printer='presentation') + + x + + + 1 + + + """ + if printer == 'presentation': + s = MathMLPresentationPrinter(settings) + else: + s = MathMLContentPrinter(settings) + xml = s._print(sympify(expr)) + s.apply_patch() + pretty_xml = xml.toprettyxml() + s.restore_patch() + + print(pretty_xml) + + +# For backward compatibility +MathMLPrinter = MathMLContentPrinter diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/numpy.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6083d8144999e033e0e8521f48d0de067414d9 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/numpy.py @@ -0,0 +1,507 @@ +from sympy.core import S +from sympy.core.function import Lambda +from sympy.core.power import Pow +from .pycode import PythonCodePrinter, _known_functions_math, _print_known_const, _print_known_func, _unpack_integral_limits, ArrayPrinter +from .codeprinter import CodePrinter + + +_not_in_numpy = 'erf erfc factorial gamma loggamma'.split() +_in_numpy = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_numpy] +_known_functions_numpy = dict(_in_numpy, **{ + 'acos': 'arccos', + 'acosh': 'arccosh', + 'asin': 'arcsin', + 'asinh': 'arcsinh', + 'atan': 'arctan', + 'atan2': 'arctan2', + 'atanh': 'arctanh', + 'exp2': 'exp2', + 'sign': 'sign', + 'logaddexp': 'logaddexp', + 'logaddexp2': 'logaddexp2', +}) +_known_constants_numpy = { + 'Exp1': 'e', + 'Pi': 'pi', + 'EulerGamma': 'euler_gamma', + 'NaN': 'nan', + 'Infinity': 'PINF', + 'NegativeInfinity': 'NINF' +} + +_numpy_known_functions = {k: 'numpy.' + v for k, v in _known_functions_numpy.items()} +_numpy_known_constants = {k: 'numpy.' + v for k, v in _known_constants_numpy.items()} + +class NumPyPrinter(ArrayPrinter, PythonCodePrinter): + """ + Numpy printer which handles vectorized piecewise functions, + logical operators, etc. + """ + + _module = 'numpy' + _kf = _numpy_known_functions + _kc = _numpy_known_constants + + def __init__(self, settings=None): + """ + `settings` is passed to CodePrinter.__init__() + `module` specifies the array module to use, currently 'NumPy', 'CuPy' + or 'JAX'. + """ + self.language = "Python with {}".format(self._module) + self.printmethod = "_{}code".format(self._module) + + self._kf = {**PythonCodePrinter._kf, **self._kf} + + super().__init__(settings=settings) + + + def _print_seq(self, seq): + "General sequence printer: converts to tuple" + # Print tuples here instead of lists because numba supports + # tuples in nopython mode. + delimiter=', ' + return '({},)'.format(delimiter.join(self._print(item) for item in seq)) + + def _print_MatMul(self, expr): + "Matrix multiplication printer" + if expr.as_coeff_matrices()[0] is not S.One: + expr_list = expr.as_coeff_matrices()[1]+[(expr.as_coeff_matrices()[0])] + return '({})'.format(').dot('.join(self._print(i) for i in expr_list)) + return '({})'.format(').dot('.join(self._print(i) for i in expr.args)) + + def _print_MatPow(self, expr): + "Matrix power printer" + return '{}({}, {})'.format(self._module_format(self._module + '.linalg.matrix_power'), + self._print(expr.args[0]), self._print(expr.args[1])) + + def _print_Inverse(self, expr): + "Matrix inverse printer" + return '{}({})'.format(self._module_format(self._module + '.linalg.inv'), + self._print(expr.args[0])) + + def _print_DotProduct(self, expr): + # DotProduct allows any shape order, but numpy.dot does matrix + # multiplication, so we have to make sure it gets 1 x n by n x 1. + arg1, arg2 = expr.args + if arg1.shape[0] != 1: + arg1 = arg1.T + if arg2.shape[1] != 1: + arg2 = arg2.T + + return "%s(%s, %s)" % (self._module_format(self._module + '.dot'), + self._print(arg1), + self._print(arg2)) + + def _print_MatrixSolve(self, expr): + return "%s(%s, %s)" % (self._module_format(self._module + '.linalg.solve'), + self._print(expr.matrix), + self._print(expr.vector)) + + def _print_ZeroMatrix(self, expr): + return '{}({})'.format(self._module_format(self._module + '.zeros'), + self._print(expr.shape)) + + def _print_OneMatrix(self, expr): + return '{}({})'.format(self._module_format(self._module + '.ones'), + self._print(expr.shape)) + + def _print_FunctionMatrix(self, expr): + from sympy.abc import i, j + lamda = expr.lamda + if not isinstance(lamda, Lambda): + lamda = Lambda((i, j), lamda(i, j)) + return '{}(lambda {}: {}, {})'.format(self._module_format(self._module + '.fromfunction'), + ', '.join(self._print(arg) for arg in lamda.args[0]), + self._print(lamda.args[1]), self._print(expr.shape)) + + def _print_HadamardProduct(self, expr): + func = self._module_format(self._module + '.multiply') + return ''.join('{}({}, '.format(func, self._print(arg)) \ + for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]), + ')' * (len(expr.args) - 1)) + + def _print_KroneckerProduct(self, expr): + func = self._module_format(self._module + '.kron') + return ''.join('{}({}, '.format(func, self._print(arg)) \ + for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]), + ')' * (len(expr.args) - 1)) + + def _print_Adjoint(self, expr): + return '{}({}({}))'.format( + self._module_format(self._module + '.conjugate'), + self._module_format(self._module + '.transpose'), + self._print(expr.args[0])) + + def _print_DiagonalOf(self, expr): + vect = '{}({})'.format( + self._module_format(self._module + '.diag'), + self._print(expr.arg)) + return '{}({}, (-1, 1))'.format( + self._module_format(self._module + '.reshape'), vect) + + def _print_DiagMatrix(self, expr): + return '{}({})'.format(self._module_format(self._module + '.diagflat'), + self._print(expr.args[0])) + + def _print_DiagonalMatrix(self, expr): + return '{}({}, {}({}, {}))'.format(self._module_format(self._module + '.multiply'), + self._print(expr.arg), self._module_format(self._module + '.eye'), + self._print(expr.shape[0]), self._print(expr.shape[1])) + + def _print_Piecewise(self, expr): + "Piecewise function printer" + from sympy.logic.boolalg import ITE, simplify_logic + def print_cond(cond): + """ Problem having an ITE in the cond. """ + if cond.has(ITE): + return self._print(simplify_logic(cond)) + else: + return self._print(cond) + exprs = '[{}]'.format(','.join(self._print(arg.expr) for arg in expr.args)) + conds = '[{}]'.format(','.join(print_cond(arg.cond) for arg in expr.args)) + # If [default_value, True] is a (expr, cond) sequence in a Piecewise object + # it will behave the same as passing the 'default' kwarg to select() + # *as long as* it is the last element in expr.args. + # If this is not the case, it may be triggered prematurely. + return '{}({}, {}, default={})'.format( + self._module_format(self._module + '.select'), conds, exprs, + self._print(S.NaN)) + + def _print_Relational(self, expr): + "Relational printer for Equality and Unequality" + op = { + '==' :'equal', + '!=' :'not_equal', + '<' :'less', + '<=' :'less_equal', + '>' :'greater', + '>=' :'greater_equal', + } + if expr.rel_op in op: + lhs = self._print(expr.lhs) + rhs = self._print(expr.rhs) + return '{op}({lhs}, {rhs})'.format(op=self._module_format(self._module + '.'+op[expr.rel_op]), + lhs=lhs, rhs=rhs) + return super()._print_Relational(expr) + + def _print_And(self, expr): + "Logical And printer" + # We have to override LambdaPrinter because it uses Python 'and' keyword. + # If LambdaPrinter didn't define it, we could use StrPrinter's + # version of the function and add 'logical_and' to NUMPY_TRANSLATIONS. + return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_and'), ','.join(self._print(i) for i in expr.args)) + + def _print_Or(self, expr): + "Logical Or printer" + # We have to override LambdaPrinter because it uses Python 'or' keyword. + # If LambdaPrinter didn't define it, we could use StrPrinter's + # version of the function and add 'logical_or' to NUMPY_TRANSLATIONS. + return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_or'), ','.join(self._print(i) for i in expr.args)) + + def _print_Not(self, expr): + "Logical Not printer" + # We have to override LambdaPrinter because it uses Python 'not' keyword. + # If LambdaPrinter didn't define it, we would still have to define our + # own because StrPrinter doesn't define it. + return '{}({})'.format(self._module_format(self._module + '.logical_not'), ','.join(self._print(i) for i in expr.args)) + + def _print_Pow(self, expr, rational=False): + # XXX Workaround for negative integer power error + if expr.exp.is_integer and expr.exp.is_negative: + expr = Pow(expr.base, expr.exp.evalf(), evaluate=False) + return self._hprint_Pow(expr, rational=rational, sqrt=self._module + '.sqrt') + + def _print_Min(self, expr): + return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amin'), ','.join(self._print(i) for i in expr.args)) + + def _print_Max(self, expr): + return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amax'), ','.join(self._print(i) for i in expr.args)) + + def _print_arg(self, expr): + return "%s(%s)" % (self._module_format(self._module + '.angle'), self._print(expr.args[0])) + + def _print_im(self, expr): + return "%s(%s)" % (self._module_format(self._module + '.imag'), self._print(expr.args[0])) + + def _print_Mod(self, expr): + return "%s(%s)" % (self._module_format(self._module + '.mod'), ', '.join( + (self._print(arg) for arg in expr.args))) + + def _print_re(self, expr): + return "%s(%s)" % (self._module_format(self._module + '.real'), self._print(expr.args[0])) + + def _print_sinc(self, expr): + return "%s(%s)" % (self._module_format(self._module + '.sinc'), self._print(expr.args[0]/S.Pi)) + + def _print_MatrixBase(self, expr): + func = self.known_functions.get(expr.__class__.__name__, None) + if func is None: + func = self._module_format(self._module + '.array') + return "%s(%s)" % (func, self._print(expr.tolist())) + + def _print_Identity(self, expr): + shape = expr.shape + if all(dim.is_Integer for dim in shape): + return "%s(%s)" % (self._module_format(self._module + '.eye'), self._print(expr.shape[0])) + else: + raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices") + + def _print_BlockMatrix(self, expr): + return '{}({})'.format(self._module_format(self._module + '.block'), + self._print(expr.args[0].tolist())) + + def _print_NDimArray(self, expr): + if len(expr.shape) == 1: + return self._module + '.array(' + self._print(expr.args[0]) + ')' + if len(expr.shape) == 2: + return self._print(expr.tomatrix()) + # Should be possible to extend to more dimensions + return CodePrinter._print_not_supported(self, expr) + + _add = "add" + _einsum = "einsum" + _transpose = "transpose" + _ones = "ones" + _zeros = "zeros" + + _print_lowergamma = CodePrinter._print_not_supported + _print_uppergamma = CodePrinter._print_not_supported + _print_fresnelc = CodePrinter._print_not_supported + _print_fresnels = CodePrinter._print_not_supported + +for func in _numpy_known_functions: + setattr(NumPyPrinter, f'_print_{func}', _print_known_func) + +for const in _numpy_known_constants: + setattr(NumPyPrinter, f'_print_{const}', _print_known_const) + + +_known_functions_scipy_special = { + 'Ei': 'expi', + 'erf': 'erf', + 'erfc': 'erfc', + 'besselj': 'jv', + 'bessely': 'yv', + 'besseli': 'iv', + 'besselk': 'kv', + 'cosm1': 'cosm1', + 'powm1': 'powm1', + 'factorial': 'factorial', + 'gamma': 'gamma', + 'loggamma': 'gammaln', + 'digamma': 'psi', + 'polygamma': 'polygamma', + 'RisingFactorial': 'poch', + 'jacobi': 'eval_jacobi', + 'gegenbauer': 'eval_gegenbauer', + 'chebyshevt': 'eval_chebyt', + 'chebyshevu': 'eval_chebyu', + 'legendre': 'eval_legendre', + 'hermite': 'eval_hermite', + 'laguerre': 'eval_laguerre', + 'assoc_laguerre': 'eval_genlaguerre', + 'beta': 'beta', + 'LambertW' : 'lambertw', +} + +_known_constants_scipy_constants = { + 'GoldenRatio': 'golden_ratio', + 'Pi': 'pi', +} +_scipy_known_functions = {k : "scipy.special." + v for k, v in _known_functions_scipy_special.items()} +_scipy_known_constants = {k : "scipy.constants." + v for k, v in _known_constants_scipy_constants.items()} + +class SciPyPrinter(NumPyPrinter): + + _kf = {**NumPyPrinter._kf, **_scipy_known_functions} + _kc = {**NumPyPrinter._kc, **_scipy_known_constants} + + def __init__(self, settings=None): + super().__init__(settings=settings) + self.language = "Python with SciPy and NumPy" + + def _print_SparseRepMatrix(self, expr): + i, j, data = [], [], [] + for (r, c), v in expr.todok().items(): + i.append(r) + j.append(c) + data.append(v) + + return "{name}(({data}, ({i}, {j})), shape={shape})".format( + name=self._module_format('scipy.sparse.coo_matrix'), + data=data, i=i, j=j, shape=expr.shape + ) + + _print_ImmutableSparseMatrix = _print_SparseRepMatrix + + # SciPy's lpmv has a different order of arguments from assoc_legendre + def _print_assoc_legendre(self, expr): + return "{0}({2}, {1}, {3})".format( + self._module_format('scipy.special.lpmv'), + self._print(expr.args[0]), + self._print(expr.args[1]), + self._print(expr.args[2])) + + def _print_lowergamma(self, expr): + return "{0}({2})*{1}({2}, {3})".format( + self._module_format('scipy.special.gamma'), + self._module_format('scipy.special.gammainc'), + self._print(expr.args[0]), + self._print(expr.args[1])) + + def _print_uppergamma(self, expr): + return "{0}({2})*{1}({2}, {3})".format( + self._module_format('scipy.special.gamma'), + self._module_format('scipy.special.gammaincc'), + self._print(expr.args[0]), + self._print(expr.args[1])) + + def _print_betainc(self, expr): + betainc = self._module_format('scipy.special.betainc') + beta = self._module_format('scipy.special.beta') + args = [self._print(arg) for arg in expr.args] + return f"({betainc}({args[0]}, {args[1]}, {args[3]}) - {betainc}({args[0]}, {args[1]}, {args[2]})) \ + * {beta}({args[0]}, {args[1]})" + + def _print_betainc_regularized(self, expr): + return "{0}({1}, {2}, {4}) - {0}({1}, {2}, {3})".format( + self._module_format('scipy.special.betainc'), + self._print(expr.args[0]), + self._print(expr.args[1]), + self._print(expr.args[2]), + self._print(expr.args[3])) + + def _print_fresnels(self, expr): + return "{}({})[0]".format( + self._module_format("scipy.special.fresnel"), + self._print(expr.args[0])) + + def _print_fresnelc(self, expr): + return "{}({})[1]".format( + self._module_format("scipy.special.fresnel"), + self._print(expr.args[0])) + + def _print_airyai(self, expr): + return "{}({})[0]".format( + self._module_format("scipy.special.airy"), + self._print(expr.args[0])) + + def _print_airyaiprime(self, expr): + return "{}({})[1]".format( + self._module_format("scipy.special.airy"), + self._print(expr.args[0])) + + def _print_airybi(self, expr): + return "{}({})[2]".format( + self._module_format("scipy.special.airy"), + self._print(expr.args[0])) + + def _print_airybiprime(self, expr): + return "{}({})[3]".format( + self._module_format("scipy.special.airy"), + self._print(expr.args[0])) + + def _print_bernoulli(self, expr): + # scipy's bernoulli is inconsistent with SymPy's so rewrite + return self._print(expr._eval_rewrite_as_zeta(*expr.args)) + + def _print_harmonic(self, expr): + return self._print(expr._eval_rewrite_as_zeta(*expr.args)) + + def _print_Integral(self, e): + integration_vars, limits = _unpack_integral_limits(e) + + if len(limits) == 1: + # nicer (but not necessary) to prefer quad over nquad for 1D case + module_str = self._module_format("scipy.integrate.quad") + limit_str = "%s, %s" % tuple(map(self._print, limits[0])) + else: + module_str = self._module_format("scipy.integrate.nquad") + limit_str = "({})".format(", ".join( + "(%s, %s)" % tuple(map(self._print, l)) for l in limits)) + + return "{}(lambda {}: {}, {})[0]".format( + module_str, + ", ".join(map(self._print, integration_vars)), + self._print(e.args[0]), + limit_str) + + def _print_Si(self, expr): + return "{}({})[0]".format( + self._module_format("scipy.special.sici"), + self._print(expr.args[0])) + + def _print_Ci(self, expr): + return "{}({})[1]".format( + self._module_format("scipy.special.sici"), + self._print(expr.args[0])) + +for func in _scipy_known_functions: + setattr(SciPyPrinter, f'_print_{func}', _print_known_func) + +for const in _scipy_known_constants: + setattr(SciPyPrinter, f'_print_{const}', _print_known_const) + + +_cupy_known_functions = {k : "cupy." + v for k, v in _known_functions_numpy.items()} +_cupy_known_constants = {k : "cupy." + v for k, v in _known_constants_numpy.items()} + +class CuPyPrinter(NumPyPrinter): + """ + CuPy printer which handles vectorized piecewise functions, + logical operators, etc. + """ + + _module = 'cupy' + _kf = _cupy_known_functions + _kc = _cupy_known_constants + + def __init__(self, settings=None): + super().__init__(settings=settings) + +for func in _cupy_known_functions: + setattr(CuPyPrinter, f'_print_{func}', _print_known_func) + +for const in _cupy_known_constants: + setattr(CuPyPrinter, f'_print_{const}', _print_known_const) + + +_jax_known_functions = {k: 'jax.numpy.' + v for k, v in _known_functions_numpy.items()} +_jax_known_constants = {k: 'jax.numpy.' + v for k, v in _known_constants_numpy.items()} + +class JaxPrinter(NumPyPrinter): + """ + JAX printer which handles vectorized piecewise functions, + logical operators, etc. + """ + _module = "jax.numpy" + + _kf = _jax_known_functions + _kc = _jax_known_constants + + def __init__(self, settings=None): + super().__init__(settings=settings) + + # These need specific override to allow for the lack of "jax.numpy.reduce" + def _print_And(self, expr): + "Logical And printer" + return "{}({}.asarray([{}]), axis=0)".format( + self._module_format(self._module + ".all"), + self._module_format(self._module), + ",".join(self._print(i) for i in expr.args), + ) + + def _print_Or(self, expr): + "Logical Or printer" + return "{}({}.asarray([{}]), axis=0)".format( + self._module_format(self._module + ".any"), + self._module_format(self._module), + ",".join(self._print(i) for i in expr.args), + ) + +for func in _jax_known_functions: + setattr(JaxPrinter, f'_print_{func}', _print_known_func) + +for const in _jax_known_constants: + setattr(JaxPrinter, f'_print_{const}', _print_known_const) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/octave.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/octave.py new file mode 100644 index 0000000000000000000000000000000000000000..397b182fb63db47caa9c077467e795e3883efc32 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/octave.py @@ -0,0 +1,719 @@ +""" +Octave (and Matlab) code printer + +The `OctaveCodePrinter` converts SymPy expressions into Octave expressions. +It uses a subset of the Octave language for Matlab compatibility. + +A complete code generator, which uses `octave_code` extensively, can be found +in `sympy.utilities.codegen`. The `codegen` module can be used to generate +complete source code files. + +""" + +from __future__ import annotations +from typing import Any + +from sympy.core import Mul, Pow, S, Rational +from sympy.core.mul import _keep_coeff +from sympy.core.numbers import equal_valued +from sympy.printing.codeprinter import CodePrinter +from sympy.printing.precedence import precedence, PRECEDENCE +from re import search + +# List of known functions. First, those that have the same name in +# SymPy and Octave. This is almost certainly incomplete! +known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc", + "asin", "acos", "acot", "atan", "atan2", "asec", "acsc", + "sinh", "cosh", "tanh", "coth", "csch", "sech", + "asinh", "acosh", "atanh", "acoth", "asech", "acsch", + "erfc", "erfi", "erf", "erfinv", "erfcinv", + "besseli", "besselj", "besselk", "bessely", + "bernoulli", "beta", "euler", "exp", "factorial", "floor", + "fresnelc", "fresnels", "gamma", "harmonic", "log", + "polylog", "sign", "zeta", "legendre"] + +# These functions have different names ("SymPy": "Octave"), more +# generally a mapping to (argument_conditions, octave_function). +known_fcns_src2 = { + "Abs": "abs", + "arg": "angle", # arg/angle ok in Octave but only angle in Matlab + "binomial": "bincoeff", + "ceiling": "ceil", + "chebyshevu": "chebyshevU", + "chebyshevt": "chebyshevT", + "Chi": "coshint", + "Ci": "cosint", + "conjugate": "conj", + "DiracDelta": "dirac", + "Heaviside": "heaviside", + "im": "imag", + "laguerre": "laguerreL", + "LambertW": "lambertw", + "li": "logint", + "loggamma": "gammaln", + "Max": "max", + "Min": "min", + "Mod": "mod", + "polygamma": "psi", + "re": "real", + "RisingFactorial": "pochhammer", + "Shi": "sinhint", + "Si": "sinint", +} + + +class OctaveCodePrinter(CodePrinter): + """ + A printer to convert expressions to strings of Octave/Matlab code. + """ + printmethod = "_octave" + language = "Octave" + + _operators = { + 'and': '&', + 'or': '|', + 'not': '~', + } + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'precision': 17, + 'user_functions': {}, + 'human': True, + 'allow_unknown_functions': False, + 'contract': True, + 'inline': True, + } + # Note: contract is for expressing tensors as loops (if True), or just + # assignment (if False). FIXME: this should be looked a more carefully + # for Octave. + + + def __init__(self, settings={}): + super().__init__(settings) + self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1)) + self.known_functions.update(dict(known_fcns_src2)) + userfuncs = settings.get('user_functions', {}) + self.known_functions.update(userfuncs) + + + def _rate_index_position(self, p): + return p*5 + + + def _get_statement(self, codestring): + return "%s;" % codestring + + + def _get_comment(self, text): + return "% {}".format(text) + + + def _declare_number_const(self, name, value): + return "{} = {};".format(name, value) + + + def _format_code(self, lines): + return self.indent_code(lines) + + + def _traverse_matrix_indices(self, mat): + # Octave uses Fortran order (column-major) + rows, cols = mat.shape + return ((i, j) for j in range(cols) for i in range(rows)) + + + def _get_loop_opening_ending(self, indices): + open_lines = [] + close_lines = [] + for i in indices: + # Octave arrays start at 1 and end at dimension + var, start, stop = map(self._print, + [i.label, i.lower + 1, i.upper + 1]) + open_lines.append("for %s = %s:%s" % (var, start, stop)) + close_lines.append("end") + return open_lines, close_lines + + + def _print_Mul(self, expr): + # print complex numbers nicely in Octave + if (expr.is_number and expr.is_imaginary and + (S.ImaginaryUnit*expr).is_Integer): + return "%si" % self._print(-S.ImaginaryUnit*expr) + + # cribbed from str.py + prec = precedence(expr) + + c, e = expr.as_coeff_Mul() + if c < 0: + expr = _keep_coeff(-c, e) + sign = "-" + else: + sign = "" + + a = [] # items in the numerator + b = [] # items that are in the denominator (if any) + + pow_paren = [] # Will collect all pow with more than one base element and exp = -1 + + if self.order not in ('old', 'none'): + args = expr.as_ordered_factors() + else: + # use make_args in case expr was something like -x -> x + args = Mul.make_args(expr) + + # Gather args for numerator/denominator + for item in args: + if (item.is_commutative and item.is_Pow and item.exp.is_Rational + and item.exp.is_negative): + if item.exp != -1: + b.append(Pow(item.base, -item.exp, evaluate=False)) + else: + if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160 + pow_paren.append(item) + b.append(Pow(item.base, -item.exp)) + elif item.is_Rational and item is not S.Infinity: + if item.p != 1: + a.append(Rational(item.p)) + if item.q != 1: + b.append(Rational(item.q)) + else: + a.append(item) + + a = a or [S.One] + + a_str = [self.parenthesize(x, prec) for x in a] + b_str = [self.parenthesize(x, prec) for x in b] + + # To parenthesize Pow with exp = -1 and having more than one Symbol + for item in pow_paren: + if item.base in b: + b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] + + # from here it differs from str.py to deal with "*" and ".*" + def multjoin(a, a_str): + # here we probably are assuming the constants will come first + r = a_str[0] + for i in range(1, len(a)): + mulsym = '*' if a[i-1].is_number else '.*' + r = r + mulsym + a_str[i] + return r + + if not b: + return sign + multjoin(a, a_str) + elif len(b) == 1: + divsym = '/' if b[0].is_number else './' + return sign + multjoin(a, a_str) + divsym + b_str[0] + else: + divsym = '/' if all(bi.is_number for bi in b) else './' + return (sign + multjoin(a, a_str) + + divsym + "(%s)" % multjoin(b, b_str)) + + def _print_Relational(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + op = expr.rel_op + return "{} {} {}".format(lhs_code, op, rhs_code) + + def _print_Pow(self, expr): + powsymbol = '^' if all(x.is_number for x in expr.args) else '.^' + + PREC = precedence(expr) + + if equal_valued(expr.exp, 0.5): + return "sqrt(%s)" % self._print(expr.base) + + if expr.is_commutative: + if equal_valued(expr.exp, -0.5): + sym = '/' if expr.base.is_number else './' + return "1" + sym + "sqrt(%s)" % self._print(expr.base) + if equal_valued(expr.exp, -1): + sym = '/' if expr.base.is_number else './' + return "1" + sym + "%s" % self.parenthesize(expr.base, PREC) + + return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol, + self.parenthesize(expr.exp, PREC)) + + + def _print_MatPow(self, expr): + PREC = precedence(expr) + return '%s^%s' % (self.parenthesize(expr.base, PREC), + self.parenthesize(expr.exp, PREC)) + + def _print_MatrixSolve(self, expr): + PREC = precedence(expr) + return "%s \\ %s" % (self.parenthesize(expr.matrix, PREC), + self.parenthesize(expr.vector, PREC)) + + def _print_Pi(self, expr): + return 'pi' + + + def _print_ImaginaryUnit(self, expr): + return "1i" + + + def _print_Exp1(self, expr): + return "exp(1)" + + + def _print_GoldenRatio(self, expr): + # FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)? + #return self._print((1+sqrt(S(5)))/2) + return "(1+sqrt(5))/2" + + + def _print_Assignment(self, expr): + from sympy.codegen.ast import Assignment + from sympy.functions.elementary.piecewise import Piecewise + from sympy.tensor.indexed import IndexedBase + # Copied from codeprinter, but remove special MatrixSymbol treatment + lhs = expr.lhs + rhs = expr.rhs + # We special case assignments that take multiple lines + if not self._settings["inline"] and isinstance(expr.rhs, Piecewise): + # Here we modify Piecewise so each expression is now + # an Assignment, and then continue on the print. + expressions = [] + conditions = [] + for (e, c) in rhs.args: + expressions.append(Assignment(lhs, e)) + conditions.append(c) + temp = Piecewise(*zip(expressions, conditions)) + return self._print(temp) + if self._settings["contract"] and (lhs.has(IndexedBase) or + rhs.has(IndexedBase)): + # Here we check if there is looping to be done, and if so + # print the required loops. + return self._doprint_loops(rhs, lhs) + else: + lhs_code = self._print(lhs) + rhs_code = self._print(rhs) + return self._get_statement("%s = %s" % (lhs_code, rhs_code)) + + + def _print_Infinity(self, expr): + return 'inf' + + + def _print_NegativeInfinity(self, expr): + return '-inf' + + + def _print_NaN(self, expr): + return 'NaN' + + + def _print_list(self, expr): + return '{' + ', '.join(self._print(a) for a in expr) + '}' + _print_tuple = _print_list + _print_Tuple = _print_list + _print_List = _print_list + + + def _print_BooleanTrue(self, expr): + return "true" + + + def _print_BooleanFalse(self, expr): + return "false" + + + def _print_bool(self, expr): + return str(expr).lower() + + + # Could generate quadrature code for definite Integrals? + #_print_Integral = _print_not_supported + + + def _print_MatrixBase(self, A): + # Handle zero dimensions: + if (A.rows, A.cols) == (0, 0): + return '[]' + elif S.Zero in A.shape: + return 'zeros(%s, %s)' % (A.rows, A.cols) + elif (A.rows, A.cols) == (1, 1): + # Octave does not distinguish between scalars and 1x1 matrices + return self._print(A[0, 0]) + return "[%s]" % "; ".join(" ".join([self._print(a) for a in A[r, :]]) + for r in range(A.rows)) + + + def _print_SparseRepMatrix(self, A): + from sympy.matrices import Matrix + L = A.col_list(); + # make row vectors of the indices and entries + I = Matrix([[k[0] + 1 for k in L]]) + J = Matrix([[k[1] + 1 for k in L]]) + AIJ = Matrix([[k[2] for k in L]]) + return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J), + self._print(AIJ), A.rows, A.cols) + + + def _print_MatrixElement(self, expr): + return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + + '(%s, %s)' % (expr.i + 1, expr.j + 1) + + + def _print_MatrixSlice(self, expr): + def strslice(x, lim): + l = x[0] + 1 + h = x[1] + step = x[2] + lstr = self._print(l) + hstr = 'end' if h == lim else self._print(h) + if step == 1: + if l == 1 and h == lim: + return ':' + if l == h: + return lstr + else: + return lstr + ':' + hstr + else: + return ':'.join((lstr, self._print(step), hstr)) + return (self._print(expr.parent) + '(' + + strslice(expr.rowslice, expr.parent.shape[0]) + ', ' + + strslice(expr.colslice, expr.parent.shape[1]) + ')') + + + def _print_Indexed(self, expr): + inds = [ self._print(i) for i in expr.indices ] + return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds)) + + + def _print_Idx(self, expr): + return self._print(expr.label) + + + def _print_KroneckerDelta(self, expr): + prec = PRECEDENCE["Pow"] + return "double(%s == %s)" % tuple(self.parenthesize(x, prec) + for x in expr.args) + + def _print_HadamardProduct(self, expr): + return '.*'.join([self.parenthesize(arg, precedence(expr)) + for arg in expr.args]) + + def _print_HadamardPower(self, expr): + PREC = precedence(expr) + return '.**'.join([ + self.parenthesize(expr.base, PREC), + self.parenthesize(expr.exp, PREC) + ]) + + def _print_Identity(self, expr): + shape = expr.shape + if len(shape) == 2 and shape[0] == shape[1]: + shape = [shape[0]] + s = ", ".join(self._print(n) for n in shape) + return "eye(" + s + ")" + + def _print_lowergamma(self, expr): + # Octave implements regularized incomplete gamma function + return "(gammainc({1}, {0}).*gamma({0}))".format( + self._print(expr.args[0]), self._print(expr.args[1])) + + + def _print_uppergamma(self, expr): + return "(gammainc({1}, {0}, 'upper').*gamma({0}))".format( + self._print(expr.args[0]), self._print(expr.args[1])) + + + def _print_sinc(self, expr): + #Note: Divide by pi because Octave implements normalized sinc function. + return "sinc(%s)" % self._print(expr.args[0]/S.Pi) + + + def _print_hankel1(self, expr): + return "besselh(%s, 1, %s)" % (self._print(expr.order), + self._print(expr.argument)) + + + def _print_hankel2(self, expr): + return "besselh(%s, 2, %s)" % (self._print(expr.order), + self._print(expr.argument)) + + + # Note: as of 2015, Octave doesn't have spherical Bessel functions + def _print_jn(self, expr): + from sympy.functions import sqrt, besselj + x = expr.argument + expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x) + return self._print(expr2) + + + def _print_yn(self, expr): + from sympy.functions import sqrt, bessely + x = expr.argument + expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x) + return self._print(expr2) + + + def _print_airyai(self, expr): + return "airy(0, %s)" % self._print(expr.args[0]) + + + def _print_airyaiprime(self, expr): + return "airy(1, %s)" % self._print(expr.args[0]) + + + def _print_airybi(self, expr): + return "airy(2, %s)" % self._print(expr.args[0]) + + + def _print_airybiprime(self, expr): + return "airy(3, %s)" % self._print(expr.args[0]) + + + def _print_expint(self, expr): + mu, x = expr.args + if mu != 1: + return self._print_not_supported(expr) + return "expint(%s)" % self._print(x) + + + def _one_or_two_reversed_args(self, expr): + assert len(expr.args) <= 2 + return '{name}({args})'.format( + name=self.known_functions[expr.__class__.__name__], + args=", ".join([self._print(x) for x in reversed(expr.args)]) + ) + + + _print_DiracDelta = _print_LambertW = _one_or_two_reversed_args + + + def _nested_binary_math_func(self, expr): + return '{name}({arg1}, {arg2})'.format( + name=self.known_functions[expr.__class__.__name__], + arg1=self._print(expr.args[0]), + arg2=self._print(expr.func(*expr.args[1:])) + ) + + _print_Max = _print_Min = _nested_binary_math_func + + + def _print_Piecewise(self, expr): + if expr.args[-1].cond != True: + # We need the last conditional to be a True, otherwise the resulting + # function may not return a result. + raise ValueError("All Piecewise expressions must contain an " + "(expr, True) statement to be used as a default " + "condition. Without one, the generated " + "expression may not evaluate to anything under " + "some condition.") + lines = [] + if self._settings["inline"]: + # Express each (cond, expr) pair in a nested Horner form: + # (condition) .* (expr) + (not cond) .* () + # Expressions that result in multiple statements won't work here. + ecpairs = ["({0}).*({1}) + (~({0})).*(".format + (self._print(c), self._print(e)) + for e, c in expr.args[:-1]] + elast = "%s" % self._print(expr.args[-1].expr) + pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs) + # Note: current need these outer brackets for 2*pw. Would be + # nicer to teach parenthesize() to do this for us when needed! + return "(" + pw + ")" + else: + for i, (e, c) in enumerate(expr.args): + if i == 0: + lines.append("if (%s)" % self._print(c)) + elif i == len(expr.args) - 1 and c == True: + lines.append("else") + else: + lines.append("elseif (%s)" % self._print(c)) + code0 = self._print(e) + lines.append(code0) + if i == len(expr.args) - 1: + lines.append("end") + return "\n".join(lines) + + + def _print_zeta(self, expr): + if len(expr.args) == 1: + return "zeta(%s)" % self._print(expr.args[0]) + else: + # Matlab two argument zeta is not equivalent to SymPy's + return self._print_not_supported(expr) + + + def indent_code(self, code): + """Accepts a string of code or a list of code lines""" + + # code mostly copied from ccode + if isinstance(code, str): + code_lines = self.indent_code(code.splitlines(True)) + return ''.join(code_lines) + + tab = " " + inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ') + dec_regex = ('^end$', '^elseif ', '^else$') + + # pre-strip left-space from the code + code = [ line.lstrip(' \t') for line in code ] + + increase = [ int(any(search(re, line) for re in inc_regex)) + for line in code ] + decrease = [ int(any(search(re, line) for re in dec_regex)) + for line in code ] + + pretty = [] + level = 0 + for n, line in enumerate(code): + if line in ('', '\n'): + pretty.append(line) + continue + level -= decrease[n] + pretty.append("%s%s" % (tab*level, line)) + level += increase[n] + return pretty + + +def octave_code(expr, assign_to=None, **settings): + r"""Converts `expr` to a string of Octave (or Matlab) code. + + The string uses a subset of the Octave language for Matlab compatibility. + + Parameters + ========== + + expr : Expr + A SymPy expression to be converted. + assign_to : optional + When given, the argument is used as the name of the variable to which + the expression is assigned. Can be a string, ``Symbol``, + ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for + expressions that generate multi-line statements. + precision : integer, optional + The precision for numbers such as pi [default=16]. + user_functions : dict, optional + A dictionary where keys are ``FunctionClass`` instances and values are + their string representations. Alternatively, the dictionary value can + be a list of tuples i.e. [(argument_test, cfunction_string)]. See + below for examples. + human : bool, optional + If True, the result is a single string that may contain some constant + declarations for the number symbols. If False, the same information is + returned in a tuple of (symbols_to_declare, not_supported_functions, + code_text). [default=True]. + contract: bool, optional + If True, ``Indexed`` instances are assumed to obey tensor contraction + rules and the corresponding nested loops over indices are generated. + Setting contract=False will not generate loops, instead the user is + responsible to provide values for the indices in the code. + [default=True]. + inline: bool, optional + If True, we try to create single-statement code instead of multiple + statements. [default=True]. + + Examples + ======== + + >>> from sympy import octave_code, symbols, sin, pi + >>> x = symbols('x') + >>> octave_code(sin(x).series(x).removeO()) + 'x.^5/120 - x.^3/6 + x' + + >>> from sympy import Rational, ceiling + >>> x, y, tau = symbols("x, y, tau") + >>> octave_code((2*tau)**Rational(7, 2)) + '8*sqrt(2)*tau.^(7/2)' + + Note that element-wise (Hadamard) operations are used by default between + symbols. This is because its very common in Octave to write "vectorized" + code. It is harmless if the values are scalars. + + >>> octave_code(sin(pi*x*y), assign_to="s") + 's = sin(pi*x.*y);' + + If you need a matrix product "*" or matrix power "^", you can specify the + symbol as a ``MatrixSymbol``. + + >>> from sympy import Symbol, MatrixSymbol + >>> n = Symbol('n', integer=True, positive=True) + >>> A = MatrixSymbol('A', n, n) + >>> octave_code(3*pi*A**3) + '(3*pi)*A^3' + + This class uses several rules to decide which symbol to use a product. + Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*". + A HadamardProduct can be used to specify componentwise multiplication ".*" + of two MatrixSymbols. There is currently there is no easy way to specify + scalar symbols, so sometimes the code might have some minor cosmetic + issues. For example, suppose x and y are scalars and A is a Matrix, then + while a human programmer might write "(x^2*y)*A^3", we generate: + + >>> octave_code(x**2*y*A**3) + '(x.^2.*y)*A^3' + + Matrices are supported using Octave inline notation. When using + ``assign_to`` with matrices, the name can be specified either as a string + or as a ``MatrixSymbol``. The dimensions must align in the latter case. + + >>> from sympy import Matrix, MatrixSymbol + >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) + >>> octave_code(mat, assign_to='A') + 'A = [x.^2 sin(x) ceil(x)];' + + ``Piecewise`` expressions are implemented with logical masking by default. + Alternatively, you can pass "inline=False" to use if-else conditionals. + Note that if the ``Piecewise`` lacks a default term, represented by + ``(expr, True)`` then an error will be thrown. This is to prevent + generating an expression that may not evaluate to anything. + + >>> from sympy import Piecewise + >>> pw = Piecewise((x + 1, x > 0), (x, True)) + >>> octave_code(pw, assign_to=tau) + 'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));' + + Note that any expression that can be generated normally can also exist + inside a Matrix: + + >>> mat = Matrix([[x**2, pw, sin(x)]]) + >>> octave_code(mat, assign_to='A') + 'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];' + + Custom printing can be defined for certain types by passing a dictionary of + "type" : "function" to the ``user_functions`` kwarg. Alternatively, the + dictionary value can be a list of tuples i.e., [(argument_test, + cfunction_string)]. This can be used to call a custom Octave function. + + >>> from sympy import Function + >>> f = Function('f') + >>> g = Function('g') + >>> custom_functions = { + ... "f": "existing_octave_fcn", + ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), + ... (lambda x: not x.is_Matrix, "my_fcn")] + ... } + >>> mat = Matrix([[1, x]]) + >>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions) + 'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])' + + Support for loops is provided through ``Indexed`` types. With + ``contract=True`` these expressions will be turned into loops, whereas + ``contract=False`` will just print the assignment expression that should be + looped over: + + >>> from sympy import Eq, IndexedBase, Idx + >>> len_y = 5 + >>> y = IndexedBase('y', shape=(len_y,)) + >>> t = IndexedBase('t', shape=(len_y,)) + >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) + >>> i = Idx('i', len_y-1) + >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) + >>> octave_code(e.rhs, assign_to=e.lhs, contract=False) + 'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));' + """ + return OctaveCodePrinter(settings).doprint(expr, assign_to) + + +def print_octave_code(expr, **settings): + """Prints the Octave (or Matlab) representation of the given expression. + + See `octave_code` for the meaning of the optional arguments. + """ + print(octave_code(expr, **settings)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/precedence.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/precedence.py new file mode 100644 index 0000000000000000000000000000000000000000..8181f5608710fbb4e2d2f146373be4c4cff47212 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/precedence.py @@ -0,0 +1,177 @@ +"""A module providing information about the necessity of brackets""" + + +# Default precedence values for some basic types +PRECEDENCE = { + "Lambda": 1, + "Xor": 10, + "Or": 20, + "And": 30, + "Relational": 35, + "Add": 40, + "Mul": 50, + "Pow": 60, + "Func": 70, + "Not": 100, + "Atom": 1000, + "BitwiseOr": 36, + "BitwiseXor": 37, + "BitwiseAnd": 38 +} + +# A dictionary assigning precedence values to certain classes. These values are +# treated like they were inherited, so not every single class has to be named +# here. +# Do not use this with printers other than StrPrinter +PRECEDENCE_VALUES = { + "Equivalent": PRECEDENCE["Xor"], + "Xor": PRECEDENCE["Xor"], + "Implies": PRECEDENCE["Xor"], + "Or": PRECEDENCE["Or"], + "And": PRECEDENCE["And"], + "Add": PRECEDENCE["Add"], + "Pow": PRECEDENCE["Pow"], + "Relational": PRECEDENCE["Relational"], + "Sub": PRECEDENCE["Add"], + "Not": PRECEDENCE["Not"], + "Function" : PRECEDENCE["Func"], + "NegativeInfinity": PRECEDENCE["Add"], + "MatAdd": PRECEDENCE["Add"], + "MatPow": PRECEDENCE["Pow"], + "MatrixSolve": PRECEDENCE["Mul"], + "Mod": PRECEDENCE["Mul"], + "TensAdd": PRECEDENCE["Add"], + # As soon as `TensMul` is a subclass of `Mul`, remove this: + "TensMul": PRECEDENCE["Mul"], + "HadamardProduct": PRECEDENCE["Mul"], + "HadamardPower": PRECEDENCE["Pow"], + "KroneckerProduct": PRECEDENCE["Mul"], + "Equality": PRECEDENCE["Mul"], + "Unequality": PRECEDENCE["Mul"], +} + +# Sometimes it's not enough to assign a fixed precedence value to a +# class. Then a function can be inserted in this dictionary that takes +# an instance of this class as argument and returns the appropriate +# precedence value. + +# Precedence functions + + +def precedence_Mul(item): + if item.could_extract_minus_sign(): + return PRECEDENCE["Add"] + return PRECEDENCE["Mul"] + + +def precedence_Rational(item): + if item.p < 0: + return PRECEDENCE["Add"] + return PRECEDENCE["Mul"] + + +def precedence_Integer(item): + if item.p < 0: + return PRECEDENCE["Add"] + return PRECEDENCE["Atom"] + + +def precedence_Float(item): + if item < 0: + return PRECEDENCE["Add"] + return PRECEDENCE["Atom"] + + +def precedence_PolyElement(item): + if item.is_generator: + return PRECEDENCE["Atom"] + elif item.is_ground: + return precedence(item.coeff(1)) + elif item.is_term: + return PRECEDENCE["Mul"] + else: + return PRECEDENCE["Add"] + + +def precedence_FracElement(item): + if item.denom == 1: + return precedence_PolyElement(item.numer) + else: + return PRECEDENCE["Mul"] + + +def precedence_UnevaluatedExpr(item): + return precedence(item.args[0]) - 0.5 + + +PRECEDENCE_FUNCTIONS = { + "Integer": precedence_Integer, + "Mul": precedence_Mul, + "Rational": precedence_Rational, + "Float": precedence_Float, + "PolyElement": precedence_PolyElement, + "FracElement": precedence_FracElement, + "UnevaluatedExpr": precedence_UnevaluatedExpr, +} + + +def precedence(item): + """Returns the precedence of a given object. + + This is the precedence for StrPrinter. + """ + if hasattr(item, "precedence"): + return item.precedence + try: + mro = item.__class__.__mro__ + except AttributeError: + return PRECEDENCE["Atom"] + for i in mro: + n = i.__name__ + if n in PRECEDENCE_FUNCTIONS: + return PRECEDENCE_FUNCTIONS[n](item) + elif n in PRECEDENCE_VALUES: + return PRECEDENCE_VALUES[n] + return PRECEDENCE["Atom"] + + +PRECEDENCE_TRADITIONAL = PRECEDENCE.copy() +PRECEDENCE_TRADITIONAL['Integral'] = PRECEDENCE["Mul"] +PRECEDENCE_TRADITIONAL['Sum'] = PRECEDENCE["Mul"] +PRECEDENCE_TRADITIONAL['Product'] = PRECEDENCE["Mul"] +PRECEDENCE_TRADITIONAL['Limit'] = PRECEDENCE["Mul"] +PRECEDENCE_TRADITIONAL['Derivative'] = PRECEDENCE["Mul"] +PRECEDENCE_TRADITIONAL['TensorProduct'] = PRECEDENCE["Mul"] +PRECEDENCE_TRADITIONAL['Transpose'] = PRECEDENCE["Pow"] +PRECEDENCE_TRADITIONAL['Adjoint'] = PRECEDENCE["Pow"] +PRECEDENCE_TRADITIONAL['Dot'] = PRECEDENCE["Mul"] - 1 +PRECEDENCE_TRADITIONAL['Cross'] = PRECEDENCE["Mul"] - 1 +PRECEDENCE_TRADITIONAL['Gradient'] = PRECEDENCE["Mul"] - 1 +PRECEDENCE_TRADITIONAL['Divergence'] = PRECEDENCE["Mul"] - 1 +PRECEDENCE_TRADITIONAL['Curl'] = PRECEDENCE["Mul"] - 1 +PRECEDENCE_TRADITIONAL['Laplacian'] = PRECEDENCE["Mul"] - 1 +PRECEDENCE_TRADITIONAL['Union'] = PRECEDENCE['Xor'] +PRECEDENCE_TRADITIONAL['Intersection'] = PRECEDENCE['Xor'] +PRECEDENCE_TRADITIONAL['Complement'] = PRECEDENCE['Xor'] +PRECEDENCE_TRADITIONAL['SymmetricDifference'] = PRECEDENCE['Xor'] +PRECEDENCE_TRADITIONAL['ProductSet'] = PRECEDENCE['Xor'] + + +def precedence_traditional(item): + """Returns the precedence of a given object according to the + traditional rules of mathematics. + + This is the precedence for the LaTeX and pretty printer. + """ + # Integral, Sum, Product, Limit have the precedence of Mul in LaTeX, + # the precedence of Atom for other printers: + from sympy.core.expr import UnevaluatedExpr + + if isinstance(item, UnevaluatedExpr): + return precedence_traditional(item.args[0]) + + n = item.__class__.__name__ + if n in PRECEDENCE_TRADITIONAL: + return PRECEDENCE_TRADITIONAL[n] + + return precedence(item) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/preview.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/preview.py new file mode 100644 index 0000000000000000000000000000000000000000..bf2cee28aa365c8f082251fd336ce18323b480a5 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/preview.py @@ -0,0 +1,390 @@ +import os +from os.path import join +import shutil +import tempfile + +try: + from subprocess import STDOUT, CalledProcessError, check_output +except ImportError: + pass + +from sympy.utilities.decorator import doctest_depends_on +from sympy.utilities.misc import debug +from .latex import latex + +__doctest_requires__ = {('preview',): ['pyglet']} + + +def _check_output_no_window(*args, **kwargs): + # Avoid showing a cmd.exe window when running this + # on Windows + if os.name == 'nt': + creation_flag = 0x08000000 # CREATE_NO_WINDOW + else: + creation_flag = 0 # Default value + return check_output(*args, creationflags=creation_flag, **kwargs) + + +def system_default_viewer(fname, fmt): + """ Open fname with the default system viewer. + + In practice, it is impossible for python to know when the system viewer is + done. For this reason, we ensure the passed file will not be deleted under + it, and this function does not attempt to block. + """ + # copy to a new temporary file that will not be deleted + with tempfile.NamedTemporaryFile(prefix='sympy-preview-', + suffix=os.path.splitext(fname)[1], + delete=False) as temp_f: + with open(fname, 'rb') as f: + shutil.copyfileobj(f, temp_f) + + import platform + if platform.system() == 'Darwin': + import subprocess + subprocess.call(('open', temp_f.name)) + elif platform.system() == 'Windows': + os.startfile(temp_f.name) + else: + import subprocess + subprocess.call(('xdg-open', temp_f.name)) + + +def pyglet_viewer(fname, fmt): + try: + from pyglet import window, image, gl + from pyglet.window import key + from pyglet.image.codecs import ImageDecodeException + except ImportError: + raise ImportError("pyglet is required for preview.\n visit https://pyglet.org/") + + try: + img = image.load(fname) + except ImageDecodeException: + raise ValueError("pyglet preview does not work for '{}' files.".format(fmt)) + + offset = 25 + + config = gl.Config(double_buffer=False) + win = window.Window( + width=img.width + 2*offset, + height=img.height + 2*offset, + caption="SymPy", + resizable=False, + config=config + ) + + win.set_vsync(False) + + try: + def on_close(): + win.has_exit = True + + win.on_close = on_close + + def on_key_press(symbol, modifiers): + if symbol in [key.Q, key.ESCAPE]: + on_close() + + win.on_key_press = on_key_press + + def on_expose(): + gl.glClearColor(1.0, 1.0, 1.0, 1.0) + gl.glClear(gl.GL_COLOR_BUFFER_BIT) + + img.blit( + (win.width - img.width) / 2, + (win.height - img.height) / 2 + ) + + win.on_expose = on_expose + + while not win.has_exit: + win.dispatch_events() + win.flip() + except KeyboardInterrupt: + pass + + win.close() + + +def _get_latex_main(expr, *, preamble=None, packages=(), extra_preamble=None, + euler=True, fontsize=None, **latex_settings): + """ + Generate string of a LaTeX document rendering ``expr``. + """ + if preamble is None: + actual_packages = packages + ("amsmath", "amsfonts") + if euler: + actual_packages += ("euler",) + package_includes = "\n" + "\n".join(["\\usepackage{%s}" % p + for p in actual_packages]) + if extra_preamble: + package_includes += extra_preamble + + if not fontsize: + fontsize = "12pt" + elif isinstance(fontsize, int): + fontsize = "{}pt".format(fontsize) + preamble = r"""\documentclass[varwidth,%s]{standalone} +%s + +\begin{document} +""" % (fontsize, package_includes) + else: + if packages or extra_preamble: + raise ValueError("The \"packages\" or \"extra_preamble\" keywords" + "must not be set if a " + "custom LaTeX preamble was specified") + + if isinstance(expr, str): + latex_string = expr + else: + latex_string = ('$\\displaystyle ' + + latex(expr, mode='plain', **latex_settings) + + '$') + + return preamble + '\n' + latex_string + '\n\n' + r"\end{document}" + + +@doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',), + disable_viewers=('evince', 'gimp', 'superior-dvi-viewer')) +def preview(expr, output='png', viewer=None, euler=True, packages=(), + filename=None, outputbuffer=None, preamble=None, dvioptions=None, + outputTexFile=None, extra_preamble=None, fontsize=None, + **latex_settings): + r""" + View expression or LaTeX markup in PNG, DVI, PostScript or PDF form. + + If the expr argument is an expression, it will be exported to LaTeX and + then compiled using the available TeX distribution. The first argument, + 'expr', may also be a LaTeX string. The function will then run the + appropriate viewer for the given output format or use the user defined + one. By default png output is generated. + + By default pretty Euler fonts are used for typesetting (they were used to + typeset the well known "Concrete Mathematics" book). For that to work, you + need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the + texlive-fonts-extra package). If you prefer default AMS fonts or your + system lacks 'eulervm' LaTeX package then unset the 'euler' keyword + argument. + + To use viewer auto-detection, lets say for 'png' output, issue + + >>> from sympy import symbols, preview, Symbol + >>> x, y = symbols("x,y") + + >>> preview(x + y, output='png') + + This will choose 'pyglet' by default. To select a different one, do + + >>> preview(x + y, output='png', viewer='gimp') + + The 'png' format is considered special. For all other formats the rules + are slightly different. As an example we will take 'dvi' output format. If + you would run + + >>> preview(x + y, output='dvi') + + then 'view' will look for available 'dvi' viewers on your system + (predefined in the function, so it will try evince, first, then kdvi and + xdvi). If nothing is found, it will fall back to using a system file + association (via ``open`` and ``xdg-open``). To always use your system file + association without searching for the above readers, use + + >>> from sympy.printing.preview import system_default_viewer + >>> preview(x + y, output='dvi', viewer=system_default_viewer) + + If this still does not find the viewer you want, it can be set explicitly. + + >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer') + + This will skip auto-detection and will run user specified + 'superior-dvi-viewer'. If ``view`` fails to find it on your system it will + gracefully raise an exception. + + You may also enter ``'file'`` for the viewer argument. Doing so will cause + this function to return a file object in read-only mode, if ``filename`` + is unset. However, if it was set, then 'preview' writes the generated + file to this filename instead. + + There is also support for writing to a ``io.BytesIO`` like object, which + needs to be passed to the ``outputbuffer`` argument. + + >>> from io import BytesIO + >>> obj = BytesIO() + >>> preview(x + y, output='png', viewer='BytesIO', + ... outputbuffer=obj) + + The LaTeX preamble can be customized by setting the 'preamble' keyword + argument. This can be used, e.g., to set a different font size, use a + custom documentclass or import certain set of LaTeX packages. + + >>> preamble = "\\documentclass[10pt]{article}\n" \ + ... "\\usepackage{amsmath,amsfonts}\\begin{document}" + >>> preview(x + y, output='png', preamble=preamble) + + It is also possible to use the standard preamble and provide additional + information to the preamble using the ``extra_preamble`` keyword argument. + + >>> from sympy import sin + >>> extra_preamble = "\\renewcommand{\\sin}{\\cos}" + >>> preview(sin(x), output='png', extra_preamble=extra_preamble) + + If the value of 'output' is different from 'dvi' then command line + options can be set ('dvioptions' argument) for the execution of the + 'dvi'+output conversion tool. These options have to be in the form of a + list of strings (see ``subprocess.Popen``). + + Additional keyword args will be passed to the :func:`~sympy.printing.latex.latex` call, + e.g., the ``symbol_names`` flag. + + >>> phidd = Symbol('phidd') + >>> preview(phidd, symbol_names={phidd: r'\ddot{\varphi}'}) + + For post-processing the generated TeX File can be written to a file by + passing the desired filename to the 'outputTexFile' keyword + argument. To write the TeX code to a file named + ``"sample.tex"`` and run the default png viewer to display the resulting + bitmap, do + + >>> preview(x + y, outputTexFile="sample.tex") + + + """ + # pyglet is the default for png + if viewer is None and output == "png": + try: + import pyglet # noqa: F401 + except ImportError: + pass + else: + viewer = pyglet_viewer + + # look up a known application + if viewer is None: + # sorted in order from most pretty to most ugly + # very discussable, but indeed 'gv' looks awful :) + candidates = { + "dvi": [ "evince", "okular", "kdvi", "xdvi" ], + "ps": [ "evince", "okular", "gsview", "gv" ], + "pdf": [ "evince", "okular", "kpdf", "acroread", "xpdf", "gv" ], + } + + for candidate in candidates.get(output, []): + path = shutil.which(candidate) + if path is not None: + viewer = path + break + + # otherwise, use the system default for file association + if viewer is None: + viewer = system_default_viewer + + if viewer == "file": + if filename is None: + raise ValueError("filename has to be specified if viewer=\"file\"") + elif viewer == "BytesIO": + if outputbuffer is None: + raise ValueError("outputbuffer has to be a BytesIO " + "compatible object if viewer=\"BytesIO\"") + elif not callable(viewer) and not shutil.which(viewer): + raise OSError("Unrecognized viewer: %s" % viewer) + + latex_main = _get_latex_main(expr, preamble=preamble, packages=packages, + euler=euler, extra_preamble=extra_preamble, + fontsize=fontsize, **latex_settings) + + debug("Latex code:") + debug(latex_main) + with tempfile.TemporaryDirectory() as workdir: + with open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh: + fh.write(latex_main) + + if outputTexFile is not None: + shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile) + + if not shutil.which('latex'): + raise RuntimeError("latex program is not installed") + + try: + _check_output_no_window( + ['latex', '-halt-on-error', '-interaction=nonstopmode', + 'texput.tex'], + cwd=workdir, + stderr=STDOUT) + except CalledProcessError as e: + raise RuntimeError( + "'latex' exited abnormally with the following output:\n%s" % + e.output) + + src = "texput.%s" % (output) + + if output != "dvi": + # in order of preference + commandnames = { + "ps": ["dvips"], + "pdf": ["dvipdfmx", "dvipdfm", "dvipdf"], + "png": ["dvipng"], + "svg": ["dvisvgm"], + } + try: + cmd_variants = commandnames[output] + except KeyError: + raise ValueError("Invalid output format: %s" % output) from None + + # find an appropriate command + for cmd_variant in cmd_variants: + cmd_path = shutil.which(cmd_variant) + if cmd_path: + cmd = [cmd_path] + break + else: + if len(cmd_variants) > 1: + raise RuntimeError("None of %s are installed" % ", ".join(cmd_variants)) + else: + raise RuntimeError("%s is not installed" % cmd_variants[0]) + + defaultoptions = { + "dvipng": ["-T", "tight", "-z", "9", "--truecolor"], + "dvisvgm": ["--no-fonts"], + } + + commandend = { + "dvips": ["-o", src, "texput.dvi"], + "dvipdf": ["texput.dvi", src], + "dvipdfm": ["-o", src, "texput.dvi"], + "dvipdfmx": ["-o", src, "texput.dvi"], + "dvipng": ["-o", src, "texput.dvi"], + "dvisvgm": ["-o", src, "texput.dvi"], + } + + if dvioptions is not None: + cmd.extend(dvioptions) + else: + cmd.extend(defaultoptions.get(cmd_variant, [])) + cmd.extend(commandend[cmd_variant]) + + try: + _check_output_no_window(cmd, cwd=workdir, stderr=STDOUT) + except CalledProcessError as e: + raise RuntimeError( + "'%s' exited abnormally with the following output:\n%s" % + (' '.join(cmd), e.output)) + + + if viewer == "file": + shutil.move(join(workdir, src), filename) + elif viewer == "BytesIO": + with open(join(workdir, src), 'rb') as fh: + outputbuffer.write(fh.read()) + elif callable(viewer): + viewer(join(workdir, src), fmt=output) + else: + try: + _check_output_no_window( + [viewer, src], cwd=workdir, stderr=STDOUT) + except CalledProcessError as e: + raise RuntimeError( + "'%s %s' exited abnormally with the following output:\n%s" % + (viewer, src, e.output)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/printer.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/printer.py new file mode 100644 index 0000000000000000000000000000000000000000..c6ddad8b8387e4e985c9b5d789a3d39a74e5792b --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/printer.py @@ -0,0 +1,396 @@ +"""Printing subsystem driver + +SymPy's printing system works the following way: Any expression can be +passed to a designated Printer who then is responsible to return an +adequate representation of that expression. + +**The basic concept is the following:** + +1. Let the object print itself if it knows how. +2. Take the best fitting method defined in the printer. +3. As fall-back use the emptyPrinter method for the printer. + +Which Method is Responsible for Printing? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The whole printing process is started by calling ``.doprint(expr)`` on the printer +which you want to use. This method looks for an appropriate method which can +print the given expression in the given style that the printer defines. +While looking for the method, it follows these steps: + +1. **Let the object print itself if it knows how.** + + The printer looks for a specific method in every object. The name of that method + depends on the specific printer and is defined under ``Printer.printmethod``. + For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``. + Look at the documentation of the printer that you want to use. + The name of the method is specified there. + + This was the original way of doing printing in sympy. Every class had + its own latex, mathml, str and repr methods, but it turned out that it + is hard to produce a high quality printer, if all the methods are spread + out that far. Therefore all printing code was combined into the different + printers, which works great for built-in SymPy objects, but not that + good for user defined classes where it is inconvenient to patch the + printers. + +2. **Take the best fitting method defined in the printer.** + + The printer loops through expr classes (class + its bases), and tries + to dispatch the work to ``_print_`` + + e.g., suppose we have the following class hierarchy:: + + Basic + | + Atom + | + Number + | + Rational + + then, for ``expr=Rational(...)``, the Printer will try + to call printer methods in the order as shown in the figure below:: + + p._print(expr) + | + |-- p._print_Rational(expr) + | + |-- p._print_Number(expr) + | + |-- p._print_Atom(expr) + | + `-- p._print_Basic(expr) + + if ``._print_Rational`` method exists in the printer, then it is called, + and the result is returned back. Otherwise, the printer tries to call + ``._print_Number`` and so on. + +3. **As a fall-back use the emptyPrinter method for the printer.** + + As fall-back ``self.emptyPrinter`` will be called with the expression. If + not defined in the Printer subclass this will be the same as ``str(expr)``. + +.. _printer_example: + +Example of Custom Printer +^^^^^^^^^^^^^^^^^^^^^^^^^ + +In the example below, we have a printer which prints the derivative of a function +in a shorter form. + +.. code-block:: python + + from sympy.core.symbol import Symbol + from sympy.printing.latex import LatexPrinter, print_latex + from sympy.core.function import UndefinedFunction, Function + + + class MyLatexPrinter(LatexPrinter): + \"\"\"Print derivative of a function of symbols in a shorter form. + \"\"\" + def _print_Derivative(self, expr): + function, *vars = expr.args + if not isinstance(type(function), UndefinedFunction) or \\ + not all(isinstance(i, Symbol) for i in vars): + return super()._print_Derivative(expr) + + # If you want the printer to work correctly for nested + # expressions then use self._print() instead of str() or latex(). + # See the example of nested modulo below in the custom printing + # method section. + return "{}_{{{}}}".format( + self._print(Symbol(function.func.__name__)), + ''.join(self._print(i) for i in vars)) + + + def print_my_latex(expr): + \"\"\" Most of the printers define their own wrappers for print(). + These wrappers usually take printer settings. Our printer does not have + any settings. + \"\"\" + print(MyLatexPrinter().doprint(expr)) + + + y = Symbol("y") + x = Symbol("x") + f = Function("f") + expr = f(x, y).diff(x, y) + + # Print the expression using the normal latex printer and our custom + # printer. + print_latex(expr) + print_my_latex(expr) + +The output of the code above is:: + + \\frac{\\partial^{2}}{\\partial x\\partial y} f{\\left(x,y \\right)} + f_{xy} + +.. _printer_method_example: + +Example of Custom Printing Method +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In the example below, the latex printing of the modulo operator is modified. +This is done by overriding the method ``_latex`` of ``Mod``. + +>>> from sympy import Symbol, Mod, Integer, print_latex + +>>> # Always use printer._print() +>>> class ModOp(Mod): +... def _latex(self, printer): +... a, b = [printer._print(i) for i in self.args] +... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) + +Comparing the output of our custom operator to the builtin one: + +>>> x = Symbol('x') +>>> m = Symbol('m') +>>> print_latex(Mod(x, m)) +x \\bmod m +>>> print_latex(ModOp(x, m)) +\\operatorname{Mod}{\\left(x, m\\right)} + +Common mistakes +~~~~~~~~~~~~~~~ +It's important to always use ``self._print(obj)`` to print subcomponents of +an expression when customizing a printer. Mistakes include: + +1. Using ``self.doprint(obj)`` instead: + + >>> # This example does not work properly, as only the outermost call may use + >>> # doprint. + >>> class ModOpModeWrong(Mod): + ... def _latex(self, printer): + ... a, b = [printer.doprint(i) for i in self.args] + ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) + + This fails when the ``mode`` argument is passed to the printer: + + >>> print_latex(ModOp(x, m), mode='inline') # ok + $\\operatorname{Mod}{\\left(x, m\\right)}$ + >>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad + $\\operatorname{Mod}{\\left($x$, $m$\\right)}$ + +2. Using ``str(obj)`` instead: + + >>> class ModOpNestedWrong(Mod): + ... def _latex(self, printer): + ... a, b = [str(i) for i in self.args] + ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) + + This fails on nested objects: + + >>> # Nested modulo. + >>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok + \\operatorname{Mod}{\\left(\\operatorname{Mod}{\\left(x, m\\right)}, 7\\right)} + >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad + \\operatorname{Mod}{\\left(ModOpNestedWrong(x, m), 7\\right)} + +3. Using ``LatexPrinter()._print(obj)`` instead. + + >>> from sympy.printing.latex import LatexPrinter + >>> class ModOpSettingsWrong(Mod): + ... def _latex(self, printer): + ... a, b = [LatexPrinter()._print(i) for i in self.args] + ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) + + This causes all the settings to be discarded in the subobjects. As an + example, the ``full_prec`` setting which shows floats to full precision is + ignored: + + >>> from sympy import Float + >>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok + \\operatorname{Mod}{\\left(1.00000000000000 x, m\\right)} + >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad + \\operatorname{Mod}{\\left(1.0 x, m\\right)} + +""" + +from __future__ import annotations +import sys +from typing import Any, Type +import inspect +from contextlib import contextmanager +from functools import cmp_to_key, update_wrapper + +from sympy.core.add import Add +from sympy.core.basic import Basic + +from sympy.core.function import AppliedUndef, UndefinedFunction, Function + + + +@contextmanager +def printer_context(printer, **kwargs): + original = printer._context.copy() + try: + printer._context.update(kwargs) + yield + finally: + printer._context = original + + +class Printer: + """ Generic printer + + Its job is to provide infrastructure for implementing new printers easily. + + If you want to define your custom Printer or your custom printing method + for your custom class then see the example above: printer_example_ . + """ + + _global_settings: dict[str, Any] = {} + + _default_settings: dict[str, Any] = {} + + printmethod = None # type: str + + @classmethod + def _get_initial_settings(cls): + settings = cls._default_settings.copy() + for key, val in cls._global_settings.items(): + if key in cls._default_settings: + settings[key] = val + return settings + + def __init__(self, settings=None): + self._str = str + + self._settings = self._get_initial_settings() + self._context = {} # mutable during printing + + if settings is not None: + self._settings.update(settings) + + if len(self._settings) > len(self._default_settings): + for key in self._settings: + if key not in self._default_settings: + raise TypeError("Unknown setting '%s'." % key) + + # _print_level is the number of times self._print() was recursively + # called. See StrPrinter._print_Float() for an example of usage + self._print_level = 0 + + @classmethod + def set_global_settings(cls, **settings): + """Set system-wide printing settings. """ + for key, val in settings.items(): + if val is not None: + cls._global_settings[key] = val + + @property + def order(self): + if 'order' in self._settings: + return self._settings['order'] + else: + raise AttributeError("No order defined.") + + def doprint(self, expr): + """Returns printer's representation for expr (as a string)""" + return self._str(self._print(expr)) + + def _print(self, expr, **kwargs) -> str: + """Internal dispatcher + + Tries the following concepts to print an expression: + 1. Let the object print itself if it knows how. + 2. Take the best fitting method defined in the printer. + 3. As fall-back use the emptyPrinter method for the printer. + """ + self._print_level += 1 + try: + # If the printer defines a name for a printing method + # (Printer.printmethod) and the object knows for itself how it + # should be printed, use that method. + if self.printmethod and hasattr(expr, self.printmethod): + if not (isinstance(expr, type) and issubclass(expr, Basic)): + return getattr(expr, self.printmethod)(self, **kwargs) + + # See if the class of expr is known, or if one of its super + # classes is known, and use that print function + # Exception: ignore the subclasses of Undefined, so that, e.g., + # Function('gamma') does not get dispatched to _print_gamma + classes = type(expr).__mro__ + if AppliedUndef in classes: + classes = classes[classes.index(AppliedUndef):] + if UndefinedFunction in classes: + classes = classes[classes.index(UndefinedFunction):] + # Another exception: if someone subclasses a known function, e.g., + # gamma, and changes the name, then ignore _print_gamma + if Function in classes: + i = classes.index(Function) + classes = tuple(c for c in classes[:i] if \ + c.__name__ == classes[0].__name__ or \ + c.__name__.endswith("Base")) + classes[i:] + for cls in classes: + printmethodname = '_print_' + cls.__name__ + printmethod = getattr(self, printmethodname, None) + if printmethod is not None: + return printmethod(expr, **kwargs) + # Unknown object, fall back to the emptyPrinter. + return self.emptyPrinter(expr) + finally: + self._print_level -= 1 + + def emptyPrinter(self, expr): + return str(expr) + + def _as_ordered_terms(self, expr, order=None): + """A compatibility function for ordering terms in Add. """ + order = order or self.order + + if order == 'old': + return sorted(Add.make_args(expr), key=cmp_to_key(Basic._compare_pretty)) + elif order == 'none': + return list(expr.args) + else: + return expr.as_ordered_terms(order=order) + + +class _PrintFunction: + """ + Function wrapper to replace ``**settings`` in the signature with printer defaults + """ + def __init__(self, f, print_cls: Type[Printer]): + # find all the non-setting arguments + params = list(inspect.signature(f).parameters.values()) + assert params.pop(-1).kind == inspect.Parameter.VAR_KEYWORD + self.__other_params = params + + self.__print_cls = print_cls + update_wrapper(self, f) + + def __reduce__(self): + # Since this is used as a decorator, it replaces the original function. + # The default pickling will try to pickle self.__wrapped__ and fail + # because the wrapped function can't be retrieved by name. + return self.__wrapped__.__qualname__ + + def __call__(self, *args, **kwargs): + return self.__wrapped__(*args, **kwargs) + + @property + def __signature__(self) -> inspect.Signature: + settings = self.__print_cls._get_initial_settings() + return inspect.Signature( + parameters=self.__other_params + [ + inspect.Parameter(k, inspect.Parameter.KEYWORD_ONLY, default=v) + for k, v in settings.items() + ], + return_annotation=self.__wrapped__.__annotations__.get('return', inspect.Signature.empty) # type:ignore + ) + + +def print_function(print_cls): + """ A decorator to replace kwargs with the printer settings in __signature__ """ + def decorator(f): + if sys.version_info < (3, 9): + # We have to create a subclass so that `help` actually shows the docstring in older Python versions. + # IPython and Sphinx do not need this, only a raw Python console. + cls = type(f'{f.__qualname__}_PrintFunction', (_PrintFunction,), {"__doc__": f.__doc__}) + else: + cls = _PrintFunction + return cls(f, print_cls) + return decorator diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/pycode.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/pycode.py new file mode 100644 index 0000000000000000000000000000000000000000..77eaf85a901df4bea09b19ae639e80f3fddcb2ed --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/pycode.py @@ -0,0 +1,750 @@ +""" +Python code printers + +This module contains Python code printers for plain Python as well as NumPy & SciPy enabled code. +""" +from collections import defaultdict +from itertools import chain +from sympy.core import S +from sympy.core.mod import Mod +from .precedence import precedence +from .codeprinter import CodePrinter + +_kw = { + 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', + 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', + 'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', + 'with', 'yield', 'None', 'False', 'nonlocal', 'True' +} + +_known_functions = { + 'Abs': 'abs', + 'Min': 'min', + 'Max': 'max', +} +_known_functions_math = { + 'acos': 'acos', + 'acosh': 'acosh', + 'asin': 'asin', + 'asinh': 'asinh', + 'atan': 'atan', + 'atan2': 'atan2', + 'atanh': 'atanh', + 'ceiling': 'ceil', + 'cos': 'cos', + 'cosh': 'cosh', + 'erf': 'erf', + 'erfc': 'erfc', + 'exp': 'exp', + 'expm1': 'expm1', + 'factorial': 'factorial', + 'floor': 'floor', + 'gamma': 'gamma', + 'hypot': 'hypot', + 'loggamma': 'lgamma', + 'log': 'log', + 'ln': 'log', + 'log10': 'log10', + 'log1p': 'log1p', + 'log2': 'log2', + 'sin': 'sin', + 'sinh': 'sinh', + 'Sqrt': 'sqrt', + 'tan': 'tan', + 'tanh': 'tanh' +} # Not used from ``math``: [copysign isclose isfinite isinf isnan ldexp frexp pow modf +# radians trunc fmod fsum gcd degrees fabs] +_known_constants_math = { + 'Exp1': 'e', + 'Pi': 'pi', + 'E': 'e', + 'Infinity': 'inf', + 'NaN': 'nan', + 'ComplexInfinity': 'nan' +} + +def _print_known_func(self, expr): + known = self.known_functions[expr.__class__.__name__] + return '{name}({args})'.format(name=self._module_format(known), + args=', '.join((self._print(arg) for arg in expr.args))) + + +def _print_known_const(self, expr): + known = self.known_constants[expr.__class__.__name__] + return self._module_format(known) + + +class AbstractPythonCodePrinter(CodePrinter): + printmethod = "_pythoncode" + language = "Python" + reserved_words = _kw + modules = None # initialized to a set in __init__ + tab = ' ' + _kf = dict(chain( + _known_functions.items(), + [(k, 'math.' + v) for k, v in _known_functions_math.items()] + )) + _kc = {k: 'math.'+v for k, v in _known_constants_math.items()} + _operators = {'and': 'and', 'or': 'or', 'not': 'not'} + _default_settings = dict( + CodePrinter._default_settings, + user_functions={}, + precision=17, + inline=True, + fully_qualified_modules=True, + contract=False, + standard='python3', + ) + + def __init__(self, settings=None): + super().__init__(settings) + + # Python standard handler + std = self._settings['standard'] + if std is None: + import sys + std = 'python{}'.format(sys.version_info.major) + if std != 'python3': + raise ValueError('Only Python 3 is supported.') + self.standard = std + + self.module_imports = defaultdict(set) + + # Known functions and constants handler + self.known_functions = dict(self._kf, **(settings or {}).get( + 'user_functions', {})) + self.known_constants = dict(self._kc, **(settings or {}).get( + 'user_constants', {})) + + def _declare_number_const(self, name, value): + return "%s = %s" % (name, value) + + def _module_format(self, fqn, register=True): + parts = fqn.split('.') + if register and len(parts) > 1: + self.module_imports['.'.join(parts[:-1])].add(parts[-1]) + + if self._settings['fully_qualified_modules']: + return fqn + else: + return fqn.split('(')[0].split('[')[0].split('.')[-1] + + def _format_code(self, lines): + return lines + + def _get_statement(self, codestring): + return "{}".format(codestring) + + def _get_comment(self, text): + return " # {}".format(text) + + def _expand_fold_binary_op(self, op, args): + """ + This method expands a fold on binary operations. + + ``functools.reduce`` is an example of a folded operation. + + For example, the expression + + `A + B + C + D` + + is folded into + + `((A + B) + C) + D` + """ + if len(args) == 1: + return self._print(args[0]) + else: + return "%s(%s, %s)" % ( + self._module_format(op), + self._expand_fold_binary_op(op, args[:-1]), + self._print(args[-1]), + ) + + def _expand_reduce_binary_op(self, op, args): + """ + This method expands a reductin on binary operations. + + Notice: this is NOT the same as ``functools.reduce``. + + For example, the expression + + `A + B + C + D` + + is reduced into: + + `(A + B) + (C + D)` + """ + if len(args) == 1: + return self._print(args[0]) + else: + N = len(args) + Nhalf = N // 2 + return "%s(%s, %s)" % ( + self._module_format(op), + self._expand_reduce_binary_op(args[:Nhalf]), + self._expand_reduce_binary_op(args[Nhalf:]), + ) + + def _print_NaN(self, expr): + return "float('nan')" + + def _print_Infinity(self, expr): + return "float('inf')" + + def _print_NegativeInfinity(self, expr): + return "float('-inf')" + + def _print_ComplexInfinity(self, expr): + return self._print_NaN(expr) + + def _print_Mod(self, expr): + PREC = precedence(expr) + return ('{} % {}'.format(*(self.parenthesize(x, PREC) for x in expr.args))) + + def _print_Piecewise(self, expr): + result = [] + i = 0 + for arg in expr.args: + e = arg.expr + c = arg.cond + if i == 0: + result.append('(') + result.append('(') + result.append(self._print(e)) + result.append(')') + result.append(' if ') + result.append(self._print(c)) + result.append(' else ') + i += 1 + result = result[:-1] + if result[-1] == 'True': + result = result[:-2] + result.append(')') + else: + result.append(' else None)') + return ''.join(result) + + def _print_Relational(self, expr): + "Relational printer for Equality and Unequality" + op = { + '==' :'equal', + '!=' :'not_equal', + '<' :'less', + '<=' :'less_equal', + '>' :'greater', + '>=' :'greater_equal', + } + if expr.rel_op in op: + lhs = self._print(expr.lhs) + rhs = self._print(expr.rhs) + return '({lhs} {op} {rhs})'.format(op=expr.rel_op, lhs=lhs, rhs=rhs) + return super()._print_Relational(expr) + + def _print_ITE(self, expr): + from sympy.functions.elementary.piecewise import Piecewise + return self._print(expr.rewrite(Piecewise)) + + def _print_Sum(self, expr): + loops = ( + 'for {i} in range({a}, {b}+1)'.format( + i=self._print(i), + a=self._print(a), + b=self._print(b)) + for i, a, b in expr.limits) + return '(builtins.sum({function} {loops}))'.format( + function=self._print(expr.function), + loops=' '.join(loops)) + + def _print_ImaginaryUnit(self, expr): + return '1j' + + def _print_KroneckerDelta(self, expr): + a, b = expr.args + + return '(1 if {a} == {b} else 0)'.format( + a = self._print(a), + b = self._print(b) + ) + + def _print_MatrixBase(self, expr): + name = expr.__class__.__name__ + func = self.known_functions.get(name, name) + return "%s(%s)" % (func, self._print(expr.tolist())) + + _print_SparseRepMatrix = \ + _print_MutableSparseMatrix = \ + _print_ImmutableSparseMatrix = \ + _print_Matrix = \ + _print_DenseMatrix = \ + _print_MutableDenseMatrix = \ + _print_ImmutableMatrix = \ + _print_ImmutableDenseMatrix = \ + lambda self, expr: self._print_MatrixBase(expr) + + def _indent_codestring(self, codestring): + return '\n'.join([self.tab + line for line in codestring.split('\n')]) + + def _print_FunctionDefinition(self, fd): + body = '\n'.join((self._print(arg) for arg in fd.body)) + return "def {name}({parameters}):\n{body}".format( + name=self._print(fd.name), + parameters=', '.join([self._print(var.symbol) for var in fd.parameters]), + body=self._indent_codestring(body) + ) + + def _print_While(self, whl): + body = '\n'.join((self._print(arg) for arg in whl.body)) + return "while {cond}:\n{body}".format( + cond=self._print(whl.condition), + body=self._indent_codestring(body) + ) + + def _print_Declaration(self, decl): + return '%s = %s' % ( + self._print(decl.variable.symbol), + self._print(decl.variable.value) + ) + + def _print_Return(self, ret): + arg, = ret.args + return 'return %s' % self._print(arg) + + def _print_Print(self, prnt): + print_args = ', '.join((self._print(arg) for arg in prnt.print_args)) + if prnt.format_string != None: # Must be '!= None', cannot be 'is not None' + print_args = '{} % ({})'.format( + self._print(prnt.format_string), print_args) + if prnt.file != None: # Must be '!= None', cannot be 'is not None' + print_args += ', file=%s' % self._print(prnt.file) + + return 'print(%s)' % print_args + + def _print_Stream(self, strm): + if str(strm.name) == 'stdout': + return self._module_format('sys.stdout') + elif str(strm.name) == 'stderr': + return self._module_format('sys.stderr') + else: + return self._print(strm.name) + + def _print_NoneToken(self, arg): + return 'None' + + def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'): + """Printing helper function for ``Pow`` + + Notes + ===== + + This preprocesses the ``sqrt`` as math formatter and prints division + + Examples + ======== + + >>> from sympy import sqrt + >>> from sympy.printing.pycode import PythonCodePrinter + >>> from sympy.abc import x + + Python code printer automatically looks up ``math.sqrt``. + + >>> printer = PythonCodePrinter() + >>> printer._hprint_Pow(sqrt(x), rational=True) + 'x**(1/2)' + >>> printer._hprint_Pow(sqrt(x), rational=False) + 'math.sqrt(x)' + >>> printer._hprint_Pow(1/sqrt(x), rational=True) + 'x**(-1/2)' + >>> printer._hprint_Pow(1/sqrt(x), rational=False) + '1/math.sqrt(x)' + >>> printer._hprint_Pow(1/x, rational=False) + '1/x' + >>> printer._hprint_Pow(1/x, rational=True) + 'x**(-1)' + + Using sqrt from numpy or mpmath + + >>> printer._hprint_Pow(sqrt(x), sqrt='numpy.sqrt') + 'numpy.sqrt(x)' + >>> printer._hprint_Pow(sqrt(x), sqrt='mpmath.sqrt') + 'mpmath.sqrt(x)' + + See Also + ======== + + sympy.printing.str.StrPrinter._print_Pow + """ + PREC = precedence(expr) + + if expr.exp == S.Half and not rational: + func = self._module_format(sqrt) + arg = self._print(expr.base) + return '{func}({arg})'.format(func=func, arg=arg) + + if expr.is_commutative and not rational: + if -expr.exp is S.Half: + func = self._module_format(sqrt) + num = self._print(S.One) + arg = self._print(expr.base) + return f"{num}/{func}({arg})" + if expr.exp is S.NegativeOne: + num = self._print(S.One) + arg = self.parenthesize(expr.base, PREC, strict=False) + return f"{num}/{arg}" + + + base_str = self.parenthesize(expr.base, PREC, strict=False) + exp_str = self.parenthesize(expr.exp, PREC, strict=False) + return "{}**{}".format(base_str, exp_str) + + +class ArrayPrinter: + + def _arrayify(self, indexed): + from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array + try: + return convert_indexed_to_array(indexed) + except Exception: + return indexed + + def _get_einsum_string(self, subranks, contraction_indices): + letters = self._get_letter_generator_for_einsum() + contraction_string = "" + counter = 0 + d = {j: min(i) for i in contraction_indices for j in i} + indices = [] + for rank_arg in subranks: + lindices = [] + for i in range(rank_arg): + if counter in d: + lindices.append(d[counter]) + else: + lindices.append(counter) + counter += 1 + indices.append(lindices) + mapping = {} + letters_free = [] + letters_dum = [] + for i in indices: + for j in i: + if j not in mapping: + l = next(letters) + mapping[j] = l + else: + l = mapping[j] + contraction_string += l + if j in d: + if l not in letters_dum: + letters_dum.append(l) + else: + letters_free.append(l) + contraction_string += "," + contraction_string = contraction_string[:-1] + return contraction_string, letters_free, letters_dum + + def _get_letter_generator_for_einsum(self): + for i in range(97, 123): + yield chr(i) + for i in range(65, 91): + yield chr(i) + raise ValueError("out of letters") + + def _print_ArrayTensorProduct(self, expr): + letters = self._get_letter_generator_for_einsum() + contraction_string = ",".join(["".join([next(letters) for j in range(i)]) for i in expr.subranks]) + return '%s("%s", %s)' % ( + self._module_format(self._module + "." + self._einsum), + contraction_string, + ", ".join([self._print(arg) for arg in expr.args]) + ) + + def _print_ArrayContraction(self, expr): + from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct + base = expr.expr + contraction_indices = expr.contraction_indices + + if isinstance(base, ArrayTensorProduct): + elems = ",".join(["%s" % (self._print(arg)) for arg in base.args]) + ranks = base.subranks + else: + elems = self._print(base) + ranks = [len(base.shape)] + + contraction_string, letters_free, letters_dum = self._get_einsum_string(ranks, contraction_indices) + + if not contraction_indices: + return self._print(base) + if isinstance(base, ArrayTensorProduct): + elems = ",".join(["%s" % (self._print(arg)) for arg in base.args]) + else: + elems = self._print(base) + return "%s(\"%s\", %s)" % ( + self._module_format(self._module + "." + self._einsum), + "{}->{}".format(contraction_string, "".join(sorted(letters_free))), + elems, + ) + + def _print_ArrayDiagonal(self, expr): + from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct + diagonal_indices = list(expr.diagonal_indices) + if isinstance(expr.expr, ArrayTensorProduct): + subranks = expr.expr.subranks + elems = expr.expr.args + else: + subranks = expr.subranks + elems = [expr.expr] + diagonal_string, letters_free, letters_dum = self._get_einsum_string(subranks, diagonal_indices) + elems = [self._print(i) for i in elems] + return '%s("%s", %s)' % ( + self._module_format(self._module + "." + self._einsum), + "{}->{}".format(diagonal_string, "".join(letters_free+letters_dum)), + ", ".join(elems) + ) + + def _print_PermuteDims(self, expr): + return "%s(%s, %s)" % ( + self._module_format(self._module + "." + self._transpose), + self._print(expr.expr), + self._print(expr.permutation.array_form), + ) + + def _print_ArrayAdd(self, expr): + return self._expand_fold_binary_op(self._module + "." + self._add, expr.args) + + def _print_OneArray(self, expr): + return "%s((%s,))" % ( + self._module_format(self._module+ "." + self._ones), + ','.join(map(self._print,expr.args)) + ) + + def _print_ZeroArray(self, expr): + return "%s((%s,))" % ( + self._module_format(self._module+ "." + self._zeros), + ','.join(map(self._print,expr.args)) + ) + + def _print_Assignment(self, expr): + #XXX: maybe this needs to happen at a higher level e.g. at _print or + #doprint? + lhs = self._print(self._arrayify(expr.lhs)) + rhs = self._print(self._arrayify(expr.rhs)) + return "%s = %s" % ( lhs, rhs ) + + def _print_IndexedBase(self, expr): + return self._print_ArraySymbol(expr) + + +class PythonCodePrinter(AbstractPythonCodePrinter): + + def _print_sign(self, e): + return '(0.0 if {e} == 0 else {f}(1, {e}))'.format( + f=self._module_format('math.copysign'), e=self._print(e.args[0])) + + def _print_Not(self, expr): + PREC = precedence(expr) + return self._operators['not'] + self.parenthesize(expr.args[0], PREC) + + def _print_Indexed(self, expr): + base = expr.args[0] + index = expr.args[1:] + return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index])) + + def _print_Pow(self, expr, rational=False): + return self._hprint_Pow(expr, rational=rational) + + def _print_Rational(self, expr): + return '{}/{}'.format(expr.p, expr.q) + + def _print_Half(self, expr): + return self._print_Rational(expr) + + def _print_frac(self, expr): + return self._print_Mod(Mod(expr.args[0], 1)) + + def _print_Symbol(self, expr): + + name = super()._print_Symbol(expr) + + if name in self.reserved_words: + if self._settings['error_on_reserved']: + msg = ('This expression includes the symbol "{}" which is a ' + 'reserved keyword in this language.') + raise ValueError(msg.format(name)) + return name + self._settings['reserved_word_suffix'] + elif '{' in name: # Remove curly braces from subscripted variables + return name.replace('{', '').replace('}', '') + else: + return name + + _print_lowergamma = CodePrinter._print_not_supported + _print_uppergamma = CodePrinter._print_not_supported + _print_fresnelc = CodePrinter._print_not_supported + _print_fresnels = CodePrinter._print_not_supported + + +for k in PythonCodePrinter._kf: + setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func) + +for k in _known_constants_math: + setattr(PythonCodePrinter, '_print_%s' % k, _print_known_const) + + +def pycode(expr, **settings): + """ Converts an expr to a string of Python code + + Parameters + ========== + + expr : Expr + A SymPy expression. + fully_qualified_modules : bool + Whether or not to write out full module names of functions + (``math.sin`` vs. ``sin``). default: ``True``. + standard : str or None, optional + Only 'python3' (default) is supported. + This parameter may be removed in the future. + + Examples + ======== + + >>> from sympy import pycode, tan, Symbol + >>> pycode(tan(Symbol('x')) + 1) + 'math.tan(x) + 1' + + """ + return PythonCodePrinter(settings).doprint(expr) + + +_not_in_mpmath = 'log1p log2'.split() +_in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath] +_known_functions_mpmath = dict(_in_mpmath, **{ + 'beta': 'beta', + 'frac': 'frac', + 'fresnelc': 'fresnelc', + 'fresnels': 'fresnels', + 'sign': 'sign', + 'loggamma': 'loggamma', + 'hyper': 'hyper', + 'meijerg': 'meijerg', + 'besselj': 'besselj', + 'bessely': 'bessely', + 'besseli': 'besseli', + 'besselk': 'besselk', +}) +_known_constants_mpmath = { + 'Exp1': 'e', + 'Pi': 'pi', + 'GoldenRatio': 'phi', + 'EulerGamma': 'euler', + 'Catalan': 'catalan', + 'NaN': 'nan', + 'Infinity': 'inf', + 'NegativeInfinity': 'ninf' +} + + +def _unpack_integral_limits(integral_expr): + """ helper function for _print_Integral that + - accepts an Integral expression + - returns a tuple of + - a list variables of integration + - a list of tuples of the upper and lower limits of integration + """ + integration_vars = [] + limits = [] + for integration_range in integral_expr.limits: + if len(integration_range) == 3: + integration_var, lower_limit, upper_limit = integration_range + else: + raise NotImplementedError("Only definite integrals are supported") + integration_vars.append(integration_var) + limits.append((lower_limit, upper_limit)) + return integration_vars, limits + + +class MpmathPrinter(PythonCodePrinter): + """ + Lambda printer for mpmath which maintains precision for floats + """ + printmethod = "_mpmathcode" + + language = "Python with mpmath" + + _kf = dict(chain( + _known_functions.items(), + [(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()] + )) + _kc = {k: 'mpmath.'+v for k, v in _known_constants_mpmath.items()} + + def _print_Float(self, e): + # XXX: This does not handle setting mpmath.mp.dps. It is assumed that + # the caller of the lambdified function will have set it to sufficient + # precision to match the Floats in the expression. + + # Remove 'mpz' if gmpy is installed. + args = str(tuple(map(int, e._mpf_))) + return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args) + + + def _print_Rational(self, e): + return "{func}({p})/{func}({q})".format( + func=self._module_format('mpmath.mpf'), + q=self._print(e.q), + p=self._print(e.p) + ) + + def _print_Half(self, e): + return self._print_Rational(e) + + def _print_uppergamma(self, e): + return "{}({}, {}, {})".format( + self._module_format('mpmath.gammainc'), + self._print(e.args[0]), + self._print(e.args[1]), + self._module_format('mpmath.inf')) + + def _print_lowergamma(self, e): + return "{}({}, 0, {})".format( + self._module_format('mpmath.gammainc'), + self._print(e.args[0]), + self._print(e.args[1])) + + def _print_log2(self, e): + return '{0}({1})/{0}(2)'.format( + self._module_format('mpmath.log'), self._print(e.args[0])) + + def _print_log1p(self, e): + return '{}({})'.format( + self._module_format('mpmath.log1p'), self._print(e.args[0])) + + def _print_Pow(self, expr, rational=False): + return self._hprint_Pow(expr, rational=rational, sqrt='mpmath.sqrt') + + def _print_Integral(self, e): + integration_vars, limits = _unpack_integral_limits(e) + + return "{}(lambda {}: {}, {})".format( + self._module_format("mpmath.quad"), + ", ".join(map(self._print, integration_vars)), + self._print(e.args[0]), + ", ".join("(%s, %s)" % tuple(map(self._print, l)) for l in limits)) + + +for k in MpmathPrinter._kf: + setattr(MpmathPrinter, '_print_%s' % k, _print_known_func) + +for k in _known_constants_mpmath: + setattr(MpmathPrinter, '_print_%s' % k, _print_known_const) + + +class SymPyPrinter(AbstractPythonCodePrinter): + + language = "Python with SymPy" + + def _print_Function(self, expr): + mod = expr.func.__module__ or '' + return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__), + ', '.join((self._print(arg) for arg in expr.args))) + + def _print_Pow(self, expr, rational=False): + return self._hprint_Pow(expr, rational=rational, sqrt='sympy.sqrt') diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/python.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/python.py new file mode 100644 index 0000000000000000000000000000000000000000..44ffd5ed7415e7c07e293229791f3dbbb28339c0 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/python.py @@ -0,0 +1,93 @@ +import keyword as kw +import sympy +from .repr import ReprPrinter +from .str import StrPrinter + +# A list of classes that should be printed using StrPrinter +STRPRINT = ("Add", "Infinity", "Integer", "Mul", "NegativeInfinity", + "Pow", "Zero") + + +class PythonPrinter(ReprPrinter, StrPrinter): + """A printer which converts an expression into its Python interpretation.""" + + def __init__(self, settings=None): + super().__init__(settings) + self.symbols = [] + self.functions = [] + + # Create print methods for classes that should use StrPrinter instead + # of ReprPrinter. + for name in STRPRINT: + f_name = "_print_%s" % name + f = getattr(StrPrinter, f_name) + setattr(PythonPrinter, f_name, f) + + def _print_Function(self, expr): + func = expr.func.__name__ + if not hasattr(sympy, func) and func not in self.functions: + self.functions.append(func) + return StrPrinter._print_Function(self, expr) + + # procedure (!) for defining symbols which have be defined in print_python() + def _print_Symbol(self, expr): + symbol = self._str(expr) + if symbol not in self.symbols: + self.symbols.append(symbol) + return StrPrinter._print_Symbol(self, expr) + + def _print_module(self, expr): + raise ValueError('Modules in the expression are unacceptable') + + +def python(expr, **settings): + """Return Python interpretation of passed expression + (can be passed to the exec() function without any modifications)""" + + printer = PythonPrinter(settings) + exprp = printer.doprint(expr) + + result = '' + # Returning found symbols and functions + renamings = {} + for symbolname in printer.symbols: + # Remove curly braces from subscripted variables + if '{' in symbolname: + newsymbolname = symbolname.replace('{', '').replace('}', '') + renamings[sympy.Symbol(symbolname)] = newsymbolname + else: + newsymbolname = symbolname + + # Escape symbol names that are reserved Python keywords + if kw.iskeyword(newsymbolname): + while True: + newsymbolname += "_" + if (newsymbolname not in printer.symbols and + newsymbolname not in printer.functions): + renamings[sympy.Symbol( + symbolname)] = sympy.Symbol(newsymbolname) + break + result += newsymbolname + ' = Symbol(\'' + symbolname + '\')\n' + + for functionname in printer.functions: + newfunctionname = functionname + # Escape function names that are reserved Python keywords + if kw.iskeyword(newfunctionname): + while True: + newfunctionname += "_" + if (newfunctionname not in printer.symbols and + newfunctionname not in printer.functions): + renamings[sympy.Function( + functionname)] = sympy.Function(newfunctionname) + break + result += newfunctionname + ' = Function(\'' + functionname + '\')\n' + + if renamings: + exprp = expr.subs(renamings) + result += 'e = ' + printer._str(exprp) + return result + + +def print_python(expr, **settings): + """Print output of python() function""" + print(python(expr, **settings)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/rcode.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/rcode.py new file mode 100644 index 0000000000000000000000000000000000000000..799ad61a7ef0750ead6a5e85f603d4ccc040cab2 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/rcode.py @@ -0,0 +1,410 @@ +""" +R code printer + +The RCodePrinter converts single SymPy expressions into single R expressions, +using the functions defined in math.h where possible. + + + +""" + +from __future__ import annotations +from typing import Any + +from sympy.core.numbers import equal_valued +from sympy.printing.codeprinter import CodePrinter +from sympy.printing.precedence import precedence, PRECEDENCE +from sympy.sets.fancysets import Range + +# dictionary mapping SymPy function to (argument_conditions, C_function). +# Used in RCodePrinter._print_Function(self) +known_functions = { + #"Abs": [(lambda x: not x.is_integer, "fabs")], + "Abs": "abs", + "sin": "sin", + "cos": "cos", + "tan": "tan", + "asin": "asin", + "acos": "acos", + "atan": "atan", + "atan2": "atan2", + "exp": "exp", + "log": "log", + "erf": "erf", + "sinh": "sinh", + "cosh": "cosh", + "tanh": "tanh", + "asinh": "asinh", + "acosh": "acosh", + "atanh": "atanh", + "floor": "floor", + "ceiling": "ceiling", + "sign": "sign", + "Max": "max", + "Min": "min", + "factorial": "factorial", + "gamma": "gamma", + "digamma": "digamma", + "trigamma": "trigamma", + "beta": "beta", + "sqrt": "sqrt", # To enable automatic rewrite +} + +# These are the core reserved words in the R language. Taken from: +# https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Reserved-words + +reserved_words = ['if', + 'else', + 'repeat', + 'while', + 'function', + 'for', + 'in', + 'next', + 'break', + 'TRUE', + 'FALSE', + 'NULL', + 'Inf', + 'NaN', + 'NA', + 'NA_integer_', + 'NA_real_', + 'NA_complex_', + 'NA_character_', + 'volatile'] + + +class RCodePrinter(CodePrinter): + """A printer to convert SymPy expressions to strings of R code""" + printmethod = "_rcode" + language = "R" + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'precision': 15, + 'user_functions': {}, + 'human': True, + 'contract': True, + 'dereference': set(), + 'error_on_reserved': False, + 'reserved_word_suffix': '_', + } + _operators = { + 'and': '&', + 'or': '|', + 'not': '!', + } + + _relationals: dict[str, str] = {} + + def __init__(self, settings={}): + CodePrinter.__init__(self, settings) + self.known_functions = dict(known_functions) + userfuncs = settings.get('user_functions', {}) + self.known_functions.update(userfuncs) + self._dereference = set(settings.get('dereference', [])) + self.reserved_words = set(reserved_words) + + def _rate_index_position(self, p): + return p*5 + + def _get_statement(self, codestring): + return "%s;" % codestring + + def _get_comment(self, text): + return "// {}".format(text) + + def _declare_number_const(self, name, value): + return "{} = {};".format(name, value) + + def _format_code(self, lines): + return self.indent_code(lines) + + def _traverse_matrix_indices(self, mat): + rows, cols = mat.shape + return ((i, j) for i in range(rows) for j in range(cols)) + + def _get_loop_opening_ending(self, indices): + """Returns a tuple (open_lines, close_lines) containing lists of codelines + """ + open_lines = [] + close_lines = [] + loopstart = "for (%(var)s in %(start)s:%(end)s){" + for i in indices: + # R arrays start at 1 and end at dimension + open_lines.append(loopstart % { + 'var': self._print(i.label), + 'start': self._print(i.lower+1), + 'end': self._print(i.upper + 1)}) + close_lines.append("}") + return open_lines, close_lines + + def _print_Pow(self, expr): + if "Pow" in self.known_functions: + return self._print_Function(expr) + PREC = precedence(expr) + if equal_valued(expr.exp, -1): + return '1.0/%s' % (self.parenthesize(expr.base, PREC)) + elif equal_valued(expr.exp, 0.5): + return 'sqrt(%s)' % self._print(expr.base) + else: + return '%s^%s' % (self.parenthesize(expr.base, PREC), + self.parenthesize(expr.exp, PREC)) + + + def _print_Rational(self, expr): + p, q = int(expr.p), int(expr.q) + return '%d.0/%d.0' % (p, q) + + def _print_Indexed(self, expr): + inds = [ self._print(i) for i in expr.indices ] + return "%s[%s]" % (self._print(expr.base.label), ", ".join(inds)) + + def _print_Idx(self, expr): + return self._print(expr.label) + + def _print_Exp1(self, expr): + return "exp(1)" + + def _print_Pi(self, expr): + return 'pi' + + def _print_Infinity(self, expr): + return 'Inf' + + def _print_NegativeInfinity(self, expr): + return '-Inf' + + def _print_Assignment(self, expr): + from sympy.codegen.ast import Assignment + + from sympy.matrices.expressions.matexpr import MatrixSymbol + from sympy.tensor.indexed import IndexedBase + lhs = expr.lhs + rhs = expr.rhs + # We special case assignments that take multiple lines + #if isinstance(expr.rhs, Piecewise): + # from sympy.functions.elementary.piecewise import Piecewise + # # Here we modify Piecewise so each expression is now + # # an Assignment, and then continue on the print. + # expressions = [] + # conditions = [] + # for (e, c) in rhs.args: + # expressions.append(Assignment(lhs, e)) + # conditions.append(c) + # temp = Piecewise(*zip(expressions, conditions)) + # return self._print(temp) + #elif isinstance(lhs, MatrixSymbol): + if isinstance(lhs, MatrixSymbol): + # Here we form an Assignment for each element in the array, + # printing each one. + lines = [] + for (i, j) in self._traverse_matrix_indices(lhs): + temp = Assignment(lhs[i, j], rhs[i, j]) + code0 = self._print(temp) + lines.append(code0) + return "\n".join(lines) + elif self._settings["contract"] and (lhs.has(IndexedBase) or + rhs.has(IndexedBase)): + # Here we check if there is looping to be done, and if so + # print the required loops. + return self._doprint_loops(rhs, lhs) + else: + lhs_code = self._print(lhs) + rhs_code = self._print(rhs) + return self._get_statement("%s = %s" % (lhs_code, rhs_code)) + + def _print_Piecewise(self, expr): + # This method is called only for inline if constructs + # Top level piecewise is handled in doprint() + if expr.args[-1].cond == True: + last_line = "%s" % self._print(expr.args[-1].expr) + else: + last_line = "ifelse(%s,%s,NA)" % (self._print(expr.args[-1].cond), self._print(expr.args[-1].expr)) + code=last_line + for e, c in reversed(expr.args[:-1]): + code= "ifelse(%s,%s," % (self._print(c), self._print(e))+code+")" + return(code) + + def _print_ITE(self, expr): + from sympy.functions import Piecewise + return self._print(expr.rewrite(Piecewise)) + + def _print_MatrixElement(self, expr): + return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"], + strict=True), expr.j + expr.i*expr.parent.shape[1]) + + def _print_Symbol(self, expr): + name = super()._print_Symbol(expr) + if expr in self._dereference: + return '(*{})'.format(name) + else: + return name + + def _print_Relational(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + op = expr.rel_op + return "{} {} {}".format(lhs_code, op, rhs_code) + + def _print_AugmentedAssignment(self, expr): + lhs_code = self._print(expr.lhs) + op = expr.op + rhs_code = self._print(expr.rhs) + return "{} {} {};".format(lhs_code, op, rhs_code) + + def _print_For(self, expr): + target = self._print(expr.target) + if isinstance(expr.iterable, Range): + start, stop, step = expr.iterable.args + else: + raise NotImplementedError("Only iterable currently supported is Range") + body = self._print(expr.body) + return 'for({target} in seq(from={start}, to={stop}, by={step}){{\n{body}\n}}'.format(target=target, start=start, + stop=stop-1, step=step, body=body) + + + def indent_code(self, code): + """Accepts a string of code or a list of code lines""" + + if isinstance(code, str): + code_lines = self.indent_code(code.splitlines(True)) + return ''.join(code_lines) + + tab = " " + inc_token = ('{', '(', '{\n', '(\n') + dec_token = ('}', ')') + + code = [ line.lstrip(' \t') for line in code ] + + increase = [ int(any(map(line.endswith, inc_token))) for line in code ] + decrease = [ int(any(map(line.startswith, dec_token))) + for line in code ] + + pretty = [] + level = 0 + for n, line in enumerate(code): + if line in ('', '\n'): + pretty.append(line) + continue + level -= decrease[n] + pretty.append("%s%s" % (tab*level, line)) + level += increase[n] + return pretty + + +def rcode(expr, assign_to=None, **settings): + """Converts an expr to a string of r code + + Parameters + ========== + + expr : Expr + A SymPy expression to be converted. + assign_to : optional + When given, the argument is used as the name of the variable to which + the expression is assigned. Can be a string, ``Symbol``, + ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of + line-wrapping, or for expressions that generate multi-line statements. + precision : integer, optional + The precision for numbers such as pi [default=15]. + user_functions : dict, optional + A dictionary where the keys are string representations of either + ``FunctionClass`` or ``UndefinedFunction`` instances and the values + are their desired R string representations. Alternatively, the + dictionary value can be a list of tuples i.e. [(argument_test, + rfunction_string)] or [(argument_test, rfunction_formater)]. See below + for examples. + human : bool, optional + If True, the result is a single string that may contain some constant + declarations for the number symbols. If False, the same information is + returned in a tuple of (symbols_to_declare, not_supported_functions, + code_text). [default=True]. + contract: bool, optional + If True, ``Indexed`` instances are assumed to obey tensor contraction + rules and the corresponding nested loops over indices are generated. + Setting contract=False will not generate loops, instead the user is + responsible to provide values for the indices in the code. + [default=True]. + + Examples + ======== + + >>> from sympy import rcode, symbols, Rational, sin, ceiling, Abs, Function + >>> x, tau = symbols("x, tau") + >>> rcode((2*tau)**Rational(7, 2)) + '8*sqrt(2)*tau^(7.0/2.0)' + >>> rcode(sin(x), assign_to="s") + 's = sin(x);' + + Simple custom printing can be defined for certain types by passing a + dictionary of {"type" : "function"} to the ``user_functions`` kwarg. + Alternatively, the dictionary value can be a list of tuples i.e. + [(argument_test, cfunction_string)]. + + >>> custom_functions = { + ... "ceiling": "CEIL", + ... "Abs": [(lambda x: not x.is_integer, "fabs"), + ... (lambda x: x.is_integer, "ABS")], + ... "func": "f" + ... } + >>> func = Function('func') + >>> rcode(func(Abs(x) + ceiling(x)), user_functions=custom_functions) + 'f(fabs(x) + CEIL(x))' + + or if the R-function takes a subset of the original arguments: + + >>> rcode(2**x + 3**x, user_functions={'Pow': [ + ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e), + ... (lambda b, e: b != 2, 'pow')]}) + 'exp2(x) + pow(3, x)' + + ``Piecewise`` expressions are converted into conditionals. If an + ``assign_to`` variable is provided an if statement is created, otherwise + the ternary operator is used. Note that if the ``Piecewise`` lacks a + default term, represented by ``(expr, True)`` then an error will be thrown. + This is to prevent generating an expression that may not evaluate to + anything. + + >>> from sympy import Piecewise + >>> expr = Piecewise((x + 1, x > 0), (x, True)) + >>> print(rcode(expr, assign_to=tau)) + tau = ifelse(x > 0,x + 1,x); + + Support for loops is provided through ``Indexed`` types. With + ``contract=True`` these expressions will be turned into loops, whereas + ``contract=False`` will just print the assignment expression that should be + looped over: + + >>> from sympy import Eq, IndexedBase, Idx + >>> len_y = 5 + >>> y = IndexedBase('y', shape=(len_y,)) + >>> t = IndexedBase('t', shape=(len_y,)) + >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) + >>> i = Idx('i', len_y-1) + >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) + >>> rcode(e.rhs, assign_to=e.lhs, contract=False) + 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' + + Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions + must be provided to ``assign_to``. Note that any expression that can be + generated normally can also exist inside a Matrix: + + >>> from sympy import Matrix, MatrixSymbol + >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) + >>> A = MatrixSymbol('A', 3, 1) + >>> print(rcode(mat, A)) + A[0] = x^2; + A[1] = ifelse(x > 0,x + 1,x); + A[2] = sin(x); + + """ + + return RCodePrinter(settings).doprint(expr, assign_to) + + +def print_rcode(expr, **settings): + """Prints R representation of the given expression.""" + print(rcode(expr, **settings)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/repr.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/repr.py new file mode 100644 index 0000000000000000000000000000000000000000..32ce3b75a5820cf4232064a62e18739c02b144fa --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/repr.py @@ -0,0 +1,342 @@ +""" +A Printer for generating executable code. + +The most important function here is srepr that returns a string so that the +relation eval(srepr(expr))=expr holds in an appropriate environment. +""" + +from __future__ import annotations +from typing import Any + +from sympy.core.function import AppliedUndef +from sympy.core.mul import Mul +from mpmath.libmp import repr_dps, to_str as mlib_to_str + +from .printer import Printer, print_function + + +class ReprPrinter(Printer): + printmethod = "_sympyrepr" + + _default_settings: dict[str, Any] = { + "order": None, + "perm_cyclic" : True, + } + + def reprify(self, args, sep): + """ + Prints each item in `args` and joins them with `sep`. + """ + return sep.join([self.doprint(item) for item in args]) + + def emptyPrinter(self, expr): + """ + The fallback printer. + """ + if isinstance(expr, str): + return expr + elif hasattr(expr, "__srepr__"): + return expr.__srepr__() + elif hasattr(expr, "args") and hasattr(expr.args, "__iter__"): + l = [] + for o in expr.args: + l.append(self._print(o)) + return expr.__class__.__name__ + '(%s)' % ', '.join(l) + elif hasattr(expr, "__module__") and hasattr(expr, "__name__"): + return "<'%s.%s'>" % (expr.__module__, expr.__name__) + else: + return str(expr) + + def _print_Add(self, expr, order=None): + args = self._as_ordered_terms(expr, order=order) + args = map(self._print, args) + clsname = type(expr).__name__ + return clsname + "(%s)" % ", ".join(args) + + def _print_Cycle(self, expr): + return expr.__repr__() + + def _print_Permutation(self, expr): + from sympy.combinatorics.permutations import Permutation, Cycle + from sympy.utilities.exceptions import sympy_deprecation_warning + + perm_cyclic = Permutation.print_cyclic + if perm_cyclic is not None: + sympy_deprecation_warning( + f""" + Setting Permutation.print_cyclic is deprecated. Instead use + init_printing(perm_cyclic={perm_cyclic}). + """, + deprecated_since_version="1.6", + active_deprecations_target="deprecated-permutation-print_cyclic", + stacklevel=7, + ) + else: + perm_cyclic = self._settings.get("perm_cyclic", True) + + if perm_cyclic: + if not expr.size: + return 'Permutation()' + # before taking Cycle notation, see if the last element is + # a singleton and move it to the head of the string + s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] + last = s.rfind('(') + if not last == 0 and ',' not in s[last:]: + s = s[last:] + s[:last] + return 'Permutation%s' %s + else: + s = expr.support() + if not s: + if expr.size < 5: + return 'Permutation(%s)' % str(expr.array_form) + return 'Permutation([], size=%s)' % expr.size + trim = str(expr.array_form[:s[-1] + 1]) + ', size=%s' % expr.size + use = full = str(expr.array_form) + if len(trim) < len(full): + use = trim + return 'Permutation(%s)' % use + + def _print_Function(self, expr): + r = self._print(expr.func) + r += '(%s)' % ', '.join([self._print(a) for a in expr.args]) + return r + + def _print_Heaviside(self, expr): + # Same as _print_Function but uses pargs to suppress default value for + # 2nd arg. + r = self._print(expr.func) + r += '(%s)' % ', '.join([self._print(a) for a in expr.pargs]) + return r + + def _print_FunctionClass(self, expr): + if issubclass(expr, AppliedUndef): + return 'Function(%r)' % (expr.__name__) + else: + return expr.__name__ + + def _print_Half(self, expr): + return 'Rational(1, 2)' + + def _print_RationalConstant(self, expr): + return str(expr) + + def _print_AtomicExpr(self, expr): + return str(expr) + + def _print_NumberSymbol(self, expr): + return str(expr) + + def _print_Integer(self, expr): + return 'Integer(%i)' % expr.p + + def _print_Complexes(self, expr): + return 'Complexes' + + def _print_Integers(self, expr): + return 'Integers' + + def _print_Naturals(self, expr): + return 'Naturals' + + def _print_Naturals0(self, expr): + return 'Naturals0' + + def _print_Rationals(self, expr): + return 'Rationals' + + def _print_Reals(self, expr): + return 'Reals' + + def _print_EmptySet(self, expr): + return 'EmptySet' + + def _print_UniversalSet(self, expr): + return 'UniversalSet' + + def _print_EmptySequence(self, expr): + return 'EmptySequence' + + def _print_list(self, expr): + return "[%s]" % self.reprify(expr, ", ") + + def _print_dict(self, expr): + sep = ", " + dict_kvs = ["%s: %s" % (self.doprint(key), self.doprint(value)) for key, value in expr.items()] + return "{%s}" % sep.join(dict_kvs) + + def _print_set(self, expr): + if not expr: + return "set()" + return "{%s}" % self.reprify(expr, ", ") + + def _print_MatrixBase(self, expr): + # special case for some empty matrices + if (expr.rows == 0) ^ (expr.cols == 0): + return '%s(%s, %s, %s)' % (expr.__class__.__name__, + self._print(expr.rows), + self._print(expr.cols), + self._print([])) + l = [] + for i in range(expr.rows): + l.append([]) + for j in range(expr.cols): + l[-1].append(expr[i, j]) + return '%s(%s)' % (expr.__class__.__name__, self._print(l)) + + def _print_BooleanTrue(self, expr): + return "true" + + def _print_BooleanFalse(self, expr): + return "false" + + def _print_NaN(self, expr): + return "nan" + + def _print_Mul(self, expr, order=None): + if self.order not in ('old', 'none'): + args = expr.as_ordered_factors() + else: + # use make_args in case expr was something like -x -> x + args = Mul.make_args(expr) + + args = map(self._print, args) + clsname = type(expr).__name__ + return clsname + "(%s)" % ", ".join(args) + + def _print_Rational(self, expr): + return 'Rational(%s, %s)' % (self._print(expr.p), self._print(expr.q)) + + def _print_PythonRational(self, expr): + return "%s(%d, %d)" % (expr.__class__.__name__, expr.p, expr.q) + + def _print_Fraction(self, expr): + return 'Fraction(%s, %s)' % (self._print(expr.numerator), self._print(expr.denominator)) + + def _print_Float(self, expr): + r = mlib_to_str(expr._mpf_, repr_dps(expr._prec)) + return "%s('%s', precision=%i)" % (expr.__class__.__name__, r, expr._prec) + + def _print_Sum2(self, expr): + return "Sum2(%s, (%s, %s, %s))" % (self._print(expr.f), self._print(expr.i), + self._print(expr.a), self._print(expr.b)) + + def _print_Str(self, s): + return "%s(%s)" % (s.__class__.__name__, self._print(s.name)) + + def _print_Symbol(self, expr): + d = expr._assumptions_orig + # print the dummy_index like it was an assumption + if expr.is_Dummy: + d['dummy_index'] = expr.dummy_index + + if d == {}: + return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name)) + else: + attr = ['%s=%s' % (k, v) for k, v in d.items()] + return "%s(%s, %s)" % (expr.__class__.__name__, + self._print(expr.name), ', '.join(attr)) + + def _print_CoordinateSymbol(self, expr): + d = expr._assumptions.generator + + if d == {}: + return "%s(%s, %s)" % ( + expr.__class__.__name__, + self._print(expr.coord_sys), + self._print(expr.index) + ) + else: + attr = ['%s=%s' % (k, v) for k, v in d.items()] + return "%s(%s, %s, %s)" % ( + expr.__class__.__name__, + self._print(expr.coord_sys), + self._print(expr.index), + ', '.join(attr) + ) + + def _print_Predicate(self, expr): + return "Q.%s" % expr.name + + def _print_AppliedPredicate(self, expr): + # will be changed to just expr.args when args overriding is removed + args = expr._args + return "%s(%s)" % (expr.__class__.__name__, self.reprify(args, ", ")) + + def _print_str(self, expr): + return repr(expr) + + def _print_tuple(self, expr): + if len(expr) == 1: + return "(%s,)" % self._print(expr[0]) + else: + return "(%s)" % self.reprify(expr, ", ") + + def _print_WildFunction(self, expr): + return "%s('%s')" % (expr.__class__.__name__, expr.name) + + def _print_AlgebraicNumber(self, expr): + return "%s(%s, %s)" % (expr.__class__.__name__, + self._print(expr.root), self._print(expr.coeffs())) + + def _print_PolyRing(self, ring): + return "%s(%s, %s, %s)" % (ring.__class__.__name__, + self._print(ring.symbols), self._print(ring.domain), self._print(ring.order)) + + def _print_FracField(self, field): + return "%s(%s, %s, %s)" % (field.__class__.__name__, + self._print(field.symbols), self._print(field.domain), self._print(field.order)) + + def _print_PolyElement(self, poly): + terms = list(poly.terms()) + terms.sort(key=poly.ring.order, reverse=True) + return "%s(%s, %s)" % (poly.__class__.__name__, self._print(poly.ring), self._print(terms)) + + def _print_FracElement(self, frac): + numer_terms = list(frac.numer.terms()) + numer_terms.sort(key=frac.field.order, reverse=True) + denom_terms = list(frac.denom.terms()) + denom_terms.sort(key=frac.field.order, reverse=True) + numer = self._print(numer_terms) + denom = self._print(denom_terms) + return "%s(%s, %s, %s)" % (frac.__class__.__name__, self._print(frac.field), numer, denom) + + def _print_FractionField(self, domain): + cls = domain.__class__.__name__ + field = self._print(domain.field) + return "%s(%s)" % (cls, field) + + def _print_PolynomialRingBase(self, ring): + cls = ring.__class__.__name__ + dom = self._print(ring.domain) + gens = ', '.join(map(self._print, ring.gens)) + order = str(ring.order) + if order != ring.default_order: + orderstr = ", order=" + order + else: + orderstr = "" + return "%s(%s, %s%s)" % (cls, dom, gens, orderstr) + + def _print_DMP(self, p): + cls = p.__class__.__name__ + rep = self._print(p.rep) + dom = self._print(p.dom) + if p.ring is not None: + ringstr = ", ring=" + self._print(p.ring) + else: + ringstr = "" + return "%s(%s, %s%s)" % (cls, rep, dom, ringstr) + + def _print_MonogenicFiniteExtension(self, ext): + # The expanded tree shown by srepr(ext.modulus) + # is not practical. + return "FiniteExtension(%s)" % str(ext.modulus) + + def _print_ExtensionElement(self, f): + rep = self._print(f.rep) + ext = self._print(f.ext) + return "ExtElem(%s, %s)" % (rep, ext) + +@print_function(ReprPrinter) +def srepr(expr, **settings): + """return expr in repr form""" + return ReprPrinter(settings).doprint(expr) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/rust.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/rust.py new file mode 100644 index 0000000000000000000000000000000000000000..04c6b6399ec84fca233ded96c53c997844f8143b --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/rust.py @@ -0,0 +1,625 @@ +""" +Rust code printer + +The `RustCodePrinter` converts SymPy expressions into Rust expressions. + +A complete code generator, which uses `rust_code` extensively, can be found +in `sympy.utilities.codegen`. The `codegen` module can be used to generate +complete source code files. + +""" + +# Possible Improvement +# +# * make sure we follow Rust Style Guidelines_ +# * make use of pattern matching +# * better support for reference +# * generate generic code and use trait to make sure they have specific methods +# * use crates_ to get more math support +# - num_ +# + BigInt_, BigUint_ +# + Complex_ +# + Rational64_, Rational32_, BigRational_ +# +# .. _crates: https://crates.io/ +# .. _Guidelines: https://github.com/rust-lang/rust/tree/master/src/doc/style +# .. _num: http://rust-num.github.io/num/num/ +# .. _BigInt: http://rust-num.github.io/num/num/bigint/struct.BigInt.html +# .. _BigUint: http://rust-num.github.io/num/num/bigint/struct.BigUint.html +# .. _Complex: http://rust-num.github.io/num/num/complex/struct.Complex.html +# .. _Rational32: http://rust-num.github.io/num/num/rational/type.Rational32.html +# .. _Rational64: http://rust-num.github.io/num/num/rational/type.Rational64.html +# .. _BigRational: http://rust-num.github.io/num/num/rational/type.BigRational.html + +from __future__ import annotations +from typing import Any + +from sympy.core import S, Rational, Float, Lambda +from sympy.core.numbers import equal_valued +from sympy.printing.codeprinter import CodePrinter + +# Rust's methods for integer and float can be found at here : +# +# * `Rust - Primitive Type f64 `_ +# * `Rust - Primitive Type i64 `_ +# +# Function Style : +# +# 1. args[0].func(args[1:]), method with arguments +# 2. args[0].func(), method without arguments +# 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp()) +# 4. func(args), function with arguments + +# dictionary mapping SymPy function to (argument_conditions, Rust_function). +# Used in RustCodePrinter._print_Function(self) + +# f64 method in Rust +known_functions = { + # "": "is_nan", + # "": "is_infinite", + # "": "is_finite", + # "": "is_normal", + # "": "classify", + "floor": "floor", + "ceiling": "ceil", + # "": "round", + # "": "trunc", + # "": "fract", + "Abs": "abs", + "sign": "signum", + # "": "is_sign_positive", + # "": "is_sign_negative", + # "": "mul_add", + "Pow": [(lambda base, exp: equal_valued(exp, -1), "recip", 2), # 1.0/x + (lambda base, exp: equal_valued(exp, 0.5), "sqrt", 2), # x ** 0.5 + (lambda base, exp: equal_valued(exp, -0.5), "sqrt().recip", 2), # 1/(x ** 0.5) + (lambda base, exp: exp == Rational(1, 3), "cbrt", 2), # x ** (1/3) + (lambda base, exp: equal_valued(base, 2), "exp2", 3), # 2 ** x + (lambda base, exp: exp.is_integer, "powi", 1), # x ** y, for i32 + (lambda base, exp: not exp.is_integer, "powf", 1)], # x ** y, for f64 + "exp": [(lambda exp: True, "exp", 2)], # e ** x + "log": "ln", + # "": "log", # number.log(base) + # "": "log2", + # "": "log10", + # "": "to_degrees", + # "": "to_radians", + "Max": "max", + "Min": "min", + # "": "hypot", # (x**2 + y**2) ** 0.5 + "sin": "sin", + "cos": "cos", + "tan": "tan", + "asin": "asin", + "acos": "acos", + "atan": "atan", + "atan2": "atan2", + # "": "sin_cos", + # "": "exp_m1", # e ** x - 1 + # "": "ln_1p", # ln(1 + x) + "sinh": "sinh", + "cosh": "cosh", + "tanh": "tanh", + "asinh": "asinh", + "acosh": "acosh", + "atanh": "atanh", + "sqrt": "sqrt", # To enable automatic rewrites +} + +# i64 method in Rust +# known_functions_i64 = { +# "": "min_value", +# "": "max_value", +# "": "from_str_radix", +# "": "count_ones", +# "": "count_zeros", +# "": "leading_zeros", +# "": "trainling_zeros", +# "": "rotate_left", +# "": "rotate_right", +# "": "swap_bytes", +# "": "from_be", +# "": "from_le", +# "": "to_be", # to big endian +# "": "to_le", # to little endian +# "": "checked_add", +# "": "checked_sub", +# "": "checked_mul", +# "": "checked_div", +# "": "checked_rem", +# "": "checked_neg", +# "": "checked_shl", +# "": "checked_shr", +# "": "checked_abs", +# "": "saturating_add", +# "": "saturating_sub", +# "": "saturating_mul", +# "": "wrapping_add", +# "": "wrapping_sub", +# "": "wrapping_mul", +# "": "wrapping_div", +# "": "wrapping_rem", +# "": "wrapping_neg", +# "": "wrapping_shl", +# "": "wrapping_shr", +# "": "wrapping_abs", +# "": "overflowing_add", +# "": "overflowing_sub", +# "": "overflowing_mul", +# "": "overflowing_div", +# "": "overflowing_rem", +# "": "overflowing_neg", +# "": "overflowing_shl", +# "": "overflowing_shr", +# "": "overflowing_abs", +# "Pow": "pow", +# "Abs": "abs", +# "sign": "signum", +# "": "is_positive", +# "": "is_negnative", +# } + +# These are the core reserved words in the Rust language. Taken from: +# http://doc.rust-lang.org/grammar.html#keywords + +reserved_words = ['abstract', + 'alignof', + 'as', + 'become', + 'box', + 'break', + 'const', + 'continue', + 'crate', + 'do', + 'else', + 'enum', + 'extern', + 'false', + 'final', + 'fn', + 'for', + 'if', + 'impl', + 'in', + 'let', + 'loop', + 'macro', + 'match', + 'mod', + 'move', + 'mut', + 'offsetof', + 'override', + 'priv', + 'proc', + 'pub', + 'pure', + 'ref', + 'return', + 'Self', + 'self', + 'sizeof', + 'static', + 'struct', + 'super', + 'trait', + 'true', + 'type', + 'typeof', + 'unsafe', + 'unsized', + 'use', + 'virtual', + 'where', + 'while', + 'yield'] + + +class RustCodePrinter(CodePrinter): + """A printer to convert SymPy expressions to strings of Rust code""" + printmethod = "_rust_code" + language = "Rust" + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'precision': 17, + 'user_functions': {}, + 'human': True, + 'contract': True, + 'dereference': set(), + 'error_on_reserved': False, + 'reserved_word_suffix': '_', + 'inline': False, + } + + def __init__(self, settings={}): + CodePrinter.__init__(self, settings) + self.known_functions = dict(known_functions) + userfuncs = settings.get('user_functions', {}) + self.known_functions.update(userfuncs) + self._dereference = set(settings.get('dereference', [])) + self.reserved_words = set(reserved_words) + + def _rate_index_position(self, p): + return p*5 + + def _get_statement(self, codestring): + return "%s;" % codestring + + def _get_comment(self, text): + return "// %s" % text + + def _declare_number_const(self, name, value): + return "const %s: f64 = %s;" % (name, value) + + def _format_code(self, lines): + return self.indent_code(lines) + + def _traverse_matrix_indices(self, mat): + rows, cols = mat.shape + return ((i, j) for i in range(rows) for j in range(cols)) + + def _get_loop_opening_ending(self, indices): + open_lines = [] + close_lines = [] + loopstart = "for %(var)s in %(start)s..%(end)s {" + for i in indices: + # Rust arrays start at 0 and end at dimension-1 + open_lines.append(loopstart % { + 'var': self._print(i), + 'start': self._print(i.lower), + 'end': self._print(i.upper + 1)}) + close_lines.append("}") + return open_lines, close_lines + + def _print_caller_var(self, expr): + if len(expr.args) > 1: + # for something like `sin(x + y + z)`, + # make sure we can get '(x + y + z).sin()' + # instead of 'x + y + z.sin()' + return '(' + self._print(expr) + ')' + elif expr.is_number: + return self._print(expr, _type=True) + else: + return self._print(expr) + + def _print_Function(self, expr): + """ + basic function for printing `Function` + + Function Style : + + 1. args[0].func(args[1:]), method with arguments + 2. args[0].func(), method without arguments + 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp()) + 4. func(args), function with arguments + """ + + if expr.func.__name__ in self.known_functions: + cond_func = self.known_functions[expr.func.__name__] + func = None + style = 1 + if isinstance(cond_func, str): + func = cond_func + else: + for cond, func, style in cond_func: + if cond(*expr.args): + break + if func is not None: + if style == 1: + ret = "%(var)s.%(method)s(%(args)s)" % { + 'var': self._print_caller_var(expr.args[0]), + 'method': func, + 'args': self.stringify(expr.args[1:], ", ") if len(expr.args) > 1 else '' + } + elif style == 2: + ret = "%(var)s.%(method)s()" % { + 'var': self._print_caller_var(expr.args[0]), + 'method': func, + } + elif style == 3: + ret = "%(var)s.%(method)s()" % { + 'var': self._print_caller_var(expr.args[1]), + 'method': func, + } + else: + ret = "%(func)s(%(args)s)" % { + 'func': func, + 'args': self.stringify(expr.args, ", "), + } + return ret + elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda): + # inlined function + return self._print(expr._imp_(*expr.args)) + elif expr.func.__name__ in self._rewriteable_functions: + # Simple rewrite to supported function possible + target_f, required_fs = self._rewriteable_functions[expr.func.__name__] + if self._can_print(target_f) and all(self._can_print(f) for f in required_fs): + return self._print(expr.rewrite(target_f)) + else: + return self._print_not_supported(expr) + + def _print_Pow(self, expr): + if expr.base.is_integer and not expr.exp.is_integer: + expr = type(expr)(Float(expr.base), expr.exp) + return self._print(expr) + return self._print_Function(expr) + + def _print_Float(self, expr, _type=False): + ret = super()._print_Float(expr) + if _type: + return ret + '_f64' + else: + return ret + + def _print_Integer(self, expr, _type=False): + ret = super()._print_Integer(expr) + if _type: + return ret + '_i32' + else: + return ret + + def _print_Rational(self, expr): + p, q = int(expr.p), int(expr.q) + return '%d_f64/%d.0' % (p, q) + + def _print_Relational(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + op = expr.rel_op + return "{} {} {}".format(lhs_code, op, rhs_code) + + def _print_Indexed(self, expr): + # calculate index for 1d array + dims = expr.shape + elem = S.Zero + offset = S.One + for i in reversed(range(expr.rank)): + elem += expr.indices[i]*offset + offset *= dims[i] + return "%s[%s]" % (self._print(expr.base.label), self._print(elem)) + + def _print_Idx(self, expr): + return expr.label.name + + def _print_Dummy(self, expr): + return expr.name + + def _print_Exp1(self, expr, _type=False): + return "E" + + def _print_Pi(self, expr, _type=False): + return 'PI' + + def _print_Infinity(self, expr, _type=False): + return 'INFINITY' + + def _print_NegativeInfinity(self, expr, _type=False): + return 'NEG_INFINITY' + + def _print_BooleanTrue(self, expr, _type=False): + return "true" + + def _print_BooleanFalse(self, expr, _type=False): + return "false" + + def _print_bool(self, expr, _type=False): + return str(expr).lower() + + def _print_NaN(self, expr, _type=False): + return "NAN" + + def _print_Piecewise(self, expr): + if expr.args[-1].cond != True: + # We need the last conditional to be a True, otherwise the resulting + # function may not return a result. + raise ValueError("All Piecewise expressions must contain an " + "(expr, True) statement to be used as a default " + "condition. Without one, the generated " + "expression may not evaluate to anything under " + "some condition.") + lines = [] + + for i, (e, c) in enumerate(expr.args): + if i == 0: + lines.append("if (%s) {" % self._print(c)) + elif i == len(expr.args) - 1 and c == True: + lines[-1] += " else {" + else: + lines[-1] += " else if (%s) {" % self._print(c) + code0 = self._print(e) + lines.append(code0) + lines.append("}") + + if self._settings['inline']: + return " ".join(lines) + else: + return "\n".join(lines) + + def _print_ITE(self, expr): + from sympy.functions import Piecewise + return self._print(expr.rewrite(Piecewise, deep=False)) + + def _print_MatrixBase(self, A): + if A.cols == 1: + return "[%s]" % ", ".join(self._print(a) for a in A) + else: + raise ValueError("Full Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).") + + def _print_SparseRepMatrix(self, mat): + # do not allow sparse matrices to be made dense + return self._print_not_supported(mat) + + def _print_MatrixElement(self, expr): + return "%s[%s]" % (expr.parent, + expr.j + expr.i*expr.parent.shape[1]) + + def _print_Symbol(self, expr): + + name = super()._print_Symbol(expr) + + if expr in self._dereference: + return '(*%s)' % name + else: + return name + + def _print_Assignment(self, expr): + from sympy.tensor.indexed import IndexedBase + lhs = expr.lhs + rhs = expr.rhs + if self._settings["contract"] and (lhs.has(IndexedBase) or + rhs.has(IndexedBase)): + # Here we check if there is looping to be done, and if so + # print the required loops. + return self._doprint_loops(rhs, lhs) + else: + lhs_code = self._print(lhs) + rhs_code = self._print(rhs) + return self._get_statement("%s = %s" % (lhs_code, rhs_code)) + + def indent_code(self, code): + """Accepts a string of code or a list of code lines""" + + if isinstance(code, str): + code_lines = self.indent_code(code.splitlines(True)) + return ''.join(code_lines) + + tab = " " + inc_token = ('{', '(', '{\n', '(\n') + dec_token = ('}', ')') + + code = [ line.lstrip(' \t') for line in code ] + + increase = [ int(any(map(line.endswith, inc_token))) for line in code ] + decrease = [ int(any(map(line.startswith, dec_token))) + for line in code ] + + pretty = [] + level = 0 + for n, line in enumerate(code): + if line in ('', '\n'): + pretty.append(line) + continue + level -= decrease[n] + pretty.append("%s%s" % (tab*level, line)) + level += increase[n] + return pretty + + +def rust_code(expr, assign_to=None, **settings): + """Converts an expr to a string of Rust code + + Parameters + ========== + + expr : Expr + A SymPy expression to be converted. + assign_to : optional + When given, the argument is used as the name of the variable to which + the expression is assigned. Can be a string, ``Symbol``, + ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of + line-wrapping, or for expressions that generate multi-line statements. + precision : integer, optional + The precision for numbers such as pi [default=15]. + user_functions : dict, optional + A dictionary where the keys are string representations of either + ``FunctionClass`` or ``UndefinedFunction`` instances and the values + are their desired C string representations. Alternatively, the + dictionary value can be a list of tuples i.e. [(argument_test, + cfunction_string)]. See below for examples. + dereference : iterable, optional + An iterable of symbols that should be dereferenced in the printed code + expression. These would be values passed by address to the function. + For example, if ``dereference=[a]``, the resulting code would print + ``(*a)`` instead of ``a``. + human : bool, optional + If True, the result is a single string that may contain some constant + declarations for the number symbols. If False, the same information is + returned in a tuple of (symbols_to_declare, not_supported_functions, + code_text). [default=True]. + contract: bool, optional + If True, ``Indexed`` instances are assumed to obey tensor contraction + rules and the corresponding nested loops over indices are generated. + Setting contract=False will not generate loops, instead the user is + responsible to provide values for the indices in the code. + [default=True]. + + Examples + ======== + + >>> from sympy import rust_code, symbols, Rational, sin, ceiling, Abs, Function + >>> x, tau = symbols("x, tau") + >>> rust_code((2*tau)**Rational(7, 2)) + '8*1.4142135623731*tau.powf(7_f64/2.0)' + >>> rust_code(sin(x), assign_to="s") + 's = x.sin();' + + Simple custom printing can be defined for certain types by passing a + dictionary of {"type" : "function"} to the ``user_functions`` kwarg. + Alternatively, the dictionary value can be a list of tuples i.e. + [(argument_test, cfunction_string)]. + + >>> custom_functions = { + ... "ceiling": "CEIL", + ... "Abs": [(lambda x: not x.is_integer, "fabs", 4), + ... (lambda x: x.is_integer, "ABS", 4)], + ... "func": "f" + ... } + >>> func = Function('func') + >>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions) + '(fabs(x) + x.CEIL()).f()' + + ``Piecewise`` expressions are converted into conditionals. If an + ``assign_to`` variable is provided an if statement is created, otherwise + the ternary operator is used. Note that if the ``Piecewise`` lacks a + default term, represented by ``(expr, True)`` then an error will be thrown. + This is to prevent generating an expression that may not evaluate to + anything. + + >>> from sympy import Piecewise + >>> expr = Piecewise((x + 1, x > 0), (x, True)) + >>> print(rust_code(expr, tau)) + tau = if (x > 0) { + x + 1 + } else { + x + }; + + Support for loops is provided through ``Indexed`` types. With + ``contract=True`` these expressions will be turned into loops, whereas + ``contract=False`` will just print the assignment expression that should be + looped over: + + >>> from sympy import Eq, IndexedBase, Idx + >>> len_y = 5 + >>> y = IndexedBase('y', shape=(len_y,)) + >>> t = IndexedBase('t', shape=(len_y,)) + >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) + >>> i = Idx('i', len_y-1) + >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) + >>> rust_code(e.rhs, assign_to=e.lhs, contract=False) + 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' + + Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions + must be provided to ``assign_to``. Note that any expression that can be + generated normally can also exist inside a Matrix: + + >>> from sympy import Matrix, MatrixSymbol + >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) + >>> A = MatrixSymbol('A', 3, 1) + >>> print(rust_code(mat, A)) + A = [x.powi(2), if (x > 0) { + x + 1 + } else { + x + }, x.sin()]; + """ + + return RustCodePrinter(settings).doprint(expr, assign_to) + + +def print_rust_code(expr, **settings): + """Prints Rust representation of the given expression.""" + print(rust_code(expr, **settings)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/smtlib.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/smtlib.py new file mode 100644 index 0000000000000000000000000000000000000000..ef268edc71ec9ff7c809717aff87d2295daa88ca --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/smtlib.py @@ -0,0 +1,526 @@ +import typing + +import sympy +from sympy.core import Add, Mul +from sympy.core import Symbol, Expr, Float, Rational, Integer, Basic +from sympy.core.function import UndefinedFunction, Function +from sympy.core.relational import Relational, Unequality, Equality, LessThan, GreaterThan, StrictLessThan, StrictGreaterThan +from sympy.functions.elementary.complexes import Abs +from sympy.functions.elementary.exponential import exp, log, Pow +from sympy.functions.elementary.hyperbolic import sinh, cosh, tanh +from sympy.functions.elementary.miscellaneous import Min, Max +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import sin, cos, tan, asin, acos, atan, atan2 +from sympy.logic.boolalg import And, Or, Xor, Implies, Boolean +from sympy.logic.boolalg import BooleanTrue, BooleanFalse, BooleanFunction, Not, ITE +from sympy.printing.printer import Printer +from sympy.sets import Interval + + +class SMTLibPrinter(Printer): + printmethod = "_smtlib" + + # based on dReal, an automated reasoning tool for solving problems that can be encoded as first-order logic formulas over the real numbers. + # dReal's special strength is in handling problems that involve a wide range of nonlinear real functions. + _default_settings: dict = { + 'precision': None, + 'known_types': { + bool: 'Bool', + int: 'Int', + float: 'Real' + }, + 'known_constants': { + # pi: 'MY_VARIABLE_PI_DECLARED_ELSEWHERE', + }, + 'known_functions': { + Add: '+', + Mul: '*', + + Equality: '=', + LessThan: '<=', + GreaterThan: '>=', + StrictLessThan: '<', + StrictGreaterThan: '>', + + exp: 'exp', + log: 'log', + Abs: 'abs', + sin: 'sin', + cos: 'cos', + tan: 'tan', + asin: 'arcsin', + acos: 'arccos', + atan: 'arctan', + atan2: 'arctan2', + sinh: 'sinh', + cosh: 'cosh', + tanh: 'tanh', + Min: 'min', + Max: 'max', + Pow: 'pow', + + And: 'and', + Or: 'or', + Xor: 'xor', + Not: 'not', + ITE: 'ite', + Implies: '=>', + } + } + + symbol_table: dict + + def __init__(self, settings: typing.Optional[dict] = None, + symbol_table=None): + settings = settings or {} + self.symbol_table = symbol_table or {} + Printer.__init__(self, settings) + self._precision = self._settings['precision'] + self._known_types = dict(self._settings['known_types']) + self._known_constants = dict(self._settings['known_constants']) + self._known_functions = dict(self._settings['known_functions']) + + for _ in self._known_types.values(): assert self._is_legal_name(_) + for _ in self._known_constants.values(): assert self._is_legal_name(_) + # for _ in self._known_functions.values(): assert self._is_legal_name(_) # +, *, <, >, etc. + + def _is_legal_name(self, s: str): + if not s: return False + if s[0].isnumeric(): return False + return all(_.isalnum() or _ == '_' for _ in s) + + def _s_expr(self, op: str, args: typing.Union[list, tuple]) -> str: + args_str = ' '.join( + a if isinstance(a, str) + else self._print(a) + for a in args + ) + return f'({op} {args_str})' + + def _print_Function(self, e): + if e in self._known_functions: + op = self._known_functions[e] + elif type(e) in self._known_functions: + op = self._known_functions[type(e)] + elif type(type(e)) == UndefinedFunction: + op = e.name + else: + op = self._known_functions[e] # throw KeyError + + return self._s_expr(op, e.args) + + def _print_Relational(self, e: Relational): + return self._print_Function(e) + + def _print_BooleanFunction(self, e: BooleanFunction): + return self._print_Function(e) + + def _print_Expr(self, e: Expr): + return self._print_Function(e) + + def _print_Unequality(self, e: Unequality): + if type(e) in self._known_functions: + return self._print_Relational(e) # default + else: + eq_op = self._known_functions[Equality] + not_op = self._known_functions[Not] + return self._s_expr(not_op, [self._s_expr(eq_op, e.args)]) + + def _print_Piecewise(self, e: Piecewise): + def _print_Piecewise_recursive(args: typing.Union[list, tuple]): + e, c = args[0] + if len(args) == 1: + assert (c is True) or isinstance(c, BooleanTrue) + return self._print(e) + else: + ite = self._known_functions[ITE] + return self._s_expr(ite, [ + c, e, _print_Piecewise_recursive(args[1:]) + ]) + + return _print_Piecewise_recursive(e.args) + + def _print_Interval(self, e: Interval): + if e.start.is_infinite and e.end.is_infinite: + return '' + elif e.start.is_infinite != e.end.is_infinite: + raise ValueError(f'One-sided intervals (`{e}`) are not supported in SMT.') + else: + return f'[{e.start}, {e.end}]' + + # todo: Sympy does not support quantifiers yet as of 2022, but quantifiers can be handy in SMT. + # For now, users can extend this class and build in their own quantifier support. + # See `test_quantifier_extensions()` in test_smtlib.py for an example of how this might look. + + # def _print_ForAll(self, e: ForAll): + # return self._s('forall', [ + # self._s('', [ + # self._s(sym.name, [self._type_name(sym), Interval(start, end)]) + # for sym, start, end in e.limits + # ]), + # e.function + # ]) + + def _print_BooleanTrue(self, x: BooleanTrue): + return 'true' + + def _print_BooleanFalse(self, x: BooleanFalse): + return 'false' + + def _print_Float(self, x: Float): + f = x.evalf(self._precision) if self._precision else x.evalf() + return str(f).rstrip('0') + + def _print_float(self, x: float): + return str(x) + + def _print_Rational(self, x: Rational): + return self._s_expr('/', [x.p, x.q]) + + def _print_Integer(self, x: Integer): + assert x.q == 1 + return str(x.p) + + def _print_int(self, x: int): + return str(x) + + def _print_Symbol(self, x: Symbol): + assert self._is_legal_name(x.name) + return x.name + + def _print_NumberSymbol(self, x): + name = self._known_constants.get(x) + return name if name else self._print_Float(x) + + def _print_UndefinedFunction(self, x): + assert self._is_legal_name(x.name) + return x.name + + def _print_Exp1(self, x): + return ( + self._print_Function(exp(1, evaluate=False)) + if exp in self._known_functions else + self._print_NumberSymbol(x) + ) + + def emptyPrinter(self, expr): + raise NotImplementedError(f'Cannot convert `{repr(expr)}` of type `{type(expr)}` to SMT.') + + +def smtlib_code( + expr, + auto_assert=True, auto_declare=True, + precision=None, + symbol_table=None, + known_types=None, known_constants=None, known_functions=None, + prefix_expressions=None, suffix_expressions=None, + log_warn=None +): + r"""Converts ``expr`` to a string of smtlib code. + + Parameters + ========== + + expr : Expr | List[Expr] + A SymPy expression or system to be converted. + auto_assert : bool, optional + If false, do not modify expr and produce only the S-Expression equivalent of expr. + If true, assume expr is a system and assert each boolean element. + auto_declare : bool, optional + If false, do not produce declarations for the symbols used in expr. + If true, prepend all necessary declarations for variables used in expr based on symbol_table. + precision : integer, optional + The ``evalf(..)`` precision for numbers such as pi. + symbol_table : dict, optional + A dictionary where keys are ``Symbol`` or ``Function`` instances and values are their Python type i.e. ``bool``, ``int``, ``float``, or ``Callable[...]``. + If incomplete, an attempt will be made to infer types from ``expr``. + known_types: dict, optional + A dictionary where keys are ``bool``, ``int``, ``float`` etc. and values are their corresponding SMT type names. + If not given, a partial listing compatible with several solvers will be used. + known_functions : dict, optional + A dictionary where keys are ``Function``, ``Relational``, ``BooleanFunction``, or ``Expr`` instances and values are their SMT string representations. + If not given, a partial listing optimized for dReal solver (but compatible with others) will be used. + known_constants: dict, optional + A dictionary where keys are ``NumberSymbol`` instances and values are their SMT variable names. + When using this feature, extra caution must be taken to avoid naming collisions between user symbols and listed constants. + If not given, constants will be expanded inline i.e. ``3.14159`` instead of ``MY_SMT_VARIABLE_FOR_PI``. + prefix_expressions: list, optional + A list of lists of ``str`` and/or expressions to convert into SMTLib and prefix to the output. + suffix_expressions: list, optional + A list of lists of ``str`` and/or expressions to convert into SMTLib and postfix to the output. + log_warn: lambda function, optional + A function to record all warnings during potentially risky operations. + Soundness is a core value in SMT solving, so it is good to log all assumptions made. + + Examples + ======== + >>> from sympy import smtlib_code, symbols, sin, Eq + >>> x = symbols('x') + >>> smtlib_code(sin(x).series(x).removeO(), log_warn=print) + Could not infer type of `x`. Defaulting to float. + Non-Boolean expression `x**5/120 - x**3/6 + x` will not be asserted. Converting to SMTLib verbatim. + '(declare-const x Real)\n(+ x (* (/ -1 6) (pow x 3)) (* (/ 1 120) (pow x 5)))' + + >>> from sympy import Rational + >>> x, y, tau = symbols("x, y, tau") + >>> smtlib_code((2*tau)**Rational(7, 2), log_warn=print) + Could not infer type of `tau`. Defaulting to float. + Non-Boolean expression `8*sqrt(2)*tau**(7/2)` will not be asserted. Converting to SMTLib verbatim. + '(declare-const tau Real)\n(* 8 (pow 2 (/ 1 2)) (pow tau (/ 7 2)))' + + ``Piecewise`` expressions are implemented with ``ite`` expressions by default. + Note that if the ``Piecewise`` lacks a default term, represented by + ``(expr, True)`` then an error will be thrown. This is to prevent + generating an expression that may not evaluate to anything. + + >>> from sympy import Piecewise + >>> pw = Piecewise((x + 1, x > 0), (x, True)) + >>> smtlib_code(Eq(pw, 3), symbol_table={x: float}, log_warn=print) + '(declare-const x Real)\n(assert (= (ite (> x 0) (+ 1 x) x) 3))' + + Custom printing can be defined for certain types by passing a dictionary of + PythonType : "SMT Name" to the ``known_types``, ``known_constants``, and ``known_functions`` kwargs. + + >>> from typing import Callable + >>> from sympy import Function, Add + >>> f = Function('f') + >>> g = Function('g') + >>> smt_builtin_funcs = { # functions our SMT solver will understand + ... f: "existing_smtlib_fcn", + ... Add: "sum", + ... } + >>> user_def_funcs = { # functions defined by the user must have their types specified explicitly + ... g: Callable[[int], float], + ... } + >>> smtlib_code(f(x) + g(x), symbol_table=user_def_funcs, known_functions=smt_builtin_funcs, log_warn=print) + Non-Boolean expression `f(x) + g(x)` will not be asserted. Converting to SMTLib verbatim. + '(declare-const x Int)\n(declare-fun g (Int) Real)\n(sum (existing_smtlib_fcn x) (g x))' + """ + log_warn = log_warn or (lambda _: None) + + if not isinstance(expr, list): expr = [expr] + expr = [ + sympy.sympify(_, strict=True, evaluate=False, convert_xor=False) + for _ in expr + ] + + if not symbol_table: symbol_table = {} + symbol_table = _auto_infer_smtlib_types( + *expr, symbol_table=symbol_table + ) + # See [FALLBACK RULES] + # Need SMTLibPrinter to populate known_functions and known_constants first. + + settings = {} + if precision: settings['precision'] = precision + del precision + + if known_types: settings['known_types'] = known_types + del known_types + + if known_functions: settings['known_functions'] = known_functions + del known_functions + + if known_constants: settings['known_constants'] = known_constants + del known_constants + + if not prefix_expressions: prefix_expressions = [] + if not suffix_expressions: suffix_expressions = [] + + p = SMTLibPrinter(settings, symbol_table) + del symbol_table + + # [FALLBACK RULES] + for e in expr: + for sym in e.atoms(Symbol, Function): + if ( + sym.is_Symbol and + sym not in p._known_constants and + sym not in p.symbol_table + ): + log_warn(f"Could not infer type of `{sym}`. Defaulting to float.") + p.symbol_table[sym] = float + if ( + sym.is_Function and + type(sym) not in p._known_functions and + type(sym) not in p.symbol_table and + not sym.is_Piecewise + ): raise TypeError( + f"Unknown type of undefined function `{sym}`. " + f"Must be mapped to ``str`` in known_functions or mapped to ``Callable[..]`` in symbol_table." + ) + + declarations = [] + if auto_declare: + constants = {sym.name: sym for e in expr for sym in e.free_symbols + if sym not in p._known_constants} + functions = {fnc.name: fnc for e in expr for fnc in e.atoms(Function) + if type(fnc) not in p._known_functions and not fnc.is_Piecewise} + declarations = \ + [ + _auto_declare_smtlib(sym, p, log_warn) + for sym in constants.values() + ] + [ + _auto_declare_smtlib(fnc, p, log_warn) + for fnc in functions.values() + ] + declarations = [decl for decl in declarations if decl] + + if auto_assert: + expr = [_auto_assert_smtlib(e, p, log_warn) for e in expr] + + # return SMTLibPrinter().doprint(expr) + return '\n'.join([ + # ';; PREFIX EXPRESSIONS', + *[ + e if isinstance(e, str) else p.doprint(e) + for e in prefix_expressions + ], + + # ';; DECLARATIONS', + *sorted(e for e in declarations), + + # ';; EXPRESSIONS', + *[ + e if isinstance(e, str) else p.doprint(e) + for e in expr + ], + + # ';; SUFFIX EXPRESSIONS', + *[ + e if isinstance(e, str) else p.doprint(e) + for e in suffix_expressions + ], + ]) + + +def _auto_declare_smtlib(sym: typing.Union[Symbol, Function], p: SMTLibPrinter, log_warn: typing.Callable[[str], None]): + if sym.is_Symbol: + type_signature = p.symbol_table[sym] + assert isinstance(type_signature, type) + type_signature = p._known_types[type_signature] + return p._s_expr('declare-const', [sym, type_signature]) + + elif sym.is_Function: + type_signature = p.symbol_table[type(sym)] + assert callable(type_signature) + type_signature = [p._known_types[_] for _ in type_signature.__args__] + assert len(type_signature) > 0 + params_signature = f"({' '.join(type_signature[:-1])})" + return_signature = type_signature[-1] + return p._s_expr('declare-fun', [type(sym), params_signature, return_signature]) + + else: + log_warn(f"Non-Symbol/Function `{sym}` will not be declared.") + return None + + +def _auto_assert_smtlib(e: Expr, p: SMTLibPrinter, log_warn: typing.Callable[[str], None]): + if isinstance(e, Boolean) or ( + e in p.symbol_table and p.symbol_table[e] == bool + ) or ( + e.is_Function and + type(e) in p.symbol_table and + p.symbol_table[type(e)].__args__[-1] == bool + ): + return p._s_expr('assert', [e]) + else: + log_warn(f"Non-Boolean expression `{e}` will not be asserted. Converting to SMTLib verbatim.") + return e + + +def _auto_infer_smtlib_types( + *exprs: Basic, + symbol_table: typing.Optional[dict] = None +) -> dict: + # [TYPE INFERENCE RULES] + # X is alone in an expr => X is bool + # X in BooleanFunction.args => X is bool + # X matches to a bool param of a symbol_table function => X is bool + # X matches to an int param of a symbol_table function => X is int + # X.is_integer => X is int + # X == Y, where X is T => Y is T + + # [FALLBACK RULES] + # see _auto_declare_smtlib(..) + # X is not bool and X is not int and X is Symbol => X is float + # else (e.g. X is Function) => error. must be specified explicitly. + + _symbols = dict(symbol_table) if symbol_table else {} + + def safe_update(syms: set, inf): + for s in syms: + assert s.is_Symbol + if (old_type := _symbols.setdefault(s, inf)) != inf: + raise TypeError(f"Could not infer type of `{s}`. Apparently both `{old_type}` and `{inf}`?") + + # EXPLICIT TYPES + safe_update({ + e + for e in exprs + if e.is_Symbol + }, bool) + + safe_update({ + symbol + for e in exprs + for boolfunc in e.atoms(BooleanFunction) + for symbol in boolfunc.args + if symbol.is_Symbol + }, bool) + + safe_update({ + symbol + for e in exprs + for boolfunc in e.atoms(Function) + if type(boolfunc) in _symbols + for symbol, param in zip(boolfunc.args, _symbols[type(boolfunc)].__args__) + if symbol.is_Symbol and param == bool + }, bool) + + safe_update({ + symbol + for e in exprs + for intfunc in e.atoms(Function) + if type(intfunc) in _symbols + for symbol, param in zip(intfunc.args, _symbols[type(intfunc)].__args__) + if symbol.is_Symbol and param == int + }, int) + + safe_update({ + symbol + for e in exprs + for symbol in e.atoms(Symbol) + if symbol.is_integer + }, int) + + safe_update({ + symbol + for e in exprs + for symbol in e.atoms(Symbol) + if symbol.is_real and not symbol.is_integer + }, float) + + # EQUALITY RELATION RULE + rels = [rel for expr in exprs for rel in expr.atoms(Equality)] + rels = [ + (rel.lhs, rel.rhs) for rel in rels if rel.lhs.is_Symbol + ] + [ + (rel.rhs, rel.lhs) for rel in rels if rel.rhs.is_Symbol + ] + for infer, reltd in rels: + inference = ( + _symbols[infer] if infer in _symbols else + _symbols[reltd] if reltd in _symbols else + + _symbols[type(reltd)].__args__[-1] + if reltd.is_Function and type(reltd) in _symbols else + + bool if reltd.is_Boolean else + int if reltd.is_integer or reltd.is_Integer else + float if reltd.is_real else + None + ) + if inference: safe_update({infer}, inference) + + return _symbols diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/str.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/str.py new file mode 100644 index 0000000000000000000000000000000000000000..d748c244758219f0278ad9f1081eeb923e9b8591 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/str.py @@ -0,0 +1,1027 @@ +""" +A Printer for generating readable representation of most SymPy classes. +""" + +from __future__ import annotations +from typing import Any + +from sympy.core import S, Rational, Pow, Basic, Mul, Number +from sympy.core.mul import _keep_coeff +from sympy.core.relational import Relational +from sympy.core.sorting import default_sort_key +from sympy.core.sympify import SympifyError +from sympy.utilities.iterables import sift +from .precedence import precedence, PRECEDENCE +from .printer import Printer, print_function + +from mpmath.libmp import prec_to_dps, to_str as mlib_to_str + + +class StrPrinter(Printer): + printmethod = "_sympystr" + _default_settings: dict[str, Any] = { + "order": None, + "full_prec": "auto", + "sympy_integers": False, + "abbrev": False, + "perm_cyclic": True, + "min": None, + "max": None, + } + + _relationals: dict[str, str] = {} + + def parenthesize(self, item, level, strict=False): + if (precedence(item) < level) or ((not strict) and precedence(item) <= level): + return "(%s)" % self._print(item) + else: + return self._print(item) + + def stringify(self, args, sep, level=0): + return sep.join([self.parenthesize(item, level) for item in args]) + + def emptyPrinter(self, expr): + if isinstance(expr, str): + return expr + elif isinstance(expr, Basic): + return repr(expr) + else: + return str(expr) + + def _print_Add(self, expr, order=None): + terms = self._as_ordered_terms(expr, order=order) + + prec = precedence(expr) + l = [] + for term in terms: + t = self._print(term) + if t.startswith('-') and not term.is_Add: + sign = "-" + t = t[1:] + else: + sign = "+" + if precedence(term) < prec or term.is_Add: + l.extend([sign, "(%s)" % t]) + else: + l.extend([sign, t]) + sign = l.pop(0) + if sign == '+': + sign = "" + return sign + ' '.join(l) + + def _print_BooleanTrue(self, expr): + return "True" + + def _print_BooleanFalse(self, expr): + return "False" + + def _print_Not(self, expr): + return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"])) + + def _print_And(self, expr): + args = list(expr.args) + for j, i in enumerate(args): + if isinstance(i, Relational) and ( + i.canonical.rhs is S.NegativeInfinity): + args.insert(0, args.pop(j)) + return self.stringify(args, " & ", PRECEDENCE["BitwiseAnd"]) + + def _print_Or(self, expr): + return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"]) + + def _print_Xor(self, expr): + return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"]) + + def _print_AppliedPredicate(self, expr): + return '%s(%s)' % ( + self._print(expr.function), self.stringify(expr.arguments, ", ")) + + def _print_Basic(self, expr): + l = [self._print(o) for o in expr.args] + return expr.__class__.__name__ + "(%s)" % ", ".join(l) + + def _print_BlockMatrix(self, B): + if B.blocks.shape == (1, 1): + self._print(B.blocks[0, 0]) + return self._print(B.blocks) + + def _print_Catalan(self, expr): + return 'Catalan' + + def _print_ComplexInfinity(self, expr): + return 'zoo' + + def _print_ConditionSet(self, s): + args = tuple([self._print(i) for i in (s.sym, s.condition)]) + if s.base_set is S.UniversalSet: + return 'ConditionSet(%s, %s)' % args + args += (self._print(s.base_set),) + return 'ConditionSet(%s, %s, %s)' % args + + def _print_Derivative(self, expr): + dexpr = expr.expr + dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count] + return 'Derivative(%s)' % ", ".join((self._print(arg) for arg in [dexpr] + dvars)) + + def _print_dict(self, d): + keys = sorted(d.keys(), key=default_sort_key) + items = [] + + for key in keys: + item = "%s: %s" % (self._print(key), self._print(d[key])) + items.append(item) + + return "{%s}" % ", ".join(items) + + def _print_Dict(self, expr): + return self._print_dict(expr) + + def _print_RandomDomain(self, d): + if hasattr(d, 'as_boolean'): + return 'Domain: ' + self._print(d.as_boolean()) + elif hasattr(d, 'set'): + return ('Domain: ' + self._print(d.symbols) + ' in ' + + self._print(d.set)) + else: + return 'Domain on ' + self._print(d.symbols) + + def _print_Dummy(self, expr): + return '_' + expr.name + + def _print_EulerGamma(self, expr): + return 'EulerGamma' + + def _print_Exp1(self, expr): + return 'E' + + def _print_ExprCondPair(self, expr): + return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond)) + + def _print_Function(self, expr): + return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ") + + def _print_GoldenRatio(self, expr): + return 'GoldenRatio' + + def _print_Heaviside(self, expr): + # Same as _print_Function but uses pargs to suppress default 1/2 for + # 2nd args + return expr.func.__name__ + "(%s)" % self.stringify(expr.pargs, ", ") + + def _print_TribonacciConstant(self, expr): + return 'TribonacciConstant' + + def _print_ImaginaryUnit(self, expr): + return 'I' + + def _print_Infinity(self, expr): + return 'oo' + + def _print_Integral(self, expr): + def _xab_tostr(xab): + if len(xab) == 1: + return self._print(xab[0]) + else: + return self._print((xab[0],) + tuple(xab[1:])) + L = ', '.join([_xab_tostr(l) for l in expr.limits]) + return 'Integral(%s, %s)' % (self._print(expr.function), L) + + def _print_Interval(self, i): + fin = 'Interval{m}({a}, {b})' + a, b, l, r = i.args + if a.is_infinite and b.is_infinite: + m = '' + elif a.is_infinite and not r: + m = '' + elif b.is_infinite and not l: + m = '' + elif not l and not r: + m = '' + elif l and r: + m = '.open' + elif l: + m = '.Lopen' + else: + m = '.Ropen' + return fin.format(**{'a': a, 'b': b, 'm': m}) + + def _print_AccumulationBounds(self, i): + return "AccumBounds(%s, %s)" % (self._print(i.min), + self._print(i.max)) + + def _print_Inverse(self, I): + return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"]) + + def _print_Lambda(self, obj): + expr = obj.expr + sig = obj.signature + if len(sig) == 1 and sig[0].is_symbol: + sig = sig[0] + return "Lambda(%s, %s)" % (self._print(sig), self._print(expr)) + + def _print_LatticeOp(self, expr): + args = sorted(expr.args, key=default_sort_key) + return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args) + + def _print_Limit(self, expr): + e, z, z0, dir = expr.args + return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print, (e, z, z0, dir))) + + + def _print_list(self, expr): + return "[%s]" % self.stringify(expr, ", ") + + def _print_List(self, expr): + return self._print_list(expr) + + def _print_MatrixBase(self, expr): + return expr._format_str(self) + + def _print_MatrixElement(self, expr): + return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + + '[%s, %s]' % (self._print(expr.i), self._print(expr.j)) + + def _print_MatrixSlice(self, expr): + def strslice(x, dim): + x = list(x) + if x[2] == 1: + del x[2] + if x[0] == 0: + x[0] = '' + if x[1] == dim: + x[1] = '' + return ':'.join((self._print(arg) for arg in x)) + return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' + + strslice(expr.rowslice, expr.parent.rows) + ', ' + + strslice(expr.colslice, expr.parent.cols) + ']') + + def _print_DeferredVector(self, expr): + return expr.name + + def _print_Mul(self, expr): + + prec = precedence(expr) + + # Check for unevaluated Mul. In this case we need to make sure the + # identities are visible, multiple Rational factors are not combined + # etc so we display in a straight-forward form that fully preserves all + # args and their order. + args = expr.args + if args[0] is S.One or any( + isinstance(a, Number) or + a.is_Pow and all(ai.is_Integer for ai in a.args) + for a in args[1:]): + d, n = sift(args, lambda x: + isinstance(x, Pow) and bool(x.exp.as_coeff_Mul()[0] < 0), + binary=True) + for i, di in enumerate(d): + if di.exp.is_Number: + e = -di.exp + else: + dargs = list(di.exp.args) + dargs[0] = -dargs[0] + e = Mul._from_args(dargs) + d[i] = Pow(di.base, e, evaluate=False) if e - 1 else di.base + + pre = [] + # don't parenthesize first factor if negative + if n and not n[0].is_Add and n[0].could_extract_minus_sign(): + pre = [self._print(n.pop(0))] + + nfactors = pre + [self.parenthesize(a, prec, strict=False) + for a in n] + if not nfactors: + nfactors = ['1'] + + # don't parenthesize first of denominator unless singleton + if len(d) > 1 and d[0].could_extract_minus_sign(): + pre = [self._print(d.pop(0))] + else: + pre = [] + dfactors = pre + [self.parenthesize(a, prec, strict=False) + for a in d] + + n = '*'.join(nfactors) + d = '*'.join(dfactors) + if len(dfactors) > 1: + return '%s/(%s)' % (n, d) + elif dfactors: + return '%s/%s' % (n, d) + return n + + c, e = expr.as_coeff_Mul() + if c < 0: + expr = _keep_coeff(-c, e) + sign = "-" + else: + sign = "" + + a = [] # items in the numerator + b = [] # items that are in the denominator (if any) + + pow_paren = [] # Will collect all pow with more than one base element and exp = -1 + + if self.order not in ('old', 'none'): + args = expr.as_ordered_factors() + else: + # use make_args in case expr was something like -x -> x + args = Mul.make_args(expr) + + # Gather args for numerator/denominator + def apow(i): + b, e = i.as_base_exp() + eargs = list(Mul.make_args(e)) + if eargs[0] is S.NegativeOne: + eargs = eargs[1:] + else: + eargs[0] = -eargs[0] + e = Mul._from_args(eargs) + if isinstance(i, Pow): + return i.func(b, e, evaluate=False) + return i.func(e, evaluate=False) + for item in args: + if (item.is_commutative and + isinstance(item, Pow) and + bool(item.exp.as_coeff_Mul()[0] < 0)): + if item.exp is not S.NegativeOne: + b.append(apow(item)) + else: + if (len(item.args[0].args) != 1 and + isinstance(item.base, (Mul, Pow))): + # To avoid situations like #14160 + pow_paren.append(item) + b.append(item.base) + elif item.is_Rational and item is not S.Infinity: + if item.p != 1: + a.append(Rational(item.p)) + if item.q != 1: + b.append(Rational(item.q)) + else: + a.append(item) + + a = a or [S.One] + + a_str = [self.parenthesize(x, prec, strict=False) for x in a] + b_str = [self.parenthesize(x, prec, strict=False) for x in b] + + # To parenthesize Pow with exp = -1 and having more than one Symbol + for item in pow_paren: + if item.base in b: + b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] + + if not b: + return sign + '*'.join(a_str) + elif len(b) == 1: + return sign + '*'.join(a_str) + "/" + b_str[0] + else: + return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str) + + def _print_MatMul(self, expr): + c, m = expr.as_coeff_mmul() + + sign = "" + if c.is_number: + re, im = c.as_real_imag() + if im.is_zero and re.is_negative: + expr = _keep_coeff(-c, m) + sign = "-" + elif re.is_zero and im.is_negative: + expr = _keep_coeff(-c, m) + sign = "-" + + return sign + '*'.join( + [self.parenthesize(arg, precedence(expr)) for arg in expr.args] + ) + + def _print_ElementwiseApplyFunction(self, expr): + return "{}.({})".format( + expr.function, + self._print(expr.expr), + ) + + def _print_NaN(self, expr): + return 'nan' + + def _print_NegativeInfinity(self, expr): + return '-oo' + + def _print_Order(self, expr): + if not expr.variables or all(p is S.Zero for p in expr.point): + if len(expr.variables) <= 1: + return 'O(%s)' % self._print(expr.expr) + else: + return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0) + else: + return 'O(%s)' % self.stringify(expr.args, ', ', 0) + + def _print_Ordinal(self, expr): + return expr.__str__() + + def _print_Cycle(self, expr): + return expr.__str__() + + def _print_Permutation(self, expr): + from sympy.combinatorics.permutations import Permutation, Cycle + from sympy.utilities.exceptions import sympy_deprecation_warning + + perm_cyclic = Permutation.print_cyclic + if perm_cyclic is not None: + sympy_deprecation_warning( + f""" + Setting Permutation.print_cyclic is deprecated. Instead use + init_printing(perm_cyclic={perm_cyclic}). + """, + deprecated_since_version="1.6", + active_deprecations_target="deprecated-permutation-print_cyclic", + stacklevel=7, + ) + else: + perm_cyclic = self._settings.get("perm_cyclic", True) + + if perm_cyclic: + if not expr.size: + return '()' + # before taking Cycle notation, see if the last element is + # a singleton and move it to the head of the string + s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] + last = s.rfind('(') + if not last == 0 and ',' not in s[last:]: + s = s[last:] + s[:last] + s = s.replace(',', '') + return s + else: + s = expr.support() + if not s: + if expr.size < 5: + return 'Permutation(%s)' % self._print(expr.array_form) + return 'Permutation([], size=%s)' % self._print(expr.size) + trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size) + use = full = self._print(expr.array_form) + if len(trim) < len(full): + use = trim + return 'Permutation(%s)' % use + + def _print_Subs(self, obj): + expr, old, new = obj.args + if len(obj.point) == 1: + old = old[0] + new = new[0] + return "Subs(%s, %s, %s)" % ( + self._print(expr), self._print(old), self._print(new)) + + def _print_TensorIndex(self, expr): + return expr._print() + + def _print_TensorHead(self, expr): + return expr._print() + + def _print_Tensor(self, expr): + return expr._print() + + def _print_TensMul(self, expr): + # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" + sign, args = expr._get_args_for_traditional_printer() + return sign + "*".join( + [self.parenthesize(arg, precedence(expr)) for arg in args] + ) + + def _print_TensAdd(self, expr): + return expr._print() + + def _print_ArraySymbol(self, expr): + return self._print(expr.name) + + def _print_ArrayElement(self, expr): + return "%s[%s]" % ( + self.parenthesize(expr.name, PRECEDENCE["Func"], True), ", ".join([self._print(i) for i in expr.indices])) + + def _print_PermutationGroup(self, expr): + p = [' %s' % self._print(a) for a in expr.args] + return 'PermutationGroup([\n%s])' % ',\n'.join(p) + + def _print_Pi(self, expr): + return 'pi' + + def _print_PolyRing(self, ring): + return "Polynomial ring in %s over %s with %s order" % \ + (", ".join((self._print(rs) for rs in ring.symbols)), + self._print(ring.domain), self._print(ring.order)) + + def _print_FracField(self, field): + return "Rational function field in %s over %s with %s order" % \ + (", ".join((self._print(fs) for fs in field.symbols)), + self._print(field.domain), self._print(field.order)) + + def _print_FreeGroupElement(self, elm): + return elm.__str__() + + def _print_GaussianElement(self, poly): + return "(%s + %s*I)" % (poly.x, poly.y) + + def _print_PolyElement(self, poly): + return poly.str(self, PRECEDENCE, "%s**%s", "*") + + def _print_FracElement(self, frac): + if frac.denom == 1: + return self._print(frac.numer) + else: + numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True) + denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True) + return numer + "/" + denom + + def _print_Poly(self, expr): + ATOM_PREC = PRECEDENCE["Atom"] - 1 + terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ] + + for monom, coeff in expr.terms(): + s_monom = [] + + for i, e in enumerate(monom): + if e > 0: + if e == 1: + s_monom.append(gens[i]) + else: + s_monom.append(gens[i] + "**%d" % e) + + s_monom = "*".join(s_monom) + + if coeff.is_Add: + if s_monom: + s_coeff = "(" + self._print(coeff) + ")" + else: + s_coeff = self._print(coeff) + else: + if s_monom: + if coeff is S.One: + terms.extend(['+', s_monom]) + continue + + if coeff is S.NegativeOne: + terms.extend(['-', s_monom]) + continue + + s_coeff = self._print(coeff) + + if not s_monom: + s_term = s_coeff + else: + s_term = s_coeff + "*" + s_monom + + if s_term.startswith('-'): + terms.extend(['-', s_term[1:]]) + else: + terms.extend(['+', s_term]) + + if terms[0] in ('-', '+'): + modifier = terms.pop(0) + + if modifier == '-': + terms[0] = '-' + terms[0] + + format = expr.__class__.__name__ + "(%s, %s" + + from sympy.polys.polyerrors import PolynomialError + + try: + format += ", modulus=%s" % expr.get_modulus() + except PolynomialError: + format += ", domain='%s'" % expr.get_domain() + + format += ")" + + for index, item in enumerate(gens): + if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"): + gens[index] = item[1:len(item) - 1] + + return format % (' '.join(terms), ', '.join(gens)) + + def _print_UniversalSet(self, p): + return 'UniversalSet' + + def _print_AlgebraicNumber(self, expr): + if expr.is_aliased: + return self._print(expr.as_poly().as_expr()) + else: + return self._print(expr.as_expr()) + + def _print_Pow(self, expr, rational=False): + """Printing helper function for ``Pow`` + + Parameters + ========== + + rational : bool, optional + If ``True``, it will not attempt printing ``sqrt(x)`` or + ``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)`` + instead. + + See examples for additional details + + Examples + ======== + + >>> from sympy import sqrt, StrPrinter + >>> from sympy.abc import x + + How ``rational`` keyword works with ``sqrt``: + + >>> printer = StrPrinter() + >>> printer._print_Pow(sqrt(x), rational=True) + 'x**(1/2)' + >>> printer._print_Pow(sqrt(x), rational=False) + 'sqrt(x)' + >>> printer._print_Pow(1/sqrt(x), rational=True) + 'x**(-1/2)' + >>> printer._print_Pow(1/sqrt(x), rational=False) + '1/sqrt(x)' + + Notes + ===== + + ``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy, + so there is no need of defining a separate printer for ``sqrt``. + Instead, it should be handled here as well. + """ + PREC = precedence(expr) + + if expr.exp is S.Half and not rational: + return "sqrt(%s)" % self._print(expr.base) + + if expr.is_commutative: + if -expr.exp is S.Half and not rational: + # Note: Don't test "expr.exp == -S.Half" here, because that will + # match -0.5, which we don't want. + return "%s/sqrt(%s)" % tuple((self._print(arg) for arg in (S.One, expr.base))) + if expr.exp is -S.One: + # Similarly to the S.Half case, don't test with "==" here. + return '%s/%s' % (self._print(S.One), + self.parenthesize(expr.base, PREC, strict=False)) + + e = self.parenthesize(expr.exp, PREC, strict=False) + if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1: + # the parenthesized exp should be '(Rational(a, b))' so strip parens, + # but just check to be sure. + if e.startswith('(Rational'): + return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1]) + return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e) + + def _print_UnevaluatedExpr(self, expr): + return self._print(expr.args[0]) + + def _print_MatPow(self, expr): + PREC = precedence(expr) + return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), + self.parenthesize(expr.exp, PREC, strict=False)) + + def _print_Integer(self, expr): + if self._settings.get("sympy_integers", False): + return "S(%s)" % (expr) + return str(expr.p) + + def _print_Integers(self, expr): + return 'Integers' + + def _print_Naturals(self, expr): + return 'Naturals' + + def _print_Naturals0(self, expr): + return 'Naturals0' + + def _print_Rationals(self, expr): + return 'Rationals' + + def _print_Reals(self, expr): + return 'Reals' + + def _print_Complexes(self, expr): + return 'Complexes' + + def _print_EmptySet(self, expr): + return 'EmptySet' + + def _print_EmptySequence(self, expr): + return 'EmptySequence' + + def _print_int(self, expr): + return str(expr) + + def _print_mpz(self, expr): + return str(expr) + + def _print_Rational(self, expr): + if expr.q == 1: + return str(expr.p) + else: + if self._settings.get("sympy_integers", False): + return "S(%s)/%s" % (expr.p, expr.q) + return "%s/%s" % (expr.p, expr.q) + + def _print_PythonRational(self, expr): + if expr.q == 1: + return str(expr.p) + else: + return "%d/%d" % (expr.p, expr.q) + + def _print_Fraction(self, expr): + if expr.denominator == 1: + return str(expr.numerator) + else: + return "%s/%s" % (expr.numerator, expr.denominator) + + def _print_mpq(self, expr): + if expr.denominator == 1: + return str(expr.numerator) + else: + return "%s/%s" % (expr.numerator, expr.denominator) + + def _print_Float(self, expr): + prec = expr._prec + if prec < 5: + dps = 0 + else: + dps = prec_to_dps(expr._prec) + if self._settings["full_prec"] is True: + strip = False + elif self._settings["full_prec"] is False: + strip = True + elif self._settings["full_prec"] == "auto": + strip = self._print_level > 1 + low = self._settings["min"] if "min" in self._settings else None + high = self._settings["max"] if "max" in self._settings else None + rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) + if rv.startswith('-.0'): + rv = '-0.' + rv[3:] + elif rv.startswith('.0'): + rv = '0.' + rv[2:] + if rv.startswith('+'): + # e.g., +inf -> inf + rv = rv[1:] + return rv + + def _print_Relational(self, expr): + + charmap = { + "==": "Eq", + "!=": "Ne", + ":=": "Assignment", + '+=': "AddAugmentedAssignment", + "-=": "SubAugmentedAssignment", + "*=": "MulAugmentedAssignment", + "/=": "DivAugmentedAssignment", + "%=": "ModAugmentedAssignment", + } + + if expr.rel_op in charmap: + return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs), + self._print(expr.rhs)) + + return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)), + self._relationals.get(expr.rel_op) or expr.rel_op, + self.parenthesize(expr.rhs, precedence(expr))) + + def _print_ComplexRootOf(self, expr): + return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'), + expr.index) + + def _print_RootSum(self, expr): + args = [self._print_Add(expr.expr, order='lex')] + + if expr.fun is not S.IdentityFunction: + args.append(self._print(expr.fun)) + + return "RootSum(%s)" % ", ".join(args) + + def _print_GroebnerBasis(self, basis): + cls = basis.__class__.__name__ + + exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs] + exprs = "[%s]" % ", ".join(exprs) + + gens = [ self._print(gen) for gen in basis.gens ] + domain = "domain='%s'" % self._print(basis.domain) + order = "order='%s'" % self._print(basis.order) + + args = [exprs] + gens + [domain, order] + + return "%s(%s)" % (cls, ", ".join(args)) + + def _print_set(self, s): + items = sorted(s, key=default_sort_key) + + args = ', '.join(self._print(item) for item in items) + if not args: + return "set()" + return '{%s}' % args + + def _print_FiniteSet(self, s): + from sympy.sets.sets import FiniteSet + items = sorted(s, key=default_sort_key) + + args = ', '.join(self._print(item) for item in items) + if any(item.has(FiniteSet) for item in items): + return 'FiniteSet({})'.format(args) + return '{{{}}}'.format(args) + + def _print_Partition(self, s): + items = sorted(s, key=default_sort_key) + + args = ', '.join(self._print(arg) for arg in items) + return 'Partition({})'.format(args) + + def _print_frozenset(self, s): + if not s: + return "frozenset()" + return "frozenset(%s)" % self._print_set(s) + + def _print_Sum(self, expr): + def _xab_tostr(xab): + if len(xab) == 1: + return self._print(xab[0]) + else: + return self._print((xab[0],) + tuple(xab[1:])) + L = ', '.join([_xab_tostr(l) for l in expr.limits]) + return 'Sum(%s, %s)' % (self._print(expr.function), L) + + def _print_Symbol(self, expr): + return expr.name + _print_MatrixSymbol = _print_Symbol + _print_RandomSymbol = _print_Symbol + + def _print_Identity(self, expr): + return "I" + + def _print_ZeroMatrix(self, expr): + return "0" + + def _print_OneMatrix(self, expr): + return "1" + + def _print_Predicate(self, expr): + return "Q.%s" % expr.name + + def _print_str(self, expr): + return str(expr) + + def _print_tuple(self, expr): + if len(expr) == 1: + return "(%s,)" % self._print(expr[0]) + else: + return "(%s)" % self.stringify(expr, ", ") + + def _print_Tuple(self, expr): + return self._print_tuple(expr) + + def _print_Transpose(self, T): + return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"]) + + def _print_Uniform(self, expr): + return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b)) + + def _print_Quantity(self, expr): + if self._settings.get("abbrev", False): + return "%s" % expr.abbrev + return "%s" % expr.name + + def _print_Quaternion(self, expr): + s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] + a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")] + return " + ".join(a) + + def _print_Dimension(self, expr): + return str(expr) + + def _print_Wild(self, expr): + return expr.name + '_' + + def _print_WildFunction(self, expr): + return expr.name + '_' + + def _print_WildDot(self, expr): + return expr.name + + def _print_WildPlus(self, expr): + return expr.name + + def _print_WildStar(self, expr): + return expr.name + + def _print_Zero(self, expr): + if self._settings.get("sympy_integers", False): + return "S(0)" + return "0" + + def _print_DMP(self, p): + try: + if p.ring is not None: + # TODO incorporate order + return self._print(p.ring.to_sympy(p)) + except SympifyError: + pass + + cls = p.__class__.__name__ + rep = self._print(p.rep) + dom = self._print(p.dom) + ring = self._print(p.ring) + + return "%s(%s, %s, %s)" % (cls, rep, dom, ring) + + def _print_DMF(self, expr): + return self._print_DMP(expr) + + def _print_Object(self, obj): + return 'Object("%s")' % obj.name + + def _print_IdentityMorphism(self, morphism): + return 'IdentityMorphism(%s)' % morphism.domain + + def _print_NamedMorphism(self, morphism): + return 'NamedMorphism(%s, %s, "%s")' % \ + (morphism.domain, morphism.codomain, morphism.name) + + def _print_Category(self, category): + return 'Category("%s")' % category.name + + def _print_Manifold(self, manifold): + return manifold.name.name + + def _print_Patch(self, patch): + return patch.name.name + + def _print_CoordSystem(self, coords): + return coords.name.name + + def _print_BaseScalarField(self, field): + return field._coord_sys.symbols[field._index].name + + def _print_BaseVectorField(self, field): + return 'e_%s' % field._coord_sys.symbols[field._index].name + + def _print_Differential(self, diff): + field = diff._form_field + if hasattr(field, '_coord_sys'): + return 'd%s' % field._coord_sys.symbols[field._index].name + else: + return 'd(%s)' % self._print(field) + + def _print_Tr(self, expr): + #TODO : Handle indices + return "%s(%s)" % ("Tr", self._print(expr.args[0])) + + def _print_Str(self, s): + return self._print(s.name) + + def _print_AppliedBinaryRelation(self, expr): + rel = expr.function + return '%s(%s, %s)' % (self._print(rel), + self._print(expr.lhs), + self._print(expr.rhs)) + + +@print_function(StrPrinter) +def sstr(expr, **settings): + """Returns the expression as a string. + + For large expressions where speed is a concern, use the setting + order='none'. If abbrev=True setting is used then units are printed in + abbreviated form. + + Examples + ======== + + >>> from sympy import symbols, Eq, sstr + >>> a, b = symbols('a b') + >>> sstr(Eq(a + b, 0)) + 'Eq(a + b, 0)' + """ + + p = StrPrinter(settings) + s = p.doprint(expr) + + return s + + +class StrReprPrinter(StrPrinter): + """(internal) -- see sstrrepr""" + + def _print_str(self, s): + return repr(s) + + def _print_Str(self, s): + # Str does not to be printed same as str here + return "%s(%s)" % (s.__class__.__name__, self._print(s.name)) + + +@print_function(StrReprPrinter) +def sstrrepr(expr, **settings): + """return expr in mixed str/repr form + + i.e. strings are returned in repr form with quotes, and everything else + is returned in str form. + + This function could be useful for hooking into sys.displayhook + """ + + p = StrReprPrinter(settings) + s = p.doprint(expr) + + return s diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tableform.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tableform.py new file mode 100644 index 0000000000000000000000000000000000000000..4322924ff1c7218da7e6ea039da713506d66e342 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tableform.py @@ -0,0 +1,366 @@ +from sympy.core.containers import Tuple +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import SympifyError + +from types import FunctionType + + +class TableForm: + r""" + Create a nice table representation of data. + + Examples + ======== + + >>> from sympy import TableForm + >>> t = TableForm([[5, 7], [4, 2], [10, 3]]) + >>> print(t) + 5 7 + 4 2 + 10 3 + + You can use the SymPy's printing system to produce tables in any + format (ascii, latex, html, ...). + + >>> print(t.as_latex()) + \begin{tabular}{l l} + $5$ & $7$ \\ + $4$ & $2$ \\ + $10$ & $3$ \\ + \end{tabular} + + """ + + def __init__(self, data, **kwarg): + """ + Creates a TableForm. + + Parameters: + + data ... + 2D data to be put into the table; data can be + given as a Matrix + + headings ... + gives the labels for rows and columns: + + Can be a single argument that applies to both + dimensions: + + - None ... no labels + - "automatic" ... labels are 1, 2, 3, ... + + Can be a list of labels for rows and columns: + The labels for each dimension can be given + as None, "automatic", or [l1, l2, ...] e.g. + ["automatic", None] will number the rows + + [default: None] + + alignments ... + alignment of the columns with: + + - "left" or "<" + - "center" or "^" + - "right" or ">" + + When given as a single value, the value is used for + all columns. The row headings (if given) will be + right justified unless an explicit alignment is + given for it and all other columns. + + [default: "left"] + + formats ... + a list of format strings or functions that accept + 3 arguments (entry, row number, col number) and + return a string for the table entry. (If a function + returns None then the _print method will be used.) + + wipe_zeros ... + Do not show zeros in the table. + + [default: True] + + pad ... + the string to use to indicate a missing value (e.g. + elements that are None or those that are missing + from the end of a row (i.e. any row that is shorter + than the rest is assumed to have missing values). + When None, nothing will be shown for values that + are missing from the end of a row; values that are + None, however, will be shown. + + [default: None] + + Examples + ======== + + >>> from sympy import TableForm, Symbol + >>> TableForm([[5, 7], [4, 2], [10, 3]]) + 5 7 + 4 2 + 10 3 + >>> TableForm([list('.'*i) for i in range(1, 4)], headings='automatic') + | 1 2 3 + --------- + 1 | . + 2 | . . + 3 | . . . + >>> TableForm([[Symbol('.'*(j if not i%2 else 1)) for i in range(3)] + ... for j in range(4)], alignments='rcl') + . + . . . + .. . .. + ... . ... + """ + from sympy.matrices.dense import Matrix + + # We only support 2D data. Check the consistency: + if isinstance(data, Matrix): + data = data.tolist() + _h = len(data) + + # fill out any short lines + pad = kwarg.get('pad', None) + ok_None = False + if pad is None: + pad = " " + ok_None = True + pad = Symbol(pad) + _w = max(len(line) for line in data) + for i, line in enumerate(data): + if len(line) != _w: + line.extend([pad]*(_w - len(line))) + for j, lj in enumerate(line): + if lj is None: + if not ok_None: + lj = pad + else: + try: + lj = S(lj) + except SympifyError: + lj = Symbol(str(lj)) + line[j] = lj + data[i] = line + _lines = Tuple(*[Tuple(*d) for d in data]) + + headings = kwarg.get("headings", [None, None]) + if headings == "automatic": + _headings = [range(1, _h + 1), range(1, _w + 1)] + else: + h1, h2 = headings + if h1 == "automatic": + h1 = range(1, _h + 1) + if h2 == "automatic": + h2 = range(1, _w + 1) + _headings = [h1, h2] + + allow = ('l', 'r', 'c') + alignments = kwarg.get("alignments", "l") + + def _std_align(a): + a = a.strip().lower() + if len(a) > 1: + return {'left': 'l', 'right': 'r', 'center': 'c'}.get(a, a) + else: + return {'<': 'l', '>': 'r', '^': 'c'}.get(a, a) + std_align = _std_align(alignments) + if std_align in allow: + _alignments = [std_align]*_w + else: + _alignments = [] + for a in alignments: + std_align = _std_align(a) + _alignments.append(std_align) + if std_align not in ('l', 'r', 'c'): + raise ValueError('alignment "%s" unrecognized' % + alignments) + if _headings[0] and len(_alignments) == _w + 1: + _head_align = _alignments[0] + _alignments = _alignments[1:] + else: + _head_align = 'r' + if len(_alignments) != _w: + raise ValueError( + 'wrong number of alignments: expected %s but got %s' % + (_w, len(_alignments))) + + _column_formats = kwarg.get("formats", [None]*_w) + + _wipe_zeros = kwarg.get("wipe_zeros", True) + + self._w = _w + self._h = _h + self._lines = _lines + self._headings = _headings + self._head_align = _head_align + self._alignments = _alignments + self._column_formats = _column_formats + self._wipe_zeros = _wipe_zeros + + def __repr__(self): + from .str import sstr + return sstr(self, order=None) + + def __str__(self): + from .str import sstr + return sstr(self, order=None) + + def as_matrix(self): + """Returns the data of the table in Matrix form. + + Examples + ======== + + >>> from sympy import TableForm + >>> t = TableForm([[5, 7], [4, 2], [10, 3]], headings='automatic') + >>> t + | 1 2 + -------- + 1 | 5 7 + 2 | 4 2 + 3 | 10 3 + >>> t.as_matrix() + Matrix([ + [ 5, 7], + [ 4, 2], + [10, 3]]) + """ + from sympy.matrices.dense import Matrix + return Matrix(self._lines) + + def as_str(self): + # XXX obsolete ? + return str(self) + + def as_latex(self): + from .latex import latex + return latex(self) + + def _sympystr(self, p): + """ + Returns the string representation of 'self'. + + Examples + ======== + + >>> from sympy import TableForm + >>> t = TableForm([[5, 7], [4, 2], [10, 3]]) + >>> s = t.as_str() + + """ + column_widths = [0] * self._w + lines = [] + for line in self._lines: + new_line = [] + for i in range(self._w): + # Format the item somehow if needed: + s = str(line[i]) + if self._wipe_zeros and (s == "0"): + s = " " + w = len(s) + if w > column_widths[i]: + column_widths[i] = w + new_line.append(s) + lines.append(new_line) + + # Check heading: + if self._headings[0]: + self._headings[0] = [str(x) for x in self._headings[0]] + _head_width = max([len(x) for x in self._headings[0]]) + + if self._headings[1]: + new_line = [] + for i in range(self._w): + # Format the item somehow if needed: + s = str(self._headings[1][i]) + w = len(s) + if w > column_widths[i]: + column_widths[i] = w + new_line.append(s) + self._headings[1] = new_line + + format_str = [] + + def _align(align, w): + return '%%%s%ss' % ( + ("-" if align == "l" else ""), + str(w)) + format_str = [_align(align, w) for align, w in + zip(self._alignments, column_widths)] + if self._headings[0]: + format_str.insert(0, _align(self._head_align, _head_width)) + format_str.insert(1, '|') + format_str = ' '.join(format_str) + '\n' + + s = [] + if self._headings[1]: + d = self._headings[1] + if self._headings[0]: + d = [""] + d + first_line = format_str % tuple(d) + s.append(first_line) + s.append("-" * (len(first_line) - 1) + "\n") + for i, line in enumerate(lines): + d = [l if self._alignments[j] != 'c' else + l.center(column_widths[j]) for j, l in enumerate(line)] + if self._headings[0]: + l = self._headings[0][i] + l = (l if self._head_align != 'c' else + l.center(_head_width)) + d = [l] + d + s.append(format_str % tuple(d)) + return ''.join(s)[:-1] # don't include trailing newline + + def _latex(self, printer): + """ + Returns the string representation of 'self'. + """ + # Check heading: + if self._headings[1]: + new_line = [] + for i in range(self._w): + # Format the item somehow if needed: + new_line.append(str(self._headings[1][i])) + self._headings[1] = new_line + + alignments = [] + if self._headings[0]: + self._headings[0] = [str(x) for x in self._headings[0]] + alignments = [self._head_align] + alignments.extend(self._alignments) + + s = r"\begin{tabular}{" + " ".join(alignments) + "}\n" + + if self._headings[1]: + d = self._headings[1] + if self._headings[0]: + d = [""] + d + first_line = " & ".join(d) + r" \\" + "\n" + s += first_line + s += r"\hline" + "\n" + for i, line in enumerate(self._lines): + d = [] + for j, x in enumerate(line): + if self._wipe_zeros and (x in (0, "0")): + d.append(" ") + continue + f = self._column_formats[j] + if f: + if isinstance(f, FunctionType): + v = f(x, i, j) + if v is None: + v = printer._print(x) + else: + v = f % x + d.append(v) + else: + v = printer._print(x) + d.append("$%s$" % v) + if self._headings[0]: + d = [self._headings[0][i]] + d + s += " & ".join(d) + r" \\" + "\n" + s += r"\end{tabular}" + return s diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tensorflow.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..5c3a342bef52e0aa504a787e4532192f18b1fc26 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tensorflow.py @@ -0,0 +1,216 @@ +from sympy.external.importtools import version_tuple +from collections.abc import Iterable + +from sympy.core.mul import Mul +from sympy.core.singleton import S +from sympy.codegen.cfunctions import Sqrt +from sympy.external import import_module +from sympy.printing.precedence import PRECEDENCE +from sympy.printing.pycode import AbstractPythonCodePrinter, ArrayPrinter +import sympy + +tensorflow = import_module('tensorflow') + +class TensorflowPrinter(ArrayPrinter, AbstractPythonCodePrinter): + """ + Tensorflow printer which handles vectorized piecewise functions, + logical operators, max/min, and relational operators. + """ + printmethod = "_tensorflowcode" + + mapping = { + sympy.Abs: "tensorflow.math.abs", + sympy.sign: "tensorflow.math.sign", + + # XXX May raise error for ints. + sympy.ceiling: "tensorflow.math.ceil", + sympy.floor: "tensorflow.math.floor", + sympy.log: "tensorflow.math.log", + sympy.exp: "tensorflow.math.exp", + Sqrt: "tensorflow.math.sqrt", + sympy.cos: "tensorflow.math.cos", + sympy.acos: "tensorflow.math.acos", + sympy.sin: "tensorflow.math.sin", + sympy.asin: "tensorflow.math.asin", + sympy.tan: "tensorflow.math.tan", + sympy.atan: "tensorflow.math.atan", + sympy.atan2: "tensorflow.math.atan2", + # XXX Also may give NaN for complex results. + sympy.cosh: "tensorflow.math.cosh", + sympy.acosh: "tensorflow.math.acosh", + sympy.sinh: "tensorflow.math.sinh", + sympy.asinh: "tensorflow.math.asinh", + sympy.tanh: "tensorflow.math.tanh", + sympy.atanh: "tensorflow.math.atanh", + + sympy.re: "tensorflow.math.real", + sympy.im: "tensorflow.math.imag", + sympy.arg: "tensorflow.math.angle", + + # XXX May raise error for ints and complexes + sympy.erf: "tensorflow.math.erf", + sympy.loggamma: "tensorflow.math.lgamma", + + sympy.Eq: "tensorflow.math.equal", + sympy.Ne: "tensorflow.math.not_equal", + sympy.StrictGreaterThan: "tensorflow.math.greater", + sympy.StrictLessThan: "tensorflow.math.less", + sympy.LessThan: "tensorflow.math.less_equal", + sympy.GreaterThan: "tensorflow.math.greater_equal", + + sympy.And: "tensorflow.math.logical_and", + sympy.Or: "tensorflow.math.logical_or", + sympy.Not: "tensorflow.math.logical_not", + sympy.Max: "tensorflow.math.maximum", + sympy.Min: "tensorflow.math.minimum", + + # Matrices + sympy.MatAdd: "tensorflow.math.add", + sympy.HadamardProduct: "tensorflow.math.multiply", + sympy.Trace: "tensorflow.linalg.trace", + + # XXX May raise error for integer matrices. + sympy.Determinant : "tensorflow.linalg.det", + } + + _default_settings = dict( + AbstractPythonCodePrinter._default_settings, + tensorflow_version=None + ) + + def __init__(self, settings=None): + super().__init__(settings) + + version = self._settings['tensorflow_version'] + if version is None and tensorflow: + version = tensorflow.__version__ + self.tensorflow_version = version + + def _print_Function(self, expr): + op = self.mapping.get(type(expr), None) + if op is None: + return super()._print_Basic(expr) + children = [self._print(arg) for arg in expr.args] + if len(children) == 1: + return "%s(%s)" % ( + self._module_format(op), + children[0] + ) + else: + return self._expand_fold_binary_op(op, children) + + _print_Expr = _print_Function + _print_Application = _print_Function + _print_MatrixExpr = _print_Function + # TODO: a better class structure would avoid this mess: + _print_Relational = _print_Function + _print_Not = _print_Function + _print_And = _print_Function + _print_Or = _print_Function + _print_HadamardProduct = _print_Function + _print_Trace = _print_Function + _print_Determinant = _print_Function + + def _print_Inverse(self, expr): + op = self._module_format('tensorflow.linalg.inv') + return "{}({})".format(op, self._print(expr.arg)) + + def _print_Transpose(self, expr): + version = self.tensorflow_version + if version and version_tuple(version) < version_tuple('1.14'): + op = self._module_format('tensorflow.matrix_transpose') + else: + op = self._module_format('tensorflow.linalg.matrix_transpose') + return "{}({})".format(op, self._print(expr.arg)) + + def _print_Derivative(self, expr): + variables = expr.variables + if any(isinstance(i, Iterable) for i in variables): + raise NotImplementedError("derivation by multiple variables is not supported") + def unfold(expr, args): + if not args: + return self._print(expr) + return "%s(%s, %s)[0]" % ( + self._module_format("tensorflow.gradients"), + unfold(expr, args[:-1]), + self._print(args[-1]), + ) + return unfold(expr.expr, variables) + + def _print_Piecewise(self, expr): + version = self.tensorflow_version + if version and version_tuple(version) < version_tuple('1.0'): + tensorflow_piecewise = "tensorflow.select" + else: + tensorflow_piecewise = "tensorflow.where" + + from sympy.functions.elementary.piecewise import Piecewise + e, cond = expr.args[0].args + if len(expr.args) == 1: + return '{}({}, {}, {})'.format( + self._module_format(tensorflow_piecewise), + self._print(cond), + self._print(e), + 0) + + return '{}({}, {}, {})'.format( + self._module_format(tensorflow_piecewise), + self._print(cond), + self._print(e), + self._print(Piecewise(*expr.args[1:]))) + + def _print_Pow(self, expr): + # XXX May raise error for + # int**float or int**complex or float**complex + base, exp = expr.args + if expr.exp == S.Half: + return "{}({})".format( + self._module_format("tensorflow.math.sqrt"), self._print(base)) + return "{}({}, {})".format( + self._module_format("tensorflow.math.pow"), + self._print(base), self._print(exp)) + + def _print_MatrixBase(self, expr): + tensorflow_f = "tensorflow.Variable" if expr.free_symbols else "tensorflow.constant" + data = "["+", ".join(["["+", ".join([self._print(j) for j in i])+"]" for i in expr.tolist()])+"]" + return "%s(%s)" % ( + self._module_format(tensorflow_f), + data, + ) + + def _print_MatMul(self, expr): + from sympy.matrices.expressions import MatrixExpr + mat_args = [arg for arg in expr.args if isinstance(arg, MatrixExpr)] + args = [arg for arg in expr.args if arg not in mat_args] + if args: + return "%s*%s" % ( + self.parenthesize(Mul.fromiter(args), PRECEDENCE["Mul"]), + self._expand_fold_binary_op( + "tensorflow.linalg.matmul", mat_args) + ) + else: + return self._expand_fold_binary_op( + "tensorflow.linalg.matmul", mat_args) + + def _print_MatPow(self, expr): + return self._expand_fold_binary_op( + "tensorflow.linalg.matmul", [expr.base]*expr.exp) + + def _print_CodeBlock(self, expr): + # TODO: is this necessary? + ret = [] + for subexpr in expr.args: + ret.append(self._print(subexpr)) + return "\n".join(ret) + + _module = "tensorflow" + _einsum = "linalg.einsum" + _add = "math.add" + _transpose = "transpose" + _ones = "ones" + _zeros = "zeros" + + +def tensorflow_code(expr, **settings): + printer = TensorflowPrinter(settings) + return printer.doprint(expr) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_aesaracode.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_aesaracode.py new file mode 100644 index 0000000000000000000000000000000000000000..21484626dce990b9e6b9a1bf1900c883c8878105 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_aesaracode.py @@ -0,0 +1,626 @@ +""" +Important note on tests in this module - the Aesara printing functions use a +global cache by default, which means that tests using it will modify global +state and thus not be independent from each other. Instead of using the "cache" +keyword argument each time, this module uses the aesara_code_ and +aesara_function_ functions defined below which default to using a new, empty +cache instead. +""" + +import logging + +from sympy.external import import_module +from sympy.testing.pytest import raises, SKIP + +from sympy.utilities.exceptions import ignore_warnings + + +aesaralogger = logging.getLogger('aesara.configdefaults') +aesaralogger.setLevel(logging.CRITICAL) +aesara = import_module('aesara') +aesaralogger.setLevel(logging.WARNING) + + +if aesara: + import numpy as np + aet = aesara.tensor + from aesara.scalar.basic import Scalar + from aesara.graph.basic import Variable + from aesara.tensor.var import TensorVariable + from aesara.tensor.elemwise import Elemwise, DimShuffle + from aesara.tensor.math import Dot + + from sympy.printing.aesaracode import true_divide + + xt, yt, zt = [aet.scalar(name, 'floatX') for name in 'xyz'] + Xt, Yt, Zt = [aet.tensor('floatX', (False, False), name=n) for n in 'XYZ'] +else: + #bin/test will not execute any tests now + disabled = True + +import sympy as sy +from sympy.core.singleton import S +from sympy.abc import x, y, z, t +from sympy.printing.aesaracode import (aesara_code, dim_handling, + aesara_function) + + +# Default set of matrix symbols for testing - make square so we can both +# multiply and perform elementwise operations between them. +X, Y, Z = [sy.MatrixSymbol(n, 4, 4) for n in 'XYZ'] + +# For testing AppliedUndef +f_t = sy.Function('f')(t) + + +def aesara_code_(expr, **kwargs): + """ Wrapper for aesara_code that uses a new, empty cache by default. """ + kwargs.setdefault('cache', {}) + return aesara_code(expr, **kwargs) + +def aesara_function_(inputs, outputs, **kwargs): + """ Wrapper for aesara_function that uses a new, empty cache by default. """ + kwargs.setdefault('cache', {}) + return aesara_function(inputs, outputs, **kwargs) + + +def fgraph_of(*exprs): + """ Transform SymPy expressions into Aesara Computation. + + Parameters + ========== + exprs + SymPy expressions + + Returns + ======= + aesara.graph.fg.FunctionGraph + """ + outs = list(map(aesara_code_, exprs)) + ins = list(aesara.graph.basic.graph_inputs(outs)) + ins, outs = aesara.graph.basic.clone(ins, outs) + return aesara.graph.fg.FunctionGraph(ins, outs) + + +def aesara_simplify(fgraph): + """ Simplify a Aesara Computation. + + Parameters + ========== + fgraph : aesara.graph.fg.FunctionGraph + + Returns + ======= + aesara.graph.fg.FunctionGraph + """ + mode = aesara.compile.get_default_mode().excluding("fusion") + fgraph = fgraph.clone() + mode.optimizer.optimize(fgraph) + return fgraph + + +def theq(a, b): + """ Test two Aesara objects for equality. + + Also accepts numeric types and lists/tuples of supported types. + + Note - debugprint() has a bug where it will accept numeric types but does + not respect the "file" argument and in this case and instead prints the number + to stdout and returns an empty string. This can lead to tests passing where + they should fail because any two numbers will always compare as equal. To + prevent this we treat numbers as a separate case. + """ + numeric_types = (int, float, np.number) + a_is_num = isinstance(a, numeric_types) + b_is_num = isinstance(b, numeric_types) + + # Compare numeric types using regular equality + if a_is_num or b_is_num: + if not (a_is_num and b_is_num): + return False + + return a == b + + # Compare sequences element-wise + a_is_seq = isinstance(a, (tuple, list)) + b_is_seq = isinstance(b, (tuple, list)) + + if a_is_seq or b_is_seq: + if not (a_is_seq and b_is_seq) or type(a) != type(b): + return False + + return list(map(theq, a)) == list(map(theq, b)) + + # Otherwise, assume debugprint() can handle it + astr = aesara.printing.debugprint(a, file='str') + bstr = aesara.printing.debugprint(b, file='str') + + # Check for bug mentioned above + for argname, argval, argstr in [('a', a, astr), ('b', b, bstr)]: + if argstr == '': + raise TypeError( + 'aesara.printing.debugprint(%s) returned empty string ' + '(%s is instance of %r)' + % (argname, argname, type(argval)) + ) + + return astr == bstr + + +def test_example_symbols(): + """ + Check that the example symbols in this module print to their Aesara + equivalents, as many of the other tests depend on this. + """ + assert theq(xt, aesara_code_(x)) + assert theq(yt, aesara_code_(y)) + assert theq(zt, aesara_code_(z)) + assert theq(Xt, aesara_code_(X)) + assert theq(Yt, aesara_code_(Y)) + assert theq(Zt, aesara_code_(Z)) + + +def test_Symbol(): + """ Test printing a Symbol to a aesara variable. """ + xx = aesara_code_(x) + assert isinstance(xx, Variable) + assert xx.broadcastable == () + assert xx.name == x.name + + xx2 = aesara_code_(x, broadcastables={x: (False,)}) + assert xx2.broadcastable == (False,) + assert xx2.name == x.name + +def test_MatrixSymbol(): + """ Test printing a MatrixSymbol to a aesara variable. """ + XX = aesara_code_(X) + assert isinstance(XX, TensorVariable) + assert XX.broadcastable == (False, False) + +@SKIP # TODO - this is currently not checked but should be implemented +def test_MatrixSymbol_wrong_dims(): + """ Test MatrixSymbol with invalid broadcastable. """ + bcs = [(), (False,), (True,), (True, False), (False, True,), (True, True)] + for bc in bcs: + with raises(ValueError): + aesara_code_(X, broadcastables={X: bc}) + +def test_AppliedUndef(): + """ Test printing AppliedUndef instance, which works similarly to Symbol. """ + ftt = aesara_code_(f_t) + assert isinstance(ftt, TensorVariable) + assert ftt.broadcastable == () + assert ftt.name == 'f_t' + + +def test_add(): + expr = x + y + comp = aesara_code_(expr) + assert comp.owner.op == aesara.tensor.add + +def test_trig(): + assert theq(aesara_code_(sy.sin(x)), aet.sin(xt)) + assert theq(aesara_code_(sy.tan(x)), aet.tan(xt)) + +def test_many(): + """ Test printing a complex expression with multiple symbols. """ + expr = sy.exp(x**2 + sy.cos(y)) * sy.log(2*z) + comp = aesara_code_(expr) + expected = aet.exp(xt**2 + aet.cos(yt)) * aet.log(2*zt) + assert theq(comp, expected) + + +def test_dtype(): + """ Test specifying specific data types through the dtype argument. """ + for dtype in ['float32', 'float64', 'int8', 'int16', 'int32', 'int64']: + assert aesara_code_(x, dtypes={x: dtype}).type.dtype == dtype + + # "floatX" type + assert aesara_code_(x, dtypes={x: 'floatX'}).type.dtype in ('float32', 'float64') + + # Type promotion + assert aesara_code_(x + 1, dtypes={x: 'float32'}).type.dtype == 'float32' + assert aesara_code_(x + y, dtypes={x: 'float64', y: 'float32'}).type.dtype == 'float64' + + +def test_broadcastables(): + """ Test the "broadcastables" argument when printing symbol-like objects. """ + + # No restrictions on shape + for s in [x, f_t]: + for bc in [(), (False,), (True,), (False, False), (True, False)]: + assert aesara_code_(s, broadcastables={s: bc}).broadcastable == bc + + # TODO - matrix broadcasting? + +def test_broadcasting(): + """ Test "broadcastable" attribute after applying element-wise binary op. """ + + expr = x + y + + cases = [ + [(), (), ()], + [(False,), (False,), (False,)], + [(True,), (False,), (False,)], + [(False, True), (False, False), (False, False)], + [(True, False), (False, False), (False, False)], + ] + + for bc1, bc2, bc3 in cases: + comp = aesara_code_(expr, broadcastables={x: bc1, y: bc2}) + assert comp.broadcastable == bc3 + + +def test_MatMul(): + expr = X*Y*Z + expr_t = aesara_code_(expr) + assert isinstance(expr_t.owner.op, Dot) + assert theq(expr_t, Xt.dot(Yt).dot(Zt)) + +def test_Transpose(): + assert isinstance(aesara_code_(X.T).owner.op, DimShuffle) + +def test_MatAdd(): + expr = X+Y+Z + assert isinstance(aesara_code_(expr).owner.op, Elemwise) + + +def test_Rationals(): + assert theq(aesara_code_(sy.Integer(2) / 3), true_divide(2, 3)) + assert theq(aesara_code_(S.Half), true_divide(1, 2)) + +def test_Integers(): + assert aesara_code_(sy.Integer(3)) == 3 + +def test_factorial(): + n = sy.Symbol('n') + assert aesara_code_(sy.factorial(n)) + +def test_Derivative(): + with ignore_warnings(UserWarning): + simp = lambda expr: aesara_simplify(fgraph_of(expr)) + assert theq(simp(aesara_code_(sy.Derivative(sy.sin(x), x, evaluate=False))), + simp(aesara.grad(aet.sin(xt), xt))) + + +def test_aesara_function_simple(): + """ Test aesara_function() with single output. """ + f = aesara_function_([x, y], [x+y]) + assert f(2, 3) == 5 + +def test_aesara_function_multi(): + """ Test aesara_function() with multiple outputs. """ + f = aesara_function_([x, y], [x+y, x-y]) + o1, o2 = f(2, 3) + assert o1 == 5 + assert o2 == -1 + +def test_aesara_function_numpy(): + """ Test aesara_function() vs Numpy implementation. """ + f = aesara_function_([x, y], [x+y], dim=1, + dtypes={x: 'float64', y: 'float64'}) + assert np.linalg.norm(f([1, 2], [3, 4]) - np.asarray([4, 6])) < 1e-9 + + f = aesara_function_([x, y], [x+y], dtypes={x: 'float64', y: 'float64'}, + dim=1) + xx = np.arange(3).astype('float64') + yy = 2*np.arange(3).astype('float64') + assert np.linalg.norm(f(xx, yy) - 3*np.arange(3)) < 1e-9 + + +def test_aesara_function_matrix(): + m = sy.Matrix([[x, y], [z, x + y + z]]) + expected = np.array([[1.0, 2.0], [3.0, 1.0 + 2.0 + 3.0]]) + f = aesara_function_([x, y, z], [m]) + np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected) + f = aesara_function_([x, y, z], [m], scalar=True) + np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected) + f = aesara_function_([x, y, z], [m, m]) + assert isinstance(f(1.0, 2.0, 3.0), type([])) + np.testing.assert_allclose(f(1.0, 2.0, 3.0)[0], expected) + np.testing.assert_allclose(f(1.0, 2.0, 3.0)[1], expected) + +def test_dim_handling(): + assert dim_handling([x], dim=2) == {x: (False, False)} + assert dim_handling([x, y], dims={x: 1, y: 2}) == {x: (False, True), + y: (False, False)} + assert dim_handling([x], broadcastables={x: (False,)}) == {x: (False,)} + +def test_aesara_function_kwargs(): + """ + Test passing additional kwargs from aesara_function() to aesara.function(). + """ + import numpy as np + f = aesara_function_([x, y, z], [x+y], dim=1, on_unused_input='ignore', + dtypes={x: 'float64', y: 'float64', z: 'float64'}) + assert np.linalg.norm(f([1, 2], [3, 4], [0, 0]) - np.asarray([4, 6])) < 1e-9 + + f = aesara_function_([x, y, z], [x+y], + dtypes={x: 'float64', y: 'float64', z: 'float64'}, + dim=1, on_unused_input='ignore') + xx = np.arange(3).astype('float64') + yy = 2*np.arange(3).astype('float64') + zz = 2*np.arange(3).astype('float64') + assert np.linalg.norm(f(xx, yy, zz) - 3*np.arange(3)) < 1e-9 + +def test_aesara_function_scalar(): + """ Test the "scalar" argument to aesara_function(). """ + from aesara.compile.function.types import Function + + args = [ + ([x, y], [x + y], None, [0]), # Single 0d output + ([X, Y], [X + Y], None, [2]), # Single 2d output + ([x, y], [x + y], {x: 0, y: 1}, [1]), # Single 1d output + ([x, y], [x + y, x - y], None, [0, 0]), # Two 0d outputs + ([x, y, X, Y], [x + y, X + Y], None, [0, 2]), # One 0d output, one 2d + ] + + # Create and test functions with and without the scalar setting + for inputs, outputs, in_dims, out_dims in args: + for scalar in [False, True]: + + f = aesara_function_(inputs, outputs, dims=in_dims, scalar=scalar) + + # Check the aesara_function attribute is set whether wrapped or not + assert isinstance(f.aesara_function, Function) + + # Feed in inputs of the appropriate size and get outputs + in_values = [ + np.ones([1 if bc else 5 for bc in i.type.broadcastable]) + for i in f.aesara_function.input_storage + ] + out_values = f(*in_values) + if not isinstance(out_values, list): + out_values = [out_values] + + # Check output types and shapes + assert len(out_dims) == len(out_values) + for d, value in zip(out_dims, out_values): + + if scalar and d == 0: + # Should have been converted to a scalar value + assert isinstance(value, np.number) + + else: + # Otherwise should be an array + assert isinstance(value, np.ndarray) + assert value.ndim == d + +def test_aesara_function_bad_kwarg(): + """ + Passing an unknown keyword argument to aesara_function() should raise an + exception. + """ + raises(Exception, lambda : aesara_function_([x], [x+1], foobar=3)) + + +def test_slice(): + assert aesara_code_(slice(1, 2, 3)) == slice(1, 2, 3) + + def theq_slice(s1, s2): + for attr in ['start', 'stop', 'step']: + a1 = getattr(s1, attr) + a2 = getattr(s2, attr) + if a1 is None or a2 is None: + if not (a1 is None or a2 is None): + return False + elif not theq(a1, a2): + return False + return True + + dtypes = {x: 'int32', y: 'int32'} + assert theq_slice(aesara_code_(slice(x, y), dtypes=dtypes), slice(xt, yt)) + assert theq_slice(aesara_code_(slice(1, x, 3), dtypes=dtypes), slice(1, xt, 3)) + +def test_MatrixSlice(): + cache = {} + + n = sy.Symbol('n', integer=True) + X = sy.MatrixSymbol('X', n, n) + + Y = X[1:2:3, 4:5:6] + Yt = aesara_code_(Y, cache=cache) + + s = Scalar('int64') + assert tuple(Yt.owner.op.idx_list) == (slice(s, s, s), slice(s, s, s)) + assert Yt.owner.inputs[0] == aesara_code_(X, cache=cache) + # == doesn't work in Aesara like it does in SymPy. You have to use + # equals. + assert all(Yt.owner.inputs[i].data == i for i in range(1, 7)) + + k = sy.Symbol('k') + aesara_code_(k, dtypes={k: 'int32'}) + start, stop, step = 4, k, 2 + Y = X[start:stop:step] + Yt = aesara_code_(Y, dtypes={n: 'int32', k: 'int32'}) + # assert Yt.owner.op.idx_list[0].stop == kt + +def test_BlockMatrix(): + n = sy.Symbol('n', integer=True) + A, B, C, D = [sy.MatrixSymbol(name, n, n) for name in 'ABCD'] + At, Bt, Ct, Dt = map(aesara_code_, (A, B, C, D)) + Block = sy.BlockMatrix([[A, B], [C, D]]) + Blockt = aesara_code_(Block) + solutions = [aet.join(0, aet.join(1, At, Bt), aet.join(1, Ct, Dt)), + aet.join(1, aet.join(0, At, Ct), aet.join(0, Bt, Dt))] + assert any(theq(Blockt, solution) for solution in solutions) + +@SKIP +def test_BlockMatrix_Inverse_execution(): + k, n = 2, 4 + dtype = 'float32' + A = sy.MatrixSymbol('A', n, k) + B = sy.MatrixSymbol('B', n, n) + inputs = A, B + output = B.I*A + + cutsizes = {A: [(n//2, n//2), (k//2, k//2)], + B: [(n//2, n//2), (n//2, n//2)]} + cutinputs = [sy.blockcut(i, *cutsizes[i]) for i in inputs] + cutoutput = output.subs(dict(zip(inputs, cutinputs))) + + dtypes = dict(zip(inputs, [dtype]*len(inputs))) + f = aesara_function_(inputs, [output], dtypes=dtypes, cache={}) + fblocked = aesara_function_(inputs, [sy.block_collapse(cutoutput)], + dtypes=dtypes, cache={}) + + ninputs = [np.random.rand(*x.shape).astype(dtype) for x in inputs] + ninputs = [np.arange(n*k).reshape(A.shape).astype(dtype), + np.eye(n).astype(dtype)] + ninputs[1] += np.ones(B.shape)*1e-5 + + assert np.allclose(f(*ninputs), fblocked(*ninputs), rtol=1e-5) + +def test_DenseMatrix(): + from aesara.tensor.basic import Join + + t = sy.Symbol('theta') + for MatrixType in [sy.Matrix, sy.ImmutableMatrix]: + X = MatrixType([[sy.cos(t), -sy.sin(t)], [sy.sin(t), sy.cos(t)]]) + tX = aesara_code_(X) + assert isinstance(tX, TensorVariable) + assert isinstance(tX.owner.op, Join) + + +def test_cache_basic(): + """ Test single symbol-like objects are cached when printed by themselves. """ + + # Pairs of objects which should be considered equivalent with respect to caching + pairs = [ + (x, sy.Symbol('x')), + (X, sy.MatrixSymbol('X', *X.shape)), + (f_t, sy.Function('f')(sy.Symbol('t'))), + ] + + for s1, s2 in pairs: + cache = {} + st = aesara_code_(s1, cache=cache) + + # Test hit with same instance + assert aesara_code_(s1, cache=cache) is st + + # Test miss with same instance but new cache + assert aesara_code_(s1, cache={}) is not st + + # Test hit with different but equivalent instance + assert aesara_code_(s2, cache=cache) is st + +def test_global_cache(): + """ Test use of the global cache. """ + from sympy.printing.aesaracode import global_cache + + backup = dict(global_cache) + try: + # Temporarily empty global cache + global_cache.clear() + + for s in [x, X, f_t]: + st = aesara_code(s) + assert aesara_code(s) is st + + finally: + # Restore global cache + global_cache.update(backup) + +def test_cache_types_distinct(): + """ + Test that symbol-like objects of different types (Symbol, MatrixSymbol, + AppliedUndef) are distinguished by the cache even if they have the same + name. + """ + symbols = [sy.Symbol('f_t'), sy.MatrixSymbol('f_t', 4, 4), f_t] + + cache = {} # Single shared cache + printed = {} + + for s in symbols: + st = aesara_code_(s, cache=cache) + assert st not in printed.values() + printed[s] = st + + # Check all printed objects are distinct + assert len(set(map(id, printed.values()))) == len(symbols) + + # Check retrieving + for s, st in printed.items(): + assert aesara_code(s, cache=cache) is st + +def test_symbols_are_created_once(): + """ + Test that a symbol is cached and reused when it appears in an expression + more than once. + """ + expr = sy.Add(x, x, evaluate=False) + comp = aesara_code_(expr) + + assert theq(comp, xt + xt) + assert not theq(comp, xt + aesara_code_(x)) + +def test_cache_complex(): + """ + Test caching on a complicated expression with multiple symbols appearing + multiple times. + """ + expr = x ** 2 + (y - sy.exp(x)) * sy.sin(z - x * y) + symbol_names = {s.name for s in expr.free_symbols} + expr_t = aesara_code_(expr) + + # Iterate through variables in the Aesara computational graph that the + # printed expression depends on + seen = set() + for v in aesara.graph.basic.ancestors([expr_t]): + # Owner-less, non-constant variables should be our symbols + if v.owner is None and not isinstance(v, aesara.graph.basic.Constant): + # Check it corresponds to a symbol and appears only once + assert v.name in symbol_names + assert v.name not in seen + seen.add(v.name) + + # Check all were present + assert seen == symbol_names + + +def test_Piecewise(): + # A piecewise linear + expr = sy.Piecewise((0, x<0), (x, x<2), (1, True)) # ___/III + result = aesara_code_(expr) + assert result.owner.op == aet.switch + + expected = aet.switch(xt<0, 0, aet.switch(xt<2, xt, 1)) + assert theq(result, expected) + + expr = sy.Piecewise((x, x < 0)) + result = aesara_code_(expr) + expected = aet.switch(xt < 0, xt, np.nan) + assert theq(result, expected) + + expr = sy.Piecewise((0, sy.And(x>0, x<2)), \ + (x, sy.Or(x>2, x<0))) + result = aesara_code_(expr) + expected = aet.switch(aet.and_(xt>0,xt<2), 0, \ + aet.switch(aet.or_(xt>2, xt<0), xt, np.nan)) + assert theq(result, expected) + + +def test_Relationals(): + assert theq(aesara_code_(sy.Eq(x, y)), aet.eq(xt, yt)) + # assert theq(aesara_code_(sy.Ne(x, y)), aet.neq(xt, yt)) # TODO - implement + assert theq(aesara_code_(x > y), xt > yt) + assert theq(aesara_code_(x < y), xt < yt) + assert theq(aesara_code_(x >= y), xt >= yt) + assert theq(aesara_code_(x <= y), xt <= yt) + + +def test_complexfunctions(): + dtypes = {x:'complex128', y:'complex128'} + xt, yt = aesara_code(x, dtypes=dtypes), aesara_code(y, dtypes=dtypes) + from sympy.functions.elementary.complexes import conjugate + from aesara.tensor import as_tensor_variable as atv + from aesara.tensor import complex as cplx + assert theq(aesara_code(y*conjugate(x), dtypes=dtypes), yt*(xt.conj())) + assert theq(aesara_code((1+2j)*x), xt*(atv(1.0)+atv(2.0)*cplx(0,1))) + + +def test_constantfunctions(): + tf = aesara_function([],[1+1j]) + assert(tf()==1+1j) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_c.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_c.py new file mode 100644 index 0000000000000000000000000000000000000000..029294d6c3191b5555df7acb25b133a313bbb05e --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_c.py @@ -0,0 +1,875 @@ +from sympy.core import ( + S, pi, oo, Symbol, symbols, Rational, Integer, Float, Function, Mod, GoldenRatio, EulerGamma, Catalan, + Lambda, Dummy, nan, Mul, Pow, UnevaluatedExpr +) +from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) +from sympy.functions import ( + Abs, acos, acosh, asin, asinh, atan, atanh, atan2, ceiling, cos, cosh, erf, + erfc, exp, floor, gamma, log, loggamma, Max, Min, Piecewise, sign, sin, sinh, + sqrt, tan, tanh, fibonacci, lucas +) +from sympy.sets import Range +from sympy.logic import ITE, Implies, Equivalent +from sympy.codegen import For, aug_assign, Assignment +from sympy.testing.pytest import raises, XFAIL +from sympy.printing.c import C89CodePrinter, C99CodePrinter, get_math_macros +from sympy.codegen.ast import ( + AddAugmentedAssignment, Element, Type, FloatType, Declaration, Pointer, Variable, value_const, pointer_const, + While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall, Return, + real, float32, float64, float80, float128, intc, Comment, CodeBlock +) +from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, fma, log10, Cbrt, hypot, Sqrt +from sympy.codegen.cnodes import restrict +from sympy.utilities.lambdify import implemented_function +from sympy.tensor import IndexedBase, Idx +from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix + +from sympy.printing.codeprinter import ccode + +x, y, z = symbols('x,y,z') + + +def test_printmethod(): + class fabs(Abs): + def _ccode(self, printer): + return "fabs(%s)" % printer._print(self.args[0]) + + assert ccode(fabs(x)) == "fabs(x)" + + +def test_ccode_sqrt(): + assert ccode(sqrt(x)) == "sqrt(x)" + assert ccode(x**0.5) == "sqrt(x)" + assert ccode(sqrt(x)) == "sqrt(x)" + + +def test_ccode_Pow(): + assert ccode(x**3) == "pow(x, 3)" + assert ccode(x**(y**3)) == "pow(x, pow(y, 3))" + g = implemented_function('g', Lambda(x, 2*x)) + assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ + "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2) + y)" + assert ccode(x**-1.0) == '1.0/x' + assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0/3.0)' + assert ccode(x**Rational(2, 3), type_aliases={real: float80}) == 'powl(x, 2.0L/3.0L)' + _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"), + (lambda base, exp: not exp.is_integer, "pow")] + assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)' + assert ccode(x**0.5, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 0.5)' + assert ccode(x**Rational(16, 5), user_functions={'Pow': _cond_cfunc}) == 'pow(x, 16.0/5.0)' + _cond_cfunc2 = [(lambda base, exp: base == 2, lambda base, exp: 'exp2(%s)' % exp), + (lambda base, exp: base != 2, 'pow')] + # Related to gh-11353 + assert ccode(2**x, user_functions={'Pow': _cond_cfunc2}) == 'exp2(x)' + assert ccode(x**2, user_functions={'Pow': _cond_cfunc2}) == 'pow(x, 2)' + # For issue 14160 + assert ccode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), + evaluate=False)) == '-2*x/(y*y)' + + +def test_ccode_Max(): + # Test for gh-11926 + assert ccode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))' + + +def test_ccode_Min_performance(): + #Shouldn't take more than a few seconds + big_min = Min(*symbols('a[0:50]')) + for curr_standard in ('c89', 'c99', 'c11'): + output = ccode(big_min, standard=curr_standard) + assert output.count('(') == output.count(')') + + +def test_ccode_constants_mathh(): + assert ccode(exp(1)) == "M_E" + assert ccode(pi) == "M_PI" + assert ccode(oo, standard='c89') == "HUGE_VAL" + assert ccode(-oo, standard='c89') == "-HUGE_VAL" + assert ccode(oo) == "INFINITY" + assert ccode(-oo, standard='c99') == "-INFINITY" + assert ccode(pi, type_aliases={real: float80}) == "M_PIl" + + +def test_ccode_constants_other(): + assert ccode(2*GoldenRatio) == "const double GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17) + assert ccode( + 2*Catalan) == "const double Catalan = %s;\n2*Catalan" % Catalan.evalf(17) + assert ccode(2*EulerGamma) == "const double EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17) + + +def test_ccode_Rational(): + assert ccode(Rational(3, 7)) == "3.0/7.0" + assert ccode(Rational(3, 7), type_aliases={real: float80}) == "3.0L/7.0L" + assert ccode(Rational(18, 9)) == "2" + assert ccode(Rational(3, -7)) == "-3.0/7.0" + assert ccode(Rational(3, -7), type_aliases={real: float80}) == "-3.0L/7.0L" + assert ccode(Rational(-3, -7)) == "3.0/7.0" + assert ccode(Rational(-3, -7), type_aliases={real: float80}) == "3.0L/7.0L" + assert ccode(x + Rational(3, 7)) == "x + 3.0/7.0" + assert ccode(x + Rational(3, 7), type_aliases={real: float80}) == "x + 3.0L/7.0L" + assert ccode(Rational(3, 7)*x) == "(3.0/7.0)*x" + assert ccode(Rational(3, 7)*x, type_aliases={real: float80}) == "(3.0L/7.0L)*x" + + +def test_ccode_Integer(): + assert ccode(Integer(67)) == "67" + assert ccode(Integer(-1)) == "-1" + + +def test_ccode_functions(): + assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))" + + +def test_ccode_inline_function(): + x = symbols('x') + g = implemented_function('g', Lambda(x, 2*x)) + assert ccode(g(x)) == "2*x" + g = implemented_function('g', Lambda(x, 2*x/Catalan)) + assert ccode( + g(x)) == "const double Catalan = %s;\n2*x/Catalan" % Catalan.evalf(17) + A = IndexedBase('A') + i = Idx('i', symbols('n', integer=True)) + g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) + assert ccode(g(A[i]), assign_to=A[i]) == ( + "for (int i=0; i y" + assert ccode(Ge(x, y)) == "x >= y" + + +def test_ccode_Piecewise(): + expr = Piecewise((x, x < 1), (x**2, True)) + assert ccode(expr) == ( + "((x < 1) ? (\n" + " x\n" + ")\n" + ": (\n" + " pow(x, 2)\n" + "))") + assert ccode(expr, assign_to="c") == ( + "if (x < 1) {\n" + " c = x;\n" + "}\n" + "else {\n" + " c = pow(x, 2);\n" + "}") + expr = Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True)) + assert ccode(expr) == ( + "((x < 1) ? (\n" + " x\n" + ")\n" + ": ((x < 2) ? (\n" + " x + 1\n" + ")\n" + ": (\n" + " pow(x, 2)\n" + ")))") + assert ccode(expr, assign_to='c') == ( + "if (x < 1) {\n" + " c = x;\n" + "}\n" + "else if (x < 2) {\n" + " c = x + 1;\n" + "}\n" + "else {\n" + " c = pow(x, 2);\n" + "}") + # Check that Piecewise without a True (default) condition error + expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) + raises(ValueError, lambda: ccode(expr)) + + +def test_ccode_sinc(): + from sympy.functions.elementary.trigonometric import sinc + expr = sinc(x) + assert ccode(expr) == ( + "((x != 0) ? (\n" + " sin(x)/x\n" + ")\n" + ": (\n" + " 1\n" + "))") + + +def test_ccode_Piecewise_deep(): + p = ccode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True))) + assert p == ( + "2*((x < 1) ? (\n" + " x\n" + ")\n" + ": ((x < 2) ? (\n" + " x + 1\n" + ")\n" + ": (\n" + " pow(x, 2)\n" + ")))") + expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1 + assert ccode(expr) == ( + "pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n" + " 0\n" + ")\n" + ": (\n" + " 1\n" + ")) + cos(z) - 1") + assert ccode(expr, assign_to='c') == ( + "c = pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n" + " 0\n" + ")\n" + ": (\n" + " 1\n" + ")) + cos(z) - 1;") + + +def test_ccode_ITE(): + expr = ITE(x < 1, y, z) + assert ccode(expr) == ( + "((x < 1) ? (\n" + " y\n" + ")\n" + ": (\n" + " z\n" + "))") + + +def test_ccode_settings(): + raises(TypeError, lambda: ccode(sin(x), method="garbage")) + + +def test_ccode_Indexed(): + s, n, m, o = symbols('s n m o', integer=True) + i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) + + x = IndexedBase('x')[j] + A = IndexedBase('A')[i, j] + B = IndexedBase('B')[i, j, k] + + p = C99CodePrinter() + + assert p._print_Indexed(x) == 'x[j]' + assert p._print_Indexed(A) == 'A[%s]' % (m*i+j) + assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k) + + A = IndexedBase('A', shape=(5,3))[i, j] + assert p._print_Indexed(A) == 'A[%s]' % (3*i + j) + + A = IndexedBase('A', shape=(5,3), strides='F')[i, j] + assert ccode(A) == 'A[%s]' % (i + 5*j) + + A = IndexedBase('A', shape=(29,29), strides=(1, s), offset=o)[i, j] + assert ccode(A) == 'A[o + s*j + i]' + + Abase = IndexedBase('A', strides=(s, m, n), offset=o) + assert ccode(Abase[i, j, k]) == 'A[m*j + n*k + o + s*i]' + assert ccode(Abase[2, 3, k]) == 'A[3*m + n*k + o + 2*s]' + + +def test_Element(): + assert ccode(Element('x', 'ij')) == 'x[i][j]' + assert ccode(Element('x', 'ij', strides='kl', offset='o')) == 'x[i*k + j*l + o]' + assert ccode(Element('x', (3,))) == 'x[3]' + assert ccode(Element('x', (3,4,5))) == 'x[3][4][5]' + + +def test_ccode_Indexed_without_looking_for_contraction(): + len_y = 5 + y = IndexedBase('y', shape=(len_y,)) + x = IndexedBase('x', shape=(len_y,)) + Dy = IndexedBase('Dy', shape=(len_y-1,)) + i = Idx('i', len_y-1) + e = Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i])) + code0 = ccode(e.rhs, assign_to=e.lhs, contract=False) + assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1) + + +def test_ccode_loops_matrix_vector(): + n, m = symbols('n m', integer=True) + A = IndexedBase('A') + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + + s = ( + 'for (int i=0; i0), (y, True)), sin(z)]) + A = MatrixSymbol('A', 3, 1) + assert ccode(mat, A) == ( + "A[0] = x*y;\n" + "if (y > 0) {\n" + " A[1] = x + 2;\n" + "}\n" + "else {\n" + " A[1] = y;\n" + "}\n" + "A[2] = sin(z);") + # Test using MatrixElements in expressions + expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] + assert ccode(expr) == ( + "((x > 0) ? (\n" + " 2*A[2]\n" + ")\n" + ": (\n" + " A[2]\n" + ")) + sin(A[1]) + A[0]") + # Test using MatrixElements in a Matrix + q = MatrixSymbol('q', 5, 1) + M = MatrixSymbol('M', 3, 3) + m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], + [q[1,0] + q[2,0], q[3, 0], 5], + [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) + assert ccode(m, M) == ( + "M[0] = sin(q[1]);\n" + "M[1] = 0;\n" + "M[2] = cos(q[2]);\n" + "M[3] = q[1] + q[2];\n" + "M[4] = q[3];\n" + "M[5] = 5;\n" + "M[6] = 2*q[4]/q[1];\n" + "M[7] = sqrt(q[0]) + 4;\n" + "M[8] = 0;") + + +def test_sparse_matrix(): + # gh-15791 + assert 'Not supported in C' in ccode(SparseMatrix([[1, 2, 3]])) + + +def test_ccode_reserved_words(): + x, y = symbols('x, if') + with raises(ValueError): + ccode(y**2, error_on_reserved=True, standard='C99') + assert ccode(y**2) == 'pow(if_, 2)' + assert ccode(x * y**2, dereference=[y]) == 'pow((*if_), 2)*x' + assert ccode(y**2, reserved_word_suffix='_unreserved') == 'pow(if_unreserved, 2)' + + +def test_ccode_sign(): + expr1, ref1 = sign(x) * y, 'y*(((x) > 0) - ((x) < 0))' + expr2, ref2 = sign(cos(x)), '(((cos(x)) > 0) - ((cos(x)) < 0))' + expr3, ref3 = sign(2 * x + x**2) * x + x**2, 'pow(x, 2) + x*(((pow(x, 2) + 2*x) > 0) - ((pow(x, 2) + 2*x) < 0))' + assert ccode(expr1) == ref1 + assert ccode(expr1, 'z') == 'z = %s;' % ref1 + assert ccode(expr2) == ref2 + assert ccode(expr3) == ref3 + +def test_ccode_Assignment(): + assert ccode(Assignment(x, y + z)) == 'x = y + z;' + assert ccode(aug_assign(x, '+', y + z)) == 'x += y + z;' + + +def test_ccode_For(): + f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)]) + assert ccode(f) == ("for (x = 0; x < 10; x += 2) {\n" + " y *= x;\n" + "}") + +def test_ccode_Max_Min(): + assert ccode(Max(x, 0), standard='C89') == '((0 > x) ? 0 : x)' + assert ccode(Max(x, 0), standard='C99') == 'fmax(0, x)' + assert ccode(Min(x, 0, sqrt(x)), standard='c89') == ( + '((0 < ((x < sqrt(x)) ? x : sqrt(x))) ? 0 : ((x < sqrt(x)) ? x : sqrt(x)))' + ) + +def test_ccode_standard(): + assert ccode(expm1(x), standard='c99') == 'expm1(x)' + assert ccode(nan, standard='c99') == 'NAN' + assert ccode(float('nan'), standard='c99') == 'NAN' + + +def test_C89CodePrinter(): + c89printer = C89CodePrinter() + assert c89printer.language == 'C' + assert c89printer.standard == 'C89' + assert 'void' in c89printer.reserved_words + assert 'template' not in c89printer.reserved_words + + +def test_C99CodePrinter(): + assert C99CodePrinter().doprint(expm1(x)) == 'expm1(x)' + assert C99CodePrinter().doprint(log1p(x)) == 'log1p(x)' + assert C99CodePrinter().doprint(exp2(x)) == 'exp2(x)' + assert C99CodePrinter().doprint(log2(x)) == 'log2(x)' + assert C99CodePrinter().doprint(fma(x, y, -z)) == 'fma(x, y, -z)' + assert C99CodePrinter().doprint(log10(x)) == 'log10(x)' + assert C99CodePrinter().doprint(Cbrt(x)) == 'cbrt(x)' # note Cbrt due to cbrt already taken. + assert C99CodePrinter().doprint(hypot(x, y)) == 'hypot(x, y)' + assert C99CodePrinter().doprint(loggamma(x)) == 'lgamma(x)' + assert C99CodePrinter().doprint(Max(x, 3, x**2)) == 'fmax(3, fmax(x, pow(x, 2)))' + assert C99CodePrinter().doprint(Min(x, 3)) == 'fmin(3, x)' + c99printer = C99CodePrinter() + assert c99printer.language == 'C' + assert c99printer.standard == 'C99' + assert 'restrict' in c99printer.reserved_words + assert 'using' not in c99printer.reserved_words + + +@XFAIL +def test_C99CodePrinter__precision_f80(): + f80_printer = C99CodePrinter({"type_aliases": {real: float80}}) + assert f80_printer.doprint(sin(x+Float('2.1'))) == 'sinl(x + 2.1L)' + + +def test_C99CodePrinter__precision(): + n = symbols('n', integer=True) + p = symbols('p', integer=True, positive=True) + f32_printer = C99CodePrinter({"type_aliases": {real: float32}}) + f64_printer = C99CodePrinter({"type_aliases": {real: float64}}) + f80_printer = C99CodePrinter({"type_aliases": {real: float80}}) + assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)' + assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)' + assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)' + + for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']): + def check(expr, ref): + assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper()) + check(Abs(n), 'abs(n)') + check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})') + check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))') + check(exp(x*8.0), 'exp{s}(8.0{S}*x)') + check(exp2(x), 'exp2{s}(x)') + check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)') + check(Mod(p, 2), 'p % 2') + check(Mod(2*p + 3, 3*p + 5, evaluate=False), '(2*p + 3) % (3*p + 5)') + check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})') + check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})') + check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)') + check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)') + check(log2(x*8.0), 'log2{s}(8.0{S}*x)') + check(log1p(x), 'log1p{s}(x)') + check(2**x, 'pow{s}(2, x)') + check(2.0**x, 'pow{s}(2.0{S}, x)') + check(x**3, 'pow{s}(x, 3)') + check(x**4.0, 'pow{s}(x, 4.0{S})') + check(sqrt(3+x), 'sqrt{s}(x + 3)') + check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})') + check(hypot(x, y), 'hypot{s}(x, y)') + check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})') + check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})') + check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})') + check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})') + check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})') + check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})') + check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)') + + check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})') + check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})') + check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})') + check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})') + check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})') + check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})') + check(erf(42.*x), 'erf{s}(42.0{S}*x)') + check(erfc(42.*x), 'erfc{s}(42.0{S}*x)') + check(gamma(x), 'tgamma{s}(x)') + check(loggamma(x), 'lgamma{s}(x)') + + check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})") + check(floor(x + 2.), "floor{s}(x + 2.0{S})") + check(fma(x, y, -z), 'fma{s}(x, y, -z)') + check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))') + check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)') + + +def test_get_math_macros(): + macros = get_math_macros() + assert macros[exp(1)] == 'M_E' + assert macros[1/Sqrt(2)] == 'M_SQRT1_2' + + +def test_ccode_Declaration(): + i = symbols('i', integer=True) + var1 = Variable(i, type=Type.from_expr(i)) + dcl1 = Declaration(var1) + assert ccode(dcl1) == 'int i' + + var2 = Variable(x, type=float32, attrs={value_const}) + dcl2a = Declaration(var2) + assert ccode(dcl2a) == 'const float x' + dcl2b = var2.as_Declaration(value=pi) + assert ccode(dcl2b) == 'const float x = M_PI' + + var3 = Variable(y, type=Type('bool')) + dcl3 = Declaration(var3) + printer = C89CodePrinter() + assert 'stdbool.h' not in printer.headers + assert printer.doprint(dcl3) == 'bool y' + assert 'stdbool.h' in printer.headers + + u = symbols('u', real=True) + ptr4 = Pointer.deduced(u, attrs={pointer_const, restrict}) + dcl4 = Declaration(ptr4) + assert ccode(dcl4) == 'double * const restrict u' + + var5 = Variable(x, Type('__float128'), attrs={value_const}) + dcl5a = Declaration(var5) + assert ccode(dcl5a) == 'const __float128 x' + var5b = Variable(var5.symbol, var5.type, pi, attrs=var5.attrs) + dcl5b = Declaration(var5b) + assert ccode(dcl5b) == 'const __float128 x = M_PI' + + +def test_C99CodePrinter_custom_type(): + # We will look at __float128 (new in glibc 2.26) + f128 = FloatType('_Float128', float128.nbits, float128.nmant, float128.nexp) + p128 = C99CodePrinter({ + "type_aliases": {real: f128}, + "type_literal_suffixes": {f128: 'Q'}, + "type_func_suffixes": {f128: 'f128'}, + "type_math_macro_suffixes": { + real: 'f128', + f128: 'f128' + }, + "type_macros": { + f128: ('__STDC_WANT_IEC_60559_TYPES_EXT__',) + } + }) + assert p128.doprint(x) == 'x' + assert not p128.headers + assert not p128.libraries + assert not p128.macros + assert p128.doprint(2.0) == '2.0Q' + assert not p128.headers + assert not p128.libraries + assert p128.macros == {'__STDC_WANT_IEC_60559_TYPES_EXT__'} + + assert p128.doprint(Rational(1, 2)) == '1.0Q/2.0Q' + assert p128.doprint(sin(x)) == 'sinf128(x)' + assert p128.doprint(cos(2., evaluate=False)) == 'cosf128(2.0Q)' + assert p128.doprint(x**-1.0) == '1.0Q/x' + + var5 = Variable(x, f128, attrs={value_const}) + + dcl5a = Declaration(var5) + assert ccode(dcl5a) == 'const _Float128 x' + var5b = Variable(x, f128, pi, attrs={value_const}) + dcl5b = Declaration(var5b) + assert p128.doprint(dcl5b) == 'const _Float128 x = M_PIf128' + var5b = Variable(x, f128, value=Catalan.evalf(38), attrs={value_const}) + dcl5c = Declaration(var5b) + assert p128.doprint(dcl5c) == 'const _Float128 x = %sQ' % Catalan.evalf(f128.decimal_dig) + + +def test_MatrixElement_printing(): + # test cases for issue #11821 + A = MatrixSymbol("A", 1, 3) + B = MatrixSymbol("B", 1, 3) + C = MatrixSymbol("C", 1, 3) + + assert(ccode(A[0, 0]) == "A[0]") + assert(ccode(3 * A[0, 0]) == "3*A[0]") + + F = C[0, 0].subs(C, A - B) + assert(ccode(F) == "(A - B)[0]") + +def test_ccode_math_macros(): + assert ccode(z + exp(1)) == 'z + M_E' + assert ccode(z + log2(exp(1))) == 'z + M_LOG2E' + assert ccode(z + 1/log(2)) == 'z + M_LOG2E' + assert ccode(z + log(2)) == 'z + M_LN2' + assert ccode(z + log(10)) == 'z + M_LN10' + assert ccode(z + pi) == 'z + M_PI' + assert ccode(z + pi/2) == 'z + M_PI_2' + assert ccode(z + pi/4) == 'z + M_PI_4' + assert ccode(z + 1/pi) == 'z + M_1_PI' + assert ccode(z + 2/pi) == 'z + M_2_PI' + assert ccode(z + 2/sqrt(pi)) == 'z + M_2_SQRTPI' + assert ccode(z + 2/Sqrt(pi)) == 'z + M_2_SQRTPI' + assert ccode(z + sqrt(2)) == 'z + M_SQRT2' + assert ccode(z + Sqrt(2)) == 'z + M_SQRT2' + assert ccode(z + 1/sqrt(2)) == 'z + M_SQRT1_2' + assert ccode(z + 1/Sqrt(2)) == 'z + M_SQRT1_2' + + +def test_ccode_Type(): + assert ccode(Type('float')) == 'float' + assert ccode(intc) == 'int' + + +def test_ccode_codegen_ast(): + # Note that C only allows comments of the form /* ... */, double forward + # slash is not standard C, and some C compilers will grind to a halt upon + # encountering them. + assert ccode(Comment("this is a comment")) == "/* this is a comment */" # not // + assert ccode(While(abs(x) > 1, [aug_assign(x, '-', 1)])) == ( + 'while (fabs(x) > 1) {\n' + ' x -= 1;\n' + '}' + ) + assert ccode(Scope([AddAugmentedAssignment(x, 1)])) == ( + '{\n' + ' x += 1;\n' + '}' + ) + inp_x = Declaration(Variable(x, type=real)) + assert ccode(FunctionPrototype(real, 'pwer', [inp_x])) == 'double pwer(double x)' + assert ccode(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) == ( + 'double pwer(double x){\n' + ' x = pow(x, 2);\n' + '}' + ) + + # Elements of CodeBlock are formatted as statements: + block = CodeBlock( + x, + Print([x, y], "%d %d"), + FunctionCall('pwer', [x]), + Return(x), + ) + assert ccode(block) == '\n'.join([ + 'x;', + 'printf("%d %d", x, y);', + 'pwer(x);', + 'return x;', + ]) + +def test_ccode_UnevaluatedExpr(): + assert ccode(UnevaluatedExpr(y * x) + z) == "z + x*y" + assert ccode(UnevaluatedExpr(y + x) + z) == "z + (x + y)" # gh-21955 + w = symbols('w') + assert ccode(UnevaluatedExpr(y + x) + UnevaluatedExpr(z + w)) == "(w + z) + (x + y)" + + p, q, r = symbols("p q r", real=True) + q_r = UnevaluatedExpr(q + r) + expr = abs(exp(p+q_r)) + assert ccode(expr) == "exp(p + (q + r))" + + +def test_ccode_array_like_containers(): + assert ccode([2,3,4]) == "{2, 3, 4}" + assert ccode((2,3,4)) == "{2, 3, 4}" diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_conventions.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_conventions.py new file mode 100644 index 0000000000000000000000000000000000000000..e8f1fa8532f96130828b89d1ba5ba11fd5bed7a4 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_conventions.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- + +from sympy.core.function import (Derivative, Function) +from sympy.core.numbers import oo +from sympy.core.symbol import symbols +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.trigonometric import cos +from sympy.integrals.integrals import Integral +from sympy.functions.special.bessel import besselj +from sympy.functions.special.polynomials import legendre +from sympy.functions.combinatorial.numbers import bell +from sympy.printing.conventions import split_super_sub, requires_partial +from sympy.testing.pytest import XFAIL + +def test_super_sub(): + assert split_super_sub("beta_13_2") == ("beta", [], ["13", "2"]) + assert split_super_sub("beta_132_20") == ("beta", [], ["132", "20"]) + assert split_super_sub("beta_13") == ("beta", [], ["13"]) + assert split_super_sub("x_a_b") == ("x", [], ["a", "b"]) + assert split_super_sub("x_1_2_3") == ("x", [], ["1", "2", "3"]) + assert split_super_sub("x_a_b1") == ("x", [], ["a", "b1"]) + assert split_super_sub("x_a_1") == ("x", [], ["a", "1"]) + assert split_super_sub("x_1_a") == ("x", [], ["1", "a"]) + assert split_super_sub("x_1^aa") == ("x", ["aa"], ["1"]) + assert split_super_sub("x_1__aa") == ("x", ["aa"], ["1"]) + assert split_super_sub("x_11^a") == ("x", ["a"], ["11"]) + assert split_super_sub("x_11__a") == ("x", ["a"], ["11"]) + assert split_super_sub("x_a_b_c_d") == ("x", [], ["a", "b", "c", "d"]) + assert split_super_sub("x_a_b^c^d") == ("x", ["c", "d"], ["a", "b"]) + assert split_super_sub("x_a_b__c__d") == ("x", ["c", "d"], ["a", "b"]) + assert split_super_sub("x_a^b_c^d") == ("x", ["b", "d"], ["a", "c"]) + assert split_super_sub("x_a__b_c__d") == ("x", ["b", "d"], ["a", "c"]) + assert split_super_sub("x^a^b_c_d") == ("x", ["a", "b"], ["c", "d"]) + assert split_super_sub("x__a__b_c_d") == ("x", ["a", "b"], ["c", "d"]) + assert split_super_sub("x^a^b^c^d") == ("x", ["a", "b", "c", "d"], []) + assert split_super_sub("x__a__b__c__d") == ("x", ["a", "b", "c", "d"], []) + assert split_super_sub("alpha_11") == ("alpha", [], ["11"]) + assert split_super_sub("alpha_11_11") == ("alpha", [], ["11", "11"]) + assert split_super_sub("w1") == ("w", [], ["1"]) + assert split_super_sub("w𝟙") == ("w", [], ["𝟙"]) + assert split_super_sub("w11") == ("w", [], ["11"]) + assert split_super_sub("w𝟙𝟙") == ("w", [], ["𝟙𝟙"]) + assert split_super_sub("w𝟙2𝟙") == ("w", [], ["𝟙2𝟙"]) + assert split_super_sub("w1^a") == ("w", ["a"], ["1"]) + assert split_super_sub("ω1") == ("ω", [], ["1"]) + assert split_super_sub("ω11") == ("ω", [], ["11"]) + assert split_super_sub("ω1^a") == ("ω", ["a"], ["1"]) + assert split_super_sub("ω𝟙^α") == ("ω", ["α"], ["𝟙"]) + assert split_super_sub("ω𝟙2^3α") == ("ω", ["3α"], ["𝟙2"]) + assert split_super_sub("") == ("", [], []) + + +def test_requires_partial(): + x, y, z, t, nu = symbols('x y z t nu') + n = symbols('n', integer=True) + + f = x * y + assert requires_partial(Derivative(f, x)) is True + assert requires_partial(Derivative(f, y)) is True + + ## integrating out one of the variables + assert requires_partial(Derivative(Integral(exp(-x * y), (x, 0, oo)), y, evaluate=False)) is False + + ## bessel function with smooth parameter + f = besselj(nu, x) + assert requires_partial(Derivative(f, x)) is True + assert requires_partial(Derivative(f, nu)) is True + + ## bessel function with integer parameter + f = besselj(n, x) + assert requires_partial(Derivative(f, x)) is False + # this is not really valid (differentiating with respect to an integer) + # but there's no reason to use the partial derivative symbol there. make + # sure we don't throw an exception here, though + assert requires_partial(Derivative(f, n)) is False + + ## bell polynomial + f = bell(n, x) + assert requires_partial(Derivative(f, x)) is False + # again, invalid + assert requires_partial(Derivative(f, n)) is False + + ## legendre polynomial + f = legendre(0, x) + assert requires_partial(Derivative(f, x)) is False + + f = legendre(n, x) + assert requires_partial(Derivative(f, x)) is False + # again, invalid + assert requires_partial(Derivative(f, n)) is False + + f = x ** n + assert requires_partial(Derivative(f, x)) is False + + assert requires_partial(Derivative(Integral((x*y) ** n * exp(-x * y), (x, 0, oo)), y, evaluate=False)) is False + + # parametric equation + f = (exp(t), cos(t)) + g = sum(f) + assert requires_partial(Derivative(g, t)) is False + + f = symbols('f', cls=Function) + assert requires_partial(Derivative(f(x), x)) is False + assert requires_partial(Derivative(f(x), y)) is False + assert requires_partial(Derivative(f(x, y), x)) is True + assert requires_partial(Derivative(f(x, y), y)) is True + assert requires_partial(Derivative(f(x, y), z)) is True + assert requires_partial(Derivative(f(x, y), x, y)) is True + +@XFAIL +def test_requires_partial_unspecified_variables(): + x, y = symbols('x y') + # function of unspecified variables + f = symbols('f', cls=Function) + assert requires_partial(Derivative(f, x)) is False + assert requires_partial(Derivative(f, x, y)) is True diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_cupy.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_cupy.py new file mode 100644 index 0000000000000000000000000000000000000000..32f486596092dcb61fcccddcadac216dba80a763 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_cupy.py @@ -0,0 +1,55 @@ +from sympy.concrete.summations import Sum +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.utilities.lambdify import lambdify +from sympy.abc import x, i, a, b +from sympy.codegen.numpy_nodes import logaddexp +from sympy.printing.numpy import CuPyPrinter, _cupy_known_constants, _cupy_known_functions + +from sympy.testing.pytest import skip +from sympy.external import import_module + +cp = import_module('cupy') + +def test_cupy_print(): + prntr = CuPyPrinter() + assert prntr.doprint(logaddexp(a, b)) == 'cupy.logaddexp(a, b)' + assert prntr.doprint(sqrt(x)) == 'cupy.sqrt(x)' + assert prntr.doprint(log(x)) == 'cupy.log(x)' + assert prntr.doprint("acos(x)") == 'cupy.arccos(x)' + assert prntr.doprint("exp(x)") == 'cupy.exp(x)' + assert prntr.doprint("Abs(x)") == 'abs(x)' + +def test_not_cupy_print(): + prntr = CuPyPrinter() + assert "Not supported" in prntr.doprint("abcd(x)") + +def test_cupy_sum(): + if not cp: + skip("CuPy not installed") + + s = Sum(x ** i, (i, a, b)) + f = lambdify((a, b, x), s, 'cupy') + + a_, b_ = 0, 10 + x_ = cp.linspace(-1, +1, 10) + assert cp.allclose(f(a_, b_, x_), sum(x_ ** i_ for i_ in range(a_, b_ + 1))) + + s = Sum(i * x, (i, a, b)) + f = lambdify((a, b, x), s, 'numpy') + + a_, b_ = 0, 10 + x_ = cp.linspace(-1, +1, 10) + assert cp.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1))) + +def test_cupy_known_funcs_consts(): + assert _cupy_known_constants['NaN'] == 'cupy.nan' + assert _cupy_known_constants['EulerGamma'] == 'cupy.euler_gamma' + + assert _cupy_known_functions['acos'] == 'cupy.arccos' + assert _cupy_known_functions['log'] == 'cupy.log' + +def test_cupy_print_methods(): + prntr = CuPyPrinter() + assert hasattr(prntr, '_print_acos') + assert hasattr(prntr, '_print_log') diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_cxx.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_cxx.py new file mode 100644 index 0000000000000000000000000000000000000000..4753d3feac350e6a968f1b327c5edc2ee5ad23c4 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_cxx.py @@ -0,0 +1,67 @@ +from sympy.core.symbol import symbols +from sympy.functions import beta, Ei, zeta, Max, Min, sqrt, riemann_xi, frac +from sympy.printing.cxx import CXX98CodePrinter, CXX11CodePrinter, CXX17CodePrinter, cxxcode +from sympy.codegen.cfunctions import log1p + + +x, y, u, v = symbols('x y u v') + + +def test_CXX98CodePrinter(): + assert CXX98CodePrinter().doprint(Max(x, 3)) in ('std::max(x, 3)', 'std::max(3, x)') + assert CXX98CodePrinter().doprint(Min(x, 3, sqrt(x))) == 'std::min(3, std::min(x, std::sqrt(x)))' + cxx98printer = CXX98CodePrinter() + assert cxx98printer.language == 'C++' + assert cxx98printer.standard == 'C++98' + assert 'template' in cxx98printer.reserved_words + assert 'alignas' not in cxx98printer.reserved_words + + +def test_CXX11CodePrinter(): + assert CXX11CodePrinter().doprint(log1p(x)) == 'std::log1p(x)' + + cxx11printer = CXX11CodePrinter() + assert cxx11printer.language == 'C++' + assert cxx11printer.standard == 'C++11' + assert 'operator' in cxx11printer.reserved_words + assert 'noexcept' in cxx11printer.reserved_words + assert 'concept' not in cxx11printer.reserved_words + + +def test_subclass_print_method(): + class MyPrinter(CXX11CodePrinter): + def _print_log1p(self, expr): + return 'my_library::log1p(%s)' % ', '.join(map(self._print, expr.args)) + + assert MyPrinter().doprint(log1p(x)) == 'my_library::log1p(x)' + + +def test_subclass_print_method__ns(): + class MyPrinter(CXX11CodePrinter): + _ns = 'my_library::' + + p = CXX11CodePrinter() + myp = MyPrinter() + + assert p.doprint(log1p(x)) == 'std::log1p(x)' + assert myp.doprint(log1p(x)) == 'my_library::log1p(x)' + + +def test_CXX17CodePrinter(): + assert CXX17CodePrinter().doprint(beta(x, y)) == 'std::beta(x, y)' + assert CXX17CodePrinter().doprint(Ei(x)) == 'std::expint(x)' + assert CXX17CodePrinter().doprint(zeta(x)) == 'std::riemann_zeta(x)' + + # Automatic rewrite + assert CXX17CodePrinter().doprint(frac(x)) == 'x - std::floor(x)' + assert CXX17CodePrinter().doprint(riemann_xi(x)) == '(1.0/2.0)*std::pow(M_PI, -1.0/2.0*x)*x*(x - 1)*std::tgamma((1.0/2.0)*x)*std::riemann_zeta(x)' + + +def test_cxxcode(): + assert sorted(cxxcode(sqrt(x)*.5).split('*')) == sorted(['0.5', 'std::sqrt(x)']) + +def test_cxxcode_nested_minmax(): + assert cxxcode(Max(Min(x, y), Min(u, v))) \ + == 'std::max(std::min(u, v), std::min(x, y))' + assert cxxcode(Min(Max(x, y), Max(u, v))) \ + == 'std::min(std::max(u, v), std::max(x, y))' diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_llvmjit.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_llvmjit.py new file mode 100644 index 0000000000000000000000000000000000000000..709476f1d7517dc629210341594a70dc6f41808f --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_llvmjit.py @@ -0,0 +1,224 @@ +from sympy.external import import_module +from sympy.testing.pytest import raises +import ctypes + + +if import_module('llvmlite'): + import sympy.printing.llvmjitcode as g +else: + disabled = True + +import sympy +from sympy.abc import a, b, n + + +# copied from numpy.isclose documentation +def isclose(a, b): + rtol = 1e-5 + atol = 1e-8 + return abs(a-b) <= atol + rtol*abs(b) + + +def test_simple_expr(): + e = a + 1.0 + f = g.llvm_callable([a], e) + res = float(e.subs({a: 4.0}).evalf()) + jit_res = f(4.0) + + assert isclose(jit_res, res) + + +def test_two_arg(): + e = 4.0*a + b + 3.0 + f = g.llvm_callable([a, b], e) + res = float(e.subs({a: 4.0, b: 3.0}).evalf()) + jit_res = f(4.0, 3.0) + + assert isclose(jit_res, res) + + +def test_func(): + e = 4.0*sympy.exp(-a) + f = g.llvm_callable([a], e) + res = float(e.subs({a: 1.5}).evalf()) + jit_res = f(1.5) + + assert isclose(jit_res, res) + + +def test_two_func(): + e = 4.0*sympy.exp(-a) + sympy.exp(b) + f = g.llvm_callable([a, b], e) + res = float(e.subs({a: 1.5, b: 2.0}).evalf()) + jit_res = f(1.5, 2.0) + + assert isclose(jit_res, res) + + +def test_two_sqrt(): + e = 4.0*sympy.sqrt(a) + sympy.sqrt(b) + f = g.llvm_callable([a, b], e) + res = float(e.subs({a: 1.5, b: 2.0}).evalf()) + jit_res = f(1.5, 2.0) + + assert isclose(jit_res, res) + + +def test_two_pow(): + e = a**1.5 + b**7 + f = g.llvm_callable([a, b], e) + res = float(e.subs({a: 1.5, b: 2.0}).evalf()) + jit_res = f(1.5, 2.0) + + assert isclose(jit_res, res) + + +def test_callback(): + e = a + 1.2 + f = g.llvm_callable([a], e, callback_type='scipy.integrate.test') + m = ctypes.c_int(1) + array_type = ctypes.c_double * 1 + inp = {a: 2.2} + array = array_type(inp[a]) + jit_res = f(m, array) + + res = float(e.subs(inp).evalf()) + + assert isclose(jit_res, res) + + +def test_callback_cubature(): + e = a + 1.2 + f = g.llvm_callable([a], e, callback_type='cubature') + m = ctypes.c_int(1) + array_type = ctypes.c_double * 1 + inp = {a: 2.2} + array = array_type(inp[a]) + out_array = array_type(0.0) + jit_ret = f(m, array, None, m, out_array) + + assert jit_ret == 0 + + res = float(e.subs(inp).evalf()) + + assert isclose(out_array[0], res) + + +def test_callback_two(): + e = 3*a*b + f = g.llvm_callable([a, b], e, callback_type='scipy.integrate.test') + m = ctypes.c_int(2) + array_type = ctypes.c_double * 2 + inp = {a: 0.2, b: 1.7} + array = array_type(inp[a], inp[b]) + jit_res = f(m, array) + + res = float(e.subs(inp).evalf()) + + assert isclose(jit_res, res) + + +def test_callback_alt_two(): + d = sympy.IndexedBase('d') + e = 3*d[0]*d[1] + f = g.llvm_callable([n, d], e, callback_type='scipy.integrate.test') + m = ctypes.c_int(2) + array_type = ctypes.c_double * 2 + inp = {d[0]: 0.2, d[1]: 1.7} + array = array_type(inp[d[0]], inp[d[1]]) + jit_res = f(m, array) + + res = float(e.subs(inp).evalf()) + + assert isclose(jit_res, res) + + +def test_multiple_statements(): + # Match return from CSE + e = [[(b, 4.0*a)], [b + 5]] + f = g.llvm_callable([a], e) + b_val = e[0][0][1].subs({a: 1.5}) + res = float(e[1][0].subs({b: b_val}).evalf()) + jit_res = f(1.5) + assert isclose(jit_res, res) + + f_callback = g.llvm_callable([a], e, callback_type='scipy.integrate.test') + m = ctypes.c_int(1) + array_type = ctypes.c_double * 1 + array = array_type(1.5) + jit_callback_res = f_callback(m, array) + assert isclose(jit_callback_res, res) + + +def test_cse(): + e = a*a + b*b + sympy.exp(-a*a - b*b) + e2 = sympy.cse(e) + f = g.llvm_callable([a, b], e2) + res = float(e.subs({a: 2.3, b: 0.1}).evalf()) + jit_res = f(2.3, 0.1) + + assert isclose(jit_res, res) + + +def eval_cse(e, sub_dict): + tmp_dict = {} + for tmp_name, tmp_expr in e[0]: + e2 = tmp_expr.subs(sub_dict) + e3 = e2.subs(tmp_dict) + tmp_dict[tmp_name] = e3 + return [e.subs(sub_dict).subs(tmp_dict) for e in e[1]] + + +def test_cse_multiple(): + e1 = a*a + e2 = a*a + b*b + e3 = sympy.cse([e1, e2]) + + raises(NotImplementedError, + lambda: g.llvm_callable([a, b], e3, callback_type='scipy.integrate')) + + f = g.llvm_callable([a, b], e3) + jit_res = f(0.1, 1.5) + assert len(jit_res) == 2 + res = eval_cse(e3, {a: 0.1, b: 1.5}) + assert isclose(res[0], jit_res[0]) + assert isclose(res[1], jit_res[1]) + + +def test_callback_cubature_multiple(): + e1 = a*a + e2 = a*a + b*b + e3 = sympy.cse([e1, e2, 4*e2]) + f = g.llvm_callable([a, b], e3, callback_type='cubature') + + # Number of input variables + ndim = 2 + # Number of output expression values + outdim = 3 + + m = ctypes.c_int(ndim) + fdim = ctypes.c_int(outdim) + array_type = ctypes.c_double * ndim + out_array_type = ctypes.c_double * outdim + inp = {a: 0.2, b: 1.5} + array = array_type(inp[a], inp[b]) + out_array = out_array_type() + jit_ret = f(m, array, None, fdim, out_array) + + assert jit_ret == 0 + + res = eval_cse(e3, inp) + + assert isclose(out_array[0], res[0]) + assert isclose(out_array[1], res[1]) + assert isclose(out_array[2], res[2]) + + +def test_symbol_not_found(): + e = a*a + b + raises(LookupError, lambda: g.llvm_callable([a], e)) + + +def test_bad_callback(): + e = a + raises(ValueError, lambda: g.llvm_callable([a], e, callback_type='bad_callback')) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_maple.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_maple.py new file mode 100644 index 0000000000000000000000000000000000000000..95cc262ea669d7f6ae7e358d9fd99ac1857c882d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_maple.py @@ -0,0 +1,384 @@ +from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer, + Tuple, Symbol, Eq, Ne, Le, Lt, Gt, Ge) +from sympy.core import EulerGamma, GoldenRatio, Catalan, Lambda, Mul, Pow +from sympy.functions import Piecewise, sqrt, ceiling, exp, sin, cos, sinc, lucas +from sympy.testing.pytest import raises +from sympy.utilities.lambdify import implemented_function +from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity, + HadamardProduct, SparseMatrix) +from sympy.functions.special.bessel import besseli + +from sympy.printing.maple import maple_code + +x, y, z = symbols('x,y,z') + + +def test_Integer(): + assert maple_code(Integer(67)) == "67" + assert maple_code(Integer(-1)) == "-1" + + +def test_Rational(): + assert maple_code(Rational(3, 7)) == "3/7" + assert maple_code(Rational(18, 9)) == "2" + assert maple_code(Rational(3, -7)) == "-3/7" + assert maple_code(Rational(-3, -7)) == "3/7" + assert maple_code(x + Rational(3, 7)) == "x + 3/7" + assert maple_code(Rational(3, 7) * x) == '(3/7)*x' + + +def test_Relational(): + assert maple_code(Eq(x, y)) == "x = y" + assert maple_code(Ne(x, y)) == "x <> y" + assert maple_code(Le(x, y)) == "x <= y" + assert maple_code(Lt(x, y)) == "x < y" + assert maple_code(Gt(x, y)) == "x > y" + assert maple_code(Ge(x, y)) == "x >= y" + + +def test_Function(): + assert maple_code(sin(x) ** cos(x)) == "sin(x)^cos(x)" + assert maple_code(abs(x)) == "abs(x)" + assert maple_code(ceiling(x)) == "ceil(x)" + + +def test_Pow(): + assert maple_code(x ** 3) == "x^3" + assert maple_code(x ** (y ** 3)) == "x^(y^3)" + + assert maple_code((x ** 3) ** y) == "(x^3)^y" + assert maple_code(x ** Rational(2, 3)) == 'x^(2/3)' + + g = implemented_function('g', Lambda(x, 2 * x)) + assert maple_code(1 / (g(x) * 3.5) ** (x - y ** x) / (x ** 2 + y)) == \ + "(3.5*2*x)^(-x + y^x)/(x^2 + y)" + # For issue 14160 + assert maple_code(Mul(-2, x, Pow(Mul(y, y, evaluate=False), -1, evaluate=False), + evaluate=False)) == '-2*x/(y*y)' + + +def test_basic_ops(): + assert maple_code(x * y) == "x*y" + assert maple_code(x + y) == "x + y" + assert maple_code(x - y) == "x - y" + assert maple_code(-x) == "-x" + + +def test_1_over_x_and_sqrt(): + # 1.0 and 0.5 would do something different in regular StrPrinter, + # but these are exact in IEEE floating point so no different here. + assert maple_code(1 / x) == '1/x' + assert maple_code(x ** -1) == maple_code(x ** -1.0) == '1/x' + assert maple_code(1 / sqrt(x)) == '1/sqrt(x)' + assert maple_code(x ** -S.Half) == maple_code(x ** -0.5) == '1/sqrt(x)' + assert maple_code(sqrt(x)) == 'sqrt(x)' + assert maple_code(x ** S.Half) == maple_code(x ** 0.5) == 'sqrt(x)' + assert maple_code(1 / pi) == '1/Pi' + assert maple_code(pi ** -1) == maple_code(pi ** -1.0) == '1/Pi' + assert maple_code(pi ** -0.5) == '1/sqrt(Pi)' + + +def test_mix_number_mult_symbols(): + assert maple_code(3 * x) == "3*x" + assert maple_code(pi * x) == "Pi*x" + assert maple_code(3 / x) == "3/x" + assert maple_code(pi / x) == "Pi/x" + assert maple_code(x / 3) == '(1/3)*x' + assert maple_code(x / pi) == "x/Pi" + assert maple_code(x * y) == "x*y" + assert maple_code(3 * x * y) == "3*x*y" + assert maple_code(3 * pi * x * y) == "3*Pi*x*y" + assert maple_code(x / y) == "x/y" + assert maple_code(3 * x / y) == "3*x/y" + assert maple_code(x * y / z) == "x*y/z" + assert maple_code(x / y * z) == "x*z/y" + assert maple_code(1 / x / y) == "1/(x*y)" + assert maple_code(2 * pi * x / y / z) == "2*Pi*x/(y*z)" + assert maple_code(3 * pi / x) == "3*Pi/x" + assert maple_code(S(3) / 5) == "3/5" + assert maple_code(S(3) / 5 * x) == '(3/5)*x' + assert maple_code(x / y / z) == "x/(y*z)" + assert maple_code((x + y) / z) == "(x + y)/z" + assert maple_code((x + y) / (z + x)) == "(x + y)/(x + z)" + assert maple_code((x + y) / EulerGamma) == '(x + y)/gamma' + assert maple_code(x / 3 / pi) == '(1/3)*x/Pi' + assert maple_code(S(3) / 5 * x * y / pi) == '(3/5)*x*y/Pi' + + +def test_mix_number_pow_symbols(): + assert maple_code(pi ** 3) == 'Pi^3' + assert maple_code(x ** 2) == 'x^2' + + assert maple_code(x ** (pi ** 3)) == 'x^(Pi^3)' + assert maple_code(x ** y) == 'x^y' + + assert maple_code(x ** (y ** z)) == 'x^(y^z)' + assert maple_code((x ** y) ** z) == '(x^y)^z' + + +def test_imag(): + I = S('I') + assert maple_code(I) == "I" + assert maple_code(5 * I) == "5*I" + + assert maple_code((S(3) / 2) * I) == "(3/2)*I" + assert maple_code(3 + 4 * I) == "3 + 4*I" + + +def test_constants(): + assert maple_code(pi) == "Pi" + assert maple_code(oo) == "infinity" + assert maple_code(-oo) == "-infinity" + assert maple_code(S.NegativeInfinity) == "-infinity" + assert maple_code(S.NaN) == "undefined" + assert maple_code(S.Exp1) == "exp(1)" + assert maple_code(exp(1)) == "exp(1)" + + +def test_constants_other(): + assert maple_code(2 * GoldenRatio) == '2*(1/2 + (1/2)*sqrt(5))' + assert maple_code(2 * Catalan) == '2*Catalan' + assert maple_code(2 * EulerGamma) == "2*gamma" + + +def test_boolean(): + assert maple_code(x & y) == "x && y" + assert maple_code(x | y) == "x || y" + assert maple_code(~x) == "!x" + assert maple_code(x & y & z) == "x && y && z" + assert maple_code(x | y | z) == "x || y || z" + assert maple_code((x & y) | z) == "z || x && y" + assert maple_code((x | y) & z) == "z && (x || y)" + + +def test_Matrices(): + assert maple_code(Matrix(1, 1, [10])) == \ + 'Matrix([[10]], storage = rectangular)' + + A = Matrix([[1, sin(x / 2), abs(x)], + [0, 1, pi], + [0, exp(1), ceiling(x)]]) + expected = \ + 'Matrix(' \ + '[[1, sin((1/2)*x), abs(x)],' \ + ' [0, 1, Pi],' \ + ' [0, exp(1), ceil(x)]], ' \ + 'storage = rectangular)' + assert maple_code(A) == expected + + # row and columns + assert maple_code(A[:, 0]) == \ + 'Matrix([[1], [0], [0]], storage = rectangular)' + assert maple_code(A[0, :]) == \ + 'Matrix([[1, sin((1/2)*x), abs(x)]], storage = rectangular)' + assert maple_code(Matrix([[x, x - y, -y]])) == \ + 'Matrix([[x, x - y, -y]], storage = rectangular)' + + # empty matrices + assert maple_code(Matrix(0, 0, [])) == \ + 'Matrix([], storage = rectangular)' + assert maple_code(Matrix(0, 3, [])) == \ + 'Matrix([], storage = rectangular)' + +def test_SparseMatrices(): + assert maple_code(SparseMatrix(Identity(2))) == 'Matrix([[1, 0], [0, 1]], storage = sparse)' + + +def test_vector_entries_hadamard(): + # For a row or column, user might to use the other dimension + A = Matrix([[1, sin(2 / x), 3 * pi / x / 5]]) + assert maple_code(A) == \ + 'Matrix([[1, sin(2/x), (3/5)*Pi/x]], storage = rectangular)' + assert maple_code(A.T) == \ + 'Matrix([[1], [sin(2/x)], [(3/5)*Pi/x]], storage = rectangular)' + + +def test_Matrices_entries_not_hadamard(): + A = Matrix([[1, sin(2 / x), 3 * pi / x / 5], [1, 2, x * y]]) + expected = \ + 'Matrix([[1, sin(2/x), (3/5)*Pi/x], [1, 2, x*y]], ' \ + 'storage = rectangular)' + assert maple_code(A) == expected + + +def test_MatrixSymbol(): + n = Symbol('n', integer=True) + A = MatrixSymbol('A', n, n) + B = MatrixSymbol('B', n, n) + assert maple_code(A * B) == "A.B" + assert maple_code(B * A) == "B.A" + assert maple_code(2 * A * B) == "2*A.B" + assert maple_code(B * 2 * A) == "2*B.A" + + assert maple_code( + A * (B + 3 * Identity(n))) == "A.(3*Matrix(n, shape = identity) + B)" + + assert maple_code(A ** (x ** 2)) == "MatrixPower(A, x^2)" + assert maple_code(A ** 3) == "MatrixPower(A, 3)" + assert maple_code(A ** (S.Half)) == "MatrixPower(A, 1/2)" + + +def test_special_matrices(): + assert maple_code(6 * Identity(3)) == "6*Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], storage = sparse)" + assert maple_code(Identity(x)) == 'Matrix(x, shape = identity)' + + +def test_containers(): + assert maple_code([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \ + "[1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]" + + assert maple_code((1, 2, (3, 4))) == "[1, 2, [3, 4]]" + assert maple_code([1]) == "[1]" + assert maple_code((1,)) == "[1]" + assert maple_code(Tuple(*[1, 2, 3])) == "[1, 2, 3]" + assert maple_code((1, x * y, (3, x ** 2))) == "[1, x*y, [3, x^2]]" + # scalar, matrix, empty matrix and empty list + + assert maple_code((1, eye(3), Matrix(0, 0, []), [])) == \ + "[1, Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], storage = rectangular), Matrix([], storage = rectangular), []]" + + +def test_maple_noninline(): + source = maple_code((x + y)/Catalan, assign_to='me', inline=False) + expected = "me := (x + y)/Catalan" + + assert source == expected + + +def test_maple_matrix_assign_to(): + A = Matrix([[1, 2, 3]]) + assert maple_code(A, assign_to='a') == "a := Matrix([[1, 2, 3]], storage = rectangular)" + A = Matrix([[1, 2], [3, 4]]) + assert maple_code(A, assign_to='A') == "A := Matrix([[1, 2], [3, 4]], storage = rectangular)" + + +def test_maple_matrix_assign_to_more(): + # assigning to Symbol or MatrixSymbol requires lhs/rhs match + A = Matrix([[1, 2, 3]]) + B = MatrixSymbol('B', 1, 3) + C = MatrixSymbol('C', 2, 3) + assert maple_code(A, assign_to=B) == "B := Matrix([[1, 2, 3]], storage = rectangular)" + raises(ValueError, lambda: maple_code(A, assign_to=x)) + raises(ValueError, lambda: maple_code(A, assign_to=C)) + + +def test_maple_matrix_1x1(): + A = Matrix([[3]]) + assert maple_code(A, assign_to='B') == "B := Matrix([[3]], storage = rectangular)" + + +def test_maple_matrix_elements(): + A = Matrix([[x, 2, x * y]]) + + assert maple_code(A[0, 0] ** 2 + A[0, 1] + A[0, 2]) == "x^2 + x*y + 2" + AA = MatrixSymbol('AA', 1, 3) + assert maple_code(AA) == "AA" + + assert maple_code(AA[0, 0] ** 2 + sin(AA[0, 1]) + AA[0, 2]) == \ + "sin(AA[1, 2]) + AA[1, 1]^2 + AA[1, 3]" + assert maple_code(sum(AA)) == "AA[1, 1] + AA[1, 2] + AA[1, 3]" + + +def test_maple_boolean(): + assert maple_code(True) == "true" + assert maple_code(S.true) == "true" + assert maple_code(False) == "false" + assert maple_code(S.false) == "false" + + +def test_sparse(): + M = SparseMatrix(5, 6, {}) + M[2, 2] = 10 + M[1, 2] = 20 + M[1, 3] = 22 + M[0, 3] = 30 + M[3, 0] = x * y + assert maple_code(M) == \ + 'Matrix([[0, 0, 0, 30, 0, 0],' \ + ' [0, 0, 20, 22, 0, 0],' \ + ' [0, 0, 10, 0, 0, 0],' \ + ' [x*y, 0, 0, 0, 0, 0],' \ + ' [0, 0, 0, 0, 0, 0]], ' \ + 'storage = sparse)' + +# Not an important point. +def test_maple_not_supported(): + assert maple_code(S.ComplexInfinity) == ( + "# Not supported in maple:\n" + "# ComplexInfinity\n" + "zoo" + ) # PROBLEM + + +def test_MatrixElement_printing(): + # test cases for issue #11821 + A = MatrixSymbol("A", 1, 3) + B = MatrixSymbol("B", 1, 3) + + assert (maple_code(A[0, 0]) == "A[1, 1]") + assert (maple_code(3 * A[0, 0]) == "3*A[1, 1]") + + F = A-B + + assert (maple_code(F[0,0]) == "A[1, 1] - B[1, 1]") + + +def test_hadamard(): + A = MatrixSymbol('A', 3, 3) + B = MatrixSymbol('B', 3, 3) + v = MatrixSymbol('v', 3, 1) + h = MatrixSymbol('h', 1, 3) + C = HadamardProduct(A, B) + assert maple_code(C) == "A*B" + + assert maple_code(C * v) == "(A*B).v" + # HadamardProduct is higher than dot product. + + assert maple_code(h * C * v) == "h.(A*B).v" + + assert maple_code(C * A) == "(A*B).A" + # mixing Hadamard and scalar strange b/c we vectorize scalars + + assert maple_code(C * x * y) == "x*y*(A*B)" + + +def test_maple_piecewise(): + expr = Piecewise((x, x < 1), (x ** 2, True)) + + assert maple_code(expr) == "piecewise(x < 1, x, x^2)" + assert maple_code(expr, assign_to="r") == ( + "r := piecewise(x < 1, x, x^2)") + + expr = Piecewise((x ** 2, x < 1), (x ** 3, x < 2), (x ** 4, x < 3), (x ** 5, True)) + expected = "piecewise(x < 1, x^2, x < 2, x^3, x < 3, x^4, x^5)" + assert maple_code(expr) == expected + assert maple_code(expr, assign_to="r") == "r := " + expected + + # Check that Piecewise without a True (default) condition error + expr = Piecewise((x, x < 1), (x ** 2, x > 1), (sin(x), x > 0)) + raises(ValueError, lambda: maple_code(expr)) + + +def test_maple_piecewise_times_const(): + pw = Piecewise((x, x < 1), (x ** 2, True)) + + assert maple_code(2 * pw) == "2*piecewise(x < 1, x, x^2)" + assert maple_code(pw / x) == "piecewise(x < 1, x, x^2)/x" + assert maple_code(pw / (x * y)) == "piecewise(x < 1, x, x^2)/(x*y)" + assert maple_code(pw / 3) == "(1/3)*piecewise(x < 1, x, x^2)" + + +def test_maple_derivatives(): + f = Function('f') + assert maple_code(f(x).diff(x)) == 'diff(f(x), x)' + assert maple_code(f(x).diff(x, 2)) == 'diff(f(x), x$2)' + + +def test_automatic_rewrites(): + assert maple_code(lucas(x)) == '2^(-x)*((1 - sqrt(5))^x + (1 + sqrt(5))^x)' + assert maple_code(sinc(x)) == 'piecewise(x <> 0, sin(x)/x, 1)' + + +def test_specfun(): + assert maple_code('asin(x)') == 'arcsin(x)' + assert maple_code(besseli(x, y)) == 'BesselI(x, y)' diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_octave.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_octave.py new file mode 100644 index 0000000000000000000000000000000000000000..0af907eb89dd801a8d6135292d6a8aaf94399d4e --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_octave.py @@ -0,0 +1,523 @@ +from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer, + Tuple, Symbol, EulerGamma, GoldenRatio, Catalan, + Lambda, Mul, Pow, Mod, Eq, Ne, Le, Lt, Gt, Ge) +from sympy.codegen.matrix_nodes import MatrixSolve +from sympy.functions import (arg, atan2, bernoulli, beta, ceiling, chebyshevu, + chebyshevt, conjugate, DiracDelta, exp, expint, + factorial, floor, harmonic, Heaviside, im, + laguerre, LambertW, log, Max, Min, Piecewise, + polylog, re, RisingFactorial, sign, sinc, sqrt, + zeta, binomial, legendre, dirichlet_eta, + riemann_xi) +from sympy.functions import (sin, cos, tan, cot, sec, csc, asin, acos, acot, + atan, asec, acsc, sinh, cosh, tanh, coth, csch, + sech, asinh, acosh, atanh, acoth, asech, acsch) +from sympy.testing.pytest import raises, XFAIL +from sympy.utilities.lambdify import implemented_function +from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity, + HadamardProduct, SparseMatrix, HadamardPower) +from sympy.functions.special.bessel import (jn, yn, besselj, bessely, besseli, + besselk, hankel1, hankel2, airyai, + airybi, airyaiprime, airybiprime) +from sympy.functions.special.gamma_functions import (gamma, lowergamma, + uppergamma, loggamma, + polygamma) +from sympy.functions.special.error_functions import (Chi, Ci, erf, erfc, erfi, + erfcinv, erfinv, fresnelc, + fresnels, li, Shi, Si, Li, + erf2, Ei) +from sympy.printing.octave import octave_code, octave_code as mcode + +x, y, z = symbols('x,y,z') + + +def test_Integer(): + assert mcode(Integer(67)) == "67" + assert mcode(Integer(-1)) == "-1" + + +def test_Rational(): + assert mcode(Rational(3, 7)) == "3/7" + assert mcode(Rational(18, 9)) == "2" + assert mcode(Rational(3, -7)) == "-3/7" + assert mcode(Rational(-3, -7)) == "3/7" + assert mcode(x + Rational(3, 7)) == "x + 3/7" + assert mcode(Rational(3, 7)*x) == "3*x/7" + + +def test_Relational(): + assert mcode(Eq(x, y)) == "x == y" + assert mcode(Ne(x, y)) == "x != y" + assert mcode(Le(x, y)) == "x <= y" + assert mcode(Lt(x, y)) == "x < y" + assert mcode(Gt(x, y)) == "x > y" + assert mcode(Ge(x, y)) == "x >= y" + + +def test_Function(): + assert mcode(sin(x) ** cos(x)) == "sin(x).^cos(x)" + assert mcode(sign(x)) == "sign(x)" + assert mcode(exp(x)) == "exp(x)" + assert mcode(log(x)) == "log(x)" + assert mcode(factorial(x)) == "factorial(x)" + assert mcode(floor(x)) == "floor(x)" + assert mcode(atan2(y, x)) == "atan2(y, x)" + assert mcode(beta(x, y)) == 'beta(x, y)' + assert mcode(polylog(x, y)) == 'polylog(x, y)' + assert mcode(harmonic(x)) == 'harmonic(x)' + assert mcode(bernoulli(x)) == "bernoulli(x)" + assert mcode(bernoulli(x, y)) == "bernoulli(x, y)" + assert mcode(legendre(x, y)) == "legendre(x, y)" + + +def test_Function_change_name(): + assert mcode(abs(x)) == "abs(x)" + assert mcode(ceiling(x)) == "ceil(x)" + assert mcode(arg(x)) == "angle(x)" + assert mcode(im(x)) == "imag(x)" + assert mcode(re(x)) == "real(x)" + assert mcode(conjugate(x)) == "conj(x)" + assert mcode(chebyshevt(y, x)) == "chebyshevT(y, x)" + assert mcode(chebyshevu(y, x)) == "chebyshevU(y, x)" + assert mcode(laguerre(x, y)) == "laguerreL(x, y)" + assert mcode(Chi(x)) == "coshint(x)" + assert mcode(Shi(x)) == "sinhint(x)" + assert mcode(Ci(x)) == "cosint(x)" + assert mcode(Si(x)) == "sinint(x)" + assert mcode(li(x)) == "logint(x)" + assert mcode(loggamma(x)) == "gammaln(x)" + assert mcode(polygamma(x, y)) == "psi(x, y)" + assert mcode(RisingFactorial(x, y)) == "pochhammer(x, y)" + assert mcode(DiracDelta(x)) == "dirac(x)" + assert mcode(DiracDelta(x, 3)) == "dirac(3, x)" + assert mcode(Heaviside(x)) == "heaviside(x, 1/2)" + assert mcode(Heaviside(x, y)) == "heaviside(x, y)" + assert mcode(binomial(x, y)) == "bincoeff(x, y)" + assert mcode(Mod(x, y)) == "mod(x, y)" + + +def test_minmax(): + assert mcode(Max(x, y) + Min(x, y)) == "max(x, y) + min(x, y)" + assert mcode(Max(x, y, z)) == "max(x, max(y, z))" + assert mcode(Min(x, y, z)) == "min(x, min(y, z))" + + +def test_Pow(): + assert mcode(x**3) == "x.^3" + assert mcode(x**(y**3)) == "x.^(y.^3)" + assert mcode(x**Rational(2, 3)) == 'x.^(2/3)' + g = implemented_function('g', Lambda(x, 2*x)) + assert mcode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ + "(3.5*2*x).^(-x + y.^x)./(x.^2 + y)" + # For issue 14160 + assert mcode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), + evaluate=False)) == '-2*x./(y.*y)' + + +def test_basic_ops(): + assert mcode(x*y) == "x.*y" + assert mcode(x + y) == "x + y" + assert mcode(x - y) == "x - y" + assert mcode(-x) == "-x" + + +def test_1_over_x_and_sqrt(): + # 1.0 and 0.5 would do something different in regular StrPrinter, + # but these are exact in IEEE floating point so no different here. + assert mcode(1/x) == '1./x' + assert mcode(x**-1) == mcode(x**-1.0) == '1./x' + assert mcode(1/sqrt(x)) == '1./sqrt(x)' + assert mcode(x**-S.Half) == mcode(x**-0.5) == '1./sqrt(x)' + assert mcode(sqrt(x)) == 'sqrt(x)' + assert mcode(x**S.Half) == mcode(x**0.5) == 'sqrt(x)' + assert mcode(1/pi) == '1/pi' + assert mcode(pi**-1) == mcode(pi**-1.0) == '1/pi' + assert mcode(pi**-0.5) == '1/sqrt(pi)' + + +def test_mix_number_mult_symbols(): + assert mcode(3*x) == "3*x" + assert mcode(pi*x) == "pi*x" + assert mcode(3/x) == "3./x" + assert mcode(pi/x) == "pi./x" + assert mcode(x/3) == "x/3" + assert mcode(x/pi) == "x/pi" + assert mcode(x*y) == "x.*y" + assert mcode(3*x*y) == "3*x.*y" + assert mcode(3*pi*x*y) == "3*pi*x.*y" + assert mcode(x/y) == "x./y" + assert mcode(3*x/y) == "3*x./y" + assert mcode(x*y/z) == "x.*y./z" + assert mcode(x/y*z) == "x.*z./y" + assert mcode(1/x/y) == "1./(x.*y)" + assert mcode(2*pi*x/y/z) == "2*pi*x./(y.*z)" + assert mcode(3*pi/x) == "3*pi./x" + assert mcode(S(3)/5) == "3/5" + assert mcode(S(3)/5*x) == "3*x/5" + assert mcode(x/y/z) == "x./(y.*z)" + assert mcode((x+y)/z) == "(x + y)./z" + assert mcode((x+y)/(z+x)) == "(x + y)./(x + z)" + assert mcode((x+y)/EulerGamma) == "(x + y)/%s" % EulerGamma.evalf(17) + assert mcode(x/3/pi) == "x/(3*pi)" + assert mcode(S(3)/5*x*y/pi) == "3*x.*y/(5*pi)" + + +def test_mix_number_pow_symbols(): + assert mcode(pi**3) == 'pi^3' + assert mcode(x**2) == 'x.^2' + assert mcode(x**(pi**3)) == 'x.^(pi^3)' + assert mcode(x**y) == 'x.^y' + assert mcode(x**(y**z)) == 'x.^(y.^z)' + assert mcode((x**y)**z) == '(x.^y).^z' + + +def test_imag(): + I = S('I') + assert mcode(I) == "1i" + assert mcode(5*I) == "5i" + assert mcode((S(3)/2)*I) == "3*1i/2" + assert mcode(3+4*I) == "3 + 4i" + assert mcode(sqrt(3)*I) == "sqrt(3)*1i" + + +def test_constants(): + assert mcode(pi) == "pi" + assert mcode(oo) == "inf" + assert mcode(-oo) == "-inf" + assert mcode(S.NegativeInfinity) == "-inf" + assert mcode(S.NaN) == "NaN" + assert mcode(S.Exp1) == "exp(1)" + assert mcode(exp(1)) == "exp(1)" + + +def test_constants_other(): + assert mcode(2*GoldenRatio) == "2*(1+sqrt(5))/2" + assert mcode(2*Catalan) == "2*%s" % Catalan.evalf(17) + assert mcode(2*EulerGamma) == "2*%s" % EulerGamma.evalf(17) + + +def test_boolean(): + assert mcode(x & y) == "x & y" + assert mcode(x | y) == "x | y" + assert mcode(~x) == "~x" + assert mcode(x & y & z) == "x & y & z" + assert mcode(x | y | z) == "x | y | z" + assert mcode((x & y) | z) == "z | x & y" + assert mcode((x | y) & z) == "z & (x | y)" + + +def test_KroneckerDelta(): + from sympy.functions import KroneckerDelta + assert mcode(KroneckerDelta(x, y)) == "double(x == y)" + assert mcode(KroneckerDelta(x, y + 1)) == "double(x == (y + 1))" + assert mcode(KroneckerDelta(2**x, y)) == "double((2.^x) == y)" + + +def test_Matrices(): + assert mcode(Matrix(1, 1, [10])) == "10" + A = Matrix([[1, sin(x/2), abs(x)], + [0, 1, pi], + [0, exp(1), ceiling(x)]]); + expected = "[1 sin(x/2) abs(x); 0 1 pi; 0 exp(1) ceil(x)]" + assert mcode(A) == expected + # row and columns + assert mcode(A[:,0]) == "[1; 0; 0]" + assert mcode(A[0,:]) == "[1 sin(x/2) abs(x)]" + # empty matrices + assert mcode(Matrix(0, 0, [])) == '[]' + assert mcode(Matrix(0, 3, [])) == 'zeros(0, 3)' + # annoying to read but correct + assert mcode(Matrix([[x, x - y, -y]])) == "[x x - y -y]" + + +def test_vector_entries_hadamard(): + # For a row or column, user might to use the other dimension + A = Matrix([[1, sin(2/x), 3*pi/x/5]]) + assert mcode(A) == "[1 sin(2./x) 3*pi./(5*x)]" + assert mcode(A.T) == "[1; sin(2./x); 3*pi./(5*x)]" + + +@XFAIL +def test_Matrices_entries_not_hadamard(): + # For Matrix with col >= 2, row >= 2, they need to be scalars + # FIXME: is it worth worrying about this? Its not wrong, just + # leave it user's responsibility to put scalar data for x. + A = Matrix([[1, sin(2/x), 3*pi/x/5], [1, 2, x*y]]) + expected = ("[1 sin(2/x) 3*pi/(5*x);\n" + "1 2 x*y]") # <- we give x.*y + assert mcode(A) == expected + + +def test_MatrixSymbol(): + n = Symbol('n', integer=True) + A = MatrixSymbol('A', n, n) + B = MatrixSymbol('B', n, n) + assert mcode(A*B) == "A*B" + assert mcode(B*A) == "B*A" + assert mcode(2*A*B) == "2*A*B" + assert mcode(B*2*A) == "2*B*A" + assert mcode(A*(B + 3*Identity(n))) == "A*(3*eye(n) + B)" + assert mcode(A**(x**2)) == "A^(x.^2)" + assert mcode(A**3) == "A^3" + assert mcode(A**S.Half) == "A^(1/2)" + + +def test_MatrixSolve(): + n = Symbol('n', integer=True) + A = MatrixSymbol('A', n, n) + x = MatrixSymbol('x', n, 1) + assert mcode(MatrixSolve(A, x)) == "A \\ x" + +def test_special_matrices(): + assert mcode(6*Identity(3)) == "6*eye(3)" + + +def test_containers(): + assert mcode([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \ + "{1, 2, 3, {4, 5, {6, 7}}, 8, {9, 10}, 11}" + assert mcode((1, 2, (3, 4))) == "{1, 2, {3, 4}}" + assert mcode([1]) == "{1}" + assert mcode((1,)) == "{1}" + assert mcode(Tuple(*[1, 2, 3])) == "{1, 2, 3}" + assert mcode((1, x*y, (3, x**2))) == "{1, x.*y, {3, x.^2}}" + # scalar, matrix, empty matrix and empty list + assert mcode((1, eye(3), Matrix(0, 0, []), [])) == "{1, [1 0 0; 0 1 0; 0 0 1], [], {}}" + + +def test_octave_noninline(): + source = mcode((x+y)/Catalan, assign_to='me', inline=False) + expected = ( + "Catalan = %s;\n" + "me = (x + y)/Catalan;" + ) % Catalan.evalf(17) + assert source == expected + + +def test_octave_piecewise(): + expr = Piecewise((x, x < 1), (x**2, True)) + assert mcode(expr) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))" + assert mcode(expr, assign_to="r") == ( + "r = ((x < 1).*(x) + (~(x < 1)).*(x.^2));") + assert mcode(expr, assign_to="r", inline=False) == ( + "if (x < 1)\n" + " r = x;\n" + "else\n" + " r = x.^2;\n" + "end") + expr = Piecewise((x**2, x < 1), (x**3, x < 2), (x**4, x < 3), (x**5, True)) + expected = ("((x < 1).*(x.^2) + (~(x < 1)).*( ...\n" + "(x < 2).*(x.^3) + (~(x < 2)).*( ...\n" + "(x < 3).*(x.^4) + (~(x < 3)).*(x.^5))))") + assert mcode(expr) == expected + assert mcode(expr, assign_to="r") == "r = " + expected + ";" + assert mcode(expr, assign_to="r", inline=False) == ( + "if (x < 1)\n" + " r = x.^2;\n" + "elseif (x < 2)\n" + " r = x.^3;\n" + "elseif (x < 3)\n" + " r = x.^4;\n" + "else\n" + " r = x.^5;\n" + "end") + # Check that Piecewise without a True (default) condition error + expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) + raises(ValueError, lambda: mcode(expr)) + + +def test_octave_piecewise_times_const(): + pw = Piecewise((x, x < 1), (x**2, True)) + assert mcode(2*pw) == "2*((x < 1).*(x) + (~(x < 1)).*(x.^2))" + assert mcode(pw/x) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))./x" + assert mcode(pw/(x*y)) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))./(x.*y)" + assert mcode(pw/3) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))/3" + + +def test_octave_matrix_assign_to(): + A = Matrix([[1, 2, 3]]) + assert mcode(A, assign_to='a') == "a = [1 2 3];" + A = Matrix([[1, 2], [3, 4]]) + assert mcode(A, assign_to='A') == "A = [1 2; 3 4];" + + +def test_octave_matrix_assign_to_more(): + # assigning to Symbol or MatrixSymbol requires lhs/rhs match + A = Matrix([[1, 2, 3]]) + B = MatrixSymbol('B', 1, 3) + C = MatrixSymbol('C', 2, 3) + assert mcode(A, assign_to=B) == "B = [1 2 3];" + raises(ValueError, lambda: mcode(A, assign_to=x)) + raises(ValueError, lambda: mcode(A, assign_to=C)) + + +def test_octave_matrix_1x1(): + A = Matrix([[3]]) + B = MatrixSymbol('B', 1, 1) + C = MatrixSymbol('C', 1, 2) + assert mcode(A, assign_to=B) == "B = 3;" + # FIXME? + #assert mcode(A, assign_to=x) == "x = 3;" + raises(ValueError, lambda: mcode(A, assign_to=C)) + + +def test_octave_matrix_elements(): + A = Matrix([[x, 2, x*y]]) + assert mcode(A[0, 0]**2 + A[0, 1] + A[0, 2]) == "x.^2 + x.*y + 2" + A = MatrixSymbol('AA', 1, 3) + assert mcode(A) == "AA" + assert mcode(A[0, 0]**2 + sin(A[0,1]) + A[0,2]) == \ + "sin(AA(1, 2)) + AA(1, 1).^2 + AA(1, 3)" + assert mcode(sum(A)) == "AA(1, 1) + AA(1, 2) + AA(1, 3)" + + +def test_octave_boolean(): + assert mcode(True) == "true" + assert mcode(S.true) == "true" + assert mcode(False) == "false" + assert mcode(S.false) == "false" + + +def test_octave_not_supported(): + assert mcode(S.ComplexInfinity) == ( + "% Not supported in Octave:\n" + "% ComplexInfinity\n" + "zoo" + ) + f = Function('f') + assert mcode(f(x).diff(x)) == ( + "% Not supported in Octave:\n" + "% Derivative\n" + "Derivative(f(x), x)" + ) + + +def test_octave_not_supported_not_on_whitelist(): + from sympy.functions.special.polynomials import assoc_laguerre + assert mcode(assoc_laguerre(x, y, z)) == ( + "% Not supported in Octave:\n" + "% assoc_laguerre\n" + "assoc_laguerre(x, y, z)" + ) + + +def test_octave_expint(): + assert mcode(expint(1, x)) == "expint(x)" + assert mcode(expint(2, x)) == ( + "% Not supported in Octave:\n" + "% expint\n" + "expint(2, x)" + ) + assert mcode(expint(y, x)) == ( + "% Not supported in Octave:\n" + "% expint\n" + "expint(y, x)" + ) + + +def test_trick_indent_with_end_else_words(): + # words starting with "end" or "else" do not confuse the indenter + t1 = S('endless'); + t2 = S('elsewhere'); + pw = Piecewise((t1, x < 0), (t2, x <= 1), (1, True)) + assert mcode(pw, inline=False) == ( + "if (x < 0)\n" + " endless\n" + "elseif (x <= 1)\n" + " elsewhere\n" + "else\n" + " 1\n" + "end") + + +def test_hadamard(): + A = MatrixSymbol('A', 3, 3) + B = MatrixSymbol('B', 3, 3) + v = MatrixSymbol('v', 3, 1) + h = MatrixSymbol('h', 1, 3) + C = HadamardProduct(A, B) + n = Symbol('n') + assert mcode(C) == "A.*B" + assert mcode(C*v) == "(A.*B)*v" + assert mcode(h*C*v) == "h*(A.*B)*v" + assert mcode(C*A) == "(A.*B)*A" + # mixing Hadamard and scalar strange b/c we vectorize scalars + assert mcode(C*x*y) == "(x.*y)*(A.*B)" + + # Testing HadamardPower: + assert mcode(HadamardPower(A, n)) == "A.**n" + assert mcode(HadamardPower(A, 1+n)) == "A.**(n + 1)" + assert mcode(HadamardPower(A*B.T, 1+n)) == "(A*B.T).**(n + 1)" + + +def test_sparse(): + M = SparseMatrix(5, 6, {}) + M[2, 2] = 10; + M[1, 2] = 20; + M[1, 3] = 22; + M[0, 3] = 30; + M[3, 0] = x*y; + assert mcode(M) == ( + "sparse([4 2 3 1 2], [1 3 3 4 4], [x.*y 20 10 30 22], 5, 6)" + ) + + +def test_sinc(): + assert mcode(sinc(x)) == 'sinc(x/pi)' + assert mcode(sinc(x + 3)) == 'sinc((x + 3)/pi)' + assert mcode(sinc(pi*(x + 3))) == 'sinc(x + 3)' + + +def test_trigfun(): + for f in (sin, cos, tan, cot, sec, csc, asin, acos, acot, atan, asec, acsc, + sinh, cosh, tanh, coth, csch, sech, asinh, acosh, atanh, acoth, + asech, acsch): + assert octave_code(f(x) == f.__name__ + '(x)') + + +def test_specfun(): + n = Symbol('n') + for f in [besselj, bessely, besseli, besselk]: + assert octave_code(f(n, x)) == f.__name__ + '(n, x)' + for f in (erfc, erfi, erf, erfinv, erfcinv, fresnelc, fresnels, gamma): + assert octave_code(f(x)) == f.__name__ + '(x)' + assert octave_code(hankel1(n, x)) == 'besselh(n, 1, x)' + assert octave_code(hankel2(n, x)) == 'besselh(n, 2, x)' + assert octave_code(airyai(x)) == 'airy(0, x)' + assert octave_code(airyaiprime(x)) == 'airy(1, x)' + assert octave_code(airybi(x)) == 'airy(2, x)' + assert octave_code(airybiprime(x)) == 'airy(3, x)' + assert octave_code(uppergamma(n, x)) == '(gammainc(x, n, \'upper\').*gamma(n))' + assert octave_code(lowergamma(n, x)) == '(gammainc(x, n).*gamma(n))' + assert octave_code(z**lowergamma(n, x)) == 'z.^(gammainc(x, n).*gamma(n))' + assert octave_code(jn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*besselj(n + 1/2, x)/2' + assert octave_code(yn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*bessely(n + 1/2, x)/2' + assert octave_code(LambertW(x)) == 'lambertw(x)' + assert octave_code(LambertW(x, n)) == 'lambertw(n, x)' + + # Automatic rewrite + assert octave_code(Ei(x)) == 'logint(exp(x))' + assert octave_code(dirichlet_eta(x)) == '((x == 1).*(log(2)) + (~(x == 1)).*((1 - 2.^(1 - x)).*zeta(x)))' + assert octave_code(riemann_xi(x)) == 'pi.^(-x/2).*x.*(x - 1).*gamma(x/2).*zeta(x)/2' + + +def test_MatrixElement_printing(): + # test cases for issue #11821 + A = MatrixSymbol("A", 1, 3) + B = MatrixSymbol("B", 1, 3) + C = MatrixSymbol("C", 1, 3) + + assert mcode(A[0, 0]) == "A(1, 1)" + assert mcode(3 * A[0, 0]) == "3*A(1, 1)" + + F = C[0, 0].subs(C, A - B) + assert mcode(F) == "(A - B)(1, 1)" + + +def test_zeta_printing_issue_14820(): + assert octave_code(zeta(x)) == 'zeta(x)' + assert octave_code(zeta(x, y)) == '% Not supported in Octave:\n% zeta\nzeta(x, y)' + + +def test_automatic_rewrite(): + assert octave_code(Li(x)) == 'logint(x) - logint(2)' + assert octave_code(erf2(x, y)) == '-erf(x) + erf(y)' diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_pycode.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_pycode.py new file mode 100644 index 0000000000000000000000000000000000000000..a800e765db38490b89b019cee3b3f88cab30d663 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_pycode.py @@ -0,0 +1,426 @@ +from sympy.codegen import Assignment +from sympy.codegen.ast import none +from sympy.codegen.cfunctions import expm1, log1p +from sympy.codegen.scipy_nodes import cosm1 +from sympy.codegen.matrix_nodes import MatrixSolve +from sympy.core import Expr, Mod, symbols, Eq, Le, Gt, zoo, oo, Rational, Pow +from sympy.core.numbers import pi +from sympy.core.singleton import S +from sympy.functions import acos, KroneckerDelta, Piecewise, sign, sqrt, Min, Max, cot, acsch, asec, coth +from sympy.logic import And, Or +from sympy.matrices import SparseMatrix, MatrixSymbol, Identity +from sympy.printing.pycode import ( + MpmathPrinter, PythonCodePrinter, pycode, SymPyPrinter +) +from sympy.printing.tensorflow import TensorflowPrinter +from sympy.printing.numpy import NumPyPrinter, SciPyPrinter +from sympy.testing.pytest import raises, skip +from sympy.tensor import IndexedBase, Idx +from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayDiagonal, ArrayContraction, ZeroArray, OneArray +from sympy.external import import_module +from sympy.functions.special.gamma_functions import loggamma + + +x, y, z = symbols('x y z') +p = IndexedBase("p") + + +def test_PythonCodePrinter(): + prntr = PythonCodePrinter() + + assert not prntr.module_imports + + assert prntr.doprint(x**y) == 'x**y' + assert prntr.doprint(Mod(x, 2)) == 'x % 2' + assert prntr.doprint(-Mod(x, y)) == '-(x % y)' + assert prntr.doprint(Mod(-x, y)) == '(-x) % y' + assert prntr.doprint(And(x, y)) == 'x and y' + assert prntr.doprint(Or(x, y)) == 'x or y' + assert prntr.doprint(1/(x+y)) == '1/(x + y)' + assert not prntr.module_imports + + assert prntr.doprint(pi) == 'math.pi' + assert prntr.module_imports == {'math': {'pi'}} + + assert prntr.doprint(x**Rational(1, 2)) == 'math.sqrt(x)' + assert prntr.doprint(sqrt(x)) == 'math.sqrt(x)' + assert prntr.module_imports == {'math': {'pi', 'sqrt'}} + + assert prntr.doprint(acos(x)) == 'math.acos(x)' + assert prntr.doprint(cot(x)) == '1/math.tan(x)' + assert prntr.doprint(coth(x)) == '(math.exp(x) + math.exp(-x))/(math.exp(x) - math.exp(-x))' + assert prntr.doprint(asec(x)) == 'math.acos(1/x)' + assert prntr.doprint(acsch(x)) == 'math.log(math.sqrt(1 + x**(-2)) + 1/x)' + + assert prntr.doprint(Assignment(x, 2)) == 'x = 2' + assert prntr.doprint(Piecewise((1, Eq(x, 0)), + (2, x>6))) == '((1) if (x == 0) else (2) if (x > 6) else None)' + assert prntr.doprint(Piecewise((2, Le(x, 0)), + (3, Gt(x, 0)), evaluate=False)) == '((2) if (x <= 0) else'\ + ' (3) if (x > 0) else None)' + assert prntr.doprint(sign(x)) == '(0.0 if x == 0 else math.copysign(1, x))' + assert prntr.doprint(p[0, 1]) == 'p[0, 1]' + assert prntr.doprint(KroneckerDelta(x,y)) == '(1 if x == y else 0)' + + assert prntr.doprint((2,3)) == "(2, 3)" + assert prntr.doprint([2,3]) == "[2, 3]" + + assert prntr.doprint(Min(x, y)) == "min(x, y)" + assert prntr.doprint(Max(x, y)) == "max(x, y)" + + +def test_PythonCodePrinter_standard(): + prntr = PythonCodePrinter() + + assert prntr.standard == 'python3' + + raises(ValueError, lambda: PythonCodePrinter({'standard':'python4'})) + + +def test_MpmathPrinter(): + p = MpmathPrinter() + assert p.doprint(sign(x)) == 'mpmath.sign(x)' + assert p.doprint(Rational(1, 2)) == 'mpmath.mpf(1)/mpmath.mpf(2)' + + assert p.doprint(S.Exp1) == 'mpmath.e' + assert p.doprint(S.Pi) == 'mpmath.pi' + assert p.doprint(S.GoldenRatio) == 'mpmath.phi' + assert p.doprint(S.EulerGamma) == 'mpmath.euler' + assert p.doprint(S.NaN) == 'mpmath.nan' + assert p.doprint(S.Infinity) == 'mpmath.inf' + assert p.doprint(S.NegativeInfinity) == 'mpmath.ninf' + assert p.doprint(loggamma(x)) == 'mpmath.loggamma(x)' + + +def test_NumPyPrinter(): + from sympy.core.function import Lambda + from sympy.matrices.expressions.adjoint import Adjoint + from sympy.matrices.expressions.diagonal import (DiagMatrix, DiagonalMatrix, DiagonalOf) + from sympy.matrices.expressions.funcmatrix import FunctionMatrix + from sympy.matrices.expressions.hadamard import HadamardProduct + from sympy.matrices.expressions.kronecker import KroneckerProduct + from sympy.matrices.expressions.special import (OneMatrix, ZeroMatrix) + from sympy.abc import a, b + p = NumPyPrinter() + assert p.doprint(sign(x)) == 'numpy.sign(x)' + A = MatrixSymbol("A", 2, 2) + B = MatrixSymbol("B", 2, 2) + C = MatrixSymbol("C", 1, 5) + D = MatrixSymbol("D", 3, 4) + assert p.doprint(A**(-1)) == "numpy.linalg.inv(A)" + assert p.doprint(A**5) == "numpy.linalg.matrix_power(A, 5)" + assert p.doprint(Identity(3)) == "numpy.eye(3)" + + u = MatrixSymbol('x', 2, 1) + v = MatrixSymbol('y', 2, 1) + assert p.doprint(MatrixSolve(A, u)) == 'numpy.linalg.solve(A, x)' + assert p.doprint(MatrixSolve(A, u) + v) == 'numpy.linalg.solve(A, x) + y' + + assert p.doprint(ZeroMatrix(2, 3)) == "numpy.zeros((2, 3))" + assert p.doprint(OneMatrix(2, 3)) == "numpy.ones((2, 3))" + assert p.doprint(FunctionMatrix(4, 5, Lambda((a, b), a + b))) == \ + "numpy.fromfunction(lambda a, b: a + b, (4, 5))" + assert p.doprint(HadamardProduct(A, B)) == "numpy.multiply(A, B)" + assert p.doprint(KroneckerProduct(A, B)) == "numpy.kron(A, B)" + assert p.doprint(Adjoint(A)) == "numpy.conjugate(numpy.transpose(A))" + assert p.doprint(DiagonalOf(A)) == "numpy.reshape(numpy.diag(A), (-1, 1))" + assert p.doprint(DiagMatrix(C)) == "numpy.diagflat(C)" + assert p.doprint(DiagonalMatrix(D)) == "numpy.multiply(D, numpy.eye(3, 4))" + + # Workaround for numpy negative integer power errors + assert p.doprint(x**-1) == 'x**(-1.0)' + assert p.doprint(x**-2) == 'x**(-2.0)' + + expr = Pow(2, -1, evaluate=False) + assert p.doprint(expr) == "2**(-1.0)" + + assert p.doprint(S.Exp1) == 'numpy.e' + assert p.doprint(S.Pi) == 'numpy.pi' + assert p.doprint(S.EulerGamma) == 'numpy.euler_gamma' + assert p.doprint(S.NaN) == 'numpy.nan' + assert p.doprint(S.Infinity) == 'numpy.PINF' + assert p.doprint(S.NegativeInfinity) == 'numpy.NINF' + + +def test_issue_18770(): + numpy = import_module('numpy') + if not numpy: + skip("numpy not installed.") + + from sympy.functions.elementary.miscellaneous import (Max, Min) + from sympy.utilities.lambdify import lambdify + + expr1 = Min(0.1*x + 3, x + 1, 0.5*x + 1) + func = lambdify(x, expr1, "numpy") + assert (func(numpy.linspace(0, 3, 3)) == [1.0, 1.75, 2.5 ]).all() + assert func(4) == 3 + + expr1 = Max(x**2, x**3) + func = lambdify(x,expr1, "numpy") + assert (func(numpy.linspace(-1, 2, 4)) == [1, 0, 1, 8] ).all() + assert func(4) == 64 + + +def test_SciPyPrinter(): + p = SciPyPrinter() + expr = acos(x) + assert 'numpy' not in p.module_imports + assert p.doprint(expr) == 'numpy.arccos(x)' + assert 'numpy' in p.module_imports + assert not any(m.startswith('scipy') for m in p.module_imports) + smat = SparseMatrix(2, 5, {(0, 1): 3}) + assert p.doprint(smat) == \ + 'scipy.sparse.coo_matrix(([3], ([0], [1])), shape=(2, 5))' + assert 'scipy.sparse' in p.module_imports + + assert p.doprint(S.GoldenRatio) == 'scipy.constants.golden_ratio' + assert p.doprint(S.Pi) == 'scipy.constants.pi' + assert p.doprint(S.Exp1) == 'numpy.e' + + +def test_pycode_reserved_words(): + s1, s2 = symbols('if else') + raises(ValueError, lambda: pycode(s1 + s2, error_on_reserved=True)) + py_str = pycode(s1 + s2) + assert py_str in ('else_ + if_', 'if_ + else_') + + +def test_issue_20762(): + # Make sure pycode removes curly braces from subscripted variables + a_b, b, a_11 = symbols('a_{b} b a_{11}') + expr = a_b*b + assert pycode(expr) == 'a_b*b' + expr = a_11*b + assert pycode(expr) == 'a_11*b' + + +def test_sqrt(): + prntr = PythonCodePrinter() + assert prntr._print_Pow(sqrt(x), rational=False) == 'math.sqrt(x)' + assert prntr._print_Pow(1/sqrt(x), rational=False) == '1/math.sqrt(x)' + + prntr = PythonCodePrinter({'standard' : 'python3'}) + assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' + assert prntr._print_Pow(1/sqrt(x), rational=True) == 'x**(-1/2)' + + prntr = MpmathPrinter() + assert prntr._print_Pow(sqrt(x), rational=False) == 'mpmath.sqrt(x)' + assert prntr._print_Pow(sqrt(x), rational=True) == \ + "x**(mpmath.mpf(1)/mpmath.mpf(2))" + + prntr = NumPyPrinter() + assert prntr._print_Pow(sqrt(x), rational=False) == 'numpy.sqrt(x)' + assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' + + prntr = SciPyPrinter() + assert prntr._print_Pow(sqrt(x), rational=False) == 'numpy.sqrt(x)' + assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' + + prntr = SymPyPrinter() + assert prntr._print_Pow(sqrt(x), rational=False) == 'sympy.sqrt(x)' + assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' + + +def test_frac(): + from sympy.functions.elementary.integers import frac + + expr = frac(x) + prntr = NumPyPrinter() + assert prntr.doprint(expr) == 'numpy.mod(x, 1)' + + prntr = SciPyPrinter() + assert prntr.doprint(expr) == 'numpy.mod(x, 1)' + + prntr = PythonCodePrinter() + assert prntr.doprint(expr) == 'x % 1' + + prntr = MpmathPrinter() + assert prntr.doprint(expr) == 'mpmath.frac(x)' + + prntr = SymPyPrinter() + assert prntr.doprint(expr) == 'sympy.functions.elementary.integers.frac(x)' + + +class CustomPrintedObject(Expr): + def _numpycode(self, printer): + return 'numpy' + + def _mpmathcode(self, printer): + return 'mpmath' + + +def test_printmethod(): + obj = CustomPrintedObject() + assert NumPyPrinter().doprint(obj) == 'numpy' + assert MpmathPrinter().doprint(obj) == 'mpmath' + + +def test_codegen_ast_nodes(): + assert pycode(none) == 'None' + + +def test_issue_14283(): + prntr = PythonCodePrinter() + + assert prntr.doprint(zoo) == "math.nan" + assert prntr.doprint(-oo) == "float('-inf')" + + +def test_NumPyPrinter_print_seq(): + n = NumPyPrinter() + + assert n._print_seq(range(2)) == '(0, 1,)' + + +def test_issue_16535_16536(): + from sympy.functions.special.gamma_functions import (lowergamma, uppergamma) + + a = symbols('a') + expr1 = lowergamma(a, x) + expr2 = uppergamma(a, x) + + prntr = SciPyPrinter() + assert prntr.doprint(expr1) == 'scipy.special.gamma(a)*scipy.special.gammainc(a, x)' + assert prntr.doprint(expr2) == 'scipy.special.gamma(a)*scipy.special.gammaincc(a, x)' + + prntr = NumPyPrinter() + assert "Not supported" in prntr.doprint(expr1) + assert "Not supported" in prntr.doprint(expr2) + + prntr = PythonCodePrinter() + assert "Not supported" in prntr.doprint(expr1) + assert "Not supported" in prntr.doprint(expr2) + + +def test_Integral(): + from sympy.functions.elementary.exponential import exp + from sympy.integrals.integrals import Integral + + single = Integral(exp(-x), (x, 0, oo)) + double = Integral(x**2*exp(x*y), (x, -z, z), (y, 0, z)) + indefinite = Integral(x**2, x) + evaluateat = Integral(x**2, (x, 1)) + + prntr = SciPyPrinter() + assert prntr.doprint(single) == 'scipy.integrate.quad(lambda x: numpy.exp(-x), 0, numpy.PINF)[0]' + assert prntr.doprint(double) == 'scipy.integrate.nquad(lambda x, y: x**2*numpy.exp(x*y), ((-z, z), (0, z)))[0]' + raises(NotImplementedError, lambda: prntr.doprint(indefinite)) + raises(NotImplementedError, lambda: prntr.doprint(evaluateat)) + + prntr = MpmathPrinter() + assert prntr.doprint(single) == 'mpmath.quad(lambda x: mpmath.exp(-x), (0, mpmath.inf))' + assert prntr.doprint(double) == 'mpmath.quad(lambda x, y: x**2*mpmath.exp(x*y), (-z, z), (0, z))' + raises(NotImplementedError, lambda: prntr.doprint(indefinite)) + raises(NotImplementedError, lambda: prntr.doprint(evaluateat)) + + +def test_fresnel_integrals(): + from sympy.functions.special.error_functions import (fresnelc, fresnels) + + expr1 = fresnelc(x) + expr2 = fresnels(x) + + prntr = SciPyPrinter() + assert prntr.doprint(expr1) == 'scipy.special.fresnel(x)[1]' + assert prntr.doprint(expr2) == 'scipy.special.fresnel(x)[0]' + + prntr = NumPyPrinter() + assert "Not supported" in prntr.doprint(expr1) + assert "Not supported" in prntr.doprint(expr2) + + prntr = PythonCodePrinter() + assert "Not supported" in prntr.doprint(expr1) + assert "Not supported" in prntr.doprint(expr2) + + prntr = MpmathPrinter() + assert prntr.doprint(expr1) == 'mpmath.fresnelc(x)' + assert prntr.doprint(expr2) == 'mpmath.fresnels(x)' + + +def test_beta(): + from sympy.functions.special.beta_functions import beta + + expr = beta(x, y) + + prntr = SciPyPrinter() + assert prntr.doprint(expr) == 'scipy.special.beta(x, y)' + + prntr = NumPyPrinter() + assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)' + + prntr = PythonCodePrinter() + assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)' + + prntr = PythonCodePrinter({'allow_unknown_functions': True}) + assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)' + + prntr = MpmathPrinter() + assert prntr.doprint(expr) == 'mpmath.beta(x, y)' + +def test_airy(): + from sympy.functions.special.bessel import (airyai, airybi) + + expr1 = airyai(x) + expr2 = airybi(x) + + prntr = SciPyPrinter() + assert prntr.doprint(expr1) == 'scipy.special.airy(x)[0]' + assert prntr.doprint(expr2) == 'scipy.special.airy(x)[2]' + + prntr = NumPyPrinter() + assert "Not supported" in prntr.doprint(expr1) + assert "Not supported" in prntr.doprint(expr2) + + prntr = PythonCodePrinter() + assert "Not supported" in prntr.doprint(expr1) + assert "Not supported" in prntr.doprint(expr2) + +def test_airy_prime(): + from sympy.functions.special.bessel import (airyaiprime, airybiprime) + + expr1 = airyaiprime(x) + expr2 = airybiprime(x) + + prntr = SciPyPrinter() + assert prntr.doprint(expr1) == 'scipy.special.airy(x)[1]' + assert prntr.doprint(expr2) == 'scipy.special.airy(x)[3]' + + prntr = NumPyPrinter() + assert "Not supported" in prntr.doprint(expr1) + assert "Not supported" in prntr.doprint(expr2) + + prntr = PythonCodePrinter() + assert "Not supported" in prntr.doprint(expr1) + assert "Not supported" in prntr.doprint(expr2) + + +def test_numerical_accuracy_functions(): + prntr = SciPyPrinter() + assert prntr.doprint(expm1(x)) == 'numpy.expm1(x)' + assert prntr.doprint(log1p(x)) == 'numpy.log1p(x)' + assert prntr.doprint(cosm1(x)) == 'scipy.special.cosm1(x)' + +def test_array_printer(): + A = ArraySymbol('A', (4,4,6,6,6)) + I = IndexedBase('I') + i,j,k = Idx('i', (0,1)), Idx('j', (2,3)), Idx('k', (4,5)) + + prntr = NumPyPrinter() + assert prntr.doprint(ZeroArray(5)) == 'numpy.zeros((5,))' + assert prntr.doprint(OneArray(5)) == 'numpy.ones((5,))' + assert prntr.doprint(ArrayContraction(A, [2,3])) == 'numpy.einsum("abccd->abd", A)' + assert prntr.doprint(I) == 'I' + assert prntr.doprint(ArrayDiagonal(A, [2,3,4])) == 'numpy.einsum("abccc->abc", A)' + assert prntr.doprint(ArrayDiagonal(A, [0,1], [2,3])) == 'numpy.einsum("aabbc->cab", A)' + assert prntr.doprint(ArrayContraction(A, [2], [3])) == 'numpy.einsum("abcde->abe", A)' + assert prntr.doprint(Assignment(I[i,j,k], I[i,j,k])) == 'I = I' + + prntr = TensorflowPrinter() + assert prntr.doprint(ZeroArray(5)) == 'tensorflow.zeros((5,))' + assert prntr.doprint(OneArray(5)) == 'tensorflow.ones((5,))' + assert prntr.doprint(ArrayContraction(A, [2,3])) == 'tensorflow.linalg.einsum("abccd->abd", A)' + assert prntr.doprint(I) == 'I' + assert prntr.doprint(ArrayDiagonal(A, [2,3,4])) == 'tensorflow.linalg.einsum("abccc->abc", A)' + assert prntr.doprint(ArrayDiagonal(A, [0,1], [2,3])) == 'tensorflow.linalg.einsum("aabbc->cab", A)' + assert prntr.doprint(ArrayContraction(A, [2], [3])) == 'tensorflow.linalg.einsum("abcde->abe", A)' + assert prntr.doprint(Assignment(I[i,j,k], I[i,j,k])) == 'I = I' diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_repr.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_repr.py new file mode 100644 index 0000000000000000000000000000000000000000..b42f4c7e81a7271ed6a01bc6666b13f200c1adfe --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_repr.py @@ -0,0 +1,374 @@ +from __future__ import annotations +from typing import Any + +from sympy.testing.pytest import raises, warns_deprecated_sympy +from sympy.assumptions.ask import Q +from sympy.core.function import (Function, WildFunction) +from sympy.core.numbers import (AlgebraicNumber, Float, Integer, Rational) +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol, Wild, symbols) +from sympy.core.sympify import sympify +from sympy.functions.elementary.complexes import Abs +from sympy.functions.elementary.miscellaneous import (root, sqrt) +from sympy.functions.elementary.trigonometric import sin +from sympy.functions.special.delta_functions import Heaviside +from sympy.logic.boolalg import (false, true) +from sympy.matrices.dense import (Matrix, ones) +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.matrices.immutable import ImmutableDenseMatrix +from sympy.combinatorics import Cycle, Permutation +from sympy.core.symbol import Str +from sympy.geometry import Point, Ellipse +from sympy.printing import srepr +from sympy.polys import ring, field, ZZ, QQ, lex, grlex, Poly +from sympy.polys.polyclasses import DMP +from sympy.polys.agca.extensions import FiniteExtension + +x, y = symbols('x,y') + +# eval(srepr(expr)) == expr has to succeed in the right environment. The right +# environment is the scope of "from sympy import *" for most cases. +ENV: dict[str, Any] = {"Str": Str} +exec("from sympy import *", ENV) + + +def sT(expr, string, import_stmt=None, **kwargs): + """ + sT := sreprTest + + Tests that srepr delivers the expected string and that + the condition eval(srepr(expr))==expr holds. + """ + if import_stmt is None: + ENV2 = ENV + else: + ENV2 = ENV.copy() + exec(import_stmt, ENV2) + + assert srepr(expr, **kwargs) == string + assert eval(string, ENV2) == expr + + +def test_printmethod(): + class R(Abs): + def _sympyrepr(self, printer): + return "foo(%s)" % printer._print(self.args[0]) + assert srepr(R(x)) == "foo(Symbol('x'))" + + +def test_Add(): + sT(x + y, "Add(Symbol('x'), Symbol('y'))") + assert srepr(x**2 + 1, order='lex') == "Add(Pow(Symbol('x'), Integer(2)), Integer(1))" + assert srepr(x**2 + 1, order='old') == "Add(Integer(1), Pow(Symbol('x'), Integer(2)))" + assert srepr(sympify('x + 3 - 2', evaluate=False), order='none') == "Add(Symbol('x'), Integer(3), Mul(Integer(-1), Integer(2)))" + + +def test_more_than_255_args_issue_10259(): + from sympy.core.add import Add + from sympy.core.mul import Mul + for op in (Add, Mul): + expr = op(*symbols('x:256')) + assert eval(srepr(expr)) == expr + + +def test_Function(): + sT(Function("f")(x), "Function('f')(Symbol('x'))") + # test unapplied Function + sT(Function('f'), "Function('f')") + + sT(sin(x), "sin(Symbol('x'))") + sT(sin, "sin") + + +def test_Heaviside(): + sT(Heaviside(x), "Heaviside(Symbol('x'))") + sT(Heaviside(x, 1), "Heaviside(Symbol('x'), Integer(1))") + + +def test_Geometry(): + sT(Point(0, 0), "Point2D(Integer(0), Integer(0))") + sT(Ellipse(Point(0, 0), 5, 1), + "Ellipse(Point2D(Integer(0), Integer(0)), Integer(5), Integer(1))") + # TODO more tests + + +def test_Singletons(): + sT(S.Catalan, 'Catalan') + sT(S.ComplexInfinity, 'zoo') + sT(S.EulerGamma, 'EulerGamma') + sT(S.Exp1, 'E') + sT(S.GoldenRatio, 'GoldenRatio') + sT(S.TribonacciConstant, 'TribonacciConstant') + sT(S.Half, 'Rational(1, 2)') + sT(S.ImaginaryUnit, 'I') + sT(S.Infinity, 'oo') + sT(S.NaN, 'nan') + sT(S.NegativeInfinity, '-oo') + sT(S.NegativeOne, 'Integer(-1)') + sT(S.One, 'Integer(1)') + sT(S.Pi, 'pi') + sT(S.Zero, 'Integer(0)') + sT(S.Complexes, 'Complexes') + sT(S.EmptySequence, 'EmptySequence') + sT(S.EmptySet, 'EmptySet') + # sT(S.IdentityFunction, 'Lambda(_x, _x)') + sT(S.Naturals, 'Naturals') + sT(S.Naturals0, 'Naturals0') + sT(S.Rationals, 'Rationals') + sT(S.Reals, 'Reals') + sT(S.UniversalSet, 'UniversalSet') + + +def test_Integer(): + sT(Integer(4), "Integer(4)") + + +def test_list(): + sT([x, Integer(4)], "[Symbol('x'), Integer(4)]") + + +def test_Matrix(): + for cls, name in [(Matrix, "MutableDenseMatrix"), (ImmutableDenseMatrix, "ImmutableDenseMatrix")]: + sT(cls([[x**+1, 1], [y, x + y]]), + "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name) + + sT(cls(), "%s([])" % name) + + sT(cls([[x**+1, 1], [y, x + y]]), "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name) + + +def test_empty_Matrix(): + sT(ones(0, 3), "MutableDenseMatrix(0, 3, [])") + sT(ones(4, 0), "MutableDenseMatrix(4, 0, [])") + sT(ones(0, 0), "MutableDenseMatrix([])") + + +def test_Rational(): + sT(Rational(1, 3), "Rational(1, 3)") + sT(Rational(-1, 3), "Rational(-1, 3)") + + +def test_Float(): + sT(Float('1.23', dps=3), "Float('1.22998', precision=13)") + sT(Float('1.23456789', dps=9), "Float('1.23456788994', precision=33)") + sT(Float('1.234567890123456789', dps=19), + "Float('1.234567890123456789013', precision=66)") + sT(Float('0.60038617995049726', dps=15), + "Float('0.60038617995049726', precision=53)") + + sT(Float('1.23', precision=13), "Float('1.22998', precision=13)") + sT(Float('1.23456789', precision=33), + "Float('1.23456788994', precision=33)") + sT(Float('1.234567890123456789', precision=66), + "Float('1.234567890123456789013', precision=66)") + sT(Float('0.60038617995049726', precision=53), + "Float('0.60038617995049726', precision=53)") + + sT(Float('0.60038617995049726', 15), + "Float('0.60038617995049726', precision=53)") + + +def test_Symbol(): + sT(x, "Symbol('x')") + sT(y, "Symbol('y')") + sT(Symbol('x', negative=True), "Symbol('x', negative=True)") + + +def test_Symbol_two_assumptions(): + x = Symbol('x', negative=0, integer=1) + # order could vary + s1 = "Symbol('x', integer=True, negative=False)" + s2 = "Symbol('x', negative=False, integer=True)" + assert srepr(x) in (s1, s2) + assert eval(srepr(x), ENV) == x + + +def test_Symbol_no_special_commutative_treatment(): + sT(Symbol('x'), "Symbol('x')") + sT(Symbol('x', commutative=False), "Symbol('x', commutative=False)") + sT(Symbol('x', commutative=0), "Symbol('x', commutative=False)") + sT(Symbol('x', commutative=True), "Symbol('x', commutative=True)") + sT(Symbol('x', commutative=1), "Symbol('x', commutative=True)") + + +def test_Wild(): + sT(Wild('x', even=True), "Wild('x', even=True)") + + +def test_Dummy(): + d = Dummy('d') + sT(d, "Dummy('d', dummy_index=%s)" % str(d.dummy_index)) + + +def test_Dummy_assumption(): + d = Dummy('d', nonzero=True) + assert d == eval(srepr(d)) + s1 = "Dummy('d', dummy_index=%s, nonzero=True)" % str(d.dummy_index) + s2 = "Dummy('d', nonzero=True, dummy_index=%s)" % str(d.dummy_index) + assert srepr(d) in (s1, s2) + + +def test_Dummy_from_Symbol(): + # should not get the full dictionary of assumptions + n = Symbol('n', integer=True) + d = n.as_dummy() + assert srepr(d + ) == "Dummy('n', dummy_index=%s)" % str(d.dummy_index) + + +def test_tuple(): + sT((x,), "(Symbol('x'),)") + sT((x, y), "(Symbol('x'), Symbol('y'))") + + +def test_WildFunction(): + sT(WildFunction('w'), "WildFunction('w')") + + +def test_settins(): + raises(TypeError, lambda: srepr(x, method="garbage")) + + +def test_Mul(): + sT(3*x**3*y, "Mul(Integer(3), Pow(Symbol('x'), Integer(3)), Symbol('y'))") + assert srepr(3*x**3*y, order='old') == "Mul(Integer(3), Symbol('y'), Pow(Symbol('x'), Integer(3)))" + assert srepr(sympify('(x+4)*2*x*7', evaluate=False), order='none') == "Mul(Add(Symbol('x'), Integer(4)), Integer(2), Symbol('x'), Integer(7))" + + +def test_AlgebraicNumber(): + a = AlgebraicNumber(sqrt(2)) + sT(a, "AlgebraicNumber(Pow(Integer(2), Rational(1, 2)), [Integer(1), Integer(0)])") + a = AlgebraicNumber(root(-2, 3)) + sT(a, "AlgebraicNumber(Pow(Integer(-2), Rational(1, 3)), [Integer(1), Integer(0)])") + + +def test_PolyRing(): + assert srepr(ring("x", ZZ, lex)[0]) == "PolyRing((Symbol('x'),), ZZ, lex)" + assert srepr(ring("x,y", QQ, grlex)[0]) == "PolyRing((Symbol('x'), Symbol('y')), QQ, grlex)" + assert srepr(ring("x,y,z", ZZ["t"], lex)[0]) == "PolyRing((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)" + + +def test_FracField(): + assert srepr(field("x", ZZ, lex)[0]) == "FracField((Symbol('x'),), ZZ, lex)" + assert srepr(field("x,y", QQ, grlex)[0]) == "FracField((Symbol('x'), Symbol('y')), QQ, grlex)" + assert srepr(field("x,y,z", ZZ["t"], lex)[0]) == "FracField((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)" + + +def test_PolyElement(): + R, x, y = ring("x,y", ZZ) + assert srepr(3*x**2*y + 1) == "PolyElement(PolyRing((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)])" + + +def test_FracElement(): + F, x, y = field("x,y", ZZ) + assert srepr((3*x**2*y + 1)/(x - y**2)) == "FracElement(FracField((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)], [((1, 0), 1), ((0, 2), -1)])" + + +def test_FractionField(): + assert srepr(QQ.frac_field(x)) == \ + "FractionField(FracField((Symbol('x'),), QQ, lex))" + assert srepr(QQ.frac_field(x, y, order=grlex)) == \ + "FractionField(FracField((Symbol('x'), Symbol('y')), QQ, grlex))" + + +def test_PolynomialRingBase(): + assert srepr(ZZ.old_poly_ring(x)) == \ + "GlobalPolynomialRing(ZZ, Symbol('x'))" + assert srepr(ZZ[x].old_poly_ring(y)) == \ + "GlobalPolynomialRing(ZZ[x], Symbol('y'))" + assert srepr(QQ.frac_field(x).old_poly_ring(y)) == \ + "GlobalPolynomialRing(FractionField(FracField((Symbol('x'),), QQ, lex)), Symbol('y'))" + + +def test_DMP(): + assert srepr(DMP([1, 2], ZZ)) == 'DMP([1, 2], ZZ)' + assert srepr(ZZ.old_poly_ring(x)([1, 2])) == \ + "DMP([1, 2], ZZ, ring=GlobalPolynomialRing(ZZ, Symbol('x')))" + + +def test_FiniteExtension(): + assert srepr(FiniteExtension(Poly(x**2 + 1, x))) == \ + "FiniteExtension(Poly(x**2 + 1, x, domain='ZZ'))" + + +def test_ExtensionElement(): + A = FiniteExtension(Poly(x**2 + 1, x)) + assert srepr(A.generator) == \ + "ExtElem(DMP([1, 0], ZZ, ring=GlobalPolynomialRing(ZZ, Symbol('x'))), FiniteExtension(Poly(x**2 + 1, x, domain='ZZ')))" + + +def test_BooleanAtom(): + assert srepr(true) == "true" + assert srepr(false) == "false" + + +def test_Integers(): + sT(S.Integers, "Integers") + + +def test_Naturals(): + sT(S.Naturals, "Naturals") + + +def test_Naturals0(): + sT(S.Naturals0, "Naturals0") + + +def test_Reals(): + sT(S.Reals, "Reals") + + +def test_matrix_expressions(): + n = symbols('n', integer=True) + A = MatrixSymbol("A", n, n) + B = MatrixSymbol("B", n, n) + sT(A, "MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True))") + sT(A*B, "MatMul(MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Str('B'), Symbol('n', integer=True), Symbol('n', integer=True)))") + sT(A + B, "MatAdd(MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Str('B'), Symbol('n', integer=True), Symbol('n', integer=True)))") + + +def test_Cycle(): + # FIXME: sT fails because Cycle is not immutable and calling srepr(Cycle(1, 2)) + # adds keys to the Cycle dict (GH-17661) + #import_stmt = "from sympy.combinatorics import Cycle" + #sT(Cycle(1, 2), "Cycle(1, 2)", import_stmt) + assert srepr(Cycle(1, 2)) == "Cycle(1, 2)" + + +def test_Permutation(): + import_stmt = "from sympy.combinatorics import Permutation" + sT(Permutation(1, 2)(3, 4), "Permutation([0, 2, 1, 4, 3])", import_stmt, perm_cyclic=False) + sT(Permutation(1, 2)(3, 4), "Permutation(1, 2)(3, 4)", import_stmt, perm_cyclic=True) + + with warns_deprecated_sympy(): + old_print_cyclic = Permutation.print_cyclic + Permutation.print_cyclic = False + sT(Permutation(1, 2)(3, 4), "Permutation([0, 2, 1, 4, 3])", import_stmt) + Permutation.print_cyclic = old_print_cyclic + +def test_dict(): + from sympy.abc import x, y, z + d = {} + assert srepr(d) == "{}" + d = {x: y} + assert srepr(d) == "{Symbol('x'): Symbol('y')}" + d = {x: y, y: z} + assert srepr(d) in ( + "{Symbol('x'): Symbol('y'), Symbol('y'): Symbol('z')}", + "{Symbol('y'): Symbol('z'), Symbol('x'): Symbol('y')}", + ) + d = {x: {y: z}} + assert srepr(d) == "{Symbol('x'): {Symbol('y'): Symbol('z')}}" + +def test_set(): + from sympy.abc import x, y + s = set() + assert srepr(s) == "set()" + s = {x, y} + assert srepr(s) in ("{Symbol('x'), Symbol('y')}", "{Symbol('y'), Symbol('x')}") + +def test_Predicate(): + sT(Q.even, "Q.even") + +def test_AppliedPredicate(): + sT(Q.even(Symbol('z')), "AppliedPredicate(Q.even, Symbol('z'))") diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_smtlib.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_smtlib.py new file mode 100644 index 0000000000000000000000000000000000000000..a85ad1fa2cc57c962d227e21bc32eb71b807519d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tests/test_smtlib.py @@ -0,0 +1,525 @@ +import contextlib +import itertools +import re +import typing +from enum import Enum +from typing import Callable + +import sympy +from sympy import Add, Implies, sqrt +from sympy.core import Mul, Pow +from sympy.core import (S, pi, symbols, Function, Rational, Integer, + Symbol, Eq, Ne, Le, Lt, Gt, Ge) +from sympy.functions import Piecewise, exp, sin, cos +from sympy.printing.smtlib import smtlib_code +from sympy.testing.pytest import raises, Failed + +x, y, z = symbols('x,y,z') + + +class _W(Enum): + DEFAULTING_TO_FLOAT = re.compile("Could not infer type of `.+`. Defaulting to float.", re.I) + WILL_NOT_DECLARE = re.compile("Non-Symbol/Function `.+` will not be declared.", re.I) + WILL_NOT_ASSERT = re.compile("Non-Boolean expression `.+` will not be asserted. Converting to SMTLib verbatim.", re.I) + + +@contextlib.contextmanager +def _check_warns(expected: typing.Iterable[_W]): + warns: typing.List[str] = [] + log_warn = warns.append + yield log_warn + + errors = [] + for i, (w, e) in enumerate(itertools.zip_longest(warns, expected)): + if not e: + errors += [f"[{i}] Received unexpected warning `{w}`."] + elif not w: + errors += [f"[{i}] Did not receive expected warning `{e.name}`."] + elif not e.value.match(w): + errors += [f"[{i}] Warning `{w}` does not match expected {e.name}."] + + if errors: raise Failed('\n'.join(errors)) + + +def test_Integer(): + with _check_warns([_W.WILL_NOT_ASSERT] * 2) as w: + assert smtlib_code(Integer(67), log_warn=w) == "67" + assert smtlib_code(Integer(-1), log_warn=w) == "-1" + with _check_warns([]) as w: + assert smtlib_code(Integer(67)) == "67" + assert smtlib_code(Integer(-1)) == "-1" + + +def test_Rational(): + with _check_warns([_W.WILL_NOT_ASSERT] * 4) as w: + assert smtlib_code(Rational(3, 7), log_warn=w) == "(/ 3 7)" + assert smtlib_code(Rational(18, 9), log_warn=w) == "2" + assert smtlib_code(Rational(3, -7), log_warn=w) == "(/ -3 7)" + assert smtlib_code(Rational(-3, -7), log_warn=w) == "(/ 3 7)" + + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT] * 2) as w: + assert smtlib_code(x + Rational(3, 7), auto_declare=False, log_warn=w) == "(+ (/ 3 7) x)" + assert smtlib_code(Rational(3, 7) * x, log_warn=w) == "(declare-const x Real)\n" \ + "(* (/ 3 7) x)" + + +def test_Relational(): + with _check_warns([_W.DEFAULTING_TO_FLOAT] * 12) as w: + assert smtlib_code(Eq(x, y), auto_declare=False, log_warn=w) == "(assert (= x y))" + assert smtlib_code(Ne(x, y), auto_declare=False, log_warn=w) == "(assert (not (= x y)))" + assert smtlib_code(Le(x, y), auto_declare=False, log_warn=w) == "(assert (<= x y))" + assert smtlib_code(Lt(x, y), auto_declare=False, log_warn=w) == "(assert (< x y))" + assert smtlib_code(Gt(x, y), auto_declare=False, log_warn=w) == "(assert (> x y))" + assert smtlib_code(Ge(x, y), auto_declare=False, log_warn=w) == "(assert (>= x y))" + + +def test_Function(): + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(sin(x) ** cos(x), auto_declare=False, log_warn=w) == "(pow (sin x) (cos x))" + + with _check_warns([_W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + abs(x), + symbol_table={x: int, y: bool}, + known_types={int: "INTEGER_TYPE"}, + known_functions={sympy.Abs: "ABSOLUTE_VALUE_OF"}, + log_warn=w + ) == "(declare-const x INTEGER_TYPE)\n" \ + "(ABSOLUTE_VALUE_OF x)" + + my_fun1 = Function('f1') + with _check_warns([_W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + my_fun1(x), + symbol_table={my_fun1: Callable[[bool], float]}, + log_warn=w + ) == "(declare-const x Bool)\n" \ + "(declare-fun f1 (Bool) Real)\n" \ + "(f1 x)" + + with _check_warns([]) as w: + assert smtlib_code( + my_fun1(x), + symbol_table={my_fun1: Callable[[bool], bool]}, + log_warn=w + ) == "(declare-const x Bool)\n" \ + "(declare-fun f1 (Bool) Bool)\n" \ + "(assert (f1 x))" + + assert smtlib_code( + Eq(my_fun1(x, z), y), + symbol_table={my_fun1: Callable[[int, bool], bool]}, + log_warn=w + ) == "(declare-const x Int)\n" \ + "(declare-const y Bool)\n" \ + "(declare-const z Bool)\n" \ + "(declare-fun f1 (Int Bool) Bool)\n" \ + "(assert (= (f1 x z) y))" + + assert smtlib_code( + Eq(my_fun1(x, z), y), + symbol_table={my_fun1: Callable[[int, bool], bool]}, + known_functions={my_fun1: "MY_KNOWN_FUN", Eq: '=='}, + log_warn=w + ) == "(declare-const x Int)\n" \ + "(declare-const y Bool)\n" \ + "(declare-const z Bool)\n" \ + "(assert (== (MY_KNOWN_FUN x z) y))" + + with _check_warns([_W.DEFAULTING_TO_FLOAT] * 3) as w: + assert smtlib_code( + Eq(my_fun1(x, z), y), + known_functions={my_fun1: "MY_KNOWN_FUN", Eq: '=='}, + log_warn=w + ) == "(declare-const x Real)\n" \ + "(declare-const y Real)\n" \ + "(declare-const z Real)\n" \ + "(assert (== (MY_KNOWN_FUN x z) y))" + + +def test_Pow(): + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(x ** 3, auto_declare=False, log_warn=w) == "(pow x 3)" + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(x ** (y ** 3), auto_declare=False, log_warn=w) == "(pow x (pow y 3))" + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(x ** Rational(2, 3), auto_declare=False, log_warn=w) == '(pow x (/ 2 3))' + + a = Symbol('a', integer=True) + b = Symbol('b', real=True) + c = Symbol('c') + + def g(x): return 2 * x + + # if x=1, y=2, then expr=2.333... + expr = 1 / (g(a) * 3.5) ** (a - b ** a) / (a ** 2 + b) + + with _check_warns([]) as w: + assert smtlib_code( + [ + Eq(a < 2, c), + Eq(b > a, c), + c & True, + Eq(expr, 2 + Rational(1, 3)) + ], + log_warn=w + ) == '(declare-const a Int)\n' \ + '(declare-const b Real)\n' \ + '(declare-const c Bool)\n' \ + '(assert (= (< a 2) c))\n' \ + '(assert (= (> b a) c))\n' \ + '(assert c)\n' \ + '(assert (= ' \ + '(* (pow (* 7. a) (+ (pow b a) (* -1 a))) (pow (+ b (pow a 2)) -1)) ' \ + '(/ 7 3)' \ + '))' + + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + Mul(-2, c, Pow(Mul(b, b, evaluate=False), -1, evaluate=False), evaluate=False), + log_warn=w + ) == '(declare-const b Real)\n' \ + '(declare-const c Real)\n' \ + '(* -2 c (pow (* b b) -1))' + + +def test_basic_ops(): + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(x * y, auto_declare=False, log_warn=w) == "(* x y)" + + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(x + y, auto_declare=False, log_warn=w) == "(+ x y)" + + # with _check_warns([_SmtlibWarnings.DEFAULTING_TO_FLOAT, _SmtlibWarnings.DEFAULTING_TO_FLOAT, _SmtlibWarnings.WILL_NOT_ASSERT]) as w: + # todo: implement re-write, currently does '(+ x (* -1 y))' instead + # assert smtlib_code(x - y, auto_declare=False, log_warn=w) == "(- x y)" + + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(-x, auto_declare=False, log_warn=w) == "(* -1 x)" + + +def test_quantifier_extensions(): + from sympy.logic.boolalg import Boolean + from sympy import Interval, Tuple, sympify + + # start For-all quantifier class example + class ForAll(Boolean): + def _smtlib(self, printer): + bound_symbol_declarations = [ + printer._s_expr(sym.name, [ + printer._known_types[printer.symbol_table[sym]], + Interval(start, end) + ]) for sym, start, end in self.limits + ] + return printer._s_expr('forall', [ + printer._s_expr('', bound_symbol_declarations), + self.function + ]) + + @property + def bound_symbols(self): + return {s for s, _, _ in self.limits} + + @property + def free_symbols(self): + bound_symbol_names = {s.name for s in self.bound_symbols} + return { + s for s in self.function.free_symbols + if s.name not in bound_symbol_names + } + + def __new__(cls, *args): + limits = [sympify(a) for a in args if isinstance(a, tuple) or isinstance(a, Tuple)] + function = [sympify(a) for a in args if isinstance(a, Boolean)] + assert len(limits) + len(function) == len(args) + assert len(function) == 1 + function = function[0] + + if isinstance(function, ForAll): return ForAll.__new__( + ForAll, *(limits + function.limits), function.function + ) + inst = Boolean.__new__(cls) + inst._args = tuple(limits + [function]) + inst.limits = limits + inst.function = function + return inst + + # end For-All Quantifier class example + + f = Function('f') + with _check_warns([_W.DEFAULTING_TO_FLOAT]) as w: + assert smtlib_code( + ForAll((x, -42, +21), Eq(f(x), f(x))), + symbol_table={f: Callable[[float], float]}, + log_warn=w + ) == '(assert (forall ( (x Real [-42, 21])) true))' + + with _check_warns([_W.DEFAULTING_TO_FLOAT] * 2) as w: + assert smtlib_code( + ForAll( + (x, -42, +21), (y, -100, 3), + Implies(Eq(x, y), Eq(f(x), f(y))) + ), + symbol_table={f: Callable[[float], float]}, + log_warn=w + ) == '(declare-fun f (Real) Real)\n' \ + '(assert (' \ + 'forall ( (x Real [-42, 21]) (y Real [-100, 3])) ' \ + '(=> (= x y) (= (f x) (f y)))' \ + '))' + + a = Symbol('a', integer=True) + b = Symbol('b', real=True) + c = Symbol('c') + + with _check_warns([]) as w: + assert smtlib_code( + ForAll( + (a, 2, 100), ForAll( + (b, 2, 100), + Implies(a < b, sqrt(a) < b) | c + )), + log_warn=w + ) == '(declare-const c Bool)\n' \ + '(assert (forall ( (a Int [2, 100]) (b Real [2, 100])) ' \ + '(or c (=> (< a b) (< (pow a (/ 1 2)) b)))' \ + '))' + + +def test_mix_number_mult_symbols(): + with _check_warns([_W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + 1 / pi, + known_constants={pi: "MY_PI"}, + log_warn=w + ) == '(pow MY_PI -1)' + + with _check_warns([_W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + [ + Eq(pi, 3.14, evaluate=False), + 1 / pi, + ], + known_constants={pi: "MY_PI"}, + log_warn=w + ) == '(assert (= MY_PI 3.14))\n' \ + '(pow MY_PI -1)' + + with _check_warns([_W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + Add(S.Zero, S.One, S.NegativeOne, S.Half, + S.Exp1, S.Pi, S.GoldenRatio, evaluate=False), + known_constants={ + S.Pi: 'p', S.GoldenRatio: 'g', + S.Exp1: 'e' + }, + known_functions={ + Add: 'plus', + exp: 'exp' + }, + precision=3, + log_warn=w + ) == '(plus 0 1 -1 (/ 1 2) (exp 1) p g)' + + with _check_warns([_W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + Add(S.Zero, S.One, S.NegativeOne, S.Half, + S.Exp1, S.Pi, S.GoldenRatio, evaluate=False), + known_constants={ + S.Pi: 'p' + }, + known_functions={ + Add: 'plus', + exp: 'exp' + }, + precision=3, + log_warn=w + ) == '(plus 0 1 -1 (/ 1 2) (exp 1) p 1.62)' + + with _check_warns([_W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + Add(S.Zero, S.One, S.NegativeOne, S.Half, + S.Exp1, S.Pi, S.GoldenRatio, evaluate=False), + known_functions={Add: 'plus'}, + precision=3, + log_warn=w + ) == '(plus 0 1 -1 (/ 1 2) 2.72 3.14 1.62)' + + with _check_warns([_W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + Add(S.Zero, S.One, S.NegativeOne, S.Half, + S.Exp1, S.Pi, S.GoldenRatio, evaluate=False), + known_constants={S.Exp1: 'e'}, + known_functions={Add: 'plus'}, + precision=3, + log_warn=w + ) == '(plus 0 1 -1 (/ 1 2) e 3.14 1.62)' + + +def test_boolean(): + with _check_warns([]) as w: + assert smtlib_code(x & y, log_warn=w) == '(declare-const x Bool)\n' \ + '(declare-const y Bool)\n' \ + '(assert (and x y))' + assert smtlib_code(x | y, log_warn=w) == '(declare-const x Bool)\n' \ + '(declare-const y Bool)\n' \ + '(assert (or x y))' + assert smtlib_code(~x, log_warn=w) == '(declare-const x Bool)\n' \ + '(assert (not x))' + assert smtlib_code(x & y & z, log_warn=w) == '(declare-const x Bool)\n' \ + '(declare-const y Bool)\n' \ + '(declare-const z Bool)\n' \ + '(assert (and x y z))' + + with _check_warns([_W.DEFAULTING_TO_FLOAT]) as w: + assert smtlib_code((x & ~y) | (z > 3), log_warn=w) == '(declare-const x Bool)\n' \ + '(declare-const y Bool)\n' \ + '(declare-const z Real)\n' \ + '(assert (or (> z 3) (and x (not y))))' + + f = Function('f') + g = Function('g') + h = Function('h') + with _check_warns([_W.DEFAULTING_TO_FLOAT]) as w: + assert smtlib_code( + [Gt(f(x), y), + Lt(y, g(z))], + symbol_table={ + f: Callable[[bool], int], g: Callable[[bool], int], + }, log_warn=w + ) == '(declare-const x Bool)\n' \ + '(declare-const y Real)\n' \ + '(declare-const z Bool)\n' \ + '(declare-fun f (Bool) Int)\n' \ + '(declare-fun g (Bool) Int)\n' \ + '(assert (> (f x) y))\n' \ + '(assert (< y (g z)))' + + with _check_warns([]) as w: + assert smtlib_code( + [Eq(f(x), y), + Lt(y, g(z))], + symbol_table={ + f: Callable[[bool], int], g: Callable[[bool], int], + }, log_warn=w + ) == '(declare-const x Bool)\n' \ + '(declare-const y Int)\n' \ + '(declare-const z Bool)\n' \ + '(declare-fun f (Bool) Int)\n' \ + '(declare-fun g (Bool) Int)\n' \ + '(assert (= (f x) y))\n' \ + '(assert (< y (g z)))' + + with _check_warns([]) as w: + assert smtlib_code( + [Eq(f(x), y), + Eq(g(f(x)), z), + Eq(h(g(f(x))), x)], + symbol_table={ + f: Callable[[float], int], + g: Callable[[int], bool], + h: Callable[[bool], float] + }, + log_warn=w + ) == '(declare-const x Real)\n' \ + '(declare-const y Int)\n' \ + '(declare-const z Bool)\n' \ + '(declare-fun f (Real) Int)\n' \ + '(declare-fun g (Int) Bool)\n' \ + '(declare-fun h (Bool) Real)\n' \ + '(assert (= (f x) y))\n' \ + '(assert (= (g (f x)) z))\n' \ + '(assert (= (h (g (f x))) x))' + + +# todo: make smtlib_code support arrays +# def test_containers(): +# assert julia_code([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \ +# "Any[1, 2, 3, Any[4, 5, Any[6, 7]], 8, Any[9, 10], 11]" +# assert julia_code((1, 2, (3, 4))) == "(1, 2, (3, 4))" +# assert julia_code([1]) == "Any[1]" +# assert julia_code((1,)) == "(1,)" +# assert julia_code(Tuple(*[1, 2, 3])) == "(1, 2, 3)" +# assert julia_code((1, x * y, (3, x ** 2))) == "(1, x .* y, (3, x .^ 2))" +# # scalar, matrix, empty matrix and empty list +# assert julia_code((1, eye(3), Matrix(0, 0, []), [])) == "(1, [1 0 0;\n0 1 0;\n0 0 1], zeros(0, 0), Any[])" + +def test_smtlib_piecewise(): + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + Piecewise((x, x < 1), + (x ** 2, True)), + auto_declare=False, + log_warn=w + ) == '(ite (< x 1) x (pow x 2))' + + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code( + Piecewise((x ** 2, x < 1), + (x ** 3, x < 2), + (x ** 4, x < 3), + (x ** 5, True)), + auto_declare=False, + log_warn=w + ) == '(ite (< x 1) (pow x 2) ' \ + '(ite (< x 2) (pow x 3) ' \ + '(ite (< x 3) (pow x 4) ' \ + '(pow x 5))))' + + # Check that Piecewise without a True (default) condition error + expr = Piecewise((x, x < 1), (x ** 2, x > 1), (sin(x), x > 0)) + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + raises(AssertionError, lambda: smtlib_code(expr, log_warn=w)) + + +def test_smtlib_piecewise_times_const(): + pw = Piecewise((x, x < 1), (x ** 2, True)) + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(2 * pw, log_warn=w) == '(declare-const x Real)\n(* 2 (ite (< x 1) x (pow x 2)))' + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(pw / x, log_warn=w) == '(declare-const x Real)\n(* (pow x -1) (ite (< x 1) x (pow x 2)))' + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(pw / (x * y), log_warn=w) == '(declare-const x Real)\n(declare-const y Real)\n(* (pow x -1) (pow y -1) (ite (< x 1) x (pow x 2)))' + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + assert smtlib_code(pw / 3, log_warn=w) == '(declare-const x Real)\n(* (/ 1 3) (ite (< x 1) x (pow x 2)))' + + +# todo: make smtlib_code support arrays / matrices ? +# def test_smtlib_matrix_assign_to(): +# A = Matrix([[1, 2, 3]]) +# assert smtlib_code(A, assign_to='a') == "a = [1 2 3]" +# A = Matrix([[1, 2], [3, 4]]) +# assert smtlib_code(A, assign_to='A') == "A = [1 2;\n3 4]" + +# def test_julia_matrix_1x1(): +# A = Matrix([[3]]) +# B = MatrixSymbol('B', 1, 1) +# C = MatrixSymbol('C', 1, 2) +# assert julia_code(A, assign_to=B) == "B = [3]" +# raises(ValueError, lambda: julia_code(A, assign_to=C)) + +# def test_julia_matrix_elements(): +# A = Matrix([[x, 2, x * y]]) +# assert julia_code(A[0, 0] ** 2 + A[0, 1] + A[0, 2]) == "x .^ 2 + x .* y + 2" +# A = MatrixSymbol('AA', 1, 3) +# assert julia_code(A) == "AA" +# assert julia_code(A[0, 0] ** 2 + sin(A[0, 1]) + A[0, 2]) == \ +# "sin(AA[1,2]) + AA[1,1] .^ 2 + AA[1,3]" +# assert julia_code(sum(A)) == "AA[1,1] + AA[1,2] + AA[1,3]" + +def test_smtlib_boolean(): + with _check_warns([]) as w: + assert smtlib_code(True, auto_assert=False, log_warn=w) == 'true' + assert smtlib_code(True, log_warn=w) == '(assert true)' + assert smtlib_code(S.true, log_warn=w) == '(assert true)' + assert smtlib_code(S.false, log_warn=w) == '(assert false)' + assert smtlib_code(False, log_warn=w) == '(assert false)' + assert smtlib_code(False, auto_assert=False, log_warn=w) == 'false' + + +def test_not_supported(): + f = Function('f') + with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w: + raises(KeyError, lambda: smtlib_code(f(x).diff(x), symbol_table={f: Callable[[float], float]}, log_warn=w)) + with _check_warns([_W.WILL_NOT_ASSERT]) as w: + raises(KeyError, lambda: smtlib_code(S.ComplexInfinity, log_warn=w)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/theanocode.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/theanocode.py new file mode 100644 index 0000000000000000000000000000000000000000..eddf48981a89d1a81a372362e319cf7f79436826 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/theanocode.py @@ -0,0 +1,565 @@ +""" +.. deprecated:: 1.8 + + ``sympy.printing.theanocode`` is deprecated. Theano has been renamed to + Aesara. Use ``sympy.printing.aesaracode`` instead. See + :ref:`theanocode-deprecated` for more information. + +""" +from __future__ import annotations +from typing import Any + +from sympy.external import import_module +from sympy.printing.printer import Printer +from sympy.utilities.iterables import is_sequence +import sympy +from functools import partial + +from sympy.utilities.decorator import doctest_depends_on +from sympy.utilities.exceptions import sympy_deprecation_warning + +theano = import_module('theano') + +if theano: + ts = theano.scalar + tt = theano.tensor + from theano.sandbox import linalg as tlinalg + + mapping = { + sympy.Add: tt.add, + sympy.Mul: tt.mul, + sympy.Abs: tt.abs_, + sympy.sign: tt.sgn, + sympy.ceiling: tt.ceil, + sympy.floor: tt.floor, + sympy.log: tt.log, + sympy.exp: tt.exp, + sympy.sqrt: tt.sqrt, + sympy.cos: tt.cos, + sympy.acos: tt.arccos, + sympy.sin: tt.sin, + sympy.asin: tt.arcsin, + sympy.tan: tt.tan, + sympy.atan: tt.arctan, + sympy.atan2: tt.arctan2, + sympy.cosh: tt.cosh, + sympy.acosh: tt.arccosh, + sympy.sinh: tt.sinh, + sympy.asinh: tt.arcsinh, + sympy.tanh: tt.tanh, + sympy.atanh: tt.arctanh, + sympy.re: tt.real, + sympy.im: tt.imag, + sympy.arg: tt.angle, + sympy.erf: tt.erf, + sympy.gamma: tt.gamma, + sympy.loggamma: tt.gammaln, + sympy.Pow: tt.pow, + sympy.Eq: tt.eq, + sympy.StrictGreaterThan: tt.gt, + sympy.StrictLessThan: tt.lt, + sympy.LessThan: tt.le, + sympy.GreaterThan: tt.ge, + sympy.And: tt.and_, + sympy.Or: tt.or_, + sympy.Max: tt.maximum, # SymPy accept >2 inputs, Theano only 2 + sympy.Min: tt.minimum, # SymPy accept >2 inputs, Theano only 2 + sympy.conjugate: tt.conj, + sympy.core.numbers.ImaginaryUnit: lambda:tt.complex(0,1), + # Matrices + sympy.MatAdd: tt.Elemwise(ts.add), + sympy.HadamardProduct: tt.Elemwise(ts.mul), + sympy.Trace: tlinalg.trace, + sympy.Determinant : tlinalg.det, + sympy.Inverse: tlinalg.matrix_inverse, + sympy.Transpose: tt.DimShuffle((False, False), [1, 0]), + } + + +class TheanoPrinter(Printer): + """ Code printer which creates Theano symbolic expression graphs. + + Parameters + ========== + + cache : dict + Cache dictionary to use. If None (default) will use + the global cache. To create a printer which does not depend on or alter + global state pass an empty dictionary. Note: the dictionary is not + copied on initialization of the printer and will be updated in-place, + so using the same dict object when creating multiple printers or making + multiple calls to :func:`.theano_code` or :func:`.theano_function` means + the cache is shared between all these applications. + + Attributes + ========== + + cache : dict + A cache of Theano variables which have been created for SymPy + symbol-like objects (e.g. :class:`sympy.core.symbol.Symbol` or + :class:`sympy.matrices.expressions.MatrixSymbol`). This is used to + ensure that all references to a given symbol in an expression (or + multiple expressions) are printed as the same Theano variable, which is + created only once. Symbols are differentiated only by name and type. The + format of the cache's contents should be considered opaque to the user. + """ + printmethod = "_theano" + + def __init__(self, *args, **kwargs): + self.cache = kwargs.pop('cache', {}) + super().__init__(*args, **kwargs) + + def _get_key(self, s, name=None, dtype=None, broadcastable=None): + """ Get the cache key for a SymPy object. + + Parameters + ========== + + s : sympy.core.basic.Basic + SymPy object to get key for. + + name : str + Name of object, if it does not have a ``name`` attribute. + """ + + if name is None: + name = s.name + + return (name, type(s), s.args, dtype, broadcastable) + + def _get_or_create(self, s, name=None, dtype=None, broadcastable=None): + """ + Get the Theano variable for a SymPy symbol from the cache, or create it + if it does not exist. + """ + + # Defaults + if name is None: + name = s.name + if dtype is None: + dtype = 'floatX' + if broadcastable is None: + broadcastable = () + + key = self._get_key(s, name, dtype=dtype, broadcastable=broadcastable) + + if key in self.cache: + return self.cache[key] + + value = tt.tensor(name=name, dtype=dtype, broadcastable=broadcastable) + self.cache[key] = value + return value + + def _print_Symbol(self, s, **kwargs): + dtype = kwargs.get('dtypes', {}).get(s) + bc = kwargs.get('broadcastables', {}).get(s) + return self._get_or_create(s, dtype=dtype, broadcastable=bc) + + def _print_AppliedUndef(self, s, **kwargs): + name = str(type(s)) + '_' + str(s.args[0]) + dtype = kwargs.get('dtypes', {}).get(s) + bc = kwargs.get('broadcastables', {}).get(s) + return self._get_or_create(s, name=name, dtype=dtype, broadcastable=bc) + + def _print_Basic(self, expr, **kwargs): + op = mapping[type(expr)] + children = [self._print(arg, **kwargs) for arg in expr.args] + return op(*children) + + def _print_Number(self, n, **kwargs): + # Integers already taken care of below, interpret as float + return float(n.evalf()) + + def _print_MatrixSymbol(self, X, **kwargs): + dtype = kwargs.get('dtypes', {}).get(X) + return self._get_or_create(X, dtype=dtype, broadcastable=(None, None)) + + def _print_DenseMatrix(self, X, **kwargs): + if not hasattr(tt, 'stacklists'): + raise NotImplementedError( + "Matrix translation not yet supported in this version of Theano") + + return tt.stacklists([ + [self._print(arg, **kwargs) for arg in L] + for L in X.tolist() + ]) + + _print_ImmutableMatrix = _print_ImmutableDenseMatrix = _print_DenseMatrix + + def _print_MatMul(self, expr, **kwargs): + children = [self._print(arg, **kwargs) for arg in expr.args] + result = children[0] + for child in children[1:]: + result = tt.dot(result, child) + return result + + def _print_MatPow(self, expr, **kwargs): + children = [self._print(arg, **kwargs) for arg in expr.args] + result = 1 + if isinstance(children[1], int) and children[1] > 0: + for i in range(children[1]): + result = tt.dot(result, children[0]) + else: + raise NotImplementedError('''Only non-negative integer + powers of matrices can be handled by Theano at the moment''') + return result + + def _print_MatrixSlice(self, expr, **kwargs): + parent = self._print(expr.parent, **kwargs) + rowslice = self._print(slice(*expr.rowslice), **kwargs) + colslice = self._print(slice(*expr.colslice), **kwargs) + return parent[rowslice, colslice] + + def _print_BlockMatrix(self, expr, **kwargs): + nrows, ncols = expr.blocks.shape + blocks = [[self._print(expr.blocks[r, c], **kwargs) + for c in range(ncols)] + for r in range(nrows)] + return tt.join(0, *[tt.join(1, *row) for row in blocks]) + + + def _print_slice(self, expr, **kwargs): + return slice(*[self._print(i, **kwargs) + if isinstance(i, sympy.Basic) else i + for i in (expr.start, expr.stop, expr.step)]) + + def _print_Pi(self, expr, **kwargs): + return 3.141592653589793 + + def _print_Exp1(self, expr, **kwargs): + return ts.exp(1) + + def _print_Piecewise(self, expr, **kwargs): + import numpy as np + e, cond = expr.args[0].args # First condition and corresponding value + + # Print conditional expression and value for first condition + p_cond = self._print(cond, **kwargs) + p_e = self._print(e, **kwargs) + + # One condition only + if len(expr.args) == 1: + # Return value if condition else NaN + return tt.switch(p_cond, p_e, np.nan) + + # Return value_1 if condition_1 else evaluate remaining conditions + p_remaining = self._print(sympy.Piecewise(*expr.args[1:]), **kwargs) + return tt.switch(p_cond, p_e, p_remaining) + + def _print_Rational(self, expr, **kwargs): + return tt.true_div(self._print(expr.p, **kwargs), + self._print(expr.q, **kwargs)) + + def _print_Integer(self, expr, **kwargs): + return expr.p + + def _print_factorial(self, expr, **kwargs): + return self._print(sympy.gamma(expr.args[0] + 1), **kwargs) + + def _print_Derivative(self, deriv, **kwargs): + rv = self._print(deriv.expr, **kwargs) + for var in deriv.variables: + var = self._print(var, **kwargs) + rv = tt.Rop(rv, var, tt.ones_like(var)) + return rv + + def emptyPrinter(self, expr): + return expr + + def doprint(self, expr, dtypes=None, broadcastables=None): + """ Convert a SymPy expression to a Theano graph variable. + + The ``dtypes`` and ``broadcastables`` arguments are used to specify the + data type, dimension, and broadcasting behavior of the Theano variables + corresponding to the free symbols in ``expr``. Each is a mapping from + SymPy symbols to the value of the corresponding argument to + ``theano.tensor.Tensor``. + + See the corresponding `documentation page`__ for more information on + broadcasting in Theano. + + .. __: http://deeplearning.net/software/theano/tutorial/broadcasting.html + + Parameters + ========== + + expr : sympy.core.expr.Expr + SymPy expression to print. + + dtypes : dict + Mapping from SymPy symbols to Theano datatypes to use when creating + new Theano variables for those symbols. Corresponds to the ``dtype`` + argument to ``theano.tensor.Tensor``. Defaults to ``'floatX'`` + for symbols not included in the mapping. + + broadcastables : dict + Mapping from SymPy symbols to the value of the ``broadcastable`` + argument to ``theano.tensor.Tensor`` to use when creating Theano + variables for those symbols. Defaults to the empty tuple for symbols + not included in the mapping (resulting in a scalar). + + Returns + ======= + + theano.gof.graph.Variable + A variable corresponding to the expression's value in a Theano + symbolic expression graph. + + """ + if dtypes is None: + dtypes = {} + if broadcastables is None: + broadcastables = {} + + return self._print(expr, dtypes=dtypes, broadcastables=broadcastables) + + +global_cache: dict[Any, Any] = {} + + +def theano_code(expr, cache=None, **kwargs): + """ + Convert a SymPy expression into a Theano graph variable. + + .. deprecated:: 1.8 + + ``sympy.printing.theanocode`` is deprecated. Theano has been renamed to + Aesara. Use ``sympy.printing.aesaracode`` instead. See + :ref:`theanocode-deprecated` for more information. + + Parameters + ========== + + expr : sympy.core.expr.Expr + SymPy expression object to convert. + + cache : dict + Cached Theano variables (see :class:`TheanoPrinter.cache + `). Defaults to the module-level global cache. + + dtypes : dict + Passed to :meth:`.TheanoPrinter.doprint`. + + broadcastables : dict + Passed to :meth:`.TheanoPrinter.doprint`. + + Returns + ======= + + theano.gof.graph.Variable + A variable corresponding to the expression's value in a Theano symbolic + expression graph. + + """ + sympy_deprecation_warning( + """ + sympy.printing.theanocode is deprecated. Theano has been renamed to + Aesara. Use sympy.printing.aesaracode instead.""", + deprecated_since_version="1.8", + active_deprecations_target='theanocode-deprecated') + + if not theano: + raise ImportError("theano is required for theano_code") + + if cache is None: + cache = global_cache + + return TheanoPrinter(cache=cache, settings={}).doprint(expr, **kwargs) + + +def dim_handling(inputs, dim=None, dims=None, broadcastables=None): + r""" + Get value of ``broadcastables`` argument to :func:`.theano_code` from + keyword arguments to :func:`.theano_function`. + + Included for backwards compatibility. + + Parameters + ========== + + inputs + Sequence of input symbols. + + dim : int + Common number of dimensions for all inputs. Overrides other arguments + if given. + + dims : dict + Mapping from input symbols to number of dimensions. Overrides + ``broadcastables`` argument if given. + + broadcastables : dict + Explicit value of ``broadcastables`` argument to + :meth:`.TheanoPrinter.doprint`. If not None function will return this value unchanged. + + Returns + ======= + dict + Dictionary mapping elements of ``inputs`` to their "broadcastable" + values (tuple of ``bool``\ s). + """ + if dim is not None: + return {s: (False,) * dim for s in inputs} + + if dims is not None: + maxdim = max(dims.values()) + return { + s: (False,) * d + (True,) * (maxdim - d) + for s, d in dims.items() + } + + if broadcastables is not None: + return broadcastables + + return {} + + +@doctest_depends_on(modules=('theano',)) +def theano_function(inputs, outputs, scalar=False, *, + dim=None, dims=None, broadcastables=None, **kwargs): + """ + Create a Theano function from SymPy expressions. + + .. deprecated:: 1.8 + + ``sympy.printing.theanocode`` is deprecated. Theano has been renamed to + Aesara. Use ``sympy.printing.aesaracode`` instead. See + :ref:`theanocode-deprecated` for more information. + + The inputs and outputs are converted to Theano variables using + :func:`.theano_code` and then passed to ``theano.function``. + + Parameters + ========== + + inputs + Sequence of symbols which constitute the inputs of the function. + + outputs + Sequence of expressions which constitute the outputs(s) of the + function. The free symbols of each expression must be a subset of + ``inputs``. + + scalar : bool + Convert 0-dimensional arrays in output to scalars. This will return a + Python wrapper function around the Theano function object. + + cache : dict + Cached Theano variables (see :class:`TheanoPrinter.cache + `). Defaults to the module-level global cache. + + dtypes : dict + Passed to :meth:`.TheanoPrinter.doprint`. + + broadcastables : dict + Passed to :meth:`.TheanoPrinter.doprint`. + + dims : dict + Alternative to ``broadcastables`` argument. Mapping from elements of + ``inputs`` to integers indicating the dimension of their associated + arrays/tensors. Overrides ``broadcastables`` argument if given. + + dim : int + Another alternative to the ``broadcastables`` argument. Common number of + dimensions to use for all arrays/tensors. + ``theano_function([x, y], [...], dim=2)`` is equivalent to using + ``broadcastables={x: (False, False), y: (False, False)}``. + + Returns + ======= + callable + A callable object which takes values of ``inputs`` as positional + arguments and returns an output array for each of the expressions + in ``outputs``. If ``outputs`` is a single expression the function will + return a Numpy array, if it is a list of multiple expressions the + function will return a list of arrays. See description of the ``squeeze`` + argument above for the behavior when a single output is passed in a list. + The returned object will either be an instance of + ``theano.compile.function_module.Function`` or a Python wrapper + function around one. In both cases, the returned value will have a + ``theano_function`` attribute which points to the return value of + ``theano.function``. + + Examples + ======== + + >>> from sympy.abc import x, y, z + >>> from sympy.printing.theanocode import theano_function + + A simple function with one input and one output: + + >>> f1 = theano_function([x], [x**2 - 1], scalar=True) + >>> f1(3) + 8.0 + + A function with multiple inputs and one output: + + >>> f2 = theano_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True) + >>> f2(3, 4, 2) + 5.0 + + A function with multiple inputs and multiple outputs: + + >>> f3 = theano_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True) + >>> f3(2, 3) + [13.0, -5.0] + + See also + ======== + + dim_handling + + """ + sympy_deprecation_warning( + """ + sympy.printing.theanocode is deprecated. Theano has been renamed to Aesara. Use sympy.printing.aesaracode instead""", + deprecated_since_version="1.8", + active_deprecations_target='theanocode-deprecated') + + if not theano: + raise ImportError("theano is required for theano_function") + + # Pop off non-theano keyword args + cache = kwargs.pop('cache', {}) + dtypes = kwargs.pop('dtypes', {}) + + broadcastables = dim_handling( + inputs, dim=dim, dims=dims, broadcastables=broadcastables, + ) + + # Print inputs/outputs + code = partial(theano_code, cache=cache, dtypes=dtypes, + broadcastables=broadcastables) + tinputs = list(map(code, inputs)) + toutputs = list(map(code, outputs)) + + #fix constant expressions as variables + toutputs = [output if isinstance(output, theano.Variable) else tt.as_tensor_variable(output) for output in toutputs] + + if len(toutputs) == 1: + toutputs = toutputs[0] + + # Compile theano func + func = theano.function(tinputs, toutputs, **kwargs) + + is_0d = [len(o.variable.broadcastable) == 0 for o in func.outputs] + + # No wrapper required + if not scalar or not any(is_0d): + func.theano_function = func + return func + + # Create wrapper to convert 0-dimensional outputs to scalars + def wrapper(*args): + out = func(*args) + # out can be array(1.0) or [array(1.0), array(2.0)] + + if is_sequence(out): + return [o[()] if is_0d[i] else o for i, o in enumerate(out)] + else: + return out[()] + + wrapper.__wrapped__ = func + wrapper.__doc__ = func.__doc__ + wrapper.theano_function = func + return wrapper diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/printing/tree.py b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..ea81e3882d891d0bc10fd053b48191d9f4baab60 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/printing/tree.py @@ -0,0 +1,175 @@ +def pprint_nodes(subtrees): + """ + Prettyprints systems of nodes. + + Examples + ======== + + >>> from sympy.printing.tree import pprint_nodes + >>> print(pprint_nodes(["a", "b1\\nb2", "c"])) + +-a + +-b1 + | b2 + +-c + + """ + def indent(s, type=1): + x = s.split("\n") + r = "+-%s\n" % x[0] + for a in x[1:]: + if a == "": + continue + if type == 1: + r += "| %s\n" % a + else: + r += " %s\n" % a + return r + if not subtrees: + return "" + f = "" + for a in subtrees[:-1]: + f += indent(a) + f += indent(subtrees[-1], 2) + return f + + +def print_node(node, assumptions=True): + """ + Returns information about the "node". + + This includes class name, string representation and assumptions. + + Parameters + ========== + + assumptions : bool, optional + See the ``assumptions`` keyword in ``tree`` + """ + s = "%s: %s\n" % (node.__class__.__name__, str(node)) + + if assumptions: + d = node._assumptions + else: + d = None + + if d: + for a in sorted(d): + v = d[a] + if v is None: + continue + s += "%s: %s\n" % (a, v) + + return s + + +def tree(node, assumptions=True): + """ + Returns a tree representation of "node" as a string. + + It uses print_node() together with pprint_nodes() on node.args recursively. + + Parameters + ========== + + asssumptions : bool, optional + The flag to decide whether to print out all the assumption data + (such as ``is_integer`, ``is_real``) associated with the + expression or not. + + Enabling the flag makes the result verbose, and the printed + result may not be determinisitic because of the randomness used + in backtracing the assumptions. + + See Also + ======== + + print_tree + + """ + subtrees = [] + for arg in node.args: + subtrees.append(tree(arg, assumptions=assumptions)) + s = print_node(node, assumptions=assumptions) + pprint_nodes(subtrees) + return s + + +def print_tree(node, assumptions=True): + """ + Prints a tree representation of "node". + + Parameters + ========== + + asssumptions : bool, optional + The flag to decide whether to print out all the assumption data + (such as ``is_integer`, ``is_real``) associated with the + expression or not. + + Enabling the flag makes the result verbose, and the printed + result may not be determinisitic because of the randomness used + in backtracing the assumptions. + + Examples + ======== + + >>> from sympy.printing import print_tree + >>> from sympy import Symbol + >>> x = Symbol('x', odd=True) + >>> y = Symbol('y', even=True) + + Printing with full assumptions information: + + >>> print_tree(y**x) + Pow: y**x + +-Symbol: y + | algebraic: True + | commutative: True + | complex: True + | even: True + | extended_real: True + | finite: True + | hermitian: True + | imaginary: False + | infinite: False + | integer: True + | irrational: False + | noninteger: False + | odd: False + | rational: True + | real: True + | transcendental: False + +-Symbol: x + algebraic: True + commutative: True + complex: True + even: False + extended_nonzero: True + extended_real: True + finite: True + hermitian: True + imaginary: False + infinite: False + integer: True + irrational: False + noninteger: False + nonzero: True + odd: True + rational: True + real: True + transcendental: False + zero: False + + Hiding the assumptions: + + >>> print_tree(y**x, assumptions=False) + Pow: y**x + +-Symbol: y + +-Symbol: x + + See Also + ======== + + tree + + """ + print(tree(node, assumptions=assumptions))