simulate self-avoiding random walk in python

Here's one way to simulate self-avoiding random walks in Python:

main.py
import numpy as np
import random

def simulate_saw(dim, steps):
    """
    Simulate a self-avoiding random walk in dim dimensions with a fixed number of steps.
    
    :param dim: Number of dimensions of the walk.
    :param steps: Number of steps in the walk.
    :return: A dim x steps array containing the coordinates of the walk.
    """
    # Initialize the array of coordinates.
    coords = np.zeros((dim, steps), dtype=int)
    # Start at the origin.
    coords[:, 0] = 0
    
    for i in range(1, steps):
        # Generate a random step.
        step = np.zeros(dim, dtype=int)
        step[random.randint(0, dim-1)] = random.choice([-1, 1])
        
        # Check if the new position is already occupied.
        new_pos = coords[:, i-1] + step
        if np.any((new_pos == coords[:, :i]).all(axis=0)):
            # If it is, reject the step and try again.
            i -= 1
        else:
            # Otherwise, add the step to the coordinates.
            coords[:, i] = new_pos
    
    return coords
1024 chars
32 lines

The simulate_saw function takes two arguments: dim, the number of dimensions of the walk, and steps, the number of steps in the walk. It returns a dim x steps array containing the coordinates of the walk.

To generate a 2D self-avoiding random walk with 1000 steps, for example, you could use:

main.py
walk_2d = simulate_saw(2, 1000)
32 chars
2 lines

This will return a 2 x 1000 array where the first row contains the x-coordinates and the second row contains the y-coordinates of the walk.

gistlibby LogSnag