How to manipulate expressions in matrices using sympy?

I am writing a library and I can create expressions using objects from my library. For example, x and y are instances from my library, and I can build expressions like:

 # below is a simplified version of my class class MySymbol(object): import random _random_value = random.randint(1,4) def __init__(self, value): self.value = value def __add__(self, symbol): return MySymbol(self.value + symbol.value) def __mul__(self, symbol): return MySymbol(self.value * symbol.value) def __repr__(self): return str(self.value) def _get_random_value(self): return self._random_value x,y = sympy.symbols('x y') x = MySymbol(9) y = MySymbol(3) import sympy A = sympy.Matrix([[x,y],[x,y]]) B = sympy.Matrix([[x+y,x*y]]) 

This is also true for matrix operations. The sympy.Matrix class converts these elements to sympy.core.numbers.Integer when I want them to retain their MySymbol type:

 BA=B*A print type(BA[0,0]) print type(x*x+y*x+x*x*y) # first element of matrix in *symbolic* form <class 'sympy.core.numbers.Integer'> <class '__main__.MySymbol'> 

Now, since BA[0,0] no longer of type MySymbol , I cannot call the methods that I want on it:

 BA[0,0]._get_random_value() # DOES NOT WORK >> AttributeError: 'Integer' object has no attribute '_get_random_value' expression = x*x+y*x+x*x*y expression._get_random_value() # THIS DOES WORK >> 4 

How can I use matrix multiplication from sympy.Matrix , but still allow the elements of the matrix to maintain their type of class MySymbol ? and still allow access to all their methods (e.g. _get_random_value() )?

+7
python oop matrix sympy
source share
1 answer

To use it in SymPy, you need a subclass of the SymPy class. Depending on what your class does, you will find out which class belongs to the subclass, but the most typical superclass is Expr . See my answer to a very similar question here .

+3
source share

All Articles