|
import matplotlib.pyplot as plt |
|
import random |
|
import gradio as gr |
|
|
|
def generate_random_walk(iters): |
|
directions = ['east', 'north', 'north', 'south'] |
|
start_point = [0, 0] |
|
|
|
def distance_from_start(final_coord, start_coord, round_to=2): |
|
return round(np.sqrt((final_coord[0] - start_coord[0])**2 + (final_coord[1] - start_coord[1])**2), round_to) |
|
|
|
def step_addition(old_coord, step): |
|
return [sum(x) for x in zip(old_coord, step)] |
|
|
|
def step_determination(): |
|
direction = random.choice(directions) |
|
if direction == 'east': |
|
return [1, 0] |
|
elif direction == 'west': |
|
return [-1, 0] |
|
elif direction == 'north': |
|
return [0, 1] |
|
elif direction == 'south': |
|
return [0, -1] |
|
|
|
coordinate_list = [start_point] |
|
|
|
for i in range(iters): |
|
new_step = step_determination() |
|
new_coordinate = step_addition(coordinate_list[-1], new_step) |
|
coordinate_list.append(new_coordinate) |
|
|
|
x = [i[0] for i in coordinate_list] |
|
y = [i[1] for i in coordinate_list] |
|
|
|
fig, ax = plt.subplots(1) |
|
|
|
base_marker_size = 10 |
|
markersize = base_marker_size / np.sqrt(iters) |
|
|
|
ax.plot(x, y, marker='o', markersize=markersize, linestyle='None') |
|
|
|
ax.plot(x[0], y[0], marker='o', markersize=5, color="red") |
|
ax.plot(x[-1], y[-1], marker='o', markersize=5, color="orange") |
|
|
|
ax.text(start_point[0], start_point[1], 'Start', color='red') |
|
ax.text(x[-1], y[-1], 'End', color='orange') |
|
|
|
x_max_index = x.index(max(x)) |
|
x_min_index = x.index(min(x)) |
|
y_max_index = y.index(max(y)) |
|
y_min_index = y.index(min(y)) |
|
|
|
info_text = 'Start point=' + str(start_point) + '\n' +'End point=' + str([x[-1],y[-1]]) + '\n' +'Displacement =' + str(distance_from_start([x[-1], y[-1]], start_point)) + '\n' +'Max x = ' + str(max(x)) + '\n' + 'Min x = ' + str(min(x)) + '\n' + 'Max y = ' + str(max(y)) + '\n' + 'Min y = ' + str(min(y)) |
|
ax.legend([info_text], loc='best', handlelength=0, handletextpad=0, fancybox=True, fontsize=8) |
|
|
|
plt.title('2D Random Walk, iterations = ' + str(iters)) |
|
plt.grid() |
|
|
|
|
|
buf = io.BytesIO() |
|
plt.savefig(buf, format='png') |
|
buf.seek(0) |
|
|
|
return buf.read() |
|
iters = gr.inputs.Textbox(label="Number of random steps") |
|
|
|
|
|
iface = gr.Interface(fn=generate_random_walk, inputs=iters, outputs="image", title="Random Walk Plot") |
|
iface.launch() |
|
|