Suggestions for improving speed

I'm working on visualizing a flow in R^3, and specifically focusing on how the flow behaves near a torus on inner radius 1 and outer radius 2, centered at the origin. The idea is to take a point (x,y,z), and look at this point using coordinates (r,z), in the plane containing (x,y,z) and the origin. Then I take equations in polar coordinates in this plane, and apply them to the point. Moving back into R^3, I take a rotation of the point, and add in the result of the flow restricted to the plane. Most of these conditions also require that I know the minimum distance from (x,y,z) to the torus mentioned.

This is taking a very long time, especially when I try to animate the flow. The last animation I tried took 20 hours, and that was before I found a flaw in the construction. This one works, but I'm hoping to optimize it before I try it again. Any suggestions on how to speed things up would be appreciated.

2 answers

I am not sure if you spend more time in just drawing pictures or in the computations. If the plot is guilty, you should look for another Python library that will be faster, but i am not specialist about pictures and animations. You can use %timeit to see which part of the program takes the most time.

If the computations take too much time, you should get rid of symbolic computations, and use floating-point arithmetic instead, using RDF where needed. Be careful that the coercion goes toward the symbolic ring, so each time you use it, the follogin computations use it as well. I did not run your code, but you can start with the following and tell if this solves your problem and if you need more hints:

First step remove the x,y,u,v = var('x y u v') at the beginning, and see for which function there is a problem, then replace those symbolic functions to PYthon function.

replace ep = 0.1 with ep = RDF(0.1) (Real Double Field is faster than Real Field with 53 bits of precision, and the coercion goes from the first to the second).

instead of the norm, using the square of the norm
saves extracting square roots, eg instead of testing
whether sqrt(x^2+y^2) < 2, test whether x^2 + y^2 < 4.
(You should test whether this really saves you time...
it could be that the norm method calls faster code
than code you might write yourself for norm_squared)