0

I am writing some tests for my sympy code, and naturally I need to compare two sympy matrices. Each matrix contains objects of type Poly as its entries (actually, it contains objects of a class that I created which extends the Poly class, but that shouldn't make a difference).

The problem is that when I try to compare these objects in the tests, the even though the expressions are the same, generators are different, yielding a failing test even though they are the same.

For example:

from sympy.matrices import Matrix 

expected_matrix = Matrix([[Poly(1.0*y1 + 2.0*x2 + 1.0*x1, y1, x2, x1, domain='RR')]])

actual_matrix = Matrix([[Poly(1.0*y1 + 1.0*x2, y2, y1, x2, x1, domain='RR') + Poly(1.0*x2 + 1.0*x1, y2, y1, x2, x1, domain='RR')]])

# however, when these get compared, they don't agree because notice that the `y2` generator does not appear in the `expected_matrix`.

My question is how to make the generators equal. How do I add generators to the actual output? Or, take the generators away from the expected output?

Since the gens attribute is a tuple, it makes this difficult, because I cannot just add an element to the gens attribute:

actual_matrix.gens = expected_matrix.gens

Perhaps I could compare the expressions alone, but that seems risky to me (unless someone with more experience with this can convince me otherwise).

How do I compare these two things?

makansij
  • 9,303
  • 37
  • 105
  • 183

1 Answers1

1

If you convert the Polys in the matrices to expressions it would work.

>>> expected_matrix.applyfunc(lambda x:x.as_expr())==actual_matrix.applyfunc(lambda x:x.as_expr())
True
makansij
  • 9,303
  • 37
  • 105
  • 183
smichr
  • 16,948
  • 2
  • 27
  • 34
  • Right, so that seems like you are comparing expressions (which is what I mentioned toward the end of my question). That seems risky because in general, there could be two expressions that are the same, but they might have different domains or different symbols. Is there another way to do this? – makansij Sep 20 '19 at 17:43
  • 1
    If you want Polys with the same symbols but different domains to compare differently then you will have to make your own comparison routine since `Poly(x, domain=RR)==Poly(x,domain=ZZ) -> True`. If so you might compare lists of elements with `list(map(lambda x: (x.as_expr(), x.domain), Matrix([Poly(x,domain=ZZ)])))` for each matrix. – smichr Sep 20 '19 at 21:09