def pingRequest(): recieved = request.args passLoc = [float(recieved['src_lat']),float(recieved['src_lon'])] x1,y1 = aco.convert_to_xy(passLoc) x2,y2 = aco.convert_to_xy(taxi['currentLoc']) dist = math.sqrt((x1-x2)**2 + (y1-y2)**2) return(json.dumps({'port': 5002, 'distance': dist}))
def pheromone_update(): global pheromone received = request.args global request_queue request_queue.append({ "timestamp": datetime.datetime.now().strftime("%H:%M:%S"), "type": "broadcastPheromone" }) centroids_new = [] route = received["route"] route = [list(map(float, i.split(','))) for i in route.split(";")] for i in route: pos = aco.convert_to_xy(i) pt = aco.get_nearest_centroid(pos) centroids_new.append(pt) for i in range(1, len(centroids_new)): try: pheromone[centroids_new[i - 1]][centroids_new[i]] = ( 1 - evaporation_factor) * pheromone[centroids_new[i - 1]][ centroids_new[i]] + evaporation_factor / float( received["cost"]) except ZeroDivisionError: pheromone[centroids_new[i - 1]][centroids_new[i]] = ( 1 - evaporation_factor) * pheromone[centroids_new[i - 1]][ centroids_new[i]] + evaporation_factor / 999 print("pheromone matrix updated for taxi id:", taxi["id"]) return ("Broadcasting Done.")
def get_nearest_taxis(): recieved = request.args passLoc = [float(recieved['src_lat']), float(recieved['src_lon'])] grid_no = aco.get_nearest_centroid(aco.convert_to_xy(passLoc)) if grid_no in taxis_in_grids: return (json.dumps({'taxis': taxis_in_grids[grid_no]})) else: return (json.dumps({'taxis': []}))
def get_next_hop(): recieved = request.args passLoc = [float(recieved['src_lat']), float(recieved['src_lon'])] x1, y1 = aco.convert_to_xy(passLoc) taxi_ids = [] for (t_id, taxi_loc) in enumerate(taxi_locations): x2, y2 = aco.convert_to_xy(taxi_loc) dist = math.sqrt((x1 - x2)**2 + (y1 - y2)**2) if dist < 500: taxi_ids.append(t_id + 1) return (json.dumps({'taxis': taxi_ids}))
def pheromone_update(): global pheromone received = request.args centroids_new = [] route = received["route"] route = [list(map(float,i.split(','))) for i in route.split(";")] for i in route: pos = aco.convert_to_xy(i) pt = aco.get_nearest_centroid(pos) centroids_new.append(pt) for i in range(1,len(centroids_new)): pheromone[centroids_new[i-1]][centroids_new[i]] = (1-evaporation_factor)*pheromone[centroids_new[i-1]][centroids_new[i]] + evaporation_factor / float(received["cost"]) print("pheromone matrix updated for taxi id:",taxi["id"]) return("Broadcasting Done.")
def update_my_pheromone(cost_params): global pheromone received = cost_params centroids_new = [] route = received["route"] route = [list(map(float,i.split(','))) for i in route.split(";")] for i in route: pos = aco.convert_to_xy(i) pt = aco.get_nearest_centroid(pos) centroids_new.append(pt) for i in range(1,len(centroids_new)): try: pheromone[centroids_new[i-1]][centroids_new[i]] = (1-evaporation_factor)*pheromone[centroids_new[i-1]][centroids_new[i]] + evaporation_factor / float(received["cost"]) except ZeroDivisionError: pheromone[centroids_new[i-1]][centroids_new[i]] = (1-evaporation_factor)*pheromone[centroids_new[i-1]][centroids_new[i]] + evaporation_factor / 999 print("pheromone matrix updated for taxi id:",taxi["id"]) return("Broadcasting Done.")
def update_taxi_location(): global taxi_locations global t print("updating...") temp_taxi_locations = [] for i in range(start_port, start_port + taxi_id - 1): r = requests.get(url=url_taxi + str(i) + "/liveTrack") data = r.json() taxiLoc = data['curr'] grid_no = aco.get_nearest_centroid( aco.convert_to_xy([float(taxiLoc[0]), float(taxiLoc[1])])) temp_taxi_locations.append([float(taxiLoc[0]), float(taxiLoc[1])]) remove_previous_grid_loc(int(i) - start_port + 1) if grid_no in taxis_in_grids: taxis_in_grids[grid_no].append(int(i) - start_port + 1) else: taxis_in_grids[grid_no] = [int(i) - start_port + 1] taxi_locations = temp_taxi_locations if (t.is_alive): t.cancel() t = Timer(int(params['update_taxi_location_timer']), update_taxi_location) t.start()
def processRequest(): global taxi recieved = request.args acoVal = {'currentLoc': taxi['currentLoc'],'newReq':{'src': [float(recieved['src_lat']),float(recieved['src_lon'])],'dest': [float(recieved['dest_lat']),float(recieved['dest_lon'])], "name":recieved["name"]},'passengers': taxi['passenger']} global broadcastDone if(taxi['noPassengers'] >= 4): if broadcastDone == 1: broadcastDone = 0 return (json.dumps({'id':taxi['id'], 'port': 5000, 'cost':-1})) broadcastDone = 1 print("Passing to my neighbor because i have 4 passengers") return(json.dumps(broadcastToAllPeers(acoVal['newReq']))) dataRecv = aco.acoData(acoVal) global cost cost = dataRecv['cost'] #return value to passenger retVal = {'id': taxi['id'], 'port':5002, 'cost': cost} if(cost != -1): global route route = [taxi["currentLoc"]]+dataRecv['route'] else: if broadcastDone == 1: broadcastDone = 0 return(json.dumps(retVal)) broadcastDone = 1 print("Passing to my neighbor because of Passenger waiting Time is more") return(json.dumps(broadcastToAllPeers(acoVal['newReq']))) print("cost for taxi:",cost," and taxis current loc:",taxi["currentLoc"]) global direction startPoint = route[0] direction = [] names_src = [] names_dst = [] pass_array = taxi["passenger"]+[{'src': [float(recieved['src_lat']),float(recieved['src_lon'])],'dest': [float(recieved['dest_lat']),float(recieved['dest_lon'])],"name":recieved["name"]}] for i in route[1:]: path = giveRegionsPassed(startPoint,i)[:-1] res, name = check_src(i,names_src,pass_array) if(res): path[len(path)-1]['src'] = 1 path[len(path)-1]['name'] = name names_src.append(name) res, name = check_dest(i,names_dst,pass_array) if(res): path[len(path)-1]['dest'] = 1 path[len(path)-1]['name'] = name names_dst.append(name) direction += path startPoint = i #check if passenger waiting time of all other current passengers changes a lot then broadcast request to other peers if(check_pwtime_constraint() == False): if broadcastDone == 1: broadcastDone = 0 return(json.dumps(retVal)) broadcastDone = 1 print("Passing to my neighbor because of Passenger Waiting Time of other customer(s)") return(json.dumps(broadcastToAllPeers(acoVal['newReq']))) if(check_dsttime_constraint()==False): if broadcastDone == 1: broadcastDone = 0 return(json.dumps(retVal)) broadcastDone = 1 print("Passing to my neighbor because of Passenger Destination Time of other customer(s)") return(json.dumps(broadcastToAllPeers(acoVal['newReq']))) retVal = {'id': taxi['id'], 'port':5002, 'cost': cost} #print("Prev cost and now cost",prevcost,cost,abs(prevcost - cost)) return(json.dumps(retVal))
params = get_parameters() centroids = np.load(params["centroids_file"]) n_grids = centroids.shape[0] no_of_taxis = int(params["no_of_taxis"]) start_port = int(params["start_port"]) url_taxi = params["url_taxi_ip"] with open(params["taxi_init_file"]) as taxi: csv_reader = csv.reader(taxi, delimiter=',') taxi_id = 1 for row in csv_reader: taxi_locations.append([float(row[0]), float(row[1])]) grid_no = aco.get_nearest_centroid( aco.convert_to_xy([float(row[0]), float(row[1])])) if grid_no in taxis_in_grids: taxis_in_grids[grid_no].append(taxi_id) else: taxis_in_grids[grid_no] = [taxi_id] taxi_id += 1 def remove_previous_grid_loc(taxi_no): for i in taxis_in_grids: if (taxi_no in taxis_in_grids[i]): taxis_in_grids[i].remove(taxi_no) break def update_taxi_location():
def processRequest(): global taxi global request_in_process global no_messages global request_queue request_queue.append({ "timestamp": datetime.datetime.now().strftime("%H:%M:%S"), "type": "getRequest" }) recieved = request.args if ((datetime.datetime.strptime( datetime.datetime.now().strftime("%H:%M:%S"), "%H:%M:%S") - (datetime.datetime.strptime(recieved["timestamp"], "%H:%M:%S")) ).total_seconds() > int(params["request_timers"])): return json.dumps({ 'id': taxi['id'], 'port': int(taxi_id), 'cost': -1, "message": "7.queued reaching taxi late" }) broadcast_taxis = recieved["all_broadcasted_taxis"].split(" ") acoVal = { 'currentLoc': taxi['currentLoc'], 'newReq': { 'src': [float(recieved['src_lat']), float(recieved['src_lon'])], 'dest': [float(recieved['dest_lat']), float(recieved['dest_lon'])], "name": recieved["name"], "all_broadcasted_taxis": broadcast_taxis, 'timestamp': recieved["timestamp"] }, 'passengers': taxi['passenger'] } global cost ''' check if taxi is waiting for someone other passenger's confirmation ''' if (request_in_process["status"] == True): return (json.dumps({ 'id': taxi['id'], 'port': int(taxi_id), 'cost': -1, 'message': "1.waiting for others pass confirmation" })) if (taxi['noPassengers'] >= 4): if 'first_hop' in request.args: return (json.dumps({ 'id': taxi['id'], 'port': int(taxi_id), 'cost': -1, "message": "2.capacity" })) else: print("Passing to my neighbor because I have 4 passengers") return (json.dumps(broadcastToAllPeers(acoVal['newReq']))) dataRecv = aco.acoData(acoVal, pheromone) #here cost is only total travel distance recv_cost = dataRecv['cost'] #return value to passenger retVal = { 'id': taxi['id'], 'port': int(taxi_id), 'cost': recv_cost, 'detour_obj': 0, 'time_obj': 0 } if (recv_cost != -1): #use these values for setting taxi['total_dist'] and taxi['total_time'] after request confirms global direction_dist global direction_time direction_dist = recv_cost direction_time = dataRecv['cost_time'] global detour_cost global tot_time_cost ''' #computing detour time for the new request - use this when #objective function for peak hours changes if(taxi['noPassengers'] == 0): detour_time = giveRegionsPassed(taxi['currentLoc'], dataRecv['route'][0], return_time = True) else: detour_time = abs(dataRecv['cost_time'] - taxi['total_time']) if detour_time != 0.0: cost = math.sqrt(detour_time**2+dataRecv['cost_time']**2) else: cost = math.sqrt(0.001**2+dataRecv['cost_time']**2) print("Detour time for taxi",int(taxi['id']),"= ",detour_time) retVal["detour_obj"] = detour_time retVal["time_obj"] = dataRecv['cost_time'] ''' #not sure if absolute is necessary if (taxi['noPassengers'] == 0): detour_distance = giveRegionsPassed(taxi['currentLoc'], dataRecv['route'][0], return_dist=True) else: detour_distance = abs(recv_cost - taxi['total_dist']) if detour_distance != 0.0: cost = math.sqrt(detour_distance**2 + dataRecv['cost_time']**2) else: cost = math.sqrt(0.001**2 + dataRecv['cost_time']**2) print("Detour distance for taxi", int(taxi['id']), "= ", detour_distance, " and time = ", dataRecv['cost_time']) retVal["detour_obj"] = detour_distance retVal["time_obj"] = dataRecv['cost_time'] global route route = [taxi["currentLoc"]] + dataRecv['route'] else: retVal["message"] = "3.Your PWT is more" return (json.dumps(retVal)) print("cost for taxi", taxi['id'], ":", cost, " and taxis current loc:", taxi["currentLoc"]) global direction startPoint = route[0] direction = [] names_src = [] names_dst = [] pass_array = taxi["passenger"] + [{ 'src': [float(recieved['src_lat']), float(recieved['src_lon'])], 'dest': [float(recieved['dest_lat']), float(recieved['dest_lon'])], "name": recieved["name"], "picked": 0 }] for i in route[1:]: path = giveRegionsPassed(startPoint, i)[:-1] res, name = check_src(i, names_src, pass_array) if (res): path[len(path) - 1]['src'] = 1 path[len(path) - 1]['name'] = name names_src.append(name) else: res, name = check_dest(i, names_dst, names_src, pass_array) if (res): path[len(path) - 1]['dest'] = 1 path[len(path) - 1]['name'] = name names_dst.append(name) direction += path startPoint = i #return value to passenger retVal = { 'id': taxi['id'], 'port': int(taxi_id), 'cost': cost, "detour_obj": detour_distance, "time_obj": dataRecv['cost_time'] } #check if passenger waiting time of all other current passengers changes a lot then broadcast request to other peers if (check_pwtime_constraint() == False): retVal["message"] = "4.PWT of other passenger" retVal["cost"] = -1 return (json.dumps(retVal)) if (check_dsttime_constraint() == False): retVal["message"] = "5. DRT of other passenger" retVal["cost"] = -1 return (json.dumps(retVal)) if (taxi["noPassengers"] > 0): global t1 if (t1.is_alive): t1.cancel() start_confirm_timer(recieved["name"]) retVal["message"] = "6. success" return (json.dumps(retVal))