Skip to content

Commit f9d463d

Browse files
committed
merge
2 parents fbef666 + 7b57406 commit f9d463d

File tree

4 files changed

+230
-42
lines changed

4 files changed

+230
-42
lines changed

mathics/builtin/arithfns/basic.py

Lines changed: 61 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
88
"""
99

10+
import sympy
11+
1012
from mathics.builtin.arithmetic import create_infix
1113
from mathics.builtin.base import (
1214
BinaryOperator,
@@ -45,7 +47,6 @@
4547
Symbol,
4648
SymbolDivide,
4749
SymbolHoldForm,
48-
SymbolNull,
4950
SymbolPower,
5051
SymbolTimes,
5152
)
@@ -56,10 +57,17 @@
5657
SymbolInfix,
5758
SymbolLeft,
5859
SymbolMinus,
60+
SymbolOverflow,
5961
SymbolPattern,
60-
SymbolSequence,
6162
)
62-
from mathics.eval.arithmetic import eval_Plus, eval_Times
63+
from mathics.eval.arithmetic import (
64+
associate_powers,
65+
eval_Exponential,
66+
eval_Plus,
67+
eval_Power_inexact,
68+
eval_Power_number,
69+
eval_Times,
70+
)
6371
from mathics.eval.nevaluator import eval_N
6472
from mathics.eval.numerify import numerify
6573

@@ -527,6 +535,8 @@ class Power(BinaryOperator, MPMathFunction):
527535
rules = {
528536
"Power[]": "1",
529537
"Power[x_]": "x",
538+
"Power[I,-1]": "-I",
539+
"Power[-1, 1/2]": "I",
530540
}
531541

532542
summary_text = "exponentiate"
@@ -535,15 +545,15 @@ class Power(BinaryOperator, MPMathFunction):
535545
# Remember to up sympy doc link when this is corrected
536546
sympy_name = "Pow"
537547

548+
def eval_exp(self, x, evaluation):
549+
"Power[E, x]"
550+
return eval_Exponential(x)
551+
538552
def eval_check(self, x, y, evaluation):
539553
"Power[x_, y_]"
540-
541-
# Power uses MPMathFunction but does some error checking first
542-
if isinstance(x, Number) and x.is_zero:
543-
if isinstance(y, Number):
544-
y_err = y
545-
else:
546-
y_err = eval_N(y, evaluation)
554+
# if x is zero
555+
if x.is_zero:
556+
y_err = y if isinstance(y, Number) else eval_N(y, evaluation)
547557
if isinstance(y_err, Number):
548558
py_y = y_err.round_to_float(permit_complex=True).real
549559
if py_y > 0:
@@ -557,17 +567,47 @@ def eval_check(self, x, y, evaluation):
557567
evaluation.message(
558568
"Power", "infy", Expression(SymbolPower, x, y_err)
559569
)
560-
return SymbolComplexInfinity
561-
if isinstance(x, Complex) and x.real.is_zero:
562-
yhalf = Expression(SymbolTimes, y, RationalOneHalf)
563-
factor = self.eval(Expression(SymbolSequence, x.imag, y), evaluation)
564-
return Expression(
565-
SymbolTimes, factor, Expression(SymbolPower, IntegerM1, yhalf)
566-
)
567-
568-
result = self.eval(Expression(SymbolSequence, x, y), evaluation)
569-
if result is None or result != SymbolNull:
570-
return result
570+
return SymbolComplexInfinity
571+
572+
# If x and y are inexact numbers, use the numerical function
573+
574+
if x.is_inexact() and y.is_inexact():
575+
try:
576+
return eval_Power_inexact(x, y)
577+
except OverflowError:
578+
evaluation.message("General", "ovfl")
579+
return Expression(SymbolOverflow)
580+
581+
# Tries to associate powers a^b^c-> a^(b*c)
582+
assoc = associate_powers(x, y)
583+
if not assoc.has_form("Power", 2):
584+
return assoc
585+
586+
assoc = numerify(assoc, evaluation)
587+
x, y = assoc.elements
588+
# If x and y are numbers
589+
if isinstance(x, Number) and isinstance(y, Number):
590+
try:
591+
return eval_Power_number(x, y)
592+
except OverflowError:
593+
evaluation.message("General", "ovfl")
594+
return Expression(SymbolOverflow)
595+
596+
# if x or y are inexact, leave the expression
597+
# as it is:
598+
if x.is_inexact() or y.is_inexact():
599+
return assoc
600+
601+
# Finally, try to convert to sympy
602+
base_sp, exp_sp = x.to_sympy(), y.to_sympy()
603+
if base_sp is None or exp_sp is None:
604+
# If base or exp can not be converted to sympy,
605+
# returns the result of applying the associative
606+
# rule.
607+
return assoc
608+
609+
result = from_sympy(sympy.Pow(base_sp, exp_sp))
610+
return result.evaluate_elements(evaluation)
571611

572612

573613
class Sqrt(SympyFunction):

mathics/eval/arithmetic.py

Lines changed: 132 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
# -*- coding: utf-8 -*-
22

33
"""
4-
arithmetic-related evaluation functions.
4+
helper functions for arithmetic evaluation, which do not
5+
depends on the evaluation context. Conversions to Sympy are
6+
used just as a last resource.
57
68
Many of these do do depend on the evaluation context. Conversions to Sympy are
79
used just as a last resource.
@@ -320,6 +322,28 @@ def eval_complex_sign(n: BaseElement) -> Optional[BaseElement]:
320322
return sign or eval_complex_sign(expr)
321323

