Sympy lambdify score on numpy mesgrid

I would like to evaluate the output of sympy.lambdify on numpy mgrid. I tried the following:

import sympy as sp
import numpy as np


theta, v = sp.symbols("theta v")
coeff = (-sp.sin(theta/2)*sp.sin(2*v) + sp.sin(v)*sp.cos(theta/2) + 3)
kb = sp.Matrix([[coeff*sp.cos(theta),
                 coeff*sp.sin(theta),
                 sp.sin(theta/2)*sp.sin(v) + sp.sin(2*v)*sp.cos(theta/2)]])
f = sp.lambdify((theta, v), kb, modules='numpy')
f(*np.mgrid[0:2*np.pi:101j, 0:2*np.pi:101j])

but I get a message that the matrix must be two-dimensional.

+3
source share
1 answer

I have found a solution.

import sympy as sp
import numpy as np


theta, v = sp.symbols("theta v")
coeff = (-sp.sin(theta/2)*sp.sin(2*v) + sp.sin(v)*sp.cos(theta/2) + 3)
kb = sp.Matrix([[coeff*sp.cos(theta),
                 coeff*sp.sin(theta),
                 sp.sin(theta/2)*sp.sin(v) +
                 sp.sin(2*v)*sp.cos(theta/2)]])

f = sp.lambdify((theta, v), kb, [{'ImmutableMatrix': np.array}, "numpy"])
x, y = np.mgrid[0:2*np.pi:101j, 0:2*np.pi:101j]
g = f(x, y)
x, y, z = g[0]
+2
source

All Articles