-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathagent.py
More file actions
341 lines (306 loc) · 17.1 KB
/
agent.py
File metadata and controls
341 lines (306 loc) · 17.1 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import math
import pandas as pd
from mesa_geo.geoagent import GeoAgent, AgentCreator
import numpy as np
import random
import networkx as nx
import osmnx as ox
ox.settings.use_cache=True
ox.settings.cache_folder = "C:/Users/user/Desktop/RA/pythonProject20/cache"
filepath_drive = "./data/columbus.graphml"
G = ox.load_graphml(filepath_drive) #DRIVE GRAPH
filepath_walk = "./data/columbus_walk.graphml"
A = ox.load_graphml(filepath_walk) #WALK GRAPH
global household_data,step,distance_data
household_data=[]
distance_data=[]
global df_distance
#columns_for_distance = ['household', 'market', 'distance']
#df_distance = pd.DataFrame(columns=columns_for_distance)
df_distance = pd.read_csv("distance_data.csv")
class erhc(GeoAgent):
def __init__(self, unique_id, model, shape,fa,fsa_sum,latitude = None, longitude=None):
super().__init__(unique_id, model, shape)
#self.atype = agent_type
#self.model = model
self.fa = fa
self.latitude = latitude
self.longitude = longitude
self.fsa_sum=fsa_sum
global step
step = 0
def step(self):
neighbors = self.model.grid.get_neighbors_within_distance(self,16889,center=False, relation="intersects") #neighbors within 10 miles
list_of_spm = []
list_of_cspm=[]
columns_for_results=['Type','id','fa','took food from(markets unique id)']
global household_data,step,distance_data,df_distance,columns_for_distance
step = step + 1
if step==1:
household_data = []#contingency when we reset the model, the dataframe should be cleared
orig = ox.distance.nearest_nodes(G, X=self.longitude, Y=self.latitude)
for neighbor in neighbors:
if type(neighbor) is spm or type(neighbor) is cspm:
if ((df_distance['household']==self.unique_id) & (df_distance['market']==neighbor.unique_id)).any():
distance = df_distance['distance'].loc[(df_distance['household']==self.unique_id) & (df_distance['market']==neighbor.unique_id)].iloc[0]
else:
dest = ox.distance.nearest_nodes(G, X=neighbor.longitude, Y=neighbor.latitude)
route = ox.shortest_path(G, orig, dest, weight="")
if route is not None:
edge_lengths = ox.utils_graph.get_route_edge_attributes(G, route, "length")
else:
edge_lengths = [math.inf]
distance = sum(edge_lengths)*0.000621371
df_distance.loc[len(df_distance)] = [self.unique_id,neighbor.unique_id,distance]
if distance<10 and neighbor.FSA >= 20:
if type(neighbor) is spm:
list_of_spm.append([neighbor,distance])
else:
list_of_cspm.append([neighbor,distance])
if len(list_of_cspm) >= 1 or len(list_of_spm)>=1:
list_of_cspm.sort(key=lambda x:x[1])
list_of_spm.sort(key=lambda x:x[1])
if list_of_cspm and list_of_spm:
if list_of_cspm[0][1] < list_of_spm[0][1]:
chosen_market_list = random.choices([list_of_cspm[0],list_of_spm[0]],weights=(24,76),k=1)[0]
else:
chosen_market_list = random.choices([list_of_cspm[0], list_of_spm[0]], weights=(20, 80),k=1)[0]
elif not list_of_cspm:
chosen_market_list = list_of_spm[0]
elif not list_of_spm:
chosen_market_list = list_of_cspm[0]
chosen_market = chosen_market_list[0]
dis = chosen_market_list[1]
#df_distance.loc[len(df_distance)] = [self.unique_id,chosen_market.unique_id,dis]
self.fsa_sum += chosen_market.FSA
self.fa = (self.fsa_sum/ 700) * 100
chosen_market.fa = round(chosen_market.fa,2)
print("Agent - ", type(self),"-",self.unique_id," ", "-", round(self.fa,2)," ")
print("Market - ", type(chosen_market),chosen_market.unique_id," ", "-", chosen_market.FSA)
#distance_chosen = df_distance['distance'].loc[(df_distance['household']==self.unique_id) & (df_distance['market']==chosen_market.unique_id)].iloc[0]
print("Distance by car between them is ",round(dis,4)," miles\n")
household_data.append(["erhc",self.unique_id,self.fa,chosen_market.unique_id])
else:
if (self.fa > 0):
self.fa -= 1.25
print("Agent - ", type(self),self.unique_id," ", "-", self.fa, "\n")
household_data.append(["erhc", self.unique_id, self.fa, "No Market"])
else:
print("Agent - ", type(self),self.unique_id," ", "-", self.fa, "\n")
df = pd.DataFrame(household_data,columns=columns_for_results)
#print(df_distance)
#print(self.steps)
df_distance.to_csv("distance_data.csv",index=False)
df.to_csv("household_data.csv")
class erlc(GeoAgent):
def __init__(self, unique_id, model, shape,fa,fsa_sum,latitude = None, longitude=None):
super().__init__(unique_id, model, shape)
#self.atype = agent_type
#self.model = model
self.fa = fa
self.latitude = latitude
self.longitude = longitude
self.fsa_sum = fsa_sum
def step(self):
neighbors = self.model.grid.get_neighbors_within_distance(self,6889,center=False, relation="intersects") #neighbors within 5 miles
list_of_cspm = []
list_of_spm=[]
columns_for_results = ['Type','id', 'fa', 'took food from(markets unique id)']
global household_data,distance_data,df_distance,columns_for_distance
orig = ox.distance.nearest_nodes(A, X=self.longitude, Y=self.latitude)
for neighbor in neighbors:
if type(neighbor) is spm or type(neighbor) is cspm:
if ((df_distance['household']==self.unique_id) & (df_distance['market']==neighbor.unique_id)).any():
distance = df_distance['distance'].loc[(df_distance['household']==self.unique_id) & (df_distance['market']==neighbor.unique_id)].iloc[0]
else:
dest = ox.distance.nearest_nodes(A, X=neighbor.longitude, Y=neighbor.latitude)
route = ox.shortest_path(A, orig, dest, weight="")
if route is not None:
edge_lengths = ox.utils_graph.get_route_edge_attributes(A, route, "length")
else:
edge_lengths = [math.inf]
distance = sum(edge_lengths) * 0.000621371
df_distance.loc[len(df_distance)] = [self.unique_id, neighbor.unique_id, distance]
if distance < 8 and neighbor.FSA >= 20:
if type(neighbor) is spm:
list_of_spm.append([neighbor,distance])
else:
list_of_cspm.append([neighbor,distance])
if len(list_of_cspm) >= 1 or len(list_of_spm)>=1:
list_of_cspm.sort(key=lambda x: x[1])
list_of_spm.sort(key=lambda x: x[1])
if list_of_cspm and list_of_spm:
chosen_market_list = random.choices([list_of_cspm[0],list_of_spm[0]],weights=(28,72),k=1)[0]
elif not list_of_cspm:
chosen_market_list = list_of_spm[0]
elif not list_of_spm:
chosen_market_list = list_of_cspm[0]
chosen_market = chosen_market_list[0]
dis = chosen_market_list[1]
#df_distance.loc[len(df_distance)] = [self.unique_id,chosen_market.unique_id,dis]
self.fsa_sum += chosen_market.FSA
self.fa = (self.fsa_sum/ 640) * 100
chosen_market.fa = round(chosen_market.fa, 2)
print("Agent - ", type(self), "-", self.unique_id, " ", "-", round(self.fa,2), " ")
print("Market - ", type(chosen_market), chosen_market.unique_id, " ", "-", chosen_market.FSA)
print("Distance by walk between them is ", round(dis,4), " miles\n")
household_data.append(["erlc", self.unique_id, self.fa, chosen_market.unique_id])
else:
if (self.fa > 0):
self.fa -= 1
print("Agent - ", type(self), self.unique_id, " ", "-", self.fa, "\n")
household_data.append(["erlc", self.unique_id, self.fa, "No Market"])
else:
print("Agent - ", type(self), self.unique_id, " ", "-", self.fa, "\n")
df = pd.DataFrame(household_data, columns=columns_for_results)
df_distance.to_csv("distance_data.csv",index=False)
df.to_csv("household_data.csv")
class lrhc(GeoAgent):
def __init__(self, unique_id, model, shape,fa,fsa_sum,latitude = None, longitude=None):
super().__init__(unique_id, model, shape)
#self.atype = agent_type
#self.model = model
self.fa = fa
self.latitude = latitude
self.longitude = longitude
self.fsa_sum=fsa_sum
def step(self):
neighbors = self.model.grid.get_neighbors_within_distance(self,16889,center=False, relation="intersects")#neighbors within 10 miles
list_of_cspm = []
list_of_spm=[]
columns_for_results = ['Type', 'id', 'fa', 'took food from(markets unique id)']
global household_data,df_distance,columns_for_distance
orig = ox.distance.nearest_nodes(G, X=self.longitude, Y=self.latitude)
for neighbor in neighbors:
if type(neighbor) is spm or type(neighbor) is cspm:
if ((df_distance['household']==self.unique_id) & (df_distance['market']==neighbor.unique_id)).any():
distance = df_distance['distance'].loc[(df_distance['household']==self.unique_id) & (df_distance['market']==neighbor.unique_id)].iloc[0]
else:
dest = ox.distance.nearest_nodes(G, X=neighbor.longitude, Y=neighbor.latitude)
route = ox.shortest_path(G, orig, dest, weight="")
if route is not None:
edge_lengths = ox.utils_graph.get_route_edge_attributes(G, route, "length")
else:
edge_lengths = [math.inf]
distance = sum(edge_lengths) * 0.000621371
df_distance.loc[len(df_distance)] = [self.unique_id, neighbor.unique_id, distance]
if distance < 10 and neighbor.FSA >= 20:
if type(neighbor) is spm:
list_of_spm.append([neighbor,distance])
else:
list_of_cspm.append([neighbor,distance])
if len(list_of_cspm) >= 1 or len(list_of_spm) >= 1:
list_of_cspm.sort(key=lambda x: x[1])
list_of_spm.sort(key=lambda x: x[1])
if list_of_cspm and list_of_spm:
chosen_market_list = random.choices([list_of_cspm[0],list_of_spm[0]],weights=(36,64),k=1)[0]
elif not list_of_cspm:
chosen_market_list = list_of_spm[0]
elif not list_of_spm:
chosen_market_list = list_of_cspm[0]
chosen_market = chosen_market_list[0]
dis = chosen_market_list[1]
#df_distance.loc[len(df_distance)] = [self.unique_id,chosen_market.unique_id,dis]
self.fsa_sum+=chosen_market.FSA
self.fa = (self.fsa_sum/600) * 100
chosen_market.fa = round(chosen_market.fa, 2)
print("Agent - ", type(self), "-", self.unique_id, " ", "-", round(self.fa,2), " ")
print("Market - ", type(chosen_market), chosen_market.unique_id, " ", "-", chosen_market.FSA)
print("Distance by car between them is ", round(dis,4), " miles\n")
household_data.append(["lrhc", self.unique_id, self.fa, chosen_market.unique_id])
else:
if (self.fa > 0):
self.fa -= 1
print("Agent - ", type(self), self.unique_id, " ", "-", self.fa, "\n")
household_data.append(["lrhc", self.unique_id, self.fa, "No Market"])
else:
print("Agent - ", type(self), self.unique_id, " ", "-", self.fa, "\n")
df = pd.DataFrame(household_data, columns=columns_for_results)
# print(self.steps)
df_distance.to_csv("distance_data.csv", index=False)
df.to_csv("household_data.csv")
class lrlc(GeoAgent):
def __init__(self, unique_id, model, shape,fa,fsa_sum,latitude = None, longitude=None):
super().__init__(unique_id, model, shape)
#self.atype = agent_type
#self.model = model
self.fa = fa
self.latitude = latitude
self.longitude = longitude
self.fsa_sum=fsa_sum
def step(self):
neighbors = self.model.grid.get_neighbors_within_distance(self,6889,center=False, relation="intersects")#neighbors within 5 miles
list_of_spm = []
list_of_cspm=[]
columns_for_results = ['Type', 'id', 'fa', 'took food from(markets unique id)']
global household_data,df_distance,columns_for_distance
orig = ox.distance.nearest_nodes(A, X=self.longitude, Y=self.latitude)
for neighbor in neighbors:
if type(neighbor) is spm or type(neighbor) is cspm:
if ((df_distance['household']==self.unique_id) & (df_distance['market']==neighbor.unique_id)).any():
distance = df_distance['distance'].loc[(df_distance['household']==self.unique_id) & (df_distance['market']==neighbor.unique_id)].iloc[0]
else:
dest = ox.distance.nearest_nodes(A, X=neighbor.longitude, Y=neighbor.latitude)
route = ox.shortest_path(A, orig, dest, weight="")
if route is not None:
edge_lengths = ox.utils_graph.get_route_edge_attributes(A, route, "length")
else:
edge_lengths = [math.inf]
distance = sum(edge_lengths) * 0.000621371
df_distance.loc[len(df_distance)] = [self.unique_id, neighbor.unique_id, distance]
if distance < 8 and neighbor.FSA >= 20:
if type(neighbor) is spm:
list_of_spm.append([neighbor,distance])
else:
list_of_cspm.append([neighbor,distance])
if len(list_of_cspm) >= 1 or len(list_of_spm) >= 1:
list_of_cspm.sort(key=lambda x: x[1])
list_of_spm.sort(key=lambda x: x[1])
if list_of_cspm and list_of_spm:
chosen_market_list = random.choices([list_of_cspm[0],list_of_spm[0]],weights=(40,60),k=1)[0]
elif not list_of_cspm:
chosen_market_list = list_of_spm[0][0]
elif not list_of_spm:
chosen_market_list = list_of_cspm[0][0]
chosen_market = chosen_market_list[0]
dis = chosen_market_list[1]
#df_distance.loc[len(df_distance)] = [self.unique_id,chosen_market.unique_id,dis]
self.fsa_sum+=chosen_market.FSA
self.fa = (self.fsa_sum/480) * 100
chosen_market.fa = round(chosen_market.fa, 2)
print("Agent - ", type(self), "-", self.unique_id, " ", "-",round(self.fa,2), " ")
print("Market - ", type(chosen_market), chosen_market.unique_id, " ", "-", chosen_market.FSA)
print("Distance by walk between them is ", round(dis,4), " miles\n")
household_data.append(["lrlc", self.unique_id, self.fa, chosen_market.unique_id])
# print(st)
else:
if (self.fa > 0):
self.fa -= 1
print("Agent - ", type(self), self.unique_id, " ", "-", self.fa, "\n")
household_data.append(["lrlc", self.unique_id, self.fa, "No Market"])
else:
print("Agent - ", type(self), self.unique_id, " ", "-", self.fa, "\n")
df = pd.DataFrame(household_data, columns=columns_for_results)
# print(self.steps)
df_distance.to_csv("distance_data.csv", index=False)
df.to_csv("household_data.csv")
class spm(GeoAgent):
def __init__(self, unique_id, model, shape,fa,latitude = None, longitude=None,FSA=None):
super().__init__(unique_id, model, shape)
self.fa = fa
self.latitude = latitude
self.longitude = longitude
self.FSA = FSA
def step(self):
if self.fa <= 0:
self.model.grid.remove_agent(self)
class cspm(GeoAgent):
def __init__(self, unique_id, model, shape,fa,latitude = None, longitude=None,FSA=None):
super().__init__(unique_id, model, shape)
self.fa = fa
self.latitude = latitude
self.longitude = longitude
self.FSA = FSA
def step(self):
if self.fa <= 0:
self.model.grid.remove_agent(self)