我有这个问题:
Create a program which constructs a lattice of one (1) dimension and 100000 sites. In this lattice put at random positions a number of trap molecules, which will have concentration c. Put 1 particle in a random position on the lattice and let it perform a random walk. In this walk you will not place a time restriction, namely you will not declare a specific number of steps. The walk will stop when the particle falls on a trap.............................. ...Beware of boundary conditions. When the particle reaches the borders of the lattice it shouldn’t be allowed to escape from it but to remain in the lattice, either by returning on it former position or by being placed in the opposite site of the lattice........
我的方法显示在我创建的代码中(我在其中有注释)。
def steps1d(self,pos,c):
#pos: number of positions
#c: concentration of trap-particles
# array full of traps (zeros)
myzeros = sc.zeros(self.c*self.pos)
# grid full of available positions(ones)
grid = sc.ones(self.pos)
# distribute c*pos zeros(traps) in random positions (number of positions is pos)
traps = sc.random.permutation(pos)[:c*pos]
# the grid in which the particle is moving which has traps inside it
grid[traps] = myzeros
steps_count = [] # list which holds the number of steps
free = 0
for i in range(pos):
# the step of the particle can be 0 or 1
step=sc.random.random_integers(0,1)
for step in grid[:]:
if step == 1:
free += 1
steps_count.append(free)
else:
break
return steps_count
我有 3 个问题:
1)我以 pos=10 为例得到的结果如下:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35...]
我希望 1 次运行各有 10 个数字(位置可变)。
2)我不知道如何处理边界条件。我在想这样的事情:
if free > grid.size:
free = free - 1
但我无法测试它。另外,我不确定这是否适用于网格的两个边框。
3)如果我想让第一步从网格中间开始,我该怎么做?
如果有人对此有任何提示,我将不胜感激。
最佳答案
在较小的格子上,看看发生了什么:
import numpy
# Populate the lattice
lattice = numpy.concatenate([numpy.ones(90), numpy.zeros(10)])
numpy.random.shuffle(lattice)
# Intialize problem
in_trap = False
steps = 0
pos = int(numpy.random.randint(0,len(lattice),1))
history = []
while in_trap == False:
# Step of -1 is backward, 1 is forward
step = numpy.random.permutation([-1,1])[0]
# Check position for edges and fix if required
if pos + step > len(lattice) - 1:
pos = 0
elif pos + step < 0:
pos = len(lattice) - 1
else:
pos += step
# Keep track of random walk
history.append(pos)
# Check if it's a trap
if lattice[pos] == 0:
in_trap = True
# If not, continue
steps += 1
print steps
print history
print lattice
我鼓励您在整个过程中加入 print 语句来查看每个变量持有什么值。在较小的晶格上进行尝试将有助于您了解其工作原理。
编辑:
我将让您弄清楚具体细节,但我会将其包装在如下函数中。它设置函数,然后准备空步骤和历史列表来保存每次运行的结果。我们运行该函数,然后将结果附加到这些列表中。
def lattice():
code
return steps, history
steps = []
histories = []
for i in range(0,10):
num_steps, history = lattice()
steps.append(num_steps)
histories.append(history)
关于python-捕获分子的晶格结构-无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8038420/