Mapytex/pymath/expression.py

456 lines
14 KiB
Python
Raw Normal View History

2013-08-09 09:35:14 +00:00
#!/usr/bin/env python
# encoding: utf-8
2014-12-22 13:14:37 +00:00
from .generic import Stack, flatten_list, expand_list, isNumber, isOperator, isNumerand
from .str2tokens import str2tokens
2014-11-14 15:48:38 +00:00
from .operator import op
from .explicable import Explicable
2013-11-01 21:58:42 +00:00
from .random_expression import RdExpression
2015-02-27 16:46:16 +00:00
__all__ = ['Expression']
2013-08-09 09:35:14 +00:00
2014-11-21 14:49:43 +00:00
2015-02-27 16:46:16 +00:00
class Expression(Explicable):
"""A calculus expression. Today it can andle only expression with numbers later it will be able to manipulate unknown"""
2014-11-21 14:49:43 +00:00
2014-11-21 14:49:43 +00:00
@classmethod
2015-02-27 16:46:16 +00:00
def random(self, form="", conditions=[], val_min = -10, val_max=10):
"""Create a random expression from form and with conditions
:param form: the form of the expression (/!\ variables need to be in brackets {})
:param conditions: condition on variables (/!\ variables need to be in brackets {})
:param val_min: min value for generate variables
:param val_max: max value for generate variables
"""
random_generator = RdExpression(form, conditions)
return Expression(random_generator(val_min, val_max))
2013-08-09 11:08:24 +00:00
@classmethod
def tmp_render(cls, render = lambda _,x:Expression(x)):
2015-02-27 16:46:16 +00:00
""" Same ad tmp_render for Renderable but default render is Expression
>>> exp = Expression("2*3/5")
>>> print(exp)
2015-02-27 16:46:16 +00:00
2 \\times \\frac{ 3 }{ 5 }
>>> for i in exp.simplify().explain():
... print(i)
2015-02-27 16:46:16 +00:00
2 \\times \\frac{ 3 }{ 5 }
\\frac{ 3 }{ 5 } \\times 2
\\frac{ 3 \\times 2 }{ 5 }
\\frac{ 6 }{ 5 }
>>> with Expression.tmp_render():
... for i in exp.simplify().explain():
... i
2015-02-28 22:13:51 +00:00
< <class 'pymath.expression.Expression'> [2, 3, 5, '/', '*'] >
< <class 'pymath.expression.Expression'> [2, < Fraction 3 / 5>, '*'] >
< <class 'pymath.expression.Expression'> [3, 5, '/', 2, '*'] >
< <class 'pymath.expression.Expression'> [3, 2, '*', 5, '/'] >
2015-02-28 22:13:51 +00:00
< <class 'pymath.expression.Expression'> [6, 5, '/'] >
2015-02-27 16:46:16 +00:00
>>> from .render import txt
>>> with Expression.tmp_render(txt):
... for i in exp.simplify().explain():
... print(i)
2 * 3 / 5
3 / 5 * 2
( 3 * 2 ) / 5
6 / 5
>>> for i in exp.simplify().explain():
... print(i)
2015-02-27 16:46:16 +00:00
2 \\times \\frac{ 3 }{ 5 }
\\frac{ 3 }{ 5 } \\times 2
\\frac{ 3 \\times 2 }{ 5 }
\\frac{ 6 }{ 5 }
"""
2015-02-27 16:46:16 +00:00
return super(Expression, cls).tmp_render(render)
def __new__(cls, exp):
"""Create Expression objects
2013-08-09 09:35:14 +00:00
:param exp: the expression. It can be a string or a list of postfix tokens.
2013-08-09 09:35:14 +00:00
"""
expression = object.__new__(cls)
2013-11-01 21:58:42 +00:00
if type(exp) == str:
expression.postfix_tokens = str2tokens(exp)
2013-11-01 21:58:42 +00:00
elif type(exp) == list:
expression.postfix_tokens = flatten_list([tok.postfix_tokens if Expression.isExpression(tok) else tok for tok in exp])
elif type(exp) == Expression:
return exp
else:
raise ValueError("Can't build Expression with {} object".format(type(exp)))
if len(expression.postfix_tokens) == 1:
token = expression.postfix_tokens[0]
if hasattr(token, 'simplify') and hasattr(token, 'explain'):
return expression.postfix_tokens[0]
elif type(token) == int:
# On crée un faux int en ajoutant la méthode simplify et simplified et la caractérisique isNumber
simplify = lambda x:x
is_number = True
methods_attr = {'simplify':simplify, 'isNumber': is_number, 'postfix_tokens': [token]}
2015-02-27 16:46:16 +00:00
fake_token = type('fake_int', (int,Explicable, ), methods_attr)(token)
2014-12-22 10:21:58 +00:00
return fake_token
elif type(token) == str:
# TODO: Pourquoi ne pas créer directement un polynom ici? |jeu. févr. 26 18:59:24 CET 2015
2014-12-22 10:21:58 +00:00
# On crée un faux str en ajoutant la méthode simplify et simplified et la caractérisique isNumber
simplify = lambda x:[x]
is_polynom = True
methods_attr = {'simplify':simplify, '_isPolynom': is_polynom, 'postfix_tokens': [token]}
2015-02-27 16:46:16 +00:00
fake_token = type('fake_str', (str,Explicable, ), methods_attr)(token)
return fake_token
else:
raise ValueError("Unknow type in Expression: {}".format(type(token)))
else:
expression._isExpression = 1
return expression
2013-11-01 21:58:42 +00:00
def __str__(self):
"""
Overload str
If you want to changer render use Expression.set_render(...) or use tmp_render context manager.
"""
return self.STR_RENDER(self.postfix_tokens)
def __repr__(self):
2015-02-27 10:38:17 +00:00
return " ".join(["<", str(self.__class__) , str(self.postfix_tokens), ">"])
2014-11-21 14:49:43 +00:00
def simplify(self):
""" Compute entirely the expression and return the result with .steps attribute """
2014-12-21 18:13:52 +00:00
self.compute_exp()
self.simplified = self.child.simplify()
if self.simplified != self.child:
try:
self.simplified.steps = self.child.steps + self.simplified.steps
except AttributeError:
pass
return self.simplified
2013-11-01 21:58:42 +00:00
def compute_exp(self):
""" Create self.child with and stock steps in it """
ini_step = Expression(self.postfix_tokens)
2013-11-01 21:58:42 +00:00
tokenList = self.postfix_tokens.copy()
tmpTokenList = []
while len(tokenList) > 2:
# on va chercher les motifs du genre A B +, quand l'operateur est d'arité 2, pour les calculer
2014-12-22 13:14:37 +00:00
if isNumerand(tokenList[0]) and isNumerand(tokenList[1]) \
and isOperator(tokenList[2]) and tokenList[2].arity == 2 :
2013-11-01 21:58:42 +00:00
# S'il y a une opération à faire
op1 = tokenList[0]
op2 = tokenList[1]
operator = tokenList[2]
2014-12-02 13:31:27 +00:00
res = operator(op1, op2)
2013-11-01 21:58:42 +00:00
tmpTokenList.append(res)
# Comme on vient de faire le calcul, on peut détruire aussi les deux prochains termes
del tokenList[0:3]
# Et les motifs du gens A -, quand l'operateur est d'arité 1
2014-12-22 13:14:37 +00:00
elif isNumerand(tokenList[0]) \
and isOperator(tokenList[1]) and tokenList[1].arity == 1:
# S'il y a une opération à faire
op1 = tokenList[0]
operator = tokenList[1]
res = operator(op1)
tmpTokenList.append(res)
# Comme on vient de faire le calcul, on peut détruire aussi les deux prochains termes
del tokenList[0:2]
2013-11-01 21:58:42 +00:00
else:
tmpTokenList.append(tokenList[0])
del tokenList[0]
2014-12-22 13:14:37 +00:00
if len(tokenList) == 2 and isNumerand(tokenList[0]) \
and isOperator(tokenList[1]) and tokenList[1].arity == 1:
# S'il reste deux éléments dont un operation d'arité 1
op1 = tokenList[0]
operator = tokenList[1]
res = operator(op1)
tmpTokenList.append(res)
# Comme on vient de faire le calcul, on peut détruire aussi les deux prochains termes
del tokenList[0:2]
2013-11-01 21:58:42 +00:00
tmpTokenList += tokenList
self.child = Expression(tmpTokenList)
if self.child.postfix_tokens == ini_step.postfix_tokens:
self.child.steps = self.develop_steps(tmpTokenList)
else:
self.child.steps = [ini_step] + self.develop_steps(tmpTokenList)
def develop_steps(self, tokenList):
""" From a list of tokens, it develops steps of each tokens """
tmp_steps = []
with Expression.tmp_render():
for t in tokenList:
if hasattr(t, "explain"):
tmp_steps.append([i for i in t.explain()])
else:
tmp_steps.append(t)
if max([len(i) if type(i) == list else 1 for i in tmp_steps]) == 1:
2015-04-07 04:44:20 +00:00
# Cas où rien n'a dû être expliqué.
return []
else:
tmp_steps = expand_list(tmp_steps)[:-1]
steps = [Expression(s) for s in tmp_steps]
return steps
2013-11-01 11:42:42 +00:00
@classmethod
def isExpression(self, other):
try:
other._isExpression
except AttributeError:
return 0
return 1
# -----------
# Expression act as container from self.postfix_tokens
def __getitem__(self, index):
return self.postfix_tokens[index]
def __setitem__(self, index, value):
self.postfix_tokens[index] = value
# -----------
# Some math manipulations
2014-11-14 15:48:38 +00:00
def operate(self, other, operator):
if type(other) == Expression:
return Expression(self.postfix_tokens + other.postfix_tokens + [operator])
elif type(other) == list:
return Expression(self.postfix_tokens + other + [operator])
else:
return Expression(self.postfix_tokens + [other] + [operator])
def roperate(self, other, operator):
if type(other) == Expression:
return Expression(other.postfix_tokens + self.postfix_tokens + [operator])
elif type(other) == list:
return Expression(other + self.postfix_tokens + [operator])
else:
return Expression([other] + self.postfix_tokens + [operator])
def __add__(self, other):
2015-02-27 10:38:17 +00:00
""" Overload +
>>> a = Expression("1+2")
>>> print(a.postfix_tokens)
[1, 2, '+']
>>> b = Expression("3+4")
>>> print(b.postfix_tokens)
[3, 4, '+']
>>> c = a + b
>>> print(c.postfix_tokens)
[1, 2, '+', 3, 4, '+', '+']
"""
2014-11-14 15:48:38 +00:00
return self.operate(other, op.add)
def __radd__(self, other):
return self.roperate(other, op.add)
def __sub__(self, other):
2015-02-27 10:38:17 +00:00
""" Overload -
>>> a = Expression("1+2")
>>> print(a.postfix_tokens)
[1, 2, '+']
>>> b = Expression("3+4")
>>> print(b.postfix_tokens)
[3, 4, '+']
>>> c = a - b
>>> print(c.postfix_tokens)
[1, 2, '+', 3, 4, '+', '-']
"""
2014-11-14 15:48:38 +00:00
return self.operate(other, op.sub)
def __rsub__(self, other):
return self.roperate(other, op.sub)
2014-11-14 15:48:38 +00:00
def __mul__(self, other):
2015-02-27 10:38:17 +00:00
""" Overload *
>>> a = Expression("1+2")
>>> print(a.postfix_tokens)
[1, 2, '+']
>>> b = Expression("3+4")
>>> print(b.postfix_tokens)
[3, 4, '+']
>>> c = a * b
>>> print(c.postfix_tokens)
[1, 2, '+', 3, 4, '+', '*']
"""
2014-11-14 15:48:38 +00:00
return self.operate(other, op.mul)
def __rmul__(self, other):
return self.roperate(other, op.mul)
2015-02-27 10:38:17 +00:00
def __truediv__(self, other):
""" Overload /
>>> a = Expression("1+2")
>>> print(a.postfix_tokens)
[1, 2, '+']
>>> b = Expression("3+4")
>>> print(b.postfix_tokens)
[3, 4, '+']
>>> c = a / b
>>> print(c.postfix_tokens)
[1, 2, '+', 3, 4, '+', '/']
2015-02-27 15:56:43 +00:00
>>>
2015-02-27 10:38:17 +00:00
"""
2014-11-14 15:48:38 +00:00
return self.operate(other, op.div)
2015-02-27 15:56:43 +00:00
def __rtruediv__(self, other):
2014-11-14 15:48:38 +00:00
return self.roperate(other, op.div)
def __pow__(self, other):
2015-02-27 10:38:17 +00:00
return self.operate(other, op.pw)
def __xor__(self, other):
return self.operate(other, op.pw)
2014-11-14 15:48:38 +00:00
def __neg__(self):
return Expression(self.postfix_tokens + [op.sub1])
2013-11-01 11:42:42 +00:00
def untest(exp):
a = Expression(exp)
b = a.simplify()
for i in b.explain():
#print(type(i))
print(i)
2013-08-09 09:35:14 +00:00
2014-12-22 13:14:37 +00:00
#print(type(a.simplified()), ":", a.simplified())
2014-12-19 14:40:35 +00:00
2013-11-08 09:05:28 +00:00
print("\n")
if __name__ == '__main__':
#render = lambda _,x : str(x)
#Expression.set_render(render)
#exp = Expression("1/2 - 4")
#print(list(exp.simplify()))
#Expression.set_render(txt)
2014-12-22 13:14:37 +00:00
#exp = "2 ^ 3 * 5"
#untest(exp)
#exp = "2x + 5"
#untest(exp)
2014-11-21 14:49:43 +00:00
2014-12-22 13:14:37 +00:00
#Expression.set_render(tex)
2014-11-21 14:49:43 +00:00
#untest(exp1)
2014-12-22 13:14:37 +00:00
#from pymath.operator import op
#exp = [2, 3, op.pw, 5, op.mul]
#untest(exp)
2014-11-21 14:49:43 +00:00
#untest([Expression(exp1), Expression(exp), op.add])
2014-12-22 13:14:37 +00:00
#exp = "1 + 3 * 5"
#e = Expression(exp)
#f = -e
#print(f)
2015-02-27 10:38:17 +00:00
#exp = "2 * 3 * 3 * 5"
#untest(exp)
2015-02-27 10:38:17 +00:00
#exp = "2 * 3 + 3 * 5"
#untest(exp)
2015-02-27 10:38:17 +00:00
#exp = "2 * ( 3 + 4 ) + 3 * 5"
#untest(exp)
2013-11-08 09:05:28 +00:00
2015-02-27 10:38:17 +00:00
#exp = "2 * ( 3 + 4 ) + ( 3 - 4 ) * 5"
#untest(exp)
2015-02-27 10:38:17 +00:00
#
#exp = "2 * ( 2 - ( 3 + 4 ) ) + ( 3 - 4 ) * 5"
#untest(exp)
2015-02-27 10:38:17 +00:00
#
#exp = "2 * ( 2 - ( 3 + 4 ) ) + 5 * ( 3 - 4 )"
#untest(exp)
2015-02-27 10:38:17 +00:00
#
#exp = "2 + 5 * ( 3 - 4 )"
#untest(exp)
2013-11-08 09:05:28 +00:00
2015-02-27 10:38:17 +00:00
#exp = "( 2 + 5 ) * ( 3 - 4 )^4"
#untest(exp)
2013-11-08 09:05:28 +00:00
2015-02-27 10:38:17 +00:00
#exp = "( 2 + 5 ) * ( 3 * 4 )"
#untest(exp)
2013-11-08 09:05:28 +00:00
2014-12-22 13:14:37 +00:00
#exp = "( 2 + 5 - 1 ) / ( 3 * 4 )"
#untest(exp)
2014-12-22 13:14:37 +00:00
#exp = "( 2 + 5 ) / ( 3 * 4 ) + 1 / 12"
#untest(exp)
2014-12-22 13:14:37 +00:00
#exp = "( 2+ 5 )/( 3 * 4 ) + 1 / 2"
#untest(exp)
2014-12-22 13:14:37 +00:00
#exp="(-2+5)/(3*4)+1/12+5*5"
#untest(exp)
2014-12-22 13:14:37 +00:00
#exp="-2*4(12 + 1)(3-12)"
#untest(exp)
2014-12-22 13:14:37 +00:00
#exp="(-2+5)/(3*4)+1/12+5*5"
#untest(exp)
# TODO: The next one doesn't work |ven. janv. 17 14:56:58 CET 2014
#exp="-2*(-a)(12 + 1)(3-12)"
#e = Expression(exp)
#print(e)
2014-01-15 15:54:33 +00:00
## Can't handle it yet!!
#exp="-(-2)"
#untest(exp)
2014-01-15 15:54:33 +00:00
#print("\n")
#exp = Expression.random("({a} + 3)({b} - 1)", ["{a} > 4"])
#for i in exp.simplify():
# print(i)
from .fraction import Fraction
f1 = Fraction(3,5)
f2 = Fraction(5,10)
q = f1+f2
print("---------")
print(q.steps)
print("---------")
for i in q.explain():
print(i)
#import doctest
#doctest.testmod()
2013-08-09 09:35:14 +00:00
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del