Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MatrixSymbol latex parsing causes invalid behaviour #20883

Open
LemurPwned opened this issue Jan 31, 2021 · 1 comment
Open

MatrixSymbol latex parsing causes invalid behaviour #20883

LemurPwned opened this issue Jan 31, 2021 · 1 comment

Comments

@LemurPwned
Copy link

python3.7.5
sympy version: 1.7
numpy version: 1.19.5

Base case (working)

The code below executes normally

A = sym.MatrixSymbol("A", 3, 3)
x1, x2, x3 = sym.symbols("x1 x2 x3")
x = sym.Matrix([x1, x2, x3])

# this produces (3x3)x(3x1) = (3x1)
r = A * x
f = sym.lambdify([x1, x2, x3, A], r, "numpy")

f(1, 2, 3, np.array([[0, 0, 0], [0, 0, 0], [0, 0, 1]])) 

returns

array([[0],  [0],  [3]]) 

Modified case (fails)

However, when I change A = sym.MatrixSymbol("A", 3, 3) to A = sym.MatrixSymbol("A_{whatever}", 3, 3) this seems to break things, and this line

f(1, 2, 3, np.array([[0, 0, 0], [0, 0, 0], [0, 0, 1]])) 

results in an error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-299-a4adefb7e356> in <module>
      7 f = sym.lambdify([x1, x2, x3, A], r, "numpy")
      8 
----> 9 f(1, 2, 3, np.array([[0, 0, 0], [0, 0, 0], [0, 0, 1]]))

<lambdifygenerated-41> in _lambdifygenerated(x1, x2, x3, Dummy_507)
      1 def _lambdifygenerated(x1, x2, x3, Dummy_507):
----> 2     return ((array([[x1], [x2], [x3]])).dot(Dummy_507))

ValueError: shapes (3,1) and (3,3) not aligned: 1 (dim 1) != 3 (dim 0)

Is this expected behaviour? A_1 or A_whatever, etc. works fine.
I have spent some time debugging this, since A_{longer text} is a valid Latex expression for long subscripts.
Should A = sym.MatrixSymbol("A_{whatever}", 3, 3) raise some parsing error before proceeding?

@oscarbenjamin
Copy link
Contributor

In the code printer if you use a name that is not a valid python identifier it has to be replaced by a different name (in the _EvaluatorPrinter._preprocess method):

def _preprocess(self, args, expr):
"""Preprocess args, expr to replace arguments that do not map
to valid Python identifiers.
Returns string form of args, and updated expr.
"""

That replaces the MatrixSymbol with a Dummy but MatMul sees the Dummy as a commutative scalar and swaps the order of multiplication.

It would be better if the code printer didn't actually modify the expression at all and just hooked into the way that symbols are printed to change the names at that point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants