Fix: simplify rendering by expanding tree. still bugs with set_render
This commit is contained in:
parent
1a20e6927d
commit
2109fc46cb
@ -108,12 +108,52 @@ x^7
|
|||||||
(6 + 6) * x + 4x^2 + 9
|
(6 + 6) * x + 4x^2 + 9
|
||||||
4x^2 + 12x + 9
|
4x^2 + 12x + 9
|
||||||
|
|
||||||
|
>>> e = Expression.from_str("(2x+3)(-x+1)")
|
||||||
|
>>> e_simplified = e.simplify()
|
||||||
|
>>> e_simplified
|
||||||
|
<Quadratic - 2x^2 - x + 3>
|
||||||
|
>>> for s in e_simplified.explain():
|
||||||
|
... print(s)
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from .expression import Expression
|
from .expression import Expression
|
||||||
|
from .tokens import Token
|
||||||
from .tokens.number import Integer, Decimal
|
from .tokens.number import Integer, Decimal
|
||||||
|
|
||||||
|
|
||||||
|
def set_render(render):
|
||||||
|
"""
|
||||||
|
:example:
|
||||||
|
>>> e = Expression.from_str("2+3*4")
|
||||||
|
>>> print(e)
|
||||||
|
2 + 3 * 4
|
||||||
|
>>> e = Expression.from_str("2+3/4")
|
||||||
|
>>> print(e)
|
||||||
|
2 + 3 / 4
|
||||||
|
>>> es = e.simplify()
|
||||||
|
>>> print(es)
|
||||||
|
11 / 4
|
||||||
|
>>> set_render('tex')
|
||||||
|
>>> Expression.RENDER
|
||||||
|
'tex'
|
||||||
|
>>> Token.RENDER
|
||||||
|
'tex'
|
||||||
|
>>> e = Expression.from_str("2+3*4")
|
||||||
|
>>> print(e)
|
||||||
|
2 + 3 \\times 4
|
||||||
|
>>> e = Expression.from_str("2+3/4")
|
||||||
|
>>> print(e)
|
||||||
|
2 + \\dfrac{3}{4}
|
||||||
|
>>> es = e.simplify()
|
||||||
|
>>> print(es)
|
||||||
|
\\dfrac{11}{4}
|
||||||
|
>>> set_render('txt')
|
||||||
|
"""
|
||||||
|
Expression.set_render(render)
|
||||||
|
Token.set_render(render)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
e = Expression.from_str("1+2/3/4/5")
|
e = Expression.from_str("1+2/3/4/5")
|
||||||
et = e._typing()
|
et = e._typing()
|
||||||
|
@ -56,33 +56,7 @@ class Expression(object):
|
|||||||
|
|
||||||
:param render: render name (txt or tex)
|
:param render: render name (txt or tex)
|
||||||
|
|
||||||
:example:
|
|
||||||
>>> e = Expression.from_str("2+3*4")
|
|
||||||
>>> print(e)
|
|
||||||
2 + 3 * 4
|
|
||||||
>>> e = Expression.from_str("2+3/4")
|
|
||||||
>>> print(e)
|
|
||||||
2 + 3 / 4
|
|
||||||
>>> es = e.simplify()
|
|
||||||
>>> print(es)
|
|
||||||
11 / 4
|
|
||||||
>>> Expression.set_render('tex')
|
|
||||||
>>> Expression.RENDER
|
|
||||||
'tex'
|
|
||||||
>>> e = Expression.from_str("2+3*4")
|
|
||||||
>>> print(e)
|
|
||||||
2 + 3 \\times 4
|
|
||||||
>>> e = Expression.from_str("2+3/4")
|
|
||||||
>>> print(e)
|
|
||||||
2 + \\dfrac{3}{4}
|
|
||||||
>>> es = e.simplify()
|
|
||||||
>>> print(es)
|
|
||||||
\\dfrac{11}{4}
|
|
||||||
>>> Expression.set_render('txt')
|
|
||||||
"""
|
"""
|
||||||
from .tokens.token import Token
|
|
||||||
|
|
||||||
Token.set_render(render)
|
|
||||||
cls.RENDER = render
|
cls.RENDER = render
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -204,7 +178,8 @@ class Expression(object):
|
|||||||
return type(leaf)
|
return type(leaf)
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
typed_leaf = typing(leaf.node, leaf.left_value, leaf.right_value)
|
typed_leaf = typing(
|
||||||
|
leaf.node, leaf.left_value, leaf.right_value)
|
||||||
return typed_leaf.signature
|
return typed_leaf.signature
|
||||||
except (AttributeError, NotImplementedError, TypingError):
|
except (AttributeError, NotImplementedError, TypingError):
|
||||||
return type(leaf)
|
return type(leaf)
|
||||||
|
@ -246,8 +246,8 @@ class Token(object):
|
|||||||
>>> c = a ** 2
|
>>> c = a ** 2
|
||||||
>>> c
|
>>> c
|
||||||
<Decimal 5.29>
|
<Decimal 5.29>
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
return self._operate(other, "^")
|
return self._operate(other, "^")
|
||||||
|
|
||||||
def _roperate(self, other, operation):
|
def _roperate(self, other, operation):
|
||||||
|
@ -259,7 +259,8 @@ class MOstr(Atom):
|
|||||||
f"An MOstr should be initiate with a single caracter string, got {val}"
|
f"An MOstr should be initiate with a single caracter string, got {val}"
|
||||||
)
|
)
|
||||||
if not val.isalpha():
|
if not val.isalpha():
|
||||||
raise MOError(f"An MOstr should be initiate with a alpha string, got {val}")
|
raise MOError(
|
||||||
|
f"An MOstr should be initiate with a alpha string, got {val}")
|
||||||
|
|
||||||
Atom.__init__(self, val)
|
Atom.__init__(self, val)
|
||||||
|
|
||||||
|
@ -32,10 +32,10 @@ class MOFraction(Molecule):
|
|||||||
>>> f = MOFraction(2, 3)
|
>>> f = MOFraction(2, 3)
|
||||||
>>> f
|
>>> f
|
||||||
<MOFraction 2 / 3>
|
<MOFraction 2 / 3>
|
||||||
>>> print(f.__txt__)
|
>>> print(f.tree)
|
||||||
2 / 3
|
/
|
||||||
>>> print(f.__tex__)
|
> 2
|
||||||
\\dfrac{2}{3}
|
> 3
|
||||||
>>> print(f)
|
>>> print(f)
|
||||||
2 / 3
|
2 / 3
|
||||||
>>> f = MOFraction(2, 3, negative = True)
|
>>> f = MOFraction(2, 3, negative = True)
|
||||||
@ -44,11 +44,13 @@ class MOFraction(Molecule):
|
|||||||
"""
|
"""
|
||||||
_numerator = MO.factory(numerator)
|
_numerator = MO.factory(numerator)
|
||||||
_denominator = MO.factory(denominator)
|
_denominator = MO.factory(denominator)
|
||||||
|
|
||||||
base_tree = Tree("/", _numerator, _denominator)
|
base_tree = Tree("/", _numerator, _denominator)
|
||||||
if negative:
|
if negative:
|
||||||
tree = Tree("-", None, base_tree)
|
tree = Tree("-", None, base_tree)
|
||||||
else:
|
else:
|
||||||
tree = base_tree
|
tree = base_tree
|
||||||
|
|
||||||
Molecule.__init__(self, tree)
|
Molecule.__init__(self, tree)
|
||||||
|
|
||||||
self._numerator = _numerator
|
self._numerator = _numerator
|
||||||
|
@ -57,20 +57,12 @@ class MO(ABC):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"<{self.__class__.__name__} {self.__txt__}>"
|
return f"<{self.__class__.__name__} {self.__str__()}>"
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def __txt__(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def __tex__(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def __hash__(self):
|
def __hash__(self):
|
||||||
try:
|
try:
|
||||||
return self._tree.__hash__()
|
return self._tree.__hash__()
|
||||||
@ -161,21 +153,21 @@ class Molecule(MO):
|
|||||||
|
|
||||||
It is a wrapping of tree
|
It is a wrapping of tree
|
||||||
|
|
||||||
Its wrapping tree can be access throw .tree property
|
Its wrapping tree can be access through .tree property
|
||||||
"""
|
"""
|
||||||
|
|
||||||
MAINOP = None
|
MAINOP = None
|
||||||
|
|
||||||
def __init__(self, value):
|
def __init__(self, tree):
|
||||||
""" Initiate the MO
|
""" Initiate the MO
|
||||||
|
|
||||||
It should be idempotent.
|
It should be idempotent.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
self._tree = value._tree
|
self._tree = tree._tree
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
self._tree = value
|
self._tree = tree
|
||||||
|
|
||||||
self.is_scalar = True
|
self.is_scalar = True
|
||||||
self._signature = None
|
self._signature = None
|
||||||
@ -186,18 +178,10 @@ class Molecule(MO):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def content(self):
|
def content(self):
|
||||||
return self._tree
|
return self.tree
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return str(self.__txt__)
|
return tree2txt(self.tree)
|
||||||
|
|
||||||
@property
|
|
||||||
def __txt__(self):
|
|
||||||
return tree2txt(self._tree)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def __tex__(self):
|
|
||||||
return tree2tex(self._tree)
|
|
||||||
|
|
||||||
|
|
||||||
# -----------------------------
|
# -----------------------------
|
||||||
|
@ -31,10 +31,10 @@ class MOstrPower(Molecule):
|
|||||||
<MOstrPower x^2>
|
<MOstrPower x^2>
|
||||||
>>> print(s)
|
>>> print(s)
|
||||||
x^2
|
x^2
|
||||||
>>> print(s.__txt__)
|
>>> print(s.tree)
|
||||||
x^2
|
^
|
||||||
>>> print(s.__tex__)
|
> x
|
||||||
x^{2}
|
> 2
|
||||||
>>> MOstrPower(3, 1)
|
>>> MOstrPower(3, 1)
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
@ -59,7 +59,8 @@ class MOstrPower(Molecule):
|
|||||||
"""
|
"""
|
||||||
_variable = MO.factory(variable)
|
_variable = MO.factory(variable)
|
||||||
if not isinstance(_variable, MOstr):
|
if not isinstance(_variable, MOstr):
|
||||||
raise MOError("The variable of a monomial should be convertible into MOstr")
|
raise MOError(
|
||||||
|
"The variable of a monomial should be convertible into MOstr")
|
||||||
self._variable = _variable
|
self._variable = _variable
|
||||||
|
|
||||||
_power = MO.factory(power)
|
_power = MO.factory(power)
|
||||||
@ -123,7 +124,8 @@ class MOstrPower(Molecule):
|
|||||||
"""
|
"""
|
||||||
if self._power > 2:
|
if self._power > 2:
|
||||||
return Tree(
|
return Tree(
|
||||||
"*", self.power, MOstrPower(self.variable, self._power._value - 1)
|
"*", self.power, MOstrPower(self.variable,
|
||||||
|
self._power._value - 1)
|
||||||
)
|
)
|
||||||
return Tree("*", self.power, MOstr(self.variable))
|
return Tree("*", self.power, MOstr(self.variable))
|
||||||
|
|
||||||
@ -147,22 +149,20 @@ class MOMonomial(Molecule):
|
|||||||
<MOMonomial 4x>
|
<MOMonomial 4x>
|
||||||
>>> print(m)
|
>>> print(m)
|
||||||
4x
|
4x
|
||||||
>>> print(m.__txt__)
|
>>> print(m.tree)
|
||||||
4x
|
*
|
||||||
>>> print(m.__tex__)
|
> 4
|
||||||
4x
|
> x
|
||||||
>>> x = MOstrPower('x', 2)
|
>>> x = MOstrPower('x', 2)
|
||||||
>>> MOMonomial(4, x)
|
>>> MOMonomial(4, x)
|
||||||
<MOMonomial 4x^2>
|
<MOMonomial 4x^2>
|
||||||
>>> m = MOMonomial(4, 'x')
|
>>> m = MOMonomial(-1, 'x')
|
||||||
>>> m
|
>>> m
|
||||||
<MOMonomial 4x>
|
<MOMonomial - x>
|
||||||
>>> print(m)
|
>>> print(m.tree)
|
||||||
4x
|
-
|
||||||
>>> print(m.__txt__)
|
> None
|
||||||
4x
|
> x
|
||||||
>>> print(m.__tex__)
|
|
||||||
4x
|
|
||||||
>>> MOMonomial(4, 'x', 1)
|
>>> MOMonomial(4, 'x', 1)
|
||||||
<MOMonomial 4x>
|
<MOMonomial 4x>
|
||||||
>>> MOMonomial(4, 'x', 2)
|
>>> MOMonomial(4, 'x', 2)
|
||||||
@ -170,6 +170,13 @@ class MOMonomial(Molecule):
|
|||||||
>>> x2 = MOstrPower('x', 2)
|
>>> x2 = MOstrPower('x', 2)
|
||||||
>>> MOMonomial(4, x2, 3)
|
>>> MOMonomial(4, x2, 3)
|
||||||
<MOMonomial 4x^6>
|
<MOMonomial 4x^6>
|
||||||
|
>>> m = MOMonomial(-1, 'x', 2)
|
||||||
|
>>> m
|
||||||
|
<MOMonomial - x^2>
|
||||||
|
>>> print(m.tree)
|
||||||
|
-
|
||||||
|
> None
|
||||||
|
> x^2
|
||||||
>>> MOMonomial(0, x)
|
>>> MOMonomial(0, x)
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
@ -199,34 +206,21 @@ class MOMonomial(Molecule):
|
|||||||
self._power = _power
|
self._power = _power
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if self._coefficient.value != 1:
|
if self.coefficient.value == 1:
|
||||||
_tree = Tree("*", self._coefficient, self.strpower)
|
|
||||||
else:
|
|
||||||
_tree = self.strpower
|
_tree = self.strpower
|
||||||
|
else:
|
||||||
|
_tree = Tree("*", self.coefficient, self.strpower)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
_tree = Tree("*", self._coefficient, self.strpower)
|
_tree = Tree("*", self.coefficient, self.strpower)
|
||||||
|
|
||||||
Molecule.__init__(self, _tree)
|
Molecule.__init__(self, _tree)
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
if self._coefficient != -1:
|
|
||||||
return super(MOMonomial, self).__str__()
|
|
||||||
else:
|
|
||||||
return "- " + self.strpower.__str__()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def __txt__(self):
|
def tree(self):
|
||||||
if self._coefficient != -1:
|
if self._coefficient == -1:
|
||||||
return super(MOMonomial, self).__txt__
|
return Tree("-", None, self.strpower)
|
||||||
else:
|
|
||||||
return "- " + self.strpower.__txt__
|
|
||||||
|
|
||||||
@property
|
return Tree("*", self.coefficient, self.strpower)
|
||||||
def __tex__(self):
|
|
||||||
if self._coefficient != -1:
|
|
||||||
return super(MOMonomial, self).__tex__
|
|
||||||
else:
|
|
||||||
return "- " + self.strpower.__tex__
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def coefficient(self):
|
def coefficient(self):
|
||||||
|
@ -70,7 +70,8 @@ def compute_capacities(node):
|
|||||||
op = OPERATIONS[node]
|
op = OPERATIONS[node]
|
||||||
lines = [[node] + [mo.__name__ for mo in MOS]]
|
lines = [[node] + [mo.__name__ for mo in MOS]]
|
||||||
for left_mo in MOS:
|
for left_mo in MOS:
|
||||||
lines.append([left_mo.__name__] + [(left_mo, i) in op.funcs for i in MOS])
|
lines.append([left_mo.__name__] +
|
||||||
|
[(left_mo, i) in op.funcs for i in MOS])
|
||||||
return lines
|
return lines
|
||||||
|
|
||||||
|
|
||||||
|
@ -210,7 +210,8 @@ def render_with_parenthesis(subtree, operator):
|
|||||||
return subtree_
|
return subtree_
|
||||||
|
|
||||||
|
|
||||||
OPERATOR2TEX = {"+": plus2tex, "-": minus2tex, "*": mul2tex, "/": div2tex, "^": pow2tex}
|
OPERATOR2TEX = {"+": plus2tex, "-": minus2tex,
|
||||||
|
"*": mul2tex, "/": div2tex, "^": pow2tex}
|
||||||
|
|
||||||
|
|
||||||
def tree2tex(tree):
|
def tree2tex(tree):
|
||||||
@ -230,8 +231,17 @@ def tree2tex(tree):
|
|||||||
from ..tree import Tree
|
from ..tree import Tree
|
||||||
|
|
||||||
if not isinstance(tree, Tree):
|
if not isinstance(tree, Tree):
|
||||||
raise ValueError(f"Can only render a Tree (got {type(tree).__name__}: {tree})")
|
raise ValueError(
|
||||||
return OPERATOR2TEX[tree.node](tree.left_value, tree.right_value)
|
f"Can only render a Tree (got {type(tree).__name__}: {tree})")
|
||||||
|
|
||||||
|
def expand(leaf):
|
||||||
|
try:
|
||||||
|
return leaf.tree
|
||||||
|
except AttributeError:
|
||||||
|
return leaf
|
||||||
|
expanded_tree = tree.map_on_leaf(expand)
|
||||||
|
|
||||||
|
return OPERATOR2TEX[expanded_tree.node](expanded_tree.left_value, expanded_tree.right_value)
|
||||||
|
|
||||||
|
|
||||||
# -----------------------------
|
# -----------------------------
|
||||||
|
@ -214,7 +214,8 @@ def render_with_parenthesis(subtree, operator):
|
|||||||
return subtree_
|
return subtree_
|
||||||
|
|
||||||
|
|
||||||
OPERATOR2TXT = {"+": plus2txt, "-": minus2txt, "*": mul2txt, "/": div2txt, "^": pow2txt}
|
OPERATOR2TXT = {"+": plus2txt, "-": minus2txt,
|
||||||
|
"*": mul2txt, "/": div2txt, "^": pow2txt}
|
||||||
|
|
||||||
|
|
||||||
def tree2txt(tree):
|
def tree2txt(tree):
|
||||||
@ -234,8 +235,17 @@ def tree2txt(tree):
|
|||||||
from ..tree import Tree
|
from ..tree import Tree
|
||||||
|
|
||||||
if not isinstance(tree, Tree):
|
if not isinstance(tree, Tree):
|
||||||
raise ValueError(f"Can only render a Tree (got {type(tree).__name__}: {tree})")
|
raise ValueError(
|
||||||
return OPERATOR2TXT[tree.node](tree.left_value, tree.right_value)
|
f"Can only render a Tree (got {type(tree).__name__}: {tree})")
|
||||||
|
|
||||||
|
def expand(leaf):
|
||||||
|
try:
|
||||||
|
return leaf.tree
|
||||||
|
except AttributeError:
|
||||||
|
return leaf
|
||||||
|
expanded_tree = tree.map_on_leaf(expand)
|
||||||
|
|
||||||
|
return OPERATOR2TXT[expanded_tree.node](expanded_tree.left_value, expanded_tree.right_value)
|
||||||
|
|
||||||
|
|
||||||
# -----------------------------
|
# -----------------------------
|
||||||
|
@ -484,7 +484,8 @@ def lookforNumbers(target):
|
|||||||
if current.replace("-", "", 1).isdigit():
|
if current.replace("-", "", 1).isdigit():
|
||||||
current += tok
|
current += tok
|
||||||
else:
|
else:
|
||||||
raise ParsingError(f"Can't build decimal with '{current}'")
|
raise ParsingError(
|
||||||
|
f"Can't build decimal with '{current}'")
|
||||||
elif tok == "-":
|
elif tok == "-":
|
||||||
if current == "":
|
if current == "":
|
||||||
current = tok
|
current = tok
|
||||||
@ -802,7 +803,8 @@ def str2(sink, convert_to_mo=True):
|
|||||||
operator_corout(missing_times(moify_cor(pparser(sink))))
|
operator_corout(missing_times(moify_cor(pparser(sink))))
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
str2_corout = lookforNumbers(operator_corout(missing_times(pparser(sink))))
|
str2_corout = lookforNumbers(
|
||||||
|
operator_corout(missing_times(pparser(sink))))
|
||||||
|
|
||||||
for i in expression.replace(" ", ""):
|
for i in expression.replace(" ", ""):
|
||||||
str2_corout.send(i)
|
str2_corout.send(i)
|
||||||
@ -828,7 +830,8 @@ def rdstr2(sink):
|
|||||||
|
|
||||||
def pipeline(expression):
|
def pipeline(expression):
|
||||||
str2_corout = look_for_rdleaf(
|
str2_corout = look_for_rdleaf(
|
||||||
lookforNumbers(operator_corout(missing_times(moify_cor(pparser(sink)))))
|
lookforNumbers(operator_corout(
|
||||||
|
missing_times(moify_cor(pparser(sink)))))
|
||||||
)
|
)
|
||||||
|
|
||||||
for i in expression.replace(" ", ""):
|
for i in expression.replace(" ", ""):
|
||||||
|
Loading…
Reference in New Issue
Block a user