How do you extend SymPy to constrain when binary operations can occur?

30 views
Skip to first unread message

Shane Kosieradzki

unread,
Nov 18, 2021, 5:38:57 AM11/18/21
to sympy
Hello,

I have been scouring the internet trying to find any examples of how to extend SymPy objects, but have had little luck.

I would like to add a constraint to regular arithmetic operations (Add and Mul) such that these operations are not allowed unless the two operands have the same "depth". Where "depth" is an attribute attached to a symbol (or number) that is initialized to 1 for all leaves of the expression tree. Whenever a symbol takes part in multiplication the depth of the product is incremented. So for example:

let a, b be two unknown quantities initalized with a depth of 1. Then their product a*b=c  would have a depth of 2. However the operation a*c and a+c are not allowed as a has depth of 1 while c has depth of 2.


How would I go about extending SymPy to impose these restrictions? Initially, I figured I might have to extend Add and Mul, but this seems problematic as those classes seem to be used globally. Furthermore, I was hoping to only impose these restrictions on particular terms in my expression. 

Would extending Expr be the way to go? If so how do I reconcile this custom arithmetic behavior with that of Add and Mul.


Any help or advice people have on not only this particular problem but also understanding how to extend SymPy in general would be greatly appreciated.
Reply all
Reply to author
Forward
0 new messages