Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manipulate expressions in matrices using sympy?

I'm writing a library, and I can construct expressions using objects from my library. For example, x and y are instances from my library, and I can construct 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 maintain their type MySymbol:

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, because BA[0,0] is not of type MySymbol anymore, I cannot call the methods 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 do I take advantage of matrix multiplication from sympy.Matrix, but yet still allow the elements of the matrix to retain their class type of MySymbol? and still allow all of their methods (such as _get_random_value()) to be accessible?

like image 951
makansij Avatar asked Feb 06 '17 07:02

makansij


1 Answers

You need to subclass from a SymPy class to use it within SymPy. Depending on what your class is doing will tell you what class to subclass, but the most typical superclass is Expr. See my answer to a very similar question here.

like image 76
asmeurer Avatar answered Oct 29 '22 15:10

asmeurer