DebasishDhal99 commited on
Commit
f115572
1 Parent(s): f7450ea

Create multi_agent_2D.py

Browse files
Files changed (1) hide show
  1. multi_agent_2D.py +136 -0
multi_agent_2D.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.pyplot as plt
2
+ import random
3
+ import numpy as np
4
+ import pandas as pd
5
+ from matplotlib.lines import Line2D
6
+
7
+ def single_random_walk(iters, agent_number, ax, step_size = 1, random_seed = None):
8
+ # random.seed(random_seed)
9
+ if random_seed:
10
+ random.seed(random_seed)
11
+
12
+ iters = int(iters)
13
+ directions = ['east', 'north', 'west', 'south']
14
+ start_point = [0, 0]
15
+
16
+ def distance_from_start(final_coord, start_coord, round_to=2):
17
+ return round(np.sqrt((final_coord[0] - start_coord[0])**2 + (final_coord[1] - start_coord[1])**2), round_to)
18
+
19
+ def step_addition(old_coord, step):
20
+ return [sum(x) for x in zip(old_coord, step)]
21
+
22
+ def step_determination():
23
+ direction = random.choice(directions)
24
+ if direction == 'east':
25
+ return [1*step_size, 0]
26
+ elif direction == 'west':
27
+ return [-1*step_size, 0]
28
+ elif direction == 'north':
29
+ return [0, 1*step_size]
30
+ elif direction == 'south':
31
+ return [0, -1*step_size]
32
+
33
+ coordinate_list = [start_point]
34
+
35
+ for _ in range(iters):
36
+ new_step = step_determination()
37
+ new_coordinate = step_addition(coordinate_list[-1], new_step)
38
+ coordinate_list.append(new_coordinate)
39
+
40
+ x = [i[0] for i in coordinate_list]
41
+ y = [i[1] for i in coordinate_list]
42
+ df = pd.DataFrame({'x':x,'y':y})
43
+
44
+
45
+ #Add the axis from the argument to the figure
46
+ base_marker_size = 10
47
+ markersize = base_marker_size / np.sqrt(iters)
48
+
49
+ plot = ax.plot(x, y, marker='o', markersize=markersize, linestyle='None', alpha=0.5, label = 'Agent {i}'.format(i=agent_number+1))
50
+ color = plot[0].get_color()
51
+ ax.plot(x[-1], y[-1], marker='o', markersize=5, color = 'black')
52
+ ax.text(x[-1], y[-1], 'End {i}'.format(i=agent_number+1), color = 'black', alpha=1.0)
53
+
54
+ return ax, df, color
55
+
56
+
57
+ def multi_agent_walk(agent_count, iters, step_size = 1, random_seed = None):
58
+ assert agent_count >= 1, "Number of agents must be >= than 1"
59
+
60
+ def displacement_calc(df):
61
+ x1,y1 = df.iloc[0]
62
+ x2,y2 = df.iloc[-1]
63
+ return np.round(np.sqrt((x2-x1)**2 + (y2-y1)**2),1)
64
+
65
+ if random_seed is None:
66
+ random_seed = random.randint(0,1000000)
67
+
68
+ assert type(random_seed) == int, "Random seed must be an integer"
69
+ #Generate a list of random seeds for each agent
70
+ random.seed(random_seed)
71
+ random_numbers = [random.randint(0,100000) for _ in range(agent_count)]
72
+
73
+
74
+ fig, ax = plt.subplots(figsize=(8,8))
75
+ color_list = []
76
+
77
+ for i in range(agent_count):
78
+ if i == 0:
79
+ ax, df, color = single_random_walk(iters=iters, ax=ax, step_size=step_size, agent_number=i, random_seed=random_numbers[i])
80
+ color_list.append(color)
81
+
82
+ else:
83
+ ax, df_new, color = single_random_walk(iters=iters, ax=ax, step_size=step_size, agent_number=i, random_seed=random_numbers[i])
84
+ df = pd.concat([df,df_new], axis=1)
85
+ x_columns = [f'x{i}' for i in range(1, i+2)]
86
+ y_columns = [f'y{i}' for i in range(1, i+2)]
87
+ new_column_names = [val for pair in zip(x_columns, y_columns) for val in pair]
88
+ df.columns = new_column_names
89
+ color_list.append(color)
90
+
91
+ ax.plot(0,0, marker='X', markersize=8, color='black')
92
+ ax.text(0, 0, 'Start (0,0)')
93
+
94
+ plt.grid()
95
+ plt.title('Random 2D Walk with {} agents\n #Steps = {}, Step size = {}, random seed = {}\nAll agents start from the origin'.format(agent_count, iters, step_size, random_seed))
96
+
97
+ displacement = [displacement_calc(df.iloc[:,[i,i+1]]) for i in range(0,agent_count*2,2)]
98
+ end_point = [(df.iloc[-1,i]) for i in range(0,agent_count*2,2)]
99
+
100
+ end_point = [(df.iloc[-1,i], df.iloc[-1,i+1]) for i in range(0,agent_count*2,2)]
101
+
102
+ agent_number = [i+1 for i in range(agent_count)]
103
+ legend_df = pd.DataFrame({'#':agent_number, 'dis.':displacement, 'End Point':end_point, })
104
+ info_box = legend_df.to_string(index=False)
105
+
106
+ ax.text(1.01, 0.99, info_box,
107
+ transform=ax.transAxes,
108
+ verticalalignment='top',
109
+ bbox=dict(boxstyle='round', facecolor='white', alpha=0.5)
110
+ )
111
+
112
+ lines = []
113
+ for i in range(len(color_list)):
114
+ lines.append(Line2D([0], [0], color=color_list[i], lw=9, linestyle=':'))
115
+
116
+ labels = [f'Agent {i+1}' for i in range(len(color_list))]
117
+ plt.legend(lines, labels,
118
+ loc='best',
119
+ handlelength=1.01,
120
+ handletextpad=0.21,
121
+ fancybox=True,
122
+ fontsize=10,
123
+ )
124
+
125
+ fig.canvas.draw()
126
+ image_array = np.array(fig.canvas.renderer.buffer_rgba())
127
+
128
+ try:
129
+ return image_array, df
130
+ except:
131
+ return image_array, None
132
+
133
+
134
+ # _, df = multi_agent_walk(agent_count=9, iters=1e5, step_size=1, random_seed=123);
135
+
136
+