gustavogrds - 11 months ago 220

Python Question

I need to calculate the curl of a vector field and plot it with matplotlib. A simple example of what I am looking for could be be put like that:

How can I calculate and plot the curl of the vector field in the quiver3d_demo.py in the matplotlib gallery?

Please let me know if I can be more specific than that.

Answer Source

You can use `sympy.curl()`

to calculate the curl of a vector field.

**Example**:

Suppose you have:

**F** = (y^{2}z,-xy,z^{2}) = y^{2}z**x** - xy**y** + z^{2}**z**, then `y`

would be `R[1]`

, `x`

is `R[0]`

and `z`

is `R[2]`

while the vectors of the 3 axes would be `R.x`

, `R.y`

, `R.z`

and the code **to calculate the vector field curl** is:

```
from sympy.physics.vector import ReferenceFrame
from sympy.physics.vector import curl
R = ReferenceFrame('R')
F = R[1]**2 * R[2] * R.x - R[0]*R[1] * R.y + R[2]**2 * R.z
G = curl(F, R)
```

In that case G would be equal to `R_y**2*R.y + (-2*R_y*R_z - R_y)*R.z`

or, in other words,

G = (0, y^{2}, -2yz-y).

**To plot it** you need to convert the above result into 3 separate functions; u,v,w.

(example below adapted from the matplotlib example on this link):

```
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
np.arange(-0.8, 1, 0.2),
np.arange(-0.8, 1, 0.8))
u = 0
v = y**2
w = -2*y*z - y
ax.quiver(x, y, z, u, v, w, length=0.1)
plt.show()
```

And the final result is this: