Skip to content
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

Draft
wants to merge 25 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
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 May 26, 2023
5110739
improve positivity test for powers. Handle constants
mmatera May 26, 2023
8e7e774
adding tests. fix typo
mmatera May 26, 2023
773aee0
Pi is a Numpy constant
mmatera May 26, 2023
e8b90f8
arithmetic refactor
mmatera May 26, 2023
757011f
flake8 mathics.eval.parts
mmatera May 26, 2023
d5be5ae
Merge branch 'arithmetic_test_zero' into arithmetic_refactor
mmatera May 26, 2023
7b6f650
Pi is a Numpy constant
mmatera May 26, 2023
f39e64e
Merge branch 'arithmetic_test_zero' into arithmetic_refactor
mmatera May 26, 2023
f44dc77
adding session.parse method, which is handy for low-level tests. remo…
mmatera May 26, 2023
2481118
Pi is a Numpy constant
mmatera May 26, 2023
d9a961a
Merge branch 'tidy_up_stuff' into arithmetic_test_zero
mmatera May 26, 2023
4cf85ac
Merge branch 'arithmetic_test_zero' into arithmetic_refactor
mmatera May 26, 2023
279ae2c
Merge branch 'master' into arithmetic_refactor
mmatera May 27, 2023
a0b5310
flake8
mmatera May 27, 2023
74e5823
Merge branch 'master' into arithmetic_refactor
mmatera Jul 15, 2023
a2ada0b
Correct typo in error message pattern
rocky Jul 16, 2023
87316dc
RealAbs and RealSign
mmatera May 29, 2023
fc54766
Merge branch 'master' into RealAbs_and_RealSign
mmatera Jul 20, 2023
b3119c5
merge
mmatera Jul 20, 2023
4d8f5b1
tiny tweaks in documentation
mmatera Jul 21, 2023
c32daa2
Merge branch 'RealAbs_and_RealSign' into arithmetic_refactor
mmatera Jul 21, 2023
ada4a4a
RealAbs and RealSign (#885)
mmatera Jul 21, 2023
261ba42
merge
mmatera Jul 21, 2023
c16e3bc
remove duplicated
mmatera Jul 21, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ New Builtins


* `Elements`

* `RealAbs` and `RealSign`

Compatibility
-------------
Expand All @@ -24,7 +24,7 @@ Internals
* ``eval_abs`` and ``eval_sign`` extracted from ``Abs`` and ``Sign`` and added to ``mathics.eval.arithmetic``.
* Maximum number of digits allowed in a string set to 7000 and can be adjusted using environment variable
``MATHICS_MAX_STR_DIGITS`` on Python versions that don't adjust automatically (like pyston).

* Real number comparisons implemented is based now in the internal implementation of `RealSign`.

Bugs
----
Expand Down
2 changes: 2 additions & 0 deletions SYMBOLS_MANIFEST.txt
Original file line number Diff line number Diff line change
Expand Up @@ -824,8 +824,10 @@ System`Read
System`ReadList
System`ReadProtected
System`Real
System`RealAbs
System`RealDigits
System`RealNumberQ
System`RealSign
System`Reals
System`Reap
System`Record
Expand Down
82 changes: 61 additions & 21 deletions mathics/builtin/arithfns/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

"""

import sympy

from mathics.builtin.arithmetic import _MPMathFunction, create_infix
from mathics.builtin.base import BinaryOperator, Builtin, PrefixOperator, SympyFunction
from mathics.core.atoms import (
Expand Down Expand Up @@ -38,7 +40,6 @@
Symbol,
SymbolDivide,
SymbolHoldForm,
SymbolNull,
SymbolPower,
SymbolTimes,
)
Expand All @@ -49,10 +50,17 @@
SymbolInfix,
SymbolLeft,
SymbolMinus,
SymbolOverflow,
SymbolPattern,
SymbolSequence,
)
from mathics.eval.arithmetic import eval_Plus, eval_Times
from mathics.eval.arithmetic import (
associate_powers,
eval_Exponential,
eval_Plus,
eval_Power_inexact,
eval_Power_number,
eval_Times,
)
from mathics.eval.nevaluator import eval_N
from mathics.eval.numerify import numerify

Expand Down Expand Up @@ -520,6 +528,8 @@ class Power(BinaryOperator, _MPMathFunction):
rules = {
"Power[]": "1",
"Power[x_]": "x",
"Power[I,-1]": "-I",
"Power[-1, 1/2]": "I",
}

summary_text = "exponentiate"
Expand All @@ -528,15 +538,15 @@ class Power(BinaryOperator, _MPMathFunction):
# Remember to up sympy doc link when this is corrected
sympy_name = "Pow"

def eval_exp(self, x, evaluation):
"Power[E, x]"
return eval_Exponential(x)

def eval_check(self, x, y, evaluation):
"Power[x_, y_]"

# Power uses _MPMathFunction but does some error checking first
if isinstance(x, Number) and x.is_zero:
if isinstance(y, Number):
y_err = y
else:
y_err = eval_N(y, evaluation)
# if x is zero
if x.is_zero:
y_err = y if isinstance(y, Number) else eval_N(y, evaluation)
if isinstance(y_err, Number):
py_y = y_err.round_to_float(permit_complex=True).real
if py_y > 0:
Expand All @@ -550,17 +560,47 @@ def eval_check(self, x, y, evaluation):
evaluation.message(
"Power", "infy", Expression(SymbolPower, x, y_err)
)
return SymbolComplexInfinity
if isinstance(x, Complex) and x.real.is_zero:
yhalf = Expression(SymbolTimes, y, RationalOneHalf)
factor = self.eval(Expression(SymbolSequence, x.imag, y), evaluation)
return Expression(
SymbolTimes, factor, Expression(SymbolPower, IntegerM1, yhalf)
)

result = self.eval(Expression(SymbolSequence, x, y), evaluation)
if result is None or result != SymbolNull:
return result
return SymbolComplexInfinity

# If x and y are inexact numbers, use the numerical function

if x.is_inexact() and y.is_inexact():
try:
return eval_Power_inexact(x, y)
except OverflowError:
evaluation.message("General", "ovfl")
return Expression(SymbolOverflow)

# Tries to associate powers a^b^c-> a^(b*c)
assoc = associate_powers(x, y)
if not assoc.has_form("Power", 2):
return assoc

assoc = numerify(assoc, evaluation)
x, y = assoc.elements
# If x and y are numbers
if isinstance(x, Number) and isinstance(y, Number):
try:
return eval_Power_number(x, y)
except OverflowError:
evaluation.message("General", "ovfl")
return Expression(SymbolOverflow)

# if x or y are inexact, leave the expression
# as it is:
if x.is_inexact() or y.is_inexact():
return assoc

# Finally, try to convert to sympy
base_sp, exp_sp = x.to_sympy(), y.to_sympy()
if base_sp is None or exp_sp is None:
# If base or exp can not be converted to sympy,
# returns the result of applying the associative
# rule.
return assoc

result = from_sympy(sympy.Pow(base_sp, exp_sp))
return result.evaluate_elements(evaluation)


class Sqrt(SympyFunction):
Expand Down
102 changes: 99 additions & 3 deletions mathics/builtin/arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,13 @@
SymbolTable,
SymbolUndefined,
)
from mathics.eval.arithmetic import eval_Abs, eval_mpmath_function, eval_Sign
from mathics.eval.arithmetic import (
eval_Abs,
eval_mpmath_function,
eval_negate_number,
eval_RealSign,
eval_Sign,
)
from mathics.eval.nevaluator import eval_N
from mathics.eval.numerify import numerify

Expand Down Expand Up @@ -823,7 +829,9 @@ def evaluate(self, evaluation: Evaluation):

class Im(SympyFunction):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Im.html</url>
<url>
:WMA link:
https://reference.wolfram.com/language/ref/Im.html</url>

<dl>
<dt>'Im[$z$]'
Expand Down Expand Up @@ -1207,6 +1215,49 @@ class Real_(Builtin):
name = "Real"


class RealAbs(Builtin):
"""
<url>
:Abs (Real):
https://en.wikipedia.org/wiki/Absolute_value</url> (<url>
:WMA link:
https://reference.wolfram.com/language/ref/RealAbs.html
</url>)

<dl>
<dt>'RealAbs[$x$]'
<dd>returns the absolute value of a real number $x$.
</dl>
'RealAbs' is also known as modulus. It is evaluated if $x$ can be compared \
with $0$.

>> RealAbs[-3.]
= 3.
'RealAbs[$z$]' is left unevaluated for complex $z$:
>> RealAbs[2. + 3. I]
= RealAbs[2. + 3. I]
>> D[RealAbs[x ^ 2], x]
= 2 x ^ 3 / RealAbs[x ^ 2]
"""

attributes = A_LISTABLE | A_NUMERIC_FUNCTION | A_PROTECTED
rules = {
"D[RealAbs[x_],x_]": "x/RealAbs[x]",
"Integrate[RealAbs[x_],x_]": "1/2 x RealAbs[x]",
"Integrate[RealAbs[u_],{u_,a_,b_}]": "1/2 b RealAbs[b]-1/2 a RealAbs[a]",
}
summary_text = "real absolute value"

def eval(self, x: BaseElement, evaluation: Evaluation):
"""RealAbs[x_]"""
real_sign = eval_RealSign(x)
if real_sign is IntegerM1:
return eval_negate_number(x)
if real_sign is None:
return
return x


class RealNumberQ(Test):
"""
## Not found in WMA
Expand Down Expand Up @@ -1237,9 +1288,54 @@ def test(self, expr) -> bool:
return isinstance(expr, (Integer, Rational, Real))


class RealSign(Builtin):
"""
<url>
:Signum:
https://en.wikipedia.org/wiki/Sign_function</url> (<url>
:WMA link:
https://reference.wolfram.com/language/ref/RealSign.html
</url>)
<dl>
<dt>'RealSign[$x$]'
<dd>returns $-1$, $0$ or $1$ depending on whether $x$ is negative,
zero or positive.
</dl>
'RealSign' is also known as $sgn$ or $signum$ function.

>> RealSign[-3.]
= -1
'RealSign[$z$]' is left unevaluated for complex $z$:
>> RealSign[2. + 3. I]
= RealSign[2. + 3. I]

>> D[RealSign[x^2],x]
= 2 x Piecewise[{{0, x ^ 2 != 0}}, Indeterminate]
>> Integrate[RealSign[u],{u,0,x}]
= RealAbs[x]
"""

attributes = A_LISTABLE | A_NUMERIC_FUNCTION | A_PROTECTED
rules = {
"D[RealSign[x_],x_]": "Piecewise[{{0, x!=0}}, Indeterminate]",
"Integrate[RealSign[x_],x_]": "RealAbs[x]",
"Integrate[RealSign[u_],{u_, a_, b_}]": "RealAbs[b]-RealSign[a]",
}
summary_text = "real sign"

def eval(self, x: Number, evaluation: Evaluation) -> Optional[Integer]:
"""RealSign[x_]"""
return eval_RealSign(x)


class Sign(SympyFunction):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Sign.html</url>
<url>
:Sign:
https://en.wikipedia.org/wiki/Sign_function</url> (<url>
:WMA link:
https://reference.wolfram.com/language/ref/Sign.html
</url>)

<dl>
<dt>'Sign[$x$]'
Expand Down
3 changes: 1 addition & 2 deletions mathics/builtin/testing_expressions/equality_inequality.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ def numerify_args(items, evaluation) -> list:
n_items = []
for item in items:
if not isinstance(item, Number):
# TODO: use $MaxExtraPrecision insterad of hard-coded 50
item = eval_N(item, evaluation, SymbolMaxPrecision)
item = eval_N(item, evaluation, SymbolMaxExtraPrecision)
n_items.append(item)
items = n_items
else:
Expand Down
4 changes: 3 additions & 1 deletion mathics/core/systemsymbols.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,9 @@
SymbolRational = Symbol("System`Rational")
SymbolRe = Symbol("System`Re")
SymbolReal = Symbol("System`Real")
SymbolRealAbs = Symbol("System`RealAbs")
SymbolRealDigits = Symbol("System`RealDigits")
SymbolRealSign = Symbol("System`RealSign")
SymbolRepeated = Symbol("System`Repeated")
SymbolRepeatedNull = Symbol("System`RepeatedNull")
SymbolReturn = Symbol("System`Return")
Expand All @@ -223,7 +225,7 @@
SymbolSlot = Symbol("System`Slot")
SymbolSparseArray = Symbol("System`SparseArray")
SymbolSplit = Symbol("System`Split")
SymbolSqrt = Symbol("System'Sqrt")
SymbolSqrt = Symbol("System`Sqrt")
SymbolSqrtBox = Symbol("System`SqrtBox")
SymbolStandardDeviation = Symbol("System`StandardDeviation")
SymbolStandardForm = Symbol("System`StandardForm")
Expand Down
Loading
Loading