Search code examples
pythonvpython

Constructing a simple atomic lattice with VPython (Python 3.6.1)


I am currently working my way through Mark Newman's Computational Physics and I've encountered some trouble doing the exercises on 3D modelling using the VPython module.

I'm attempting to construct a simple L*L lattice and display it using the VPython module. I'm running Python 3.6.1.

My code looks like this:

from vpython import sphere

L = 5 # lattice size
R = 0.3 # atom radius

for i in range(-L,L+1):
    for j in range(-L,L+1):
        for k in range(-L,L+1):
            sphere(pos=[i,j,k],radius=R)

I get the following attribute error:

Traceback (most recent call last):
  File "C:\Users\xxx\Desktop\python\computational physics\web resources\lattice.py", line 7, in <module>
    sphere(pos=[i,j,k],radius=R)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\site-packages\vpython\vpython.py", line 1168, in __init__
    super(sphere, self).setup(args)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\site-packages\vpython\vpython.py", line 631, in setup
    else: raise AttributeError(a+' must be a vector')
AttributeError: pos must be a vector

The examples in the book use the visual module so I suspect that my problem is due to some compatibility issues between my version of Python and VPython.

Is there any way to fix my code so it displays the lattice using VPython? If not, is there an alternative to VPython?


Solution

  • You need to create a vector: http://vpython.org/contents/docs/vector.html

    First, you have to import it via

    from vpython import vector
    

    Now you change your last line to

    sphere(pos=vector(i,j,k),radius=R)
    

    and it hopefully should work!