322324

325+
def eval_Sign_number(n: Number) -> Number:
326+
"""
327+
Evals the absolute value of a number.
328+
"""
329+
if n.is_zero:
330+
return Integer0
331+
if isinstance(n, (Integer, Rational, Real)):
332+
return Integer1 if n.value > 0 else IntegerM1
333+
if isinstance(n, Complex):
334+
abs_sq = eval_add_numbers(
335+
*(eval_multiply_numbers(x, x) for x in (n.real, n.imag))
336+
)
337+
criteria = eval_add_numbers(abs_sq, IntegerM1)
338+
if test_zero_arithmetic_expr(criteria):
339+
return n
340+
if n.is_inexact():
341+
return eval_multiply_numbers(n, eval_Power_number(abs_sq, RealM0p5))
342+
if test_zero_arithmetic_expr(criteria, numeric=True):
343+
return n
344+
return eval_multiply_numbers(n, eval_Power_number(abs_sq, RationalMOneHalf))
345+
346+
323347
def eval_mpmath_function(
324348
mpmath_function: Callable, *args: Number, prec: Optional[int] = None
325349
) -> Optional[Number]:
@@ -347,6 +371,31 @@ def eval_mpmath_function(
347371
return call_mpmath(mpmath_function, tuple(mpmath_args), prec)
348372

349373

374+
def eval_Exponential(exp: BaseElement) -> BaseElement:
375+
"""
376+
Eval E^exp
377+
"""
378+
# If both base and exponent are exact quantities,
379+
# use sympy.
380+
381+
if not exp.is_inexact():
382+
exp_sp = exp.to_sympy()
383+
if exp_sp is None:
384+
return None
385+
return from_sympy(sympy.Exp(exp_sp))
386+
387+
prec = exp.get_precision()
388+
if prec is not None:
389+
if exp.is_machine_precision():
390+
number = mpmath.exp(exp.to_mpmath())
391+
result = from_mpmath(number)
392+
return result
393+
else:
394+
with mpmath.workprec(prec):
395+
number = mpmath.exp(exp.to_mpmath())
396+
return from_mpmath(number, prec)
397+
398+
350399
def eval_Plus(*items: BaseElement) -> BaseElement:
351400
"evaluate Plus for general elements"
352401
numbers, items_tuple = segregate_numbers_from_sorted_list(*items)
@@ -645,8 +694,88 @@ def eval_Times(*items: BaseElement) -> BaseElement:
645694
)
646695

