创建具有周期性边界的3D晶格 - 创建(x,y,z)的每个组合

时间:2012-10-02 10:16:26

标签: python

我正在尝试创建一个程序,将直径为d的相同非重叠粒子放在具有周期性边界条件的立方(3d)晶格中。

这真的意味着我需要一个程序来创建一个类似于下面的XYZ文件,但是会经历每一次合作:

H 0.0000000.0000005.000000
H 0.0000000.0000006.000000
H 0.0000000.0000007.000000
H 0.0000000.0000008.000000
H 0.0000000.0000009.000000

现在由于某种原因,我的下面的代码是保持我的z值为0而不是通过值来创建其他组合......而是仅通过x和y。

#create a file and enter first two lines
text_file=open("question1.xyz","w")
text_file.write("\n")
text_file.write("comment goes here\n")

L=10
d=1

#first particle or line will be at 0,0,0, counter used to count how many lines
x,y,z = 0,0,0
counter=0

#placing the particles
while x<=L-d:
    while y<=L-d:
        while z<=L-d:
            text_file.write('H ')
            text_file.write('%f'%x)
            text_file.write('%f'%y)
            text_file.write('%f\n'%z)
            counter=counter+1
            z=z+d
        z=0
        y=y+d
    z,y=0,0
    x=x+d

text_file.close()

with open("question1.xyz") as infile:
    with open("outputfile.xyz","w") as outfile:
        for i,line in enumerate(infile):
            if i==0:
                outfile.write('%f\n'%counter)
            else:
                outfile.write(line)

关于它为何发生的任何想法?我的声明有点凌乱,但我不确定如何做到这一点

1 个答案:

答案 0 :(得分:1)

有一种更简单的方法。使用itertools.product

import itertools

L = 3
d = 1
counter = 0
with open("question1.xyz","w") as text_file:
    text_file.write("\ncomment goes here\n")
    for x,y,z in itertools.product(range(L),repeat = 3):
        text_file.write('H %f %f %f\n' % (x, y, z))
        counter=counter+1