dingo_d
dingo_d

Reputation: 11680

Drawing cubic lattice in Python

So I want to draw a simple cubic lattice in Python using visual package.

I have a simple way of making a lattice with small spheres which all have the same color, but I want the colors to alternate: to make NaCl lattice I need to have a sphere of one color surrounded by 6 spheres of other color.

So I did this:

from __future__ import division
from visual import sphere,color

L = 5
R = 0.3

even = []
odd = []

for i in range(-L,L+1):
    if i%2==0:
        even.append(i)
    else:
        odd.append(i)

for i in even:
    for j in even:
        for k in even:
            sphere(pos=[i,j+1,k+1],radius=R,color=color.green)

for i in odd:
    for j in odd:
        for k in odd:
            sphere(pos=[i,j,k],radius=R,color=color.yellow)

And I get spheres of one color next to speres of different color, but they are in rows:

lattice

But I need them to alternate :\ The correct placement is only in the i direction. How do I correct the others to make a simple cubic lattice? I tried fiddling with the positions of the spheres (i,j,k+-number), but that way I got bcc lattice (one green sphere in the middle, others around it).

I'm stuck...

Upvotes: 1

Views: 4550

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

A slightly generalized version:

from visual import sphere,color
from itertools import product

L = 2
R = 0.25

xvals = range(-L, L+1)
yvals = range(-L, L+1)
zvals = range(-L, L+1)

colorfn = lambda *args: [color.yellow, color.green][sum(args)%2]

for pos in product(xvals, yvals, zvals):
    sphere(pos=pos, radius=R, color=colorfn(*pos))

results in

enter image description here

Upvotes: 1

UltraInstinct
UltraInstinct

Reputation: 44444

What you would need is this:

from visual import sphere,color

count = 3
R=0.3

for x in range(-count,count+1):
    for y in range(-count,count+1):
        for z in range(-count,count+1):
            if ((x+y+z+3*count)%2) == 0:
                sphere(pos=[x,y,z],radius=R,color=color.green)
            else:
                sphere(pos=[x,y,z],radius=R,color=color.yellow)

The point is, you should switch colors depending on whether the sum of the (integral, in this case) coordinates is divisible by 2 or not.

Upvotes: 3

Related Questions