647696

697+
# Here I used the convention of calling eval_* to functions that can produce a new expression, or None
698+
# if the result can not be evaluated, or is trivial. For example, if we call eval_Power_number(Integer2, RationalOneHalf)
699+
# it returns ``None`` instead of ``Expression(SymbolPower, Integer2, RationalOneHalf)``.
700+
# The reason is that these functions are written to be part of replacement rules, to be applied during the evaluation process.
701+
# In that process, a rule is considered applied if produces an expression that is different from the original one, or
702+
# if the replacement function returns (Python's) ``None``.
703+
#
704+
# For example, when the expression ``Power[4, 1/2]`` is evaluated, a (Builtin) rule ``Power[base_, exp_]->eval_repl_rule(base, expr)``
705+
# is applied. If the rule matches, `repl_rule` is called with arguments ``(4, 1/2)`` and produces `2`. As `Integer2.sameQ(Power[4, 1/2])`
706+
# is False, then no new rules for `Power` are checked, and a new round of evaluation is atempted.
707+
#
708+
# On the other hand, if ``Power[3, 1/2]``, ``repl_rule`` can do two possible things: one is return ``Power[3, 1/2]``. If it does,
709+
# the rule is considered applied. Then, the evaluation method checks if `Power[3, 1/2].sameQ(Power[3, 1/2])`. In this case it is true,
710+
# and then the expression is kept as it is.
711+
# The other possibility is to return (Python's) `None`. In that case, the evaluator considers that the rule failed to be applied,
712+
# and look for another rule associated to ``Power``. To return ``None`` produces then a faster evaluation, since no ``sameQ`` call is needed,
713+
# and do not prevent that other rules are attempted.
714+
#
715+
# The bad part of using ``None`` as a return is that I would expect that ``eval`` produces always a valid Expression, so if at some point of
716+
# the code I call ``eval_Power_number(Integer3, RationalOneHalf)`` I get ``Expression(SymbolPower, Integer3, RationalOneHalf)``.
717+
#
718+
# From my point of view, it would make more sense to use the following convention:
719+
# * if the method has signature ``eval_method(...)->BaseElement:`` then use the prefix ``eval_``
720+
# * if the method has the siguature ``apply_method(...)->Optional[BaseElement]`` use the prefix ``apply_`` or maybe ``repl_``.
721+
#
722+
# In any case, let's keep the current convention.
723+
#
724+
#
725+
726+
727+
def associate_powers(expr: BaseElement, power: BaseElement = Integer1) -> BaseElement:
728+
"""
729+
base^a^b^c^...^power -> base^(a*b*c*...power)
730+
provided one of the following cases
731+
* `a`, `b`, ... `power` are all integer numbers
732+
* `a`, `b`,... are Rational/Real number with absolute value <=1,
733+
and the other powers are not integer numbers.
734+
* `a` is not a Rational/Real number, and b, c, ... power are all
735+
integer numbers.
736+
"""
737+
powers = []
738+
base = expr
739+
if power is not Integer1:
740+
powers.append(power)
741+
742+
while base.has_form("Power", 2):
743+
previous_base, outer_power = base, power
744+
base, power = base.elements
745+
if len(powers) == 0:
746+
if power is not Integer1:
747+
powers.append(power)
748+
continue
749+
if power is IntegerM1:
750+
powers.append(power)
751+
continue
752+
if isinstance(power, (Rational, Real)):
753+
if abs(power.value) < 1:
754+
powers.append(power)
755+
continue
756+
# power is not rational/real and outer_power is integer,
757+
elif isinstance(outer_power, Integer):
758+
if power is not Integer1:
759+
powers.append(power)
760+
if isinstance(power, Integer):
761+
continue
762+
else:
763+
break
764+
# in any other case, use the previous base and
765+
# exit the loop
766+
base = previous_base
767+
break
768+
769+
if len(powers) == 0:
770+
return base
771+
elif len(powers) == 1:
772+
return Expression(SymbolPower, base, powers[0])
773+
result = Expression(SymbolPower, base, Expression(SymbolTimes, *powers))
774+
return result
775+
776+
648777
def eval_add_numbers(
649-
*numbers: Number,
778+
*numbers: List[Number],
650779
) -> BaseElement:
651780
"""
652781
Add the elements in ``numbers``.
@@ -693,7 +822,7 @@ def eval_inverse_number(n: Number) -> Number:
693822
return eval_Power_number(n, IntegerM1)
694823

695824

696-
def eval_multiply_numbers(*numbers: Number) -> Number:
825+
def eval_multiply_numbers(*numbers: Number) -> BaseElement:
697826
"""
698827
Multiply the elements in ``numbers``.
699828
"""

test/builtin/arithmetic/test_basic.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -153,8 +153,8 @@ def test_multiply(str_expr, str_expected, msg):
153153
("a b DirectedInfinity[q]", "a b (q Infinity)", ""),
154154
# Failing tests
155155
# Problem with formatting. Parenthezise are missing...
156-
# ("a b DirectedInfinity[-I]", "a b (-I Infinity)", ""),
157-
# ("a b DirectedInfinity[-3]", "a b (-Infinity)", ""),
156+
("a b DirectedInfinity[-I]", "a b (-I Infinity)", ""),
157+
("a b DirectedInfinity[-3]", "a b (-Infinity)", ""),
158158
],
159159
)
160160
def test_directed_infinity_precedence(str_expr, str_expected, msg):
@@ -197,7 +197,7 @@ def test_directed_infinity_precedence(str_expr, str_expected, msg):
197197
("I^(2/3)", "(-1) ^ (1 / 3)", None),
198198
# In WMA, the next test would return ``-(-I)^(2/3)``
199199
# which is less compact and elegant...
200-
# ("(-I)^(2/3)", "(-1) ^ (-1 / 3)", None),
200+
("(-I)^(2/3)", "(-1) ^ (-1 / 3)", None),
201201
("(2+3I)^3", "-46 + 9 I", None),
202202
("(1.+3. I)^.6", "1.46069 + 1.35921 I", None),
203203
("3^(1+2 I)", "3 ^ (1 + 2 I)", None),
@@ -208,15 +208,15 @@ def test_directed_infinity_precedence(str_expr, str_expected, msg):
208208
# sympy, which produces the result
209209
("(3/Pi)^(-I)", "(3 / Pi) ^ (-I)", None),
210210
# Association rules
211-
# ('(a^"w")^2', 'a^(2 "w")', "Integer power of a power with string exponent"),
211+
('(a^"w")^2', 'a^(2 "w")', "Integer power of a power with string exponent"),
212212
('(a^2)^"w"', '(a ^ 2) ^ "w"', None),
213213
('(a^2)^"w"', '(a ^ 2) ^ "w"', None),
214214
("(a^2)^(1/2)", "Sqrt[a ^ 2]", None),
215215
("(a^(1/2))^2", "a", None),
216216
("(a^(1/2))^2", "a", None),
217217
("(a^(3/2))^3.", "(a ^ (3 / 2)) ^ 3.", None),
218-
# ("(a^(1/2))^3.", "a ^ 1.5", "Power associativity rational, real"),
219-
# ("(a^(.3))^3.", "a ^ 0.9", "Power associativity for real powers"),
218+
("(a^(1/2))^3.", "a ^ 1.5", "Power associativity rational, real"),
219+
("(a^(.3))^3.", "a ^ 0.9", "Power associativity for real powers"),
220220
("(a^(1.3))^3.", "(a ^ 1.3) ^ 3.", None),
221221
# Exponentials involving expressions
222222
("(a^(p-2 q))^3", "a ^ (3 p - 6 q)", None),

0 commit comments

Comments
 (0)