To simulate the flea jumping randomly between dogs for a given number of time steps, you can modify your code as follows:
import numpy as np
import matplotlib.pyplot as plt
def generate_lattice(L, p):
# Generate a square lattice with random values based on probability p
lattice = np.random.choice([0, 1], size=(L, L), p=[1 - p, p])
return lattice
def plot_lattice_with_values(lattice):
# Plot the lattice with values using matplotlib
fig, ax = plt.subplots()
im = ax.imshow(lattice, cmap='gray_r', interpolation='nearest')
for i in range(len(lattice)):
for j in range(len(lattice[0])):
text = ax.text(j, i, lattice[i, j], ha='center', va='center', color='red')
plt.xticks([]) # Hide x-axis ticks
plt.yticks([]) # Hide y-axis ticks
plt.show()
def flea_simulation(L, p, t):
# Generate lattice
lattice = generate_lattice(L, p)
# Find the indices of the first cell with value '1'
first_cell_indices = np.where(lattice == 1)
# Set the flea on the very first cell with value '1'
if first_cell_indices[0].size > 0:
i, j = first_cell_indices[0][0], first_cell_indices[1][0]
lattice[i, j] = 2 # Set the value to '2' to mark as visited
# Perform flea jumps for t time steps
for _ in range(t):
# Find the indices of all cells with value '2'
flea_indices = np.where(lattice == 2)
# Perform a random jump for each flea cell
for i in range(flea_indices[0].size):
x, y = flea_indices[0][i], flea_indices[1][i]
neighbors = []
# Find valid neighbors (cells with value '1') for the flea to jump to
if x > 0 and lattice[x-1, y] == 1:
neighbors.append((x-1, y))
if x < L-1 and lattice[x+1, y] == 1:
neighbors.append((x+1, y))
if y > 0 and lattice[x, y-1] == 1:
neighbors.append((x, y-1))
if y < L-1 and lattice[x, y+1] == 1:
neighbors.append((x, y+1))
# Randomly select a neighbor to jump to
if len(neighbors) > 0:
nx, ny = neighbors[np.random.choice(len(neighbors))]
lattice[nx, ny] = 2
# Plot the lattice with values
plot_lattice_with_values(lattice)
# Set lattice size (L), probability (p), and number of time steps (t)
L = 10
p = 0.5
t = 5
# Run the flea simulation
flea_simulation(L, p, t)
This code will simulate the flea jumping randomly between dogs for 5 time steps. You can adjust the values of L, p, and t to fit your specific requirements.