python- construction of lattice which traps molecules - doesn't work right

瘦欲@ 提交于 2019-12-02 03:57:01

On a smaller lattice, to see what is happening:

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

I would encourage you to thrown in print statements throughout to see what values each variable is holding. Trying it out on smaller lattices will help you understand how this works.

EDIT:

I'm going to let you figure out the specifics, but I would wrap this in a function like follows. It sets up the function, then prepares empty steps and histories lists to hold the results of each run. We run the function, then append the results to those lists.

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)

The part where the grid is created is OK (although you used traps twice - I suppose you don't need the 1st line and the 4th line should be grid[traps]=0).

Then according to the problem you have to put a molecule and make it walk on the grid, and this part of your program is completely wrong. What you need to do is find a random starting point for the molecule (with sc.random.randint(pos) maybe), and then count the number of steps the molecule makes before falling in a trap. Steps in 1d random walk can be either to the left (starting_point - 1) or to the right (starting_point + 1). You have to choose randomly between [-1, +1], add the step to the index of the molecule on the grid and if the resultant index appears to be free on the grid then increment your free variable. If the resultant index hits the trap, then append the free variable to the steps_count list.

To answer your second question, periodic boundary conditions can be applied seamlessly to the grid if you take the remainder of index % pos division as the index of the molecule.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!