File size: 2,556 Bytes
0dfb40d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1da4f55
0dfb40d
 
1da4f55
0dfb40d
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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()
    
    # Save the plot to an in-memory buffer and return it
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    
    return buf.read()
iters = gr.inputs.Textbox(label="Number of random steps")

# Create a Gradio interface
iface = gr.Interface(fn=generate_random_walk, inputs=iters, outputs="image", title="Random Walk Plot")
iface.launch()