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

Unexpected shape when for lambdifyed matrix #19259

Open
StefanKaeser opened this issue May 6, 2020 · 1 comment
Open

Unexpected shape when for lambdifyed matrix #19259

StefanKaeser opened this issue May 6, 2020 · 1 comment

Comments

@StefanKaeser
Copy link

Hey,

I stumbled over something using lambdify on a matrix expression with version 1.5.1 and wanted to ask if this behavior is intended.

I wanted to lambdify a matrix and give numpy arrays as input for some symbols and constant ints for others.
As a minimal example I construct following matrix

import sympy
import numpy as np

a, b, c, d = sympy.symbols("a b c d")
matrix = sympy.Matrix([ [a, b], [c, d]])
matrix_fct = sympy.lambdify([a, b, c, d], matrix)

If I would now like to evaluate the matrix for multiple values of a but fixed b, c and d, I assumed that this expression

a_values = np.array([0, 1, 2, 3])
matrix_values = matrix_fct(a_values, 1, 2, 3)

would produce matrix_values as a (2, 2, 4) shapped numpy array. But instead I get

print(matrix_values)
print(matrix_values.shape)
>>>[[array([0, 1, 2, 3]) 1]
[2 3]]
>>> (2, 2)

To get the desired I need to use constant arrays

a_values = np.array([0, 1, 2, 3])
a_shape = a_values.shape
matrix_values = matrix_fct(a_values, 1 * np.ones(a_shape), 2 * np.ones(a_shape), 3 * np.ones(a_shape))

print(matrix_values)
print(matrix_values.shape)
>>>[[[0. 1. 2. 3.]
  [1. 1. 1. 1.]]

 [[2. 2. 2. 2.]
  [3. 3. 3. 3.]]]
>>>(2, 2, 4)

Is this behavior intended?
I find the array that I get for the first version highly unusable and don't see in what situation I would want it.

@sylee957
Copy link
Member

sylee957 commented May 8, 2020

Sympy lambdify is basically dispatching to `numpy.array([[a, b], [c, d]]), and if numpy is not broadcasting the scalars into ragged array by default, we shouldn't do that because it breaks other consistency.
I'm alternatively thinking of providing a fully symbolic API for matrix shape, because I don't think that there is any way to bind matrix shape into any code generation purposes unless it is accessed in implicit way.

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

2 participants