|
|
|
|
Quelle transformer.py
Sprache: Python
|
|
from __future__ import annotations
import re
from copy import copy
import sympy
from sympy.external import import_module
from sympy.parsing.latex.errors import LaTeXParsingError
lark = import_module( "lark")
if lark:
from lark import Transformer, Token, Tree # type: ignore
else:
class Transformer: # type: ignore
def transform(self, *args):
pass
class Token: # type: ignore
pass
class Tree: # type: ignore
pass
class _FactorsAfterArgument:
"""The argument of a function command followed by more factors, in the reading where
the function applies to the argument alone: ``\\sin x y`` as ``sin(x)*y``."""
def __init__(self, argument, factors):
self.argument = argument
self.factors = factors
class _DerivativeOperator:
"""``\\frac{d}{dx}`` or ``\\frac{d^n}{dx^n}``, before the expression it applies to."""
def __init__(self, variable, order):
self.variable = variable
self.order = order
def __call__(self, expression):
return sympy.Derivative(expression, (self.variable, self.order))
def _sympy_(self):
raise LaTeXParsingError( "A derivative must be applied to an expression.")
# noinspection PyPep8Naming,PyMethodMayBeStatic
class TransformToSymPyExpr(Transformer):
"""Returns a SymPy expression that is generated by traversing the ``lark.Tree``
passed to the ``.transform()`` function.
Notes
=====
**This class is never supposed to be used directly.**
In order to tweak the behavior of this class, it has to be subclassed and then after
the required modifications are made, the name of the new class should be passed to
the :py:class:`LarkLaTeXParser` class by using the ``transformer`` argument in the
constructor.
Parameters
==========
visit_tokens : bool, optional
For information about what this option does, see `here
<https://lark-parser.readthedocs.io/en/latest/visitors.html#lark.visitors.Transformer>`_.
Note that the option must be set to ``True`` for the default parser to work.
"""
SYMBOL = sympy.Symbol
DIGIT = sympy.core.numbers.Integer
locals: dict = {}
def with_locals(self, locals):
"""Returns a copy of the transformer that reads the commands in ``locals``
as the objects given there. See :py:func:`~.parse_latex_lark`."""
for command in locals:
if not (command in self._constants or command in self._trigonometric_functions
or command in self._exponential_functions
or re.fullmatch(r "\\operatorname\{[a-zA-Z]+\}", command)):
raise ValueError( "The reading of %s cannot be overridden." % command)
transformer = copy(self)
transformer.locals = dict(locals)
return transformer
_constants = { "\\pi": sympy.pi, "\\mathrm{e}": sympy.E, "\\infty": sympy.oo,
"\\imaginaryunit": sympy.I}
def _constant(self, token):
return self.locals.get(str(token), self._constants[str(token)])
CMD_PI = EULER_NUMBER = CMD_INFTY = _constant
def GREEK_SYMBOL_WITH_PRIMES(self, tokens):
# we omit the first character because it is a backslash. Also, if the variable name has "var" in it,
# like "varphi" or "varepsilon", we remove that too
variable_name = re.sub( "var(?!pi)", "", tokens[ 1:])
return sympy.Symbol(variable_name)
SUBSCRIPTED_GREEK_SYMBOL = GREEK_SYMBOL_WITH_PRIMES
def LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT(self, tokens):
base, sub = tokens.value.split( "_")
if sub.startswith( "{"):
return sympy.Symbol( "%s_{%s}" % (base, sub[ 1:- 1].replace( " ", "")))
else:
return sympy.Symbol( "%s_{%s}" % (base, sub))
def GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT(self, tokens):
base, sub = tokens.value.split( "_")
greek_letter = re.sub( "var(?!pi)", "", base[ 1:])
if sub.startswith( "{"):
return sympy.Symbol( "%s_{%s}" % (greek_letter, sub[ 1:- 1].replace( " ", "")))
else:
return sympy.Symbol( "%s_{%s}" % (greek_letter, sub))
def LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens):
base, sub = tokens.value.split( "_")
if sub.startswith( "{"):
greek_letter = sub[ 2:- 1]
else:
greek_letter = sub[ 1:]
greek_letter = re.sub( "var(?!pi)", "", greek_letter)
return sympy.Symbol( "%s_{%s}" % (base, greek_letter))
def GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens):
base, sub = tokens.value.split( "_")
greek_base = re.sub( "var(?!pi)", "", base[ 1:])
if sub.startswith( "{"):
greek_sub = sub[ 2:- 1]
else:
greek_sub = sub[ 1:]
greek_sub = re.sub( "var(?!pi)", "", greek_sub)
return sympy.Symbol( "%s_{%s}" % (greek_base, greek_sub))
def multi_letter_symbol(self, tokens):
if len(tokens) == 4: # no primes (single quotes) on symbol
return sympy.Symbol(tokens[ 2])
if len(tokens) == 5: # there are primes on the symbol
return sympy.Symbol(tokens[ 2] + tokens[ 4])
def number(self, tokens):
if tokens[ 0].type == "CMD_IMAGINARY_UNIT":
return self._constant(tokens[ 0])
if "." in tokens[ 0]:
return sympy.core.numbers.Float(tokens[ 0])
else:
return sympy.core.numbers.Integer(tokens[ 0])
def transform(self, tree):
for fraction in tree.find_data( "fraction"):
self._mark_leibniz_notation(fraction)
return super().transform(tree)
def _mark_leibniz_notation(self, fraction):
# A fraction written as \frac{d^n f}{d x^n}, with d the first factor of the numerator
# and of the denominator, becomes a node on its own. The factors are told apart
# here because a product does not remember their order.
def content(argument):
if isinstance(argument, Tree) and argument.data == "group_curly_parentheses":
return argument.children[ 1]
return argument
def is_d(node):
return isinstance(node, Token) and node.type == "SYMBOL" and node == "d"
def is_power_of_d(node):
return is_d(node) or (isinstance(node, Tree) and node.data == "superscript"
and is_d(node.children[ 0]))
def is_product(node):
return isinstance(node, Tree) and node.data == "adjacent_expressions"
numerator, denominator = [content(argument) for argument in fraction.children[ 1:]]
if not (is_product(denominator) and is_d(denominator.children[ 0])):
return
if is_power_of_d(numerator):
factors = [numerator]
elif is_product(numerator) and is_power_of_d(numerator.children[ 0]):
factors = list(numerator.children)
else:
return
fraction.data = "leibniz_fraction"
fraction.children = factors + [denominator.children[ 1]]
def latex_string(self, tokens):
if isinstance(tokens[ 0], _DerivativeOperator):
raise LaTeXParsingError( "A derivative must be applied to an expression.")
return tokens[ 0]
def _ambig(self, tokens):
# parse trees giving the same expression are one reading, not several
readings = []
for token in tokens:
if token not in readings:
readings.append(token)
if len(readings) == 1:
return readings[ 0]
return Tree( "_ambig", readings)
def group_round_parentheses(self, tokens):
return tokens[ 1]
def group_square_brackets(self, tokens):
return tokens[ 1]
def group_curly_parentheses(self, tokens):
return tokens[ 1]
def group_curly_literal_parentheses(self, tokens):
return tokens[ 1]
def eq(self, tokens):
return sympy.Eq(tokens[ 0], tokens[ 2])
def ne(self, tokens):
return sympy.Ne(tokens[ 0], tokens[ 2])
def lt(self, tokens):
return sympy.Lt(tokens[ 0], tokens[ 2])
def lte(self, tokens):
return sympy.Le(tokens[ 0], tokens[ 2])
def gt(self, tokens):
return sympy.Gt(tokens[ 0], tokens[ 2])
def gte(self, tokens):
return sympy.Ge(tokens[ 0], tokens[ 2])
_relations = { "EQUAL": sympy.Eq, "NOT_EQUAL": sympy.Ne, "LT": sympy.Lt,
"LTE": sympy.Le, "GT": sympy.Gt, "GTE": sympy.Ge}
def relation_chain(self, tokens):
return sympy. And(*[self._relations[tokens[i].type](tokens[i - 1], tokens[i + 1])
for i in range( 1, len(tokens), 2)])
_number_sets = { "N": sympy.S.Naturals, "Z": sympy.S.Integers, "Q": sympy.S.Rationals,
"R": sympy.S.Reals, "C": sympy.S.Complexes}
def number_set(self, tokens):
name = str(tokens[ 2])
if name not in self._number_sets:
raise LaTeXParsingError( "Unknown number set \\mathbb{%s}." % name)
return self._number_sets[name]
def membership(self, tokens):
contains = sympy.Contains(tokens[ 0], tokens[ 2])
return sympy. Not(contains) if tokens[ 1].type == "CMD_NOTIN" else contains
def add(self, tokens):
if len(tokens) == 2: # +a
return tokens[ 1]
if len(tokens) == 3: # a + b
lh = tokens[ 0]
rh = tokens[ 2]
if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
return sympy.MatAdd(lh, rh)
return sympy.Add(lh, rh)
def sub(self, tokens):
if len(tokens) == 2: # -a
x = tokens[ 1]
if isinstance(x, _FactorsAfterArgument):
return _FactorsAfterArgument(-x.argument, x.factors)
if self._obj_is_sympy_Matrix(x):
return sympy.MatMul(- 1, x)
return -x
if len(tokens) == 3: # a - b
lh = tokens[ 0]
rh = tokens[ 2]
if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
return sympy.MatAdd(lh, sympy.MatMul(- 1, rh))
return sympy.Add(lh, -rh)
def unary_sign(self, tokens):
return self.sub(tokens) if tokens[ 0].type == "SUB" else tokens[ 1]
def mul(self, tokens):
return self._multiply(tokens[ 0], tokens[ 2])
def _multiply(self, lh, rh):
if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
return sympy.MatMul(lh, rh)
return sympy.Mul(lh, rh)
def div(self, tokens):
return self._handle_division(tokens[ 0], tokens[ 2])
def adjacent_expressions(self, tokens):
# Most of the time, if two expressions are next to each other, it means implicit multiplication,
# but not always
from sympy.physics.quantum import Bra, Ket
if isinstance(tokens[ 0], Ket) and isinstance(tokens[ 1], Bra):
from sympy.physics.quantum import OuterProduct
return OuterProduct(tokens[ 0], tokens[ 1])
elif isinstance(tokens[ 0], _DerivativeOperator):
return tokens[ 0](tokens[ 1])
else:
return self._multiply(tokens[ 0], tokens[ 1])
def factors_after_argument(self, tokens):
return _FactorsAfterArgument(tokens[ 0], tokens[ 1])
def _apply(self, function, argument):
# ``function`` applied to the argument of a function command, and multiplied by
# the factors that follow it when the argument is read as the first factor alone
if isinstance(argument, _FactorsAfterArgument):
return self._multiply(function(argument.argument), argument.factors)
return function(argument)
def superscript(self, tokens):
def isprime(x):
return isinstance(x, Token) and x.type == "PRIMES"
def iscmdprime(x):
return isinstance(x, Token) and (x.type == "PRIMES_VIA_CMD"
or x.type == "CMD_PRIME")
def isstar(x):
return isinstance(x, Token) and x.type == "STARS"
def iscmdstar(x):
return isinstance(x, Token) and (x.type == "STARS_VIA_CMD"
or x.type == "CMD_ASTERISK")
base = tokens[ 0]
if len(tokens) == 3: # a^b OR a^\prime OR a^\ast
sup = tokens[ 2]
elif len(tokens) == 5:
# a^{'}, a^{''}, ... OR
# a^{*}, a^{**}, ... OR
# a^{\prime}, a^{\prime\prime}, ... OR
# a^{\ast}, a^{\ast\ast}, ...
sup = tokens[ 3]
if self._obj_is_sympy_Matrix(base):
if sup == sympy.Symbol( "T"):
return sympy.Transpose(base)
if sup == sympy.Symbol( "H"):
return sympy.adjoint(base)
if isprime(sup):
sup = sup.value
if len(sup) % 2 == 0:
return base
return sympy.Transpose(base)
if iscmdprime(sup):
sup = sup.value
if (len(sup)/len(r "\prime")) % 2 == 0:
return base
return sympy.Transpose(base)
if isstar(sup):
sup = sup.value
# need .doit() in order to be consistent with
# sympy.adjoint() which returns the evaluated adjoint
# of a matrix
if len(sup) % 2 == 0:
return base.doit()
return sympy.adjoint(base)
if iscmdstar(sup):
sup = sup.value
# need .doit() for same reason as above
if (len(sup)/len(r "\ast")) % 2 == 0:
return base.doit()
return sympy.adjoint(base)
if isprime(sup) or iscmdprime(sup) or isstar(sup) or iscmdstar(sup):
raise LaTeXParsingError(f "{base} with superscript {sup} is not understood.")
return sympy.Pow(base, sup)
def degree(self, args):
base = args[ 0]
return base * (sympy.pi / 180)
def matrix_prime(self, tokens):
base = tokens[ 0]
primes = tokens[ 1].value
if not self._obj_is_sympy_Matrix(base):
raise LaTeXParsingError(f "({base}){primes} is not understood.")
if len(primes) % 2 == 0:
return base
return sympy.Transpose(base)
def power_with_subscript(self, tokens):
subscript = tokens[ 3][ 1:].strip( "{}").replace( " ", "")
return sympy.Pow(sympy.Symbol( "%s_{%s}" % (tokens[ 0].name, subscript)), tokens[ 2])
def symbol_prime(self, tokens):
base = tokens[ 0]
primes = tokens[ 1].value
return sympy.Symbol(f "{base.name}{primes}")
def fraction(self, tokens):
return self._handle_division(tokens[ 1], tokens[ 2])
def leibniz_fraction(self, tokens):
# \frac{d}{dx}, \frac{d^2}{dx^2}: an operator; \frac{dy}{dx}, \frac{d^2 y}{dx^2}: a derivative
d = sympy.Symbol( "d")
power_of_d, function, power_of_variable = tokens[ 0], tokens[ 1:- 1], tokens[- 1]
if isinstance(power_of_variable, sympy.Expr):
base, order = power_of_d.as_base_exp()
variable, order_of_variable = power_of_variable.as_base_exp()
if (base == d and isinstance(variable, sympy.Symbol) and order == order_of_variable
and (order.is_Integer and order.is_positive or order.is_Symbol)):
operator = _DerivativeOperator(variable, order)
return operator(*function) if function else operator
numerator = self._multiply(power_of_d, *function) if function else power_of_d
return self._handle_division(numerator, self._multiply(d, power_of_variable))
def binomial(self, tokens):
return sympy.binomial(tokens[ 1], tokens[ 2])
def normal_integral(self, tokens):
underscore_index = None
caret_index = None
if "_" in tokens:
# we need to know the index because the next item in the list is the
# arguments for the lower bound of the integral
underscore_index = tokens.index( "_")
if "^" in tokens:
# we need to know the index because the next item in the list is the
# arguments for the upper bound of the integral
caret_index = tokens.index( "^")
lower_bound = tokens[underscore_index + 1] if underscore_index else None
upper_bound = tokens[caret_index + 1] if caret_index else None
differential_symbol = self._extract_differential_symbol(tokens)
if differential_symbol is None:
raise LaTeXParsingError( "Differential symbol was not found in the expression."
"Valid differential symbols are \"d\ ", \"\\text{d}, and \ "\\mathrm{d}\". ")
# else we can assume that a differential symbol was found
differential_variable_index = tokens.index(differential_symbol) + 1
differential_variable = tokens[differential_variable_index]
# we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would
# evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero
if lower_bound is not None and upper_bound is None:
# then one was given and the other wasn't
raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not foun d.")
if upper_bound is not None and lower_bound is None:
# then one was given and the other wasn't
raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
# check if any expression was given or not. If it wasn't, then set the integrand to 1.
if underscore_index is not None and underscore_index == differential_variable_index - 3:
# The Token at differential_variable_index - 2 should be the integrand. However, if going one more step
# backwards after that gives us the underscore, then that means that there _was_ no integrand.
# Example: \int^7_0 dx
integrand = 1
elif caret_index is not None and caret_index == differential_variable_index - 3:
# The Token at differential_variable_index - 2 should be the integrand. However, if going one more step
# backwards after that gives us the caret, then that means that there _was_ no integrand.
# Example: \int_0^7 dx
integrand = 1
elif differential_variable_index == 2:
# this means we have something like "\int dx", because the "\int" symbol will always be
# at index 0 in `tokens`
integrand = 1
else:
# The Token at differential_variable_index - 1 is the differential symbol itself, so we need to go one
# more step before that.
integrand = tokens[differential_variable_index - 2]
if lower_bound is not None:
# then we have a definite integral
# we can assume that either both the lower and upper bounds are given, or
# neither of them are
return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound))
else:
# we have an indefinite integral
return sympy.Integral(integrand, differential_variable)
def group_curly_parentheses_int(self, tokens):
# return signature is a tuple consisting of the expression in the numerator, along with the variable of
# integration
if len(tokens) == 3:
return 1, tokens[1]
elif len(tokens) == 4:
return tokens[1], tokens[2]
# there are no other possibilities
def special_fraction(self, tokens):
numerator, variable = tokens[1]
denominator = tokens[2]
# We pass the integrand, along with information about the variable of integration, upw
return sympy.Mul(numerator, sympy.Pow(denominator, -1)), variable
def integral_with_special_fraction(self, tokens):
underscore_index = None
caret_index = None
if "_" in tokens:
# we need to know the index because the next item in the list is the
# arguments for the lower bound of the integral
underscore_index = tokens.index("_")
if "^" in tokens:
# we need to know the index because the next item in the list is the
# arguments for the upper bound of the integral
caret_index = tokens.index("^")
lower_bound = tokens[underscore_index + 1] if underscore_index else None
upper_bound = tokens[caret_index + 1] if caret_index else None
# we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would
# evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero
if lower_bound is not None and upper_bound is None:
# then one was given and the other wasn't
raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
if upper_bound is not None and lower_bound is None:
# then one was given and the other wasn't
raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
integrand, differential_variable = tokens[-1]
if lower_bound is not None:
# then we have a definite integral
# we can assume that either both the lower and upper bounds are given, or
# neither of them are
return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound))
else:
# we have an indefinite integral
return sympy.Integral(integrand, differential_variable)
def group_curly_parentheses_special(self, tokens):
underscore_index = tokens.index("_")
caret_index = tokens.index("^")
# given the type of expressions we are parsing, we can assume that the lower limit
# will always use braces around its arguments. This is because we don't support
# converting unconstrained sums into SymPy expressions.
# first we isolate the bottom limit
left_brace_index = tokens.index("{", underscore_index)
right_brace_index = tokens.index("}", underscore_index)
bottom_limit = tokens[left_brace_index + 1: right_brace_index]
# next, we isolate the upper limit
top_limit = tokens[caret_index + 1:]
# the code below will be useful for supporting things like `\sum_{n = 0}^{n = 5} n^2`
# if "{" in top_limit:
# left_brace_index = tokens.index("{", caret_index)
# if left_brace_index != -1:
# # then there's a left brace in the string, and we need to find the closing right brace
# right_brace_index = tokens.index("}", caret_index)
# top_limit = tokens[left_brace_index + 1: right_brace_index]
# print(f"top limit = {top_limit}")
index_variable = bottom_limit[0]
lower_limit = bottom_limit[-1]
upper_limit = top_limit[0] # for now, the index will always be 0
# print(f"return value = ({index_variable}, {lower_limit}, {upper_limit})")
return index_variable, lower_limit, upper_limit
def summation(self, tokens):
return sympy.Sum(tokens[2], tokens[1])
def product(self, tokens):
return sympy.Product(tokens[2], tokens[1])
def limit_dir_expr(self, tokens):
caret_index = tokens.index("^")
if "{" in tokens:
left_curly_brace_index = tokens.index("{", caret_index)
direction = tokens[left_curly_brace_index + 1]
else:
direction = tokens[caret_index + 1]
if direction == "+":
return tokens[0], "+"
elif direction == "-":
return tokens[0], "-"
else:
return tokens[0], "+-"
def group_curly_parentheses_lim(self, tokens):
limit_variable = tokens[1]
if isinstance(tokens[3], tuple):
destination, direction = tokens[3]
else:
destination = tokens[3]
direction = "+-"
return limit_variable, destination, direction
def limit(self, tokens):
limit_variable, destination, direction = tokens[2]
return sympy.Limit(tokens[-1], limit_variable, destination, direction)
def differential(self, tokens):
return tokens[1]
def derivative(self, tokens):
return sympy.Derivative(tokens[-1], tokens[5])
def list_of_expressions(self, tokens):
if len(tokens) == 1:
# we return it verbatim because the function_applied node expects
# a list
return tokens
else:
def remove_tokens(args):
if isinstance(args, Token):
if args.type != "COMMA":
# An unexpected token was encountered
raise LaTeXParsingError("A comma token was expected, but some other token was encountered.")
return False
return True
return filter(remove_tokens, tokens)
def function_applied(self, tokens):
return sympy.Function(tokens[0])(*tokens[2])
def inverse_function_applied(self, tokens):
return sympy.Function("%s^{-1}" % tokens[0])(*tokens[-2])
def min(self, tokens):
return sympy.Min(*tokens[2])
def max(self, tokens):
return sympy.Max(*tokens[2])
def bra(self, tokens):
from sympy.physics.quantum import Bra
return Bra(tokens[1])
def ket(self, tokens):
from sympy.physics.quantum import Ket
return Ket(tokens[1])
def inner_product(self, tokens):
from sympy.physics.quantum import Bra, Ket, InnerProduct
return InnerProduct(Bra(tokens[1]), Ket(tokens[3]))
_trigonometric_functions = {
"\\sin": sympy.sin, "\\cos": sympy.cos, "\\tan": sympy.tan,
"\\csc": sympy.csc, "\\sec": sympy.sec, "\\cot": sympy.cot,
"\\arcsin": sympy.asin, "\\arccos": sympy.acos, "\\arctan": sympy.atan,
"\\arccsc": sympy.acsc, "\\arcsec": sympy.asec, "\\arccot": sympy.acot,
"\\sinh": sympy.sinh, "\\cosh": sympy.cosh, "\\tanh": sympy.tanh,
"\\coth": sympy.coth, "\\sech": sympy.sech, "\\csch": sympy.csch,
"\\arsinh": sympy.asinh, "\\arcosh": sympy.acosh, "\\artanh": sympy.atanh,
"\\arcsinh": sympy.asinh, "\\arccosh": sympy.acosh, "\\arctanh": sympy.atanh,
}
_inverse_trigonometric_functions = {
sympy.sin: sympy.asin, sympy.cos: sympy.acos, sympy.tan: sympy.atan,
sympy.csc: sympy.acsc, sympy.sec: sympy.asec, sympy.cot: sympy.acot,
sympy.sinh: sympy.asinh, sympy.cosh: sympy.acosh, sympy.tanh: sympy.atanh,
sympy.coth: sympy.acoth, sympy.sech: sympy.asech, sympy.csch: sympy.acsch,
}
# TODO: ANTLR refers to ISO 80000-2:2019. should we keep base 10 or base 2 for \lg?
_exponential_functions = {
"\\exp": sympy.exp, "\\ln": sympy.log, "\\log": sympy.log,
"\\lg": lambda argument: sympy.log(argument, 10),
}
def _function(self, command):
command = str(command)
if command in self.locals:
return self.locals[command]
if command in self._trigonometric_functions:
return self._trigonometric_functions[command]
return self._exponential_functions[command]
def trigonometric_function(self, tokens):
return self._apply(self._function(tokens[0]), tokens[1])
def trigonometric_function_power(self, tokens):
function = self._function(tokens[0])
exponent = tokens[2]
if exponent == -1 and function in self._inverse_trigonometric_functions:
return self._apply(self._inverse_trigonometric_functions[function], tokens[-1])
return self._apply(lambda argument: sympy.Pow(function(argument), exponent), tokens[-1])
_named_functions = {
"exp": sympy.exp, "ln": sympy.log, "log": sympy.log, "min": sympy.Min, "max": sympy.Max,
"sqrt": sympy.sqrt, "abs": sympy.Abs, "sign": sympy.sign, "sgn": sympy.sign,
"Re": sympy.re, "Im": sympy.im, "arg": sympy.arg,
"erf": sympy.erf, "erfc": sympy.erfc, "sinc": sympy.sinc,
}
def _named_function(self, name):
if "\\operatorname{%s}" % name in self.locals:
return self.locals["\\operatorname{%s}" % name]
if name in self._named_functions:
return self._named_functions[name]
if "\\" + name in self._trigonometric_functions:
return self._trigonometric_functions["\\" + name]
if name == "lg":
return self._exponential_functions["\\lg"]
if name == "det":
return self._determinant
if name in ("tr", "trace"):
return self._trace
if name in ("adj", "adjugate"):
return self._adjugate
return sympy.Function(name)
def named_function(self, tokens):
name = re.match(r"\\operatorname\s*\{\s*([a-zA-Z]+)\s*\}", tokens[0]).group(1)
function = self._named_function(name)
if len(tokens) == 2:
return self._apply(function, tokens[1])
if tokens[1].type == "CARET":
exponent = tokens[2]
if exponent == -1 and function in self._inverse_trigonometric_functions:
return self._apply(self._inverse_trigonometric_functions[function], tokens[3])
return self._apply(lambda argument: sympy.Pow(function(argument), exponent), tokens[3])
if not (function in (sympy.Min, sympy.Max) or "\\operatorname{%s}" % name in self.locals
or isinstance(function, sympy.core.function.UndefinedFunction)):
raise LaTeXParsingError("\\operatorname{%s} takes one argument." % name)
return function(*tokens[2:-1:2])
def abs(self, tokens):
return sympy.Abs(tokens[1])
def floor(self, tokens):
return sympy.floor(tokens[1])
def ceil(self, tokens):
return sympy.ceiling(tokens[1])
def factorial(self, tokens):
return sympy.factorial(tokens[0])
def conjugate(self, tokens):
return sympy.conjugate(tokens[1])
def square_root(self, tokens):
if len(tokens) == 2:
# then there was no square bracket argument
return sympy.sqrt(tokens[1])
elif len(tokens) == 3:
# then there _was_ a square bracket argument
return sympy.root(tokens[2], tokens[1])
def exponential(self, tokens):
return self._apply(self._function(tokens[0]), tokens[1])
def function_power(self, tokens):
function = self._function(tokens[0])
return self._apply(lambda argument: sympy.Pow(function(argument), tokens[2]), tokens[3])
def log(self, tokens):
function = self._function(tokens[0])
# only \log takes a base
if "_" in tokens:
return self._apply(lambda argument: function(argument, tokens[2]), tokens[3])
return self._apply(function, tokens[1])
def _extract_differential_symbol(self, s: str):
differential_symbols = {"d", r"\text{d}", r"\mathrm{d}"}
differential_symbol = next((symbol for symbol in differential_symbols if symbol in s), None)
return differential_symbol
def matrix(self, tokens):
def is_matrix_row(x):
return (isinstance(x, Tree) and x.data == "matrix_row")
def is_not_col_delim(y):
return (not isinstance(y, Token) or y.type != "MATRIX_COL_DELIM")
matrix_body = tokens[1].children
return sympy.Matrix([[y for y in x.children if is_not_col_delim(y)]
for x in matrix_body if is_matrix_row(x)])
def determinant(self, tokens):
if len(tokens) == 2: # \det A
return self._apply(self._determinant, tokens[1])
if len(tokens) == 3: # | A |
return self.matrix(tokens).det()
def _determinant(self, matrix):
if not self._obj_is_sympy_Matrix(matrix):
raise LaTeXParsingError("Cannot take determinant of non-matrix.")
return matrix.det()
def trace(self, tokens):
return self._apply(self._trace, tokens[1])
def _trace(self, matrix):
if not self._obj_is_sympy_Matrix(matrix):
raise LaTeXParsingError("Cannot take trace of non-matrix.")
return sympy.Trace(matrix)
def adjugate(self, tokens):
return self._apply(self._adjugate, tokens[1])
def _adjugate(self, matrix):
if not self._obj_is_sympy_Matrix(matrix):
raise LaTeXParsingError("Cannot take adjugate of non-matrix.")
# need .doit() since MatAdd does not support .adjugate() method
return matrix.doit().adjugate()
def _obj_is_sympy_Matrix(self, obj):
if hasattr(obj, "is_Matrix"):
return obj.is_Matrix
return isinstance(obj, sympy.Matrix)
def _handle_division(self, numerator, denominator):
if self._obj_is_sympy_Matrix(denominator):
raise LaTeXParsingError("Cannot divide by matrices like this since "
"it is not clear if left or right multiplication "
"by the inverse is intended. Try explicitly "
"multiplying by the inverse instead.")
if self._obj_is_sympy_Matrix(numerator):
return sympy.MatMul(numerator, sympy.Pow(denominator, -1))
return sympy.Mul(numerator, sympy.Pow(denominator, -1))
¤ Dauer der Verarbeitung: 0.5 Sekunden
(vorverarbeitet am 2026-11-24)
¤
*© Formatika GbR, Deutschland
|
|
2026-11-24
|
|
|
|
|