I'm trying to rewrite some vpython script in jupyter notebooks. So far I've not ran into many problems, but the last one I've tried to rewrite became significantly slower. It runs very quickly in VIDLE. I'm using sierraOS with Python 3.5.0 and Jupyter 4.1.0.
The code creates some objects, and then changes their positions in a while-loop.
Initially the loop had visual.rate(5000)
, but I tried reducing that to 50 with no avail. I also tried reducing the number of objects to only two but still working very slowly. Here's my simplest version of the code:
from vpython import scene, sphere, color, curve, arrow, mag, vector, rate,canvas
scene = canvas(width=800, height=600)
obj0 = sphere(pos=vector(0,0,0), radius=5e11)
obj1 = sphere(pos=vector(5e12,0,0), radius=5e11)
trail1= curve()
#some initial value
G = 6.7E-11
obj0.mass = 2.0E30
obj0.momentum = vector(0,0,0)
obj1.mass = 1.0E26
obj1.momentum = vector(0,0,0)
dt=200000.
CrashFlag=0
while(CrashFlag==0):
rate(1000)
obj1.force= -G*(obj0.mass*obj1.mass*obj1.pos)/(mag(obj1.pos)**3)
obj1.momentum = obj1.momentum+ dt*(obj1.force)
obj1.pos = obj1.pos + dt*obj1.momentum/obj1.mass
trail1.append(pos=obj1.pos)
if (mag(obj1.pos)<2.e11) :
CrashFlag=1
Can you identify anything that would cause this to be particularly slow in a Jupyter notebook, or suggest any way around it? Otherwise, is it possible to have the simulation outputted in VIDLE rather than inline in the Jupyter notebook (while the code would still run from the Jupyter notebook)
Some VPython operations are slower in Jupyter than Classic because much of Classic was written in C++ whereas Jupyter VPython is implemented in Python (though the vector class has been Cythonized). However, a separate issue is that it's costly to send lots of data from the Python program to the notebook, so I recommend getting rid of trail1 and trail1.append, because you're sending data in every loop iteration. Instead, say obj1 = sphere(pos=vector(5e12,0,0), radius=5e11, make_trail=True). Then points will be added to the trail on the notebook side, without having to send anything to the notebook. You might also consider in the obj1 constructor setting interval to something other than the default value of 1.
A similar issue exists for updating obj1.pos in every loop iteration. You're sending 1000 obj1.pos updates every second through the relatively narrow pipe that runs from the server to the browser. Consider updating a variable "pos" in every iteration but updating obj1.pos only every 50 iterations, say.