1

Calculate curl of a vector field in Python and plot it with matplotlib

In the first answer,

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) 

Now he prints G, obtains the expressions for the components of the curl field, manually and assigns them as

u = 0
v = y**2
w = -2*y*z - y 

How to obtain, u,v,w directly from G, instead how manually printing and assigning? What is G? Can we convert it into a string ? I don't want to plot, I just want the expressions for the components of the curl.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • The link/answer uses `sympy`. If that's what you are using as well, fix the tags. And expand on your code so we have a clearer idea of the context and variables. – hpaulj Nov 04 '19 at 17:37
  • @hpaulj I've edited the question, kindly take a look – Aravindh Vasu Nov 04 '19 at 17:44
  • The curl docs - https://docs.sympy.org/latest/modules/physics/vector/api/fieldfunctions.html – hpaulj Nov 04 '19 at 21:07

2 Answers2

2

Like this?

>>> list(G.args[0][0])
[0, R_y**2, -2*R_y*R_z - R_y]

Or, using the varlist attribute of R, we can replace R_x with x, etc..., as

>>> u,v,w = G.args[0][0].subs(dict(zip(R.varlist, var('x:z'))))
>>> u, v, w
(0, y**2, -2*y*z - y)
smichr
  • 16,948
  • 2
  • 27
  • 34
1

To elaborate further on @smichr 's answer:

from sympy.abc import x, y, z
print(list(G.args[0][0].subs([(R[0], x), (R[1], y), (R[2], z)])))

Results in

[0, y**2, -2*y*z - y]

And

u, v, w = list(G.args[0][0].subs([(R[0], x), (R[1], y), (R[2], z)]))

gets everything in the same form as your question.

PS: G.args gives the top-level arguments of G. print(G.args)can be used to investigate how it is built up. In SymPy srepr() can help to figure out the internal representation of symbols.

PPS: about your question in the comments:

R = ReferenceFrame('R')
P = y**2 *z
Q =- x*y
R = z**2
H = P* R.x +Q * R.y + RR* R.z

Does not work because R = z**2 erases R = ReferenceFrame('R'). You should use different variable names.

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • I'm new to python, please bare with me. Can you please explain what is G? what does G.args[0][0] do? – Aravindh Vasu Nov 05 '19 at 01:06
  • `from sympy.abc import x, y, z P=y**2 * z Q=- x*y R=z**2 R = ReferenceFrame('R') H = P* R.x +Q * R.y + R * R.z F=H.subs([(x, R[0]), (y, R[1]), (z, R[2])]) print(F) G = curl(F, R) print(list(G.args[0][0].subs([(R[0], x), (R[1], y), (R[2], z)])))` This throws up an error, how to substitute P,Q,R in F? – Aravindh Vasu Nov 05 '19 at 01:29