Help implementing new associative expression

109 views
Skip to first unread message

Rouslan Korneychuk

unread,
Jan 23, 2016, 7:05:19 PM1/23/16
to sympy
I want to implement a new type of expression so that, given:
import sympy

class MyExpr(sympy.Expr,...):
    ...

a,b,c,x = sympy.symbols('a b c x')

e1 = MyExpr(a,b,c)
e2 = MyExpr(b,c)

this would be so:

e1.subs(e2,x) == MyExpr(a,x)

I need a new kind of operation because I'm not working with numbers and need a very specific set of operations. MyExpr needs to be associative but not commutative.

So far I have basically this (I'm working with Python 3):
class MyExpr(sympy.Expr):
    @sympy.cacheit
    def __new__(cls,*args):
        tmp = []
        for a in args:
            a = sympy.sympify(a,strict=True)
            if type(a) is cls:
                tmp.extend(a.args)
            else:
                tmp.append(a)
        return super().__new__(cls,*tmp)

    is_commutative = False

What do I need for the above to work? I looked at the source for sympy.Add and some other classes and figure I need to implement match() and compare contiguous slices, but the implementation for Add.match is far from straight-forward.

Aaron Meurer

unread,
Jan 25, 2016, 10:47:13 AM1/25/16
to sy...@googlegroups.com
Mul is a better model for a noncommutative expression, since Mul handles noncommutatives. In either case, Mul.match and Add.match are going to be complicated by the automatic collecting of terms (x + x -> 2*x or x*x -> x**2). Assumedly you don't want that on your object (if you do, you should just use Mul).

I'm not sure if match is needed to make subs work. For that you should only need _eval_subs.

Aaron Meurer

--
You received this message because you are subscribed to the Google Groups "sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
To post to this group, send email to sy...@googlegroups.com.
Visit this group at https://groups.google.com/group/sympy.
To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/5cbbc510-eba7-4c66-9661-2531258a6f45%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Rouslan Korneychuk

unread,
Jan 25, 2016, 3:35:09 PM1/25/16
to sympy
Thanks for the tip, and yeah, collecting terms makes no sense for my objects.

In the mean time, I found a library called LogPy and managed to get associative operations working in it. I'm going to try it and see if I can get it to do everything I want.
Reply all
Reply to author
Forward
0 new messages