Vector Analysis with Sympy: Gradient, Curl, and Divergence
Your Daily Dose of Computer Algebra
About this series: Learning to use computer algebra systems with ease requires a lot of practice. To help you on your journey to mastery, follow me in this series and solve common and not-so-common problems using systems like SymPy, Sage, or Mathematica.
Today’s Problem
Suppose we have the following scalar and vector fields

where 𝑟=|𝑟⃗|. Calculate the gradient for the scalar fields and divergence and curl for the vector field.
Solution with SymPy
Basically, there are two different ways how one can treat the problem in SymPy. The first way is to use the sympy.vector subpackage, which is convenient, because it already provides functions for the usual operators in vector analysis. So this is the easiest way to go. However, the vectorsubpackage is restricted to 3 dimensions and does not generalize to more or fewer dimensions. So if your problem is 3D, sympy.vector is fine, otherwise the second way is for you: write your own vector analysis operators, which is much easier than it may sound. We will go both ways here.
Using sympy.vector
First, we have to create our cartesian coordinate system:

The base_scalars method are special symbols for the coordinate variables that have knowledge about which coordinate system they belong to. We don't need that special knowledge here, it's just necessary if you work with several coordinate systems and want to transform between them.
Now define some more symbols and the vector 𝑟⃗:


Now define the field


Then take the ready-to-use functions from sympy.vector. For the gradient, we have


We can also take the Laplacian (divergence of the gradient):

Finally, the curl of 𝐴⃗ should be just zero, because it’s a gradient field:

Using custom operators
Writing the vector operators from scratch is very easy. For the gradient, just define your own Python function that returns a column vector:

The divergence is similarly easy. You just build the summation yourself using the sympy.Add class:

The curl needs a little bit more bookkeeping. It’s easiest to remember this trick to derive vector identities so that you can write the cross product in terms of Levi-Civita symbols.
Then you can immediately write down:

Let’s try it out. Define the symbols and field:

Take the gradient


Now the divergence:



And finally, the curl:

Judge for yourself which way you prefer. Personally, I would go for the second one.
If you found this article useful, you may want to consider becoming a Medium member to get unlimited access to all Medium articles. By registering using this link you can even support me as a writer.






