-
-
Notifications
You must be signed in to change notification settings - Fork 60
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Arithmetic refactor #766
Closed
Closed
Arithmetic refactor #766
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
17e6ed1
test_zero_arithmetic_expr
mmatera 5110739
improve positivity test for powers. Handle constants
mmatera 8e7e774
adding tests. fix typo
mmatera 773aee0
Pi is a Numpy constant
mmatera e8b90f8
arithmetic refactor
mmatera 757011f
flake8 mathics.eval.parts
mmatera d5be5ae
Merge branch 'arithmetic_test_zero' into arithmetic_refactor
mmatera 7b6f650
Pi is a Numpy constant
mmatera f39e64e
Merge branch 'arithmetic_test_zero' into arithmetic_refactor
mmatera f44dc77
adding session.parse method, which is handy for low-level tests. remo…
mmatera 2481118
Pi is a Numpy constant
mmatera d9a961a
Merge branch 'tidy_up_stuff' into arithmetic_test_zero
mmatera 4cf85ac
Merge branch 'arithmetic_test_zero' into arithmetic_refactor
mmatera 279ae2c
Merge branch 'master' into arithmetic_refactor
mmatera a0b5310
flake8
mmatera 74e5823
Merge branch 'master' into arithmetic_refactor
mmatera a2ada0b
Correct typo in error message pattern
rocky 87316dc
RealAbs and RealSign
mmatera fc54766
Merge branch 'master' into RealAbs_and_RealSign
mmatera b3119c5
merge
mmatera 4d8f5b1
tiny tweaks in documentation
mmatera c32daa2
Merge branch 'RealAbs_and_RealSign' into arithmetic_refactor
mmatera 261ba42
merge
mmatera c16e3bc
remove duplicated
mmatera 539a29b
Merge branch 'master' into arithmetic_refactor
mmatera File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,9 @@ | ||
# -*- coding: utf-8 -*- | ||
|
||
""" | ||
arithmetic-related evaluation functions. | ||
helper functions for arithmetic evaluation, which do not | ||
depends on the evaluation context. Conversions to Sympy are | ||
used just as a last resource. | ||
|
||
Many of these do do depend on the evaluation context. Conversions to Sympy are | ||
used just as a last resource. | ||
|
@@ -320,6 +322,28 @@ def eval_complex_sign(n: BaseElement) -> Optional[BaseElement]: | |
return sign or eval_complex_sign(expr) | ||
|
||
|
||
def eval_Sign_number(n: Number) -> Number: | ||
""" | ||
Evals the absolute value of a number. | ||
""" | ||
if n.is_zero: | ||
return Integer0 | ||
if isinstance(n, (Integer, Rational, Real)): | ||
return Integer1 if n.value > 0 else IntegerM1 | ||
if isinstance(n, Complex): | ||
abs_sq = eval_add_numbers( | ||
*(eval_multiply_numbers(x, x) for x in (n.real, n.imag)) | ||
) | ||
criteria = eval_add_numbers(abs_sq, IntegerM1) | ||
if test_zero_arithmetic_expr(criteria): | ||
return n | ||
if n.is_inexact(): | ||
return eval_multiply_numbers(n, eval_Power_number(abs_sq, RealM0p5)) | ||
if test_zero_arithmetic_expr(criteria, numeric=True): | ||
return n | ||
return eval_multiply_numbers(n, eval_Power_number(abs_sq, RationalMOneHalf)) | ||
|
||
|
||
def eval_mpmath_function( | ||
mpmath_function: Callable, *args: Number, prec: Optional[int] = None | ||
) -> Optional[Number]: | ||
|
@@ -345,6 +369,31 @@ def eval_mpmath_function( | |
return call_mpmath(mpmath_function, tuple(mpmath_args), prec) | ||
|
||
|
||
def eval_Exponential(exp: BaseElement) -> BaseElement: | ||
""" | ||
Eval E^exp | ||
""" | ||
# If both base and exponent are exact quantities, | ||
# use sympy. | ||
|
||
if not exp.is_inexact(): | ||
exp_sp = exp.to_sympy() | ||
if exp_sp is None: | ||
return None | ||
return from_sympy(sympy.Exp(exp_sp)) | ||
|
||
prec = exp.get_precision() | ||
if prec is not None: | ||
if exp.is_machine_precision(): | ||
number = mpmath.exp(exp.to_mpmath()) | ||
result = from_mpmath(number) | ||
return result | ||
else: | ||
with mpmath.workprec(prec): | ||
number = mpmath.exp(exp.to_mpmath()) | ||
return from_mpmath(number, prec) | ||
|
||
|
||
def eval_Plus(*items: BaseElement) -> BaseElement: | ||
"evaluate Plus for general elements" | ||
numbers, items_tuple = segregate_numbers_from_sorted_list(*items) | ||
|
@@ -643,9 +692,112 @@ def eval_Times(*items: BaseElement) -> BaseElement: | |
) | ||
|
||
|
||
# Here I used the convention of calling eval_* to functions that can produce a new expression, or None | ||
# if the result can not be evaluated, or is trivial. For example, if we call eval_Power_number(Integer2, RationalOneHalf) | ||
# it returns ``None`` instead of ``Expression(SymbolPower, Integer2, RationalOneHalf)``. | ||
# The reason is that these functions are written to be part of replacement rules, to be applied during the evaluation process. | ||
# In that process, a rule is considered applied if produces an expression that is different from the original one, or | ||
# if the replacement function returns (Python's) ``None``. | ||
# | ||
# For example, when the expression ``Power[4, 1/2]`` is evaluated, a (Builtin) rule ``Power[base_, exp_]->eval_repl_rule(base, expr)`` | ||
# 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])` | ||
# is False, then no new rules for `Power` are checked, and a new round of evaluation is atempted. | ||
# | ||
# 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, | ||
# 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, | ||
# and then the expression is kept as it is. | ||
# The other possibility is to return (Python's) `None`. In that case, the evaluator considers that the rule failed to be applied, | ||
# and look for another rule associated to ``Power``. To return ``None`` produces then a faster evaluation, since no ``sameQ`` call is needed, | ||
# and do not prevent that other rules are attempted. | ||
# | ||
# 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 | ||
# the code I call ``eval_Power_number(Integer3, RationalOneHalf)`` I get ``Expression(SymbolPower, Integer3, RationalOneHalf)``. | ||
# | ||
# From my point of view, it would make more sense to use the following convention: | ||
# * if the method has signature ``eval_method(...)->BaseElement:`` then use the prefix ``eval_`` | ||
# * if the method has the siguature ``apply_method(...)->Optional[BaseElement]`` use the prefix ``apply_`` or maybe ``repl_``. | ||
# | ||
# In any case, let's keep the current convention. | ||
# | ||
# | ||
|
||
|
||
def associate_powers(expr: BaseElement, power: BaseElement = Integer1) -> BaseElement: | ||
""" | ||
base^a^b^c^...^power -> base^(a*b*c*...power) | ||
provided one of the following cases | ||
* `a`, `b`, ... `power` are all integer numbers | ||
* `a`, `b`,... are Rational/Real number with absolute value <=1, | ||
and the other powers are not integer numbers. | ||
* `a` is not a Rational/Real number, and b, c, ... power are all | ||
integer numbers. | ||
""" | ||
powers = [] | ||
base = expr | ||
if power is not Integer1: | ||
powers.append(power) | ||
|
||
while base.has_form("Power", 2): | ||
previous_base, outer_power = base, power | ||
base, power = base.elements | ||
if len(powers) == 0: | ||
if power is not Integer1: | ||
powers.append(power) | ||
continue | ||
if power is IntegerM1: | ||
powers.append(power) | ||
continue | ||
if isinstance(power, (Rational, Real)): | ||
if abs(power.value) < 1: | ||
powers.append(power) | ||
continue | ||
# power is not rational/real and outer_power is integer, | ||
elif isinstance(outer_power, Integer): | ||
if power is not Integer1: | ||
powers.append(power) | ||
if isinstance(power, Integer): | ||
continue | ||
else: | ||
break | ||
# in any other case, use the previous base and | ||
# exit the loop | ||
base = previous_base | ||
break | ||
|
||
if len(powers) == 0: | ||
return base | ||
elif len(powers) == 1: | ||
return Expression(SymbolPower, base, powers[0]) | ||
result = Expression(SymbolPower, base, Expression(SymbolTimes, *powers)) | ||
return result | ||
|
||
|
||
def distribute_factor(expr: BaseElement, factor: BaseElement) -> BaseElement: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am not seeing |
||
""" | ||
q * (a + b + c) -> (q a + q b + q c) | ||
""" | ||
if not expr.has_form("Plus", None): | ||
return expr | ||
terms = (Expression(SymbolTimes, factor, term) for term in expr.elements) | ||
return Expression(SymbolPlus, *terms) | ||
|
||
|
||
def distribute_powers(expr: BaseElement) -> BaseElement: | ||
""" | ||
(a b c)^p -> (a^p b^p c^p) | ||
""" | ||
if not expr.has_form("Power", 2): | ||
return expr | ||
base, exp = expr.elements | ||
if not base.has_form("Times", None): | ||
return expr | ||
factors = (Expression(SymbolPower, factor, exp) for factor in base.elements) | ||
return Expression(SymbolTimes, *factors) | ||
|
||
|
||
def eval_add_numbers( | ||
*numbers: Number, | ||
) -> BaseElement: | ||
*numbers: List[Number], | ||
) -> Number: | ||
""" | ||
Add the elements in ``numbers``. | ||
""" | ||
|
@@ -671,6 +823,16 @@ def eval_add_numbers( | |
return from_sympy(sum(item.to_sympy() for item in numbers)) | ||
|
||
|
||
def eval_complex_conjugate(z: Number) -> Number: | ||
""" | ||
Evaluates the complex conjugate of z. | ||
""" | ||
if isinstance(z, Complex): | ||
re, im = z.real, z.imag | ||
return Complex(re, eval_negate_number(im)) | ||
return z | ||
|
||
|
||
def eval_inverse_number(n: Number) -> Number: | ||
""" | ||
Eval 1/n | ||
|
@@ -729,6 +891,24 @@ def eval_negate_number(n: Number) -> Number: | |
return eval_multiply_numbers(IntegerM1, n) | ||
|
||
|
||
def flat_arithmetic_operators(expr: Expression) -> Expression: | ||
""" | ||
operation[a_number, b, operation[c_number, d], e]-> operation[a, c, b, c, d, e] | ||
""" | ||
# items is a dict with two keys: True and False. | ||
# In True we store numeric items, and in False the symbolic ones. | ||
items = {True: [], False: []} | ||
head = expr.get_head() | ||
for element in expr.elements: | ||
# If the element is also head[elements], | ||
# take its elements, and append to the main expression. | ||
if element.get_head() is head: | ||
for item in flat_arithmetic_operators(element).elements: | ||
item[isinstance(item, Number)].append(item) | ||
item[isinstance(item, Number)].append(item) | ||
return Expression(head, *items[True], *items[False]) | ||
|
||
|
||
def segregate_numbers( | ||
*elements: BaseElement, | ||
) -> Tuple[List[Number], List[BaseElement]]: | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@rocky, I leave this long comment here about the eval<-> apply semantics. Maybe we want to go over this again before merging this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I looked at this and there is information here that I a do not believe is elsewhere. I think it should be elsewhere but I don't know right now where that elsewhere is.