transformer.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. import re
  2. import sympy
  3. from sympy.external import import_module
  4. from sympy.parsing.latex.errors import LaTeXParsingError
  5. lark = import_module("lark")
  6. if lark:
  7. from lark import Transformer, Token, Tree # type: ignore
  8. else:
  9. class Transformer: # type: ignore
  10. def transform(self, *args):
  11. pass
  12. class Token: # type: ignore
  13. pass
  14. class Tree: # type: ignore
  15. pass
  16. # noinspection PyPep8Naming,PyMethodMayBeStatic
  17. class TransformToSymPyExpr(Transformer):
  18. """Returns a SymPy expression that is generated by traversing the ``lark.Tree``
  19. passed to the ``.transform()`` function.
  20. Notes
  21. =====
  22. **This class is never supposed to be used directly.**
  23. In order to tweak the behavior of this class, it has to be subclassed and then after
  24. the required modifications are made, the name of the new class should be passed to
  25. the :py:class:`LarkLaTeXParser` class by using the ``transformer`` argument in the
  26. constructor.
  27. Parameters
  28. ==========
  29. visit_tokens : bool, optional
  30. For information about what this option does, see `here
  31. <https://lark-parser.readthedocs.io/en/latest/visitors.html#lark.visitors.Transformer>`_.
  32. Note that the option must be set to ``True`` for the default parser to work.
  33. """
  34. SYMBOL = sympy.Symbol
  35. DIGIT = sympy.core.numbers.Integer
  36. def CMD_INFTY(self, tokens):
  37. return sympy.oo
  38. def GREEK_SYMBOL_WITH_PRIMES(self, tokens):
  39. # we omit the first character because it is a backslash. Also, if the variable name has "var" in it,
  40. # like "varphi" or "varepsilon", we remove that too
  41. variable_name = re.sub("var", "", tokens[1:])
  42. return sympy.Symbol(variable_name)
  43. def LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT(self, tokens):
  44. base, sub = tokens.value.split("_")
  45. if sub.startswith("{"):
  46. return sympy.Symbol("%s_{%s}" % (base, sub[1:-1]))
  47. else:
  48. return sympy.Symbol("%s_{%s}" % (base, sub))
  49. def GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT(self, tokens):
  50. base, sub = tokens.value.split("_")
  51. greek_letter = re.sub("var", "", base[1:])
  52. if sub.startswith("{"):
  53. return sympy.Symbol("%s_{%s}" % (greek_letter, sub[1:-1]))
  54. else:
  55. return sympy.Symbol("%s_{%s}" % (greek_letter, sub))
  56. def LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens):
  57. base, sub = tokens.value.split("_")
  58. if sub.startswith("{"):
  59. greek_letter = sub[2:-1]
  60. else:
  61. greek_letter = sub[1:]
  62. greek_letter = re.sub("var", "", greek_letter)
  63. return sympy.Symbol("%s_{%s}" % (base, greek_letter))
  64. def GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens):
  65. base, sub = tokens.value.split("_")
  66. greek_base = re.sub("var", "", base[1:])
  67. if sub.startswith("{"):
  68. greek_sub = sub[2:-1]
  69. else:
  70. greek_sub = sub[1:]
  71. greek_sub = re.sub("var", "", greek_sub)
  72. return sympy.Symbol("%s_{%s}" % (greek_base, greek_sub))
  73. def multi_letter_symbol(self, tokens):
  74. if len(tokens) == 4: # no primes (single quotes) on symbol
  75. return sympy.Symbol(tokens[2])
  76. if len(tokens) == 5: # there are primes on the symbol
  77. return sympy.Symbol(tokens[2] + tokens[4])
  78. def number(self, tokens):
  79. if tokens[0].type == "CMD_IMAGINARY_UNIT":
  80. return sympy.I
  81. if "." in tokens[0]:
  82. return sympy.core.numbers.Float(tokens[0])
  83. else:
  84. return sympy.core.numbers.Integer(tokens[0])
  85. def latex_string(self, tokens):
  86. return tokens[0]
  87. def group_round_parentheses(self, tokens):
  88. return tokens[1]
  89. def group_square_brackets(self, tokens):
  90. return tokens[1]
  91. def group_curly_parentheses(self, tokens):
  92. return tokens[1]
  93. def eq(self, tokens):
  94. return sympy.Eq(tokens[0], tokens[2])
  95. def ne(self, tokens):
  96. return sympy.Ne(tokens[0], tokens[2])
  97. def lt(self, tokens):
  98. return sympy.Lt(tokens[0], tokens[2])
  99. def lte(self, tokens):
  100. return sympy.Le(tokens[0], tokens[2])
  101. def gt(self, tokens):
  102. return sympy.Gt(tokens[0], tokens[2])
  103. def gte(self, tokens):
  104. return sympy.Ge(tokens[0], tokens[2])
  105. def add(self, tokens):
  106. if len(tokens) == 2: # +a
  107. return tokens[1]
  108. if len(tokens) == 3: # a + b
  109. lh = tokens[0]
  110. rh = tokens[2]
  111. if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
  112. return sympy.MatAdd(lh, rh)
  113. return sympy.Add(lh, rh)
  114. def sub(self, tokens):
  115. if len(tokens) == 2: # -a
  116. x = tokens[1]
  117. if self._obj_is_sympy_Matrix(x):
  118. return sympy.MatMul(-1, x)
  119. return -x
  120. if len(tokens) == 3: # a - b
  121. lh = tokens[0]
  122. rh = tokens[2]
  123. if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
  124. return sympy.MatAdd(lh, sympy.MatMul(-1, rh))
  125. return sympy.Add(lh, -rh)
  126. def mul(self, tokens):
  127. lh = tokens[0]
  128. rh = tokens[2]
  129. if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
  130. return sympy.MatMul(lh, rh)
  131. return sympy.Mul(lh, rh)
  132. def div(self, tokens):
  133. return self._handle_division(tokens[0], tokens[2])
  134. def adjacent_expressions(self, tokens):
  135. # Most of the time, if two expressions are next to each other, it means implicit multiplication,
  136. # but not always
  137. from sympy.physics.quantum import Bra, Ket
  138. if isinstance(tokens[0], Ket) and isinstance(tokens[1], Bra):
  139. from sympy.physics.quantum import OuterProduct
  140. return OuterProduct(tokens[0], tokens[1])
  141. elif tokens[0] == sympy.Symbol("d"):
  142. # If the leftmost token is a "d", then it is highly likely that this is a differential
  143. return tokens[0], tokens[1]
  144. elif isinstance(tokens[0], tuple):
  145. # then we have a derivative
  146. return sympy.Derivative(tokens[1], tokens[0][1])
  147. else:
  148. return sympy.Mul(tokens[0], tokens[1])
  149. def superscript(self, tokens):
  150. def isprime(x):
  151. return isinstance(x, Token) and x.type == "PRIMES"
  152. def iscmdprime(x):
  153. return isinstance(x, Token) and (x.type == "PRIMES_VIA_CMD"
  154. or x.type == "CMD_PRIME")
  155. def isstar(x):
  156. return isinstance(x, Token) and x.type == "STARS"
  157. def iscmdstar(x):
  158. return isinstance(x, Token) and (x.type == "STARS_VIA_CMD"
  159. or x.type == "CMD_ASTERISK")
  160. base = tokens[0]
  161. if len(tokens) == 3: # a^b OR a^\prime OR a^\ast
  162. sup = tokens[2]
  163. if len(tokens) == 5:
  164. # a^{'}, a^{''}, ... OR
  165. # a^{*}, a^{**}, ... OR
  166. # a^{\prime}, a^{\prime\prime}, ... OR
  167. # a^{\ast}, a^{\ast\ast}, ...
  168. sup = tokens[3]
  169. if self._obj_is_sympy_Matrix(base):
  170. if sup == sympy.Symbol("T"):
  171. return sympy.Transpose(base)
  172. if sup == sympy.Symbol("H"):
  173. return sympy.adjoint(base)
  174. if isprime(sup):
  175. sup = sup.value
  176. if len(sup) % 2 == 0:
  177. return base
  178. return sympy.Transpose(base)
  179. if iscmdprime(sup):
  180. sup = sup.value
  181. if (len(sup)/len(r"\prime")) % 2 == 0:
  182. return base
  183. return sympy.Transpose(base)
  184. if isstar(sup):
  185. sup = sup.value
  186. # need .doit() in order to be consistent with
  187. # sympy.adjoint() which returns the evaluated adjoint
  188. # of a matrix
  189. if len(sup) % 2 == 0:
  190. return base.doit()
  191. return sympy.adjoint(base)
  192. if iscmdstar(sup):
  193. sup = sup.value
  194. # need .doit() for same reason as above
  195. if (len(sup)/len(r"\ast")) % 2 == 0:
  196. return base.doit()
  197. return sympy.adjoint(base)
  198. if isprime(sup) or iscmdprime(sup) or isstar(sup) or iscmdstar(sup):
  199. raise LaTeXParsingError(f"{base} with superscript {sup} is not understood.")
  200. return sympy.Pow(base, sup)
  201. def matrix_prime(self, tokens):
  202. base = tokens[0]
  203. primes = tokens[1].value
  204. if not self._obj_is_sympy_Matrix(base):
  205. raise LaTeXParsingError(f"({base}){primes} is not understood.")
  206. if len(primes) % 2 == 0:
  207. return base
  208. return sympy.Transpose(base)
  209. def symbol_prime(self, tokens):
  210. base = tokens[0]
  211. primes = tokens[1].value
  212. return sympy.Symbol(f"{base.name}{primes}")
  213. def fraction(self, tokens):
  214. numerator = tokens[1]
  215. if isinstance(tokens[2], tuple):
  216. # we only need the variable w.r.t. which we are differentiating
  217. _, variable = tokens[2]
  218. # we will pass this information upwards
  219. return "derivative", variable
  220. else:
  221. denominator = tokens[2]
  222. return self._handle_division(numerator, denominator)
  223. def binomial(self, tokens):
  224. return sympy.binomial(tokens[1], tokens[2])
  225. def normal_integral(self, tokens):
  226. underscore_index = None
  227. caret_index = None
  228. if "_" in tokens:
  229. # we need to know the index because the next item in the list is the
  230. # arguments for the lower bound of the integral
  231. underscore_index = tokens.index("_")
  232. if "^" in tokens:
  233. # we need to know the index because the next item in the list is the
  234. # arguments for the upper bound of the integral
  235. caret_index = tokens.index("^")
  236. lower_bound = tokens[underscore_index + 1] if underscore_index else None
  237. upper_bound = tokens[caret_index + 1] if caret_index else None
  238. differential_symbol = self._extract_differential_symbol(tokens)
  239. if differential_symbol is None:
  240. raise LaTeXParsingError("Differential symbol was not found in the expression."
  241. "Valid differential symbols are \"d\", \"\\text{d}, and \"\\mathrm{d}\".")
  242. # else we can assume that a differential symbol was found
  243. differential_variable_index = tokens.index(differential_symbol) + 1
  244. differential_variable = tokens[differential_variable_index]
  245. # we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would
  246. # evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero
  247. if lower_bound is not None and upper_bound is None:
  248. # then one was given and the other wasn't
  249. raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
  250. if upper_bound is not None and lower_bound is None:
  251. # then one was given and the other wasn't
  252. raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
  253. # check if any expression was given or not. If it wasn't, then set the integrand to 1.
  254. if underscore_index is not None and underscore_index == differential_variable_index - 3:
  255. # The Token at differential_variable_index - 2 should be the integrand. However, if going one more step
  256. # backwards after that gives us the underscore, then that means that there _was_ no integrand.
  257. # Example: \int^7_0 dx
  258. integrand = 1
  259. elif caret_index is not None and caret_index == differential_variable_index - 3:
  260. # The Token at differential_variable_index - 2 should be the integrand. However, if going one more step
  261. # backwards after that gives us the caret, then that means that there _was_ no integrand.
  262. # Example: \int_0^7 dx
  263. integrand = 1
  264. elif differential_variable_index == 2:
  265. # this means we have something like "\int dx", because the "\int" symbol will always be
  266. # at index 0 in `tokens`
  267. integrand = 1
  268. else:
  269. # The Token at differential_variable_index - 1 is the differential symbol itself, so we need to go one
  270. # more step before that.
  271. integrand = tokens[differential_variable_index - 2]
  272. if lower_bound is not None:
  273. # then we have a definite integral
  274. # we can assume that either both the lower and upper bounds are given, or
  275. # neither of them are
  276. return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound))
  277. else:
  278. # we have an indefinite integral
  279. return sympy.Integral(integrand, differential_variable)
  280. def group_curly_parentheses_int(self, tokens):
  281. # return signature is a tuple consisting of the expression in the numerator, along with the variable of
  282. # integration
  283. if len(tokens) == 3:
  284. return 1, tokens[1]
  285. elif len(tokens) == 4:
  286. return tokens[1], tokens[2]
  287. # there are no other possibilities
  288. def special_fraction(self, tokens):
  289. numerator, variable = tokens[1]
  290. denominator = tokens[2]
  291. # We pass the integrand, along with information about the variable of integration, upw
  292. return sympy.Mul(numerator, sympy.Pow(denominator, -1)), variable
  293. def integral_with_special_fraction(self, tokens):
  294. underscore_index = None
  295. caret_index = None
  296. if "_" in tokens:
  297. # we need to know the index because the next item in the list is the
  298. # arguments for the lower bound of the integral
  299. underscore_index = tokens.index("_")
  300. if "^" in tokens:
  301. # we need to know the index because the next item in the list is the
  302. # arguments for the upper bound of the integral
  303. caret_index = tokens.index("^")
  304. lower_bound = tokens[underscore_index + 1] if underscore_index else None
  305. upper_bound = tokens[caret_index + 1] if caret_index else None
  306. # we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would
  307. # evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero
  308. if lower_bound is not None and upper_bound is None:
  309. # then one was given and the other wasn't
  310. raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
  311. if upper_bound is not None and lower_bound is None:
  312. # then one was given and the other wasn't
  313. raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
  314. integrand, differential_variable = tokens[-1]
  315. if lower_bound is not None:
  316. # then we have a definite integral
  317. # we can assume that either both the lower and upper bounds are given, or
  318. # neither of them are
  319. return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound))
  320. else:
  321. # we have an indefinite integral
  322. return sympy.Integral(integrand, differential_variable)
  323. def group_curly_parentheses_special(self, tokens):
  324. underscore_index = tokens.index("_")
  325. caret_index = tokens.index("^")
  326. # given the type of expressions we are parsing, we can assume that the lower limit
  327. # will always use braces around its arguments. This is because we don't support
  328. # converting unconstrained sums into SymPy expressions.
  329. # first we isolate the bottom limit
  330. left_brace_index = tokens.index("{", underscore_index)
  331. right_brace_index = tokens.index("}", underscore_index)
  332. bottom_limit = tokens[left_brace_index + 1: right_brace_index]
  333. # next, we isolate the upper limit
  334. top_limit = tokens[caret_index + 1:]
  335. # the code below will be useful for supporting things like `\sum_{n = 0}^{n = 5} n^2`
  336. # if "{" in top_limit:
  337. # left_brace_index = tokens.index("{", caret_index)
  338. # if left_brace_index != -1:
  339. # # then there's a left brace in the string, and we need to find the closing right brace
  340. # right_brace_index = tokens.index("}", caret_index)
  341. # top_limit = tokens[left_brace_index + 1: right_brace_index]
  342. # print(f"top limit = {top_limit}")
  343. index_variable = bottom_limit[0]
  344. lower_limit = bottom_limit[-1]
  345. upper_limit = top_limit[0] # for now, the index will always be 0
  346. # print(f"return value = ({index_variable}, {lower_limit}, {upper_limit})")
  347. return index_variable, lower_limit, upper_limit
  348. def summation(self, tokens):
  349. return sympy.Sum(tokens[2], tokens[1])
  350. def product(self, tokens):
  351. return sympy.Product(tokens[2], tokens[1])
  352. def limit_dir_expr(self, tokens):
  353. caret_index = tokens.index("^")
  354. if "{" in tokens:
  355. left_curly_brace_index = tokens.index("{", caret_index)
  356. direction = tokens[left_curly_brace_index + 1]
  357. else:
  358. direction = tokens[caret_index + 1]
  359. if direction == "+":
  360. return tokens[0], "+"
  361. elif direction == "-":
  362. return tokens[0], "-"
  363. else:
  364. return tokens[0], "+-"
  365. def group_curly_parentheses_lim(self, tokens):
  366. limit_variable = tokens[1]
  367. if isinstance(tokens[3], tuple):
  368. destination, direction = tokens[3]
  369. else:
  370. destination = tokens[3]
  371. direction = "+-"
  372. return limit_variable, destination, direction
  373. def limit(self, tokens):
  374. limit_variable, destination, direction = tokens[2]
  375. return sympy.Limit(tokens[-1], limit_variable, destination, direction)
  376. def differential(self, tokens):
  377. return tokens[1]
  378. def derivative(self, tokens):
  379. return sympy.Derivative(tokens[-1], tokens[5])
  380. def list_of_expressions(self, tokens):
  381. if len(tokens) == 1:
  382. # we return it verbatim because the function_applied node expects
  383. # a list
  384. return tokens
  385. else:
  386. def remove_tokens(args):
  387. if isinstance(args, Token):
  388. if args.type != "COMMA":
  389. # An unexpected token was encountered
  390. raise LaTeXParsingError("A comma token was expected, but some other token was encountered.")
  391. return False
  392. return True
  393. return filter(remove_tokens, tokens)
  394. def function_applied(self, tokens):
  395. return sympy.Function(tokens[0])(*tokens[2])
  396. def min(self, tokens):
  397. return sympy.Min(*tokens[2])
  398. def max(self, tokens):
  399. return sympy.Max(*tokens[2])
  400. def bra(self, tokens):
  401. from sympy.physics.quantum import Bra
  402. return Bra(tokens[1])
  403. def ket(self, tokens):
  404. from sympy.physics.quantum import Ket
  405. return Ket(tokens[1])
  406. def inner_product(self, tokens):
  407. from sympy.physics.quantum import Bra, Ket, InnerProduct
  408. return InnerProduct(Bra(tokens[1]), Ket(tokens[3]))
  409. def sin(self, tokens):
  410. return sympy.sin(tokens[1])
  411. def cos(self, tokens):
  412. return sympy.cos(tokens[1])
  413. def tan(self, tokens):
  414. return sympy.tan(tokens[1])
  415. def csc(self, tokens):
  416. return sympy.csc(tokens[1])
  417. def sec(self, tokens):
  418. return sympy.sec(tokens[1])
  419. def cot(self, tokens):
  420. return sympy.cot(tokens[1])
  421. def sin_power(self, tokens):
  422. exponent = tokens[2]
  423. if exponent == -1:
  424. return sympy.asin(tokens[-1])
  425. else:
  426. return sympy.Pow(sympy.sin(tokens[-1]), exponent)
  427. def cos_power(self, tokens):
  428. exponent = tokens[2]
  429. if exponent == -1:
  430. return sympy.acos(tokens[-1])
  431. else:
  432. return sympy.Pow(sympy.cos(tokens[-1]), exponent)
  433. def tan_power(self, tokens):
  434. exponent = tokens[2]
  435. if exponent == -1:
  436. return sympy.atan(tokens[-1])
  437. else:
  438. return sympy.Pow(sympy.tan(tokens[-1]), exponent)
  439. def csc_power(self, tokens):
  440. exponent = tokens[2]
  441. if exponent == -1:
  442. return sympy.acsc(tokens[-1])
  443. else:
  444. return sympy.Pow(sympy.csc(tokens[-1]), exponent)
  445. def sec_power(self, tokens):
  446. exponent = tokens[2]
  447. if exponent == -1:
  448. return sympy.asec(tokens[-1])
  449. else:
  450. return sympy.Pow(sympy.sec(tokens[-1]), exponent)
  451. def cot_power(self, tokens):
  452. exponent = tokens[2]
  453. if exponent == -1:
  454. return sympy.acot(tokens[-1])
  455. else:
  456. return sympy.Pow(sympy.cot(tokens[-1]), exponent)
  457. def arcsin(self, tokens):
  458. return sympy.asin(tokens[1])
  459. def arccos(self, tokens):
  460. return sympy.acos(tokens[1])
  461. def arctan(self, tokens):
  462. return sympy.atan(tokens[1])
  463. def arccsc(self, tokens):
  464. return sympy.acsc(tokens[1])
  465. def arcsec(self, tokens):
  466. return sympy.asec(tokens[1])
  467. def arccot(self, tokens):
  468. return sympy.acot(tokens[1])
  469. def sinh(self, tokens):
  470. return sympy.sinh(tokens[1])
  471. def cosh(self, tokens):
  472. return sympy.cosh(tokens[1])
  473. def tanh(self, tokens):
  474. return sympy.tanh(tokens[1])
  475. def asinh(self, tokens):
  476. return sympy.asinh(tokens[1])
  477. def acosh(self, tokens):
  478. return sympy.acosh(tokens[1])
  479. def atanh(self, tokens):
  480. return sympy.atanh(tokens[1])
  481. def abs(self, tokens):
  482. return sympy.Abs(tokens[1])
  483. def floor(self, tokens):
  484. return sympy.floor(tokens[1])
  485. def ceil(self, tokens):
  486. return sympy.ceiling(tokens[1])
  487. def factorial(self, tokens):
  488. return sympy.factorial(tokens[0])
  489. def conjugate(self, tokens):
  490. return sympy.conjugate(tokens[1])
  491. def square_root(self, tokens):
  492. if len(tokens) == 2:
  493. # then there was no square bracket argument
  494. return sympy.sqrt(tokens[1])
  495. elif len(tokens) == 3:
  496. # then there _was_ a square bracket argument
  497. return sympy.root(tokens[2], tokens[1])
  498. def exponential(self, tokens):
  499. return sympy.exp(tokens[1])
  500. def log(self, tokens):
  501. if tokens[0].type == "FUNC_LG":
  502. # we don't need to check if there's an underscore or not because having one
  503. # in this case would be meaningless
  504. # TODO: ANTLR refers to ISO 80000-2:2019. should we keep base 10 or base 2?
  505. return sympy.log(tokens[1], 10)
  506. elif tokens[0].type == "FUNC_LN":
  507. return sympy.log(tokens[1])
  508. elif tokens[0].type == "FUNC_LOG":
  509. # we check if a base was specified or not
  510. if "_" in tokens:
  511. # then a base was specified
  512. return sympy.log(tokens[3], tokens[2])
  513. else:
  514. # a base was not specified
  515. return sympy.log(tokens[1])
  516. def _extract_differential_symbol(self, s: str):
  517. differential_symbols = {"d", r"\text{d}", r"\mathrm{d}"}
  518. differential_symbol = next((symbol for symbol in differential_symbols if symbol in s), None)
  519. return differential_symbol
  520. def matrix(self, tokens):
  521. def is_matrix_row(x):
  522. return (isinstance(x, Tree) and x.data == "matrix_row")
  523. def is_not_col_delim(y):
  524. return (not isinstance(y, Token) or y.type != "MATRIX_COL_DELIM")
  525. matrix_body = tokens[1].children
  526. return sympy.Matrix([[y for y in x.children if is_not_col_delim(y)]
  527. for x in matrix_body if is_matrix_row(x)])
  528. def determinant(self, tokens):
  529. if len(tokens) == 2: # \det A
  530. if not self._obj_is_sympy_Matrix(tokens[1]):
  531. raise LaTeXParsingError("Cannot take determinant of non-matrix.")
  532. return tokens[1].det()
  533. if len(tokens) == 3: # | A |
  534. return self.matrix(tokens).det()
  535. def trace(self, tokens):
  536. if not self._obj_is_sympy_Matrix(tokens[1]):
  537. raise LaTeXParsingError("Cannot take trace of non-matrix.")
  538. return sympy.Trace(tokens[1])
  539. def adjugate(self, tokens):
  540. if not self._obj_is_sympy_Matrix(tokens[1]):
  541. raise LaTeXParsingError("Cannot take adjugate of non-matrix.")
  542. # need .doit() since MatAdd does not support .adjugate() method
  543. return tokens[1].doit().adjugate()
  544. def _obj_is_sympy_Matrix(self, obj):
  545. if hasattr(obj, "is_Matrix"):
  546. return obj.is_Matrix
  547. return isinstance(obj, sympy.Matrix)
  548. def _handle_division(self, numerator, denominator):
  549. if self._obj_is_sympy_Matrix(denominator):
  550. raise LaTeXParsingError("Cannot divide by matrices like this since "
  551. "it is not clear if left or right multiplication "
  552. "by the inverse is intended. Try explicitly "
  553. "multiplying by the inverse instead.")
  554. if self._obj_is_sympy_Matrix(numerator):
  555. return sympy.MatMul(numerator, sympy.Pow(denominator, -1))
  556. return sympy.Mul(numerator, sympy.Pow(denominator, -1))