def get24HrRoutes(self,geo0,geo1,planned_date): route24Hr=[] init_routes_info=self.listRoutes(geo0,geo1) for route in init_routes_info: index=0 total= 24*60 step =5 while index < total: mm=index%60 hh=index/60 if mm<10: mm_str='0'+str(mm) else: mm_str=str(mm) if hh<10: hh_str='0'+str(hh) else: hh_str=str(hh) planned_time=planned_date+hh_str+mm_str route_info=Route(route,planned_time,geo0,geo1) route_info.calculateRoute(index) route24Hr.append(route_info); index +=step # ****** Attention ******** # only select the first route break return route24Hr
def gatePing(): global gate Route.route() #print Route.gate if Route.gate == '*': print '*****GO WRONG*****' gate = 0 else: cmdfl = subp.Popen(['ping -c 5 '+Route.gate],stdin = subp.PIPE,stdout = subp.PIPE,stderr = subp.PIPE,shell = True) oput = cmdfl.stdout.read() #print oput #reout = re.compile('Maxi = (\d+)ms,Min = (\d+)ms,Aver = (\d+)ms',re.S) reout = re.compile('received.*? (.*?)%.*?= (.*?)/(.*?)/(.*?)/(.*?) ms',re.S) pGet = re.findall(reout,oput) if len(pGet) != 0: print "packet loss:"+ str(pGet[0][0]),"average time:"+ str(pGet[0][2]) print '*****WORKS*****' gate = 1 else: reout = re.compile('received.*? (.*?)%.*?=' ,re.S) pGet = re.findall(reout,oput) if len(pGet) != 0: print "packet loss:"+ str(pGet[0][0]) print '*****GO WRONG*****' gate = 0 else: print "******TIME OUT *****" gate = 1
def execute_app(self, ades, iaf): # TODO Currently we are not checking which destination the # user asked for, and just clear for approach to the current destination self.app_auth = True self._map = False self.iaf = '' for i in range(len(self.route), 0, -1): if self.route[i - 1].fix in fir.iaps.keys(): self.iaf = self.route[i - 1].fix break if self.iaf == '': # No encuentra procedimiento de aprox. pass (puntos_alt, llz, puntos_map) = fir.iaps[self.iaf] # En este paso se desciende el tráfico y se añaden los puntos logging.debug('Altitud: ' + str(puntos_alt[0][3])) self.set_cfl(puntos_alt[0][3] / 100.) self.set_std_rate() if self.to_do == 'hld': pass else: self.to_do = 'app' for i in range(len(self.route), 0, -1): if self.route[i - 1].fix == self.iaf: self.route = self.route[:i] break self.route.extend([Route.WayPoint(p[1]) for p in puntos_alt]) wp = Route.WayPoint("_LLZ") wp._pos = llz[0] self.route.append(wp) logging.debug("Autorizado aproximación: " + str(self.route))
def _getNextTrafficLight(vhId): edge = traci.vehicle.getRoadID(vhId) nextTL = Route.getTrafficLightsOnRoute(vhId) if len(nextTL)== 0: return None if edge == nextTL[0][2]: Route.visitTrafficLight(vhId) if len(nextTL)== 0: return None return nextTL[0]
def fly_route(self, route): """Introduces a new route, and changes the flight mode to FPR""" self.cancel_app_auth() self.route = Route.Route(Route.get_waypoints(route)) self.to_do = 'fpr' self.to_do_aux = [] self.route = TLPV.sector_intersections(self.route) self.set_app_fix() self.calc_eto() self.set_campo_eco()
def getRoutes(self,geo0,geo1,planned_time): routeOption=[] init_routes_info=self.listRoutes(geo0,geo1) for route in init_routes_info: route_info=Route(route,planned_time,geo0,geo1) route_info.calculateRoute() routeOption.append(route_info) return routeOption
def select(self): """Computes the best possible route and its price when an employee is selected""" name = self.box1name.get() route=Route(self.look) bestRoute=route.getAirports(name) if len(bestRoute)==7:#If there are 6 airports self.answer.set("The best Route is: "+bestRoute[0]+" "+bestRoute[1]+" "+bestRoute[2]+" "+bestRoute[3]+" "+bestRoute[4]+" "+bestRoute[5]+"\nPrice= "+str(bestRoute[6]))#Prints string to the GUI if len(bestRoute)==8:#If there are seven airports self.answer.set("The best Route is: "+bestRoute[0]+" "+bestRoute[1]+" "+bestRoute[2]+" "+bestRoute[3]+" "+bestRoute[4]+" "+bestRoute[5]+" "+bestRoute[6]+"\nPrice= "+str(bestRoute[7])) f = open('Output.csv','w') # Writes to file wr = csv.writer(f, dialect='excel') wr.writerow(bestRoute) f.close()
def set_route(self, points): """Takes a comma or spaced separated list of points and sets and replaces the aircraft route""" self.route = Route.Route(Route.get_waypoints(points)) # In order to save processing time, we add the sector intersection # waypoints ahead of time, so that when the Aircraft calculates its ETO, # there already are ETOs for the TLPV important points as well. if not self.no_estimates: for wp in [wp for wp in self.route[:] if wp.type == Route.TLPV]: self.route.remove(wp) self.complete_flight_plan() if not self.no_estimates: self.route = TLPV.sector_intersections(self.route) self.route = self.route.reduce()
def distance_to_user(self): """ Gets distance from bomb to User using A* algorithm :return: """ user = self.players_list.players_list[-1] i_bomb = self.position[0] j_bomb = self.position[1] i_objective = user.get_x() j_objective = user.get_y() a_star = Route(i_bomb, j_bomb, i_objective, j_objective) route = a_star.get_commands() distance = len(route) return distance
def ctor_create_from_initial_cities(self, cities): for i in range(self.number_of_routes_in_population): route = Route(cities) route.shuffle() route.calculate_total_distance() route.calculate_fitness() self.routes.append(route)
def initbord(self): # subset van kaart listOfCities = [ "Berlijn", "Wenen", "Warschau", "Kiev", "Boekarest" # 0, 1, 2, 3, 4 ] routes = [] # Berlijn to # Wenen to #rou = Route.Route('', 0, ["", ""], 0) routes.append(Route.Route('yellow', 1, [listOfCities[1], listOfCities[0]], 0)) # Berlijn (yellow) routes.append(Route.Route('red', 1, [listOfCities[1], listOfCities[0]], 0)) # Berlijn (red) # Warschau to routes.append(Route.Route('blue', 2, [listOfCities[2], listOfCities[0]], 0)) # Berlijn (blue) routes.append(Route.Route('green', 2, [listOfCities[2], listOfCities[0]], 0)) # Berlijn (green) routes.append(Route.Route('black', 1, [listOfCities[2], listOfCities[1]], 0)) # Wenen (black) # Kiev to routes.append(Route.Route('white', 3, [listOfCities[3], listOfCities[1]], 0)) # Wenen (white) routes.append(Route.Route('yellow', 1, [listOfCities[3], listOfCities[2]], 0)) # Warschau (yellow) # Boekarest to routes.append(Route.Route('yellow', 2, [listOfCities[4], listOfCities[1]], 0)) # Wenen (yellow) routes.append(Route.Route('blue', 2, [listOfCities[4], listOfCities[1]], 0)) # Wenen (blue) routes.append(Route.Route('red', 2, [listOfCities[4], listOfCities[3]], 0)) # Kiev (red) board = nx.Graph() for city in listOfCities: board.add_node(city) print(city) for route in routes: # # from city # to city # path cost # color of path board.add_edge(route.get_cities()[0], route.get_cities()[1], weight=route.get_pathCost(), edgeColors=route.get_color()) print(route.get_cities()[0] + " naar " + route.get_cities()[1] + " kleur " + route.get_color()) copyBoard = board.copy() pos = nx.spring_layout(board) #nx.draw(board) nx.draw_networkx_nodes(board, pos, node_size=700) nx.draw_networkx_edge_labels(board, pos) plt.axis('off') plt.show() return routes
def __init__(self, args_model, args_step, args_t, args_grid, simulate_time): self.set_args(args_model, args_step, args_t, args_grid, simulate_time) self.set_grid() self.Personroute = Route.route(self.grid, self.locations) self.set_home_loc() self.set_work_loc()
def event_stream(): #TODO: Get these inputs from client: city = "IUB" #Buses whose coordinates listColloquialBusNumbers = ['3 College Mall / Bradford Place','6 Campus Shuttle - Fri','6 Limited', '9 IU Campus / College Mall / Campus Corner', 'A Route', 'B Route', 'C Route', 'D Route'] #target location coordinates targetCoordinates = (39.17159402400064, -86.51633620262146) #10th St Bloomington, IN 47408 alertDistance = 0.3 #miles #Create constans object to fetch all constant values constantsObject = Constants() constantsObject.load_constants("constants.json") #Create bus operations object busOperationsObject = BusOperations(constantsObject, city) #Create route object routeObject = Route(constantsObject, city) #Create a map of actual to colloquial bus numbers map_actual_bus_numbers_to_colloquial_bus_numbers = routeObject.get_colloquial_bus_numbers_from_actual_bus_numbers() #Make a list of bus objects listOfActualBusNumbers = routeObject.get_actual_bus_numbers(listColloquialBusNumbers) #Create bus objects listOfBusObjects = [] #Stores list of all bus objects for actualNumber in listOfActualBusNumbers: busObject = Bus(constantsObject) busObject.set_actual_number(actualNumber) listOfBusObjects.append(busObject) flag = True while flag: #gevent.sleep(2) #sleep for 2 second before updating status of each bus to avoid overloading servers with requests listOfBusObjects = busOperationsObject.updateBusStatus(listOfBusObjects) #check which buses are approaching, then track them or show them or whatever for bus in listOfBusObjects: status = bus.getBusMovementAgainstTarget(targetCoordinates) if status == constantsObject.APPROACHING: status = "APPROACHING" elif status == constantsObject.LEAVING: status = "LEAVING" else: status = "STOPPED" data = map_actual_bus_numbers_to_colloquial_bus_numbers[bus.get_actual_number()]," :",status, " is at distance: ",str(bus.getBusDistanceFromTarget(targetCoordinates))," miles" printableData = " ".join(data) gevent.sleep(2) #sleep for 2 second before updating status of each bus to avoid overloading servers with requests if status == "APPROACHING" and bus.getBusDistanceFromTarget(targetCoordinates) <= alertDistance: printableData = "ALERT! bus: "+str(map_actual_bus_numbers_to_colloquial_bus_numbers[bus.get_actual_number()])+" is near" #print type(printableData) #print printableData yield 'data: %s\n\n' % printableData
def int_ils(self): if self.to_do <> 'hdg': self.tgt_hdg = self.hdg # Se supone que ha sido autorizado previamente self.to_do = 'app' self.app_auth = True (puntos_alt, llz, puntos_map) = fir.iaps[self.iaf] [xy_llz, rdl, dist_ayuda, pdte_ayuda, alt_pista] = llz wp = Route.WP('_LLZ') wp._pos = xy_llz self.route = Route.Route([wp]) self.int_loc = True (puntos_alt, llz, puntos_map) = fir.iaps[self.iaf] # En este paso se desciende el tráfico y se añaden los puntos logging.debug('Altitud: ' + str(puntos_alt[0][3])) self.set_cfl(puntos_alt[0][3] / 100.) self.set_std_rate()
def __init__(self, callsign, type, adep, ades, rfl, ecl, rte, eobt=None, next_wp=None, next_wp_eto=None, init=True): if (next_wp and not next_wp_eto) or (not next_wp and next_wp_eto): raise ( "Unable to calculate flight profile, either the next waypoint or the eto for the next waypoint is missing" ) if not next_wp and not next_wp_eto and not eobt: raise ( "Either the EOBT, or the next waypoint and its ETO are mandatory parameters" ) self.callsign = callsign self.radio_callsign = '' self.set_callsign(callsign) self.adep = adep self.ades = ades self.type = type self.eobt = eobt self.rfl = rfl self.ecl = ecl self.filed_tas = None self.route = Route.Route(Route.get_waypoints(rte)) self.next_wp = None # Next WP (in SACTA terminology this is the Entry Point (Punto de Entrada) self.next_wp_eto = None self.squawk = None self.squawk_alt = None self.status = None # Pending, Coordinated, Preactive, Active self.ucs = None # Which UCS is controlling it self.track = None # If the flight is being tracked through the TDR, this links to the Track self.sector_entry_t = { } # Sector entry times for each of the sectors it traverses self.fs_print_t = { } # Printing time of the flight strips for each sector self.fir_entry_t = None # Time it first enters our FIR (local departures do count) self.fir_exit_t = None # Time it leaves the FIR (if ever)
def receiveRouteAdd(destination, gateway): print "ROUT_T: Adding Route: dst: " + destination + " gw: " + gateway newRoute = Route.Route(destination, gateway, "eth0") newRoute.add() buffer.release(destination, defaultSocket)
def own(self): """Computes the best possible route and its price when 5 airports are selected""" home=self.box2.get() visit1=self.box3.get() visit2=self.box4.get() visit3=self.box5.get() visit4=self.box6.get() airports=[home,visit1,visit2,visit3,visit4,home] route=Route(self.look) bestRoute=route.permutatuions(airports) if len(bestRoute)==7: self.answer.set("The best Route is: "+bestRoute[0]+" "+bestRoute[1]+" "+bestRoute[2]+" "+bestRoute[3]+" "+bestRoute[4]+" "+bestRoute[5]+"\nPrice= "+str(bestRoute[6])) if len(bestRoute)==8: self.answer.set("The best Route is: "+bestRoute[0]+" "+bestRoute[1]+" "+bestRoute[2]+" "+bestRoute[3]+" "+bestRoute[4]+" "+bestRoute[5]+" "+bestRoute[6]+"\nPrice= "+str(bestRoute[7])) f = open('Output.csv','w') wr = csv.writer(f, dialect='excel') wr.writerow(bestRoute) f.close()
def __init__(self,args_model, args_step, args_t, simulate_time,args_grid): self.set_args(args_model, args_step, args_t, simulate_time) self.set_grid(args_grid) self.Personroute=Route.route(self.grid, self.locations) self.set_home_loc() self.set_work_loc() self.home_locationList = [] self.work_locatonList = [] self.commute_LocationList = []
def routeDel(destinationID, gatewayID) : destination = NET_PREFIX + str(destinationID) gateway = NET_PREFIX + str(gatewayID) print "ROUT_T: Deleting Route: dst: " + destination + " gw: " + gateway oldRoute = Route.Route(destination, gateway, NET_IFACE) oldRoute.delete()
def CalculateRegretValue(route_list_input, removed_nodes, demand_pass, demand_pack, time_window, mydict): # Calculates the regret value of the nodes denied_nodes = [] delta_cost_list = [] best_index_node_list = [] for i in range(len(route_list_input)): route_list_input[i].removed_nodes = [] evaluated_route = route_list_input[i] additional_driver = Parameters.cost_driver if not evaluated_route.current_nodes: # Cost of Driver additional_driver = Parameters.cost_driver starting_nodes = evaluated_route.starting_nodes[:] starting_nodes.extend(removed_nodes) trip_ids = HelpingFunctions.GetTripId( starting_nodes ) # Get Trip_id of the starting nodes --> important for rearranging nodes and get demand and time_window starting_nodes = HelpingFunctions.GenerateTuple( starting_nodes ) # Generate Tuple of starting nodes --> needed for input of new class demand_pass_route, demand_pack_route, time_window_route = HelpingFunctions.GetDemandAndTimeWindow( demand_pass, demand_pack, time_window, trip_ids) # Get the demand and time-window of the starting nodes starting_nodes, demand_pass_route, demand_pack_route, time_window_route = HelpingFunctions.RearrangeStartingNodes( starting_nodes, demand_pass_route, demand_pack_route, time_window_route, trip_ids ) # Rearrange starting nodes that 0 comes first, then 1 and so on --> fitting demand, time-windows route_testing = Route.route(starting_nodes, demand_pass_route, mydict, time_window_route, demand_pack_route) route_testing.removed_nodes = removed_nodes[:] # Add removed nodes (with unfitting + removed nodes) to class route_testing.UpdateCurrentRoute( evaluated_route.current_nodes ) # new route gets the same current nodes as the previous one route_testing, best_index_node, delta_cost = ALNS_Sub_Parallel.GreedyInsertion( route_testing) delta_cost += additional_driver if len(best_index_node) != 2: delta_cost = 5000 best_index_node_list.append( best_index_node) # saves, where the best index for the nodes was delta_cost_list.append( delta_cost) # saves the increase in costs because of the insertion if not best_index_node_list: # if no possible solution found --> node is denied denied_nodes.append(removed_nodes) print("Denied nodes:" + str(denied_nodes)) index_best_route = min( enumerate(delta_cost_list), key=itemgetter(1))[0] # index of least increase in cost index_insertion_nodes = best_index_node_list[index_best_route] index_third_best_route = int( heapq.nsmallest( 4, enumerate(delta_cost_list), key=itemgetter(1))[2][0]) # index of third to least increase regret_value = delta_cost_list[index_third_best_route] - delta_cost_list[ index_best_route] # calculates regret value return index_best_route, regret_value, index_insertion_nodes, denied_nodes
def sector_intersections(route): """Given a fp, add waypoints in the intersections of the route with the FIR sectors""" rte_orig = route[:] # Remove previous TLPV waypoints for wp in (wp for wp in rte_orig[:] if wp.type == Route.TLPV): rte_orig.remove(wp) n_added = 0 # Number of added intersections for i in range(len(rte_orig) - 1): xpoints = [] for name, boundary in fir.boundaries.items(): xp_list = MathUtil.get_entry_exit_points(rte_orig[i].pos(), rte_orig[i + 1].pos(), boundary) for xp in xp_list: xp.append(name) xpoints += xp_list xpoints.sort(lambda x, y: cmp(x[2], y[2]) ) # Sort according to distance to the first waypoint for xp in xpoints: wp = Route.WayPoint("X%fY%f" % (xp[1][0], xp[1][1]), type=Route.TLPV) if xp[0] == MathUtil.ENTRY: wp.sector_entry = xp[3] else: wp.sector_exit = xp[3] route = route[:i + 1 + n_added] + Route.Route( [wp]) + route[i + 1 + n_added:] n_added += 1 # If the first point in the route is within a known sector, make sure we note it. for sector, boundary in fir.boundaries.items(): if MathUtil.point_within_polygon(route[0].pos(), boundary): route[0].sector_entry = sector n_added += 1 if not n_added: logging.warning("No sector entry points found in %s" % str(route)) return route # Eliminates redundancy
class Person(): #attributes home_loc=[] work_loc=[] #location of family and work. grid=[] locations=[] #model coorditions work_time=[] rest_time=[] # set the time to work[start,end] and sleep[start,end] args_model = [0, 0.6, -0.21] #set the gama and p for model,the Probability of explore is p*pow(S,gama) args_time = [-1.55, 0, 17, 10000] #set powerlaw disput time.beta=-1.55,time is between [0,17],simulate time is 10000 args_steps = [-1.80, 5] #set steplegth ,beta and up limit # grid dimension,grid_args(powerlaw contains [beta,min,max],normal contains [xmean,xsigma,ymean,ysigema]),number of point simulate_time = 10000 #simulate times=10000 home_locationList=[] work_locatonList=[] commute_LocationList=[] #the place the person has visit time=0 time24=0 stept=[] Personroute=Route.route([],[]) #function def set_grid(self): pass def set_home_loc(self): pass def set_work_loc(self): pass def set_work_time(self): pass def set_rest_time(self): pass def set_args(self, args_model, args_step, args_t, simulate_time): self.args_model = args_model self.args_step = args_step self.args_t = args_t self.simulate_time = simulate_time def simulate(self): pass def set_time(self,time): self.time+=time self.time24=time%24 print (self.time24)
class TestAll(unittest.TestCase): def setUp(self): self.bus = Bus(1, 1, "mercedes", 3) self.route = Route(1, 10) self.busRepo = BusRepository() self.ruteRepo = RouteRepository() self.controller = Controller(self.busRepo, self.ruteRepo) def testComputeKm(self): self.assertEqual( self.controller.computeKm(self.bus.getId(), self.route.getRouteCode()), 30)
def routeAdd(destinationID, gatewayID) : destination = NET_PREFIX + str(destinationID) gateway = NET_PREFIX + str(gatewayID) print "ROUT_T: Adding Route: dst: " + destination + " gw: " + gateway newRoute = Route.Route(destination, gateway, NET_IFACE) newRoute.add() #add to our own current route tracking buffer.release(destination, defaultSocket)
def get_route(self,flag): route=Route.route([],[]) L_place = [] L_tempPlace = self.visited_Place # 访问的集合 if (self.grid != 0): for item in self.locations: if (item not in L_tempPlace): L_place.append(item) # 没有访问的集合 else: exit() gama = self.args_model[2] S = self.args_model[0] r = self.args_model[1] # 随机选择起始点,并初始化所要用到的循环数据 if (flag == 0): postion = self.HomePosition if (flag == 1): postion = self.WorkPosition if (postion in L_place): L_place.remove(postion) L_tempPlace.append(postion) self.start_position = postion S = S + 1 index = 1 while ((self.t_now < self.t_end) & (index < len(self.ts) - 1)): tag = r * S ** (gama) tag2 = random.random() if (tag > tag2): # 这时候去探索新的场所代码 next_postion = self.get_next_position(L_place,flag) if (next_postion == 0): continue postion = next_postion ##更新当前坐标 L_tempPlace.append(postion) L_place.remove(postion) S = S + 1 index = index + 1 else: postion = random.choice(L_tempPlace) L_tempPlace.append(postion) index = index + 1 route.time.append(self.t_now) route.route.append(postion) self.t_now = self.t_now + self.ts[index] for tempPlace in L_tempPlace: self.ids.append(tempPlace[2]) return L_tempPlace,route
def depart(self, sid, cfl, t): # Ahora se depega el avión y se elimina de la lista self.t = t # Get the actual sid object, but only if a SID has been given, # and we had a previous SID if not sid == '' and self.sid: sid = fir.aerodromes[self.adep].get_sid(sid) if self.sid: self.route.substitute_before(Route.WP(self.sid.end_fix), sid.rte) else: self.rte = sid.rte + self.rte self.cfl = cfl self.pof = TAKEOFF self.next(t) self.calc_eto()
def search_a_power_up(self): """ Action that searches the closest power up :brief: given the closest power up the method uses the A* algorithm to move towards it """ closest_power_up_position = self.find_closest_object( "+h@s") # chsz are all the possible power ups if closest_power_up_position == []: return enemy_i = self.get_x() enemy_j = self.get_y() target_i = closest_power_up_position[0] target_j = closest_power_up_position[1] a_star_route = Route.Route(enemy_i, enemy_j, target_i, target_j) self.move_enemy_aux(a_star_route.get_commands())
def search_an_enemy(self): """ Action that searches the closest player :brief: given the closest player (enemy or user) the method uses A* algorithm to move towards it """ closest_enemy_position = self.find_closest_object( "eu") # "eu" means enemy or user if closest_enemy_position == []: self.choose_next_action() enemy_i = self.get_x() enemy_j = self.get_y() target_i = closest_enemy_position[0] target_j = closest_enemy_position[1] if isinstance(self, Enemy): a_star_route = Route.Route(enemy_i, enemy_j, target_i, target_j) self.move_enemy_aux(a_star_route.get_commands())
def __init__(self, userRequest): if 'alertDistance' in userRequest: self.alertDistance = userRequest['alertDistance'] if 'busList' in userRequest: self.busList = userRequest['busList'] #if post data contains latitude it contains target co-ordinates if 'lat' in userRequest: self.targetCoordinates = (float(userRequest['lat']), float(userRequest['lng'])) if 'city' in userRequest: self.city = userRequest['city'] #TODO work on the direction of bus (would be specified by user) self.constantsObject = Constants() #TODO constants path :/ self.constantsObject.load_constants("/Users/pushkarjoshi/constants.json") #Create bus operations object self.busOperationsObject = BusOperations(self.constantsObject, self.city) #Create route object self.routeObject = Route(self.constantsObject, self.city)
def __init__(self, route,important_place=[],fig=[],filename='fig'): self.filename=filename self.route = Route.route([], []) self.visit_location_number_disput = [] self.visite_weight_disput = [] self.rog_disput = [] self.important_place = [] self.cal = Cal_para.Cal_para([]) self.route.set_route_from_route(route) self.important_place=important_place self.cal = Cal_para.Cal_para(self.route.route) self.visit_location_number_disput = self.cal.get_visit_location_number_disput() self.visite_weight_disput = self.cal.get_weight_disput() self.rog_disput = self.cal.get_rog_disput() if(len(fig)==0): self.fig1 = plt.figure(1) self.fig2 = plt.figure(2) else: self.fig1=fig[0] self.fig2=fig[1]
def crossover(self, route_1, route_2): child = RT.Route(self.cities) init_state = int(random.random() * len(route_1)) final_state = int(random.random() * len(route_2)) for i in range(0, len(child)): if init_state < final_state and init_state < i < final_state: child.assign_city(i, route_1.get_city(i)) elif init_state > final_state: if not (init_state > i > final_state): child.assign_city(i, route_1.get_city(i)) for i in range(0, len(route_2)): if not child.__contains__(route_2.get_city(i)): for j in range(0, len(child)): if child.get_city(j) is None: child.assign_city(j, route_2.get_city(i)) break return child
def __init__(self, ip, port, threads): # Ctrl + C handler signal.signal(signal.SIGINT, self.signal_handler) # Set some basic variable, and data structure self.ip = ip self.port = port self.counter = 0 self.request_queue = queue.Queue() self.threads = [] self.event = threading.Event() # Setup Flask with Route self.app = Route.initialize(self.counter, self.request_queue) # Create worker thread self.num_of_worker_threads = threads for i in range(0, self.num_of_worker_threads, 1): thread = Worker.HTTPRequestHandler(i, str(i), self.threads, self.event, self.request_queue) thread.daemon = True thread.start() self.threads.append(thread)
#create schools from file x = 0 while (x < len(schoolMatrix)): schoolObjects.append( School.School(schoolMatrix[x][0], schoolMatrix[x][1], schoolMatrix[x][2], schoolMatrix[x][3], schoolMatrix[x][4], schoolMatrix[x][5], schoolMatrix[x][6], schoolMatrix[x][7], schoolMatrix[x][8], schoolMatrix[x][9])) x += 1 #create routes from file x = 0 while (x < len(routeMatrix)): routeObjects.append( Route.Route(routeMatrix[x][0], routeMatrix[x][1], routeMatrix[x][2])) x += 1 for e in studentObjects: for x in schoolObjects: if x.name == e.placementName: e.school = x e.placementId = x.id #set the school's master distance matrix index. This will need to be changed later #this allows us to find an objects position in the distance matrix easily. #the student objects have their values set in the loop where they are constructed schoolObjects[0].distanceMatrixPosition = 251 schoolObjects[1].distanceMatrixPosition = 251 schoolObjects[2].distanceMatrixPosition = 252 schoolObjects[3].distanceMatrixPosition = 253
class Draw(): route=Route.route([],[]) cal = Cal_para.Cal_para([]) visit_location_number_disput = [] visite_weight_disput = [] rog_disput = [] important_place=[] fig1=plt.figure(1) fig2=plt.figure(2) filename='' def __init__(self, route,important_place=[],fig=[],filename='fig'): self.filename=filename self.route = Route.route([], []) self.visit_location_number_disput = [] self.visite_weight_disput = [] self.rog_disput = [] self.important_place = [] self.cal = Cal_para.Cal_para([]) self.route.set_route_from_route(route) self.important_place=important_place self.cal = Cal_para.Cal_para(self.route.route) self.visit_location_number_disput = self.cal.get_visit_location_number_disput() self.visite_weight_disput = self.cal.get_weight_disput() self.rog_disput = self.cal.get_rog_disput() if(len(fig)==0): self.fig1 = plt.figure(1) self.fig2 = plt.figure(2) else: self.fig1=fig[0] self.fig2=fig[1] def draw_visit_location_number_disput(self): ##绘图 fig = self.fig1 axes = fig.add_subplot(2, 2, 1, xlim=(1, 100 * len(self.visit_location_number_disput)), ylim=(0, 600)) line, = axes.plot([], [], lw=2) y = self.visit_location_number_disput x = [(i * 100) for i in range(len(self.visit_location_number_disput))] axes.set_xlabel("time") axes.set_ylabel("number of place") #axes.set_title("number of place distribution") axes.plot(x, y) axes2 = fig.add_subplot(2, 2, 2, xlim=(0, len(self.visite_weight_disput)), ylim=(0, 100)) line, = axes.plot([], [], lw=2) y = self.visite_weight_disput x = [i for i in range(len(self.visite_weight_disput))] axes2.plot(x, y) axes2.set_xlabel("range") axes2.set_ylabel("visit frequency") #axes2.set_title("visit frequency distribution") axes3 = fig.add_subplot(2, 2, 3, xlim=(1, len(self.rog_disput)), ylim=(0, 2)) line, = axes.plot([], [], lw=2) y = self.rog_disput x = [pow(2,i) for i in range(len(self.rog_disput))] axes3.plot(x, y) axes3.set_xlabel("time") axes3.set_ylabel("ROG") #axes3.set_title("ROG distribution") axes4 = fig.add_subplot(2, 2, 4, xlim=(0, 2), ylim=(0, 4)) line, = axes.plot([], [], lw=2) visite_frequency_plus1 = [i + 1 for i in self.visite_weight_disput] y = [math.log10(i) for i in visite_frequency_plus1] x = [math.log10(i) for i in range(1, len(self.visite_weight_disput) + 1)] axes4.scatter(x, y, s=35) k, b = self.cal.cal_leastsq(x, y) xtemp = np.linspace(0, math.log(len(self.visite_weight_disput) + 1), 1000) ytemp = k * xtemp + b axes4.plot(xtemp, ytemp) axes4.set_ylabel("try") axes4.set_xlabel("time") axes4.set_ylabel("number of place") # 比较不同栅格拜访数量的大小 def draw_location_disput(self): tag = 0 fig2 = plt.figure(2) locationWeight = self.cal.get_location_size_disput() axes = fig2.add_subplot(1, 1, 1, xlim=(1, 20), ylim=(0, 20)) ims = [] for i in range(len(locationWeight)): x = [] y = [] for j in range(len(locationWeight[0])): x.append(self.route.grid[j][0]) y.append(self.route.grid[j][1]) size = locationWeight[i] im = plt.scatter(x, y, s=size) ims.append([im]) anim1 = animation.ArtistAnimation(fig2, ims, interval=500, blit=True) plt.show() # 比较不同的点被访问的数量的大小 def draw_location_disput_raster(self): tag = 0 fig2 = self.fig2 locationWeight = self.cal.get_location_size_raster_disput() axes = fig2.add_subplot(1, 1, 1, xlim=(1, 20), ylim=(0, 20)) ims = [] for i in range(len(locationWeight)): x = [] y = [] c = [] size = [] for item in self.important_place: x.append(item[0]) y.append(item[1]) c.append('r') size.append(100) for j in range(len(locationWeight[0])): x.append(self.route.locations[j][0]) y.append(self.route.locations[j][1]) c.append('b') size += locationWeight[i] im = plt.scatter(x, y, s=size, c=c) ims.append([im]) # if(i%10==0): # plt.savefig('D:/figname'+str(i)+".png", facecolor="white", transparent=True, dpi=600) anim1 = animation.ArtistAnimation(fig2, ims, interval=5000, blit=True) plt.savefig('d:/'+self.filename+'location.png', facecolor="white",transparent=True,dpi=600) plt.show()
def RegretHeuristic(route_list_input, demand_pass, demand_pack, time_window, mydict, unfitting_nodes, removed_nodelist): cost_driver = 0 denied_nodes = [] for i in range(len(route_list_input)): route_list_input[i].best_nodes = route_list_input[i].current_nodes[:] if route_list_input[i].best_nodes: cost_driver += Parameters.cost_driver random.shuffle(unfitting_nodes) # randomly shuffle the unfitting nodes unfitting_nodes = list( itertools.chain(*unfitting_nodes) ) # unfitting nodes is currently tuple --> unpack it into list removed_nodelist.extend(unfitting_nodes) while removed_nodelist: regret_value_list = [] index_best_route_list = [] index_best_insertion_nodes_list = [] for k in range(int(len(removed_nodelist) / 2)): removed_nodes = [ removed_nodelist[k * 2], removed_nodelist[k * 2 + 1] ] # get through all removed nodes index_best_route, regret_value, index_insertion_nodes, denied_nodes_outcome = CalculateRegretValue( route_list_input, removed_nodes, demand_pass, demand_pack, time_window, mydict) index_best_route_list.append(index_best_route) regret_value_list.append(regret_value) index_best_insertion_nodes_list.append(index_insertion_nodes) index_regret_maximum = max(enumerate(regret_value_list), key=itemgetter(1))[0] removed_nodes = [ removed_nodelist[index_regret_maximum * 2], removed_nodelist[index_regret_maximum * 2 + 1] ] index_overall_best_route = index_best_route_list[index_regret_maximum] best_fitting_route = route_list_input[index_overall_best_route] if len(index_best_insertion_nodes_list[index_regret_maximum]) < 2: denied_nodes.append(removed_nodes) else: best_fitting_route.current_nodes.insert( index_best_insertion_nodes_list[index_regret_maximum][0], removed_nodes[0] ) # insert removed nodes at position with highest regret value best_fitting_route.current_nodes.insert( index_best_insertion_nodes_list[index_regret_maximum][1], removed_nodes[1]) old_starting_nodes = best_fitting_route.starting_nodes[:] # find the old strating nodes old_starting_nodes.extend(removed_nodes) trip_ids = HelpingFunctions.GetTripId( old_starting_nodes ) # Get Trip_id of the starting nodes --> important for rearranging nodes and get demand and time_window new_starting_nodes = HelpingFunctions.GenerateTuple( old_starting_nodes ) # Generate Tuple of starting nodes --> needed for input of new class demand_pass_route, demand_pack_route, time_window_route = HelpingFunctions.GetDemandAndTimeWindow( demand_pass, demand_pack, time_window, trip_ids) new_starting_nodes, demand_pack_route, demand_pass_route, time_window_route = HelpingFunctions.RearrangeStartingNodes( new_starting_nodes, demand_pass_route, demand_pack_route, time_window_route, trip_ids) new_route = Route.route(new_starting_nodes, demand_pass_route, mydict, time_window_route, demand_pack_route) new_route.current_nodes = best_fitting_route.current_nodes[:] # overwrite the current nodes of the new route with the previously calculated current nodes new_route.best_nodes = new_route.current_nodes[:] new_route = HelpingFunctions.UpdateRoute( new_route ) # update the values of the new route with the ones of the old route route_list_input[index_overall_best_route] = copy.deepcopy( new_route) removed_nodelist.remove(removed_nodes[0]) removed_nodelist.remove(removed_nodes[1]) for i in range( len(route_list_input) ): # Update Route if it was not previosuly changed --> need to adapt time_earlist_dep, because nodes have been removed if len(route_list_input[i].current_nodes) == 0: route_list_input[i] = HelpingFunctions.ClearRoute( route_list_input[i]) if len(route_list_input[i].demand_node_current) > len( route_list_input[i].current_nodes): storage_current_node = route_list_input[i].current_nodes[:] trip_ids = HelpingFunctions.GetTripId( route_list_input[i].starting_nodes) # Get Trip IDs new_starting_nodes = HelpingFunctions.GenerateTuple( route_list_input[i].starting_nodes ) # Generate Tuple of starting nodes --> needed for input of new class demand_pass_route, demand_pack_route, time_window_route = HelpingFunctions.GetDemandAndTimeWindow( demand_pass, demand_pack, time_window, trip_ids) new_starting_nodes, demand_pass_route, demand_pack_route, time_window_route = HelpingFunctions.RearrangeStartingNodes( new_starting_nodes, demand_pass_route, demand_pack_route, time_window_route, trip_ids) new_route = Route.route(new_starting_nodes, demand_pass_route, mydict, time_window_route, demand_pack_route) new_route.current_nodes = storage_current_node[:] new_route.best_nodes = new_route.current_nodes[:] route_list_input[i] = HelpingFunctions.UpdateRoute(new_route) return route_list_input, denied_nodes
class Simulation(object): def __init__(self): self.temps = 5 * 60.0 # Durée de la simulation en secondes self.delta = 1 / 15.0 # Intervalle de temps entre chaque calcul self.route = Route(3000, 36, self.delta) def initialisation(self, espacement, vitesse): self.route.initialisation(espacement, vitesse) def parametres(self, flux, densite): if not flux: self.route.desactiver_flux() if not densite: self.route.desactiver_densite() def lancer(self): if len(self.route.sections) == 0: print("Il faut au moins une section !") return None temps_total = 0 p = 0 # Avancement de la simulation i = 0 indice = 0 # Nombre de tours dans la boucle while temps_total <= self.temps: # Boucle principale du programme self.route.update(temps_total, indice) indice += 1 temps_total += self.delta i += self.delta / self.temps if i >= 0.01: p += 0.01 i -= 0.01 print("Avancement de la simulation : " + str(round(p * 100)) + "%") print("Fin de la simulation") """ Lancement des analyses """ self.route.analyse_voitures(nombre=10) self.route.animation() # self.route.analyse_trafic() """ Fin des analyses """ # self.route.sauvegarde() # Sauvegarde des données print("Nombre de voiture", self.route.N_tot) print("Arrêt de la simulation")
def __init__(self): self.temps = 5 * 60.0 # Durée de la simulation en secondes self.delta = 1 / 15.0 # Intervalle de temps entre chaque calcul self.route = Route(3000, 36, self.delta)
if __name__ == "__main__": #Input city = "IUB" #target location coordinates targetCoordinates = (39.17155659473131, -86.50890111923218) #Create constans object to fetch all constant values constantsObject = Constants() constantsObject.load_constants("constants.json") #Create bus operations object busOperationsObject = BusOperations(constantsObject, city) #Create route object routeObject = Route(constantsObject, city) #Create a map of actual to colloquial bus numbers map_actual_bus_numbers_to_colloquial_bus_numbers = routeObject.get_colloquial_bus_numbers_from_actual_bus_numbers() print "-"*50 print map_actual_bus_numbers_to_colloquial_bus_numbers print '-'*50 #Make a list of bus objects listColloquialBusNumbers = ['3 College Mall / Bradford Place','6 Limited','9 Limited'] listOfActualBusNumbers = routeObject.get_actual_bus_numbers(listColloquialBusNumbers) print "Colloquial no:",listColloquialBusNumbers print "Actual nos:",listOfActualBusNumbers #Create bus objects listOfBusObjects = [] #Stores list of all bus objects for actualNumber in listOfActualBusNumbers: busObject = Bus(constantsObject)
#coding:utf-8 import tornado.ioloop import tornado.web import Route url = Route.getAppRoute() application = tornado.web.Application(url) if __name__ == "__main__": port = 8888 application.listen(port) print("server on http://127.0.0.1:%s/" % (port)) tornado.ioloop.IOLoop.instance().start()
nodes, time_window, time_windows_est = DemandSets.Integration(nodes,time_window,time_windows_est) if Parameters.separation: nodes, time_window, time_windows_est = DemandSets.ParameterSeparation() demand_passenger = [] demand_package = [] for i in range(len(nodes)): if int(nodes[i][0]) > 9000 and int(nodes[i][1]) > 9000: # If Stop is no shop --> add passenger demand_passenger.append(1) demand_package.append(0) else: # If stop is shop/pickup station --> add package demand_passenger.append(0) demand_package.append(1) nodes, time_window, demand_passenger, demand_package, time_windows_est = HelpingFunctions.PutInRightOrder(nodes,time_window, demand_passenger, demand_package, time_windows_est) main_route = Route.route(nodes, demand_passenger, mydict, time_window, demand_package) index_passengers = len(nodes)-1 degree_of_deconstruction = Parameters.degree_of_deconstruction route_list = [] nodes_fixed = HelpingFunctions.GenerateTuple(main_route.starting_nodes) if Parameters.predefined_no_busses == 3: # Distribute if number of busses is 3 nodes_1 = nodes_fixed[0::3] nodes_2 = nodes_fixed[1::3] nodes_3 = nodes_fixed[2::3] time_window_1 = time_window[0::3] time_window_2 = time_window[1::3] time_window_3 = time_window[2::3] demand_pack_1 = demand_package[0::3] demand_pack_2 = demand_package[1::3]
class TripleMapClient: alertDistance = 0.3 busList = [] targetCoordinates = (39.17155659473131, -86.50890111923218) city = "IUB" #interface = Interface() def __init__(self, userRequest): if 'alertDistance' in userRequest: self.alertDistance = userRequest['alertDistance'] if 'busList' in userRequest: self.busList = userRequest['busList'] #if post data contains latitude it contains target co-ordinates if 'lat' in userRequest: self.targetCoordinates = (float(userRequest['lat']), float(userRequest['lng'])) if 'city' in userRequest: self.city = userRequest['city'] #TODO work on the direction of bus (would be specified by user) self.constantsObject = Constants() #TODO constants path :/ self.constantsObject.load_constants("/Users/pushkarjoshi/constants.json") #Create bus operations object self.busOperationsObject = BusOperations(self.constantsObject, self.city) #Create route object self.routeObject = Route(self.constantsObject, self.city) def pollDistance(self): #get the actual bus objects from the user specified name list pprint(self.busList) print '-'*20 listOfActualBusNumbers = self.routeObject.get_actual_bus_numbers(self.busList) print '-'*20 pprint(listOfActualBusNumbers) #Create bus objects listOfBusObjects = [] #Stores list of all bus objects for actualNumber in listOfActualBusNumbers: busObject = Bus(self.constantsObject) busObject.set_actual_number(actualNumber) listOfBusObjects.append(busObject) #Create a map of actual to colloquial bus numbers map_actual_bus_numbers_to_colloquial_bus_numbers = self.routeObject.get_colloquial_bus_numbers_from_actual_bus_numbers() while True: time.sleep(2) #sleep for 2 second before updating status of each bus listOfBusObjects = self.busOperationsObject.updateBusStatus(listOfBusObjects) #check which buses are approaching, then track them or show them or whatever for bus in listOfBusObjects: status = bus.getBusMovementAgainstTarget(self.targetCoordinates) if status == self.constantsObject.APPROACHING: status = "APPROACHING" elif status == self.constantsObject.LEAVING: status = "LEAVING" else: status = "STOPPED" currentDist = bus.getBusDistanceFromTarget(self.targetCoordinates) if currentDist <= 0.4: #send notification & remove it from the list #TODO sending notification to the client listOfBusObjects.remove(bus) yield bus.get_colloquial_number() print map_actual_bus_numbers_to_colloquial_bus_numbers[bus.get_actual_number()]," :",status, \ " is at distance: ",bus.getBusDistanceFromTarget(self.targetCoordinates)," miles"
def run_route(): # Start time for the business to open and delivery trucks leave the hub START_TIME = datetime.datetime.strptime('08:00:00', '%I:%M:%S') # Start time for truck waiting on delayed packages to reduce the number of return trips DELAYED_START_TIME = datetime.datetime.strptime('09:05:00', '%I:%M:%S') # Permanent location of the hub hub = 'Western Governors University 4001 South 700 East, Salt Lake City, UT 84107' curr_time = datetime.datetime total_miles = 0 curr_miles = 0 time_of_update = datetime.datetime.strptime('10:20:00', '%I:%M:%S') loc_dis_list = DataInput.Data.distances truck_1 = {} truck_2 = {} packages_for_truck1 = [] packages_for_truck2 = [] morning_packages = [] any_time_packages = [] late_run_only_list = [] aux_packages = [] correlated_packages = {} packages = DataInput.Data.packages deliveries = {} # O(2n) # Send packages through the rule set and put them in their respective list for package in packages: package_time = package.getValue().get_deadline() package_notes = package.getValue().get_notes() if isinstance(package_time, str): if RuleSet.fill_truck1_only_list(package_notes): packages_for_truck1.append(package) elif RuleSet.fill_truck2_only_list(package_notes): packages_for_truck2.append(package) elif RuleSet.fill_anytime_list(package_time, package_notes): any_time_packages.append(package) elif RuleSet.fill_late_list(package_time, package_notes): late_run_only_list.append(package) else: aux_packages.append(package) elif isinstance(package_time, datetime.time): if RuleSet.fill_morning_list(package_time, package_notes): morning_packages.append(package) elif RuleSet.fill_truck1_only_list(package_notes): packages_for_truck1.append(package) elif RuleSet.fill_truck2_only_list(package_notes): packages_for_truck2.append(package) elif RuleSet.fill_late_list(package_time, package_notes): late_run_only_list.append(package) else: aux_packages.append(package) # O(n^2) # Further filter the aux list to deal with special cases/notes for i, p in enumerate(aux_packages): notes = p.getValue().get_notes() p_id = p.getValue().get_id() results = RuleSet.deal_with_aux_packages(notes) if results is not None: correlated_packages[p_id] = results aux_packages[i] = None # O(n^3) # remove any package correlated with another package from all list for key, v in correlated_packages.items(): for val1 in v: for index, elem in enumerate(packages_for_truck1): if elem.getValue().get_id() == val1: packages_for_truck1.pop(index) for index, elem in enumerate(packages_for_truck2): if elem.getValue().get_id() == val1: packages_for_truck2.pop(index) for index, elem in enumerate(morning_packages): if elem.getValue().get_id() == val1: morning_packages.pop(index) for index, elem in enumerate(late_run_only_list): if elem.getValue().get_id() == val1: late_run_only_list.pop(index) for index, elem in enumerate(any_time_packages): if elem.getValue().get_id() == val1: any_time_packages.pop(index) # O(n) # put all correlated packages that need to be delivered together in the same list to go into the same truck. the list depends on priority of the delivery deadline and/or notes for key, v in correlated_packages.items(): packages.find(v[0]).getValue().get_deadline() if RuleSet.fill_morning_list( packages.find(v[0]).getValue().get_deadline(), packages.find( v[0]).getValue().get_notes()) or RuleSet.fill_morning_list( packages.find(v[1]).getValue().get_deadline(), packages.find(v[1]).getValue().get_notes()): morning_packages.append(packages.find(v[0])) morning_packages.append(packages.find(v[1])) morning_packages.append(packages.find(key)) elif RuleSet.fill_late_list( packages.find(v[0]).getValue().get_deadline(), packages.find( v[0]).getValue().get_notes()) or RuleSet.fill_late_list( packages.find(v[1]).getValue().get_deadline(), packages.find(v[1]).getValue().get_notes()): late_run_only_list.append(packages.find(v[0])) late_run_only_list.append(packages.find(v[1])) late_run_only_list.append(packages.find(key)) elif RuleSet.fill_anytime_list( packages.find(v[0]).getValue().get_deadline(), packages.find( v[0]).getValue().get_notes()) or RuleSet.fill_anytime_list( packages.find(v[1]).getValue().get_deadline(), packages.find(v[1]).getValue().get_notes()): any_time_packages.append(packages.find(v[0])) any_time_packages.append(packages.find(v[1])) any_time_packages.append(packages.find(key)) # O(n^2) # change each list of packages to dict structure for better searching and sorting morning_packages = Route.change_to_dict(morning_packages) packages_for_truck1 = Route.change_to_dict(packages_for_truck1) packages_for_truck2 = Route.change_to_dict(packages_for_truck2) any_time_packages = Route.change_to_dict(any_time_packages) late_run_only_list = Route.change_to_dict(late_run_only_list) aux_packages = Route.change_to_dict(aux_packages) # O(n) # keep a list of all package ids and what dict the package is in for referencing multiple times morning_packages_keys = list(morning_packages.keys()) packages_for_truck2_keys = list(packages_for_truck2.keys()) any_time_packages_keys = list(any_time_packages.keys()) late_run_only_list_keys = list(late_run_only_list.keys()) # print(packages_for_truck1) # print(len(packages_for_truck2)) # print(morning_packages) # print(len(any_time_packages)) # print(len(late_run_only_list)) # print(len(aux_packages)) # print(loc_dis_list) ###################################### V2 ##################################### # fill morning run truck1 with packages from list based on greedy route # O(n) # since this is the first truck and packages to go out, get the packages that needs to be delivered first earliest = [] for k, v in morning_packages.items(): if isinstance(v.get_deadline(), datetime.datetime): if v.get_deadline().hour < 10: truck_1[k] = v earliest.append(k) # O(n^2) # The route of truck 1s morning run. Based on greedy algorithm morning_run_truck1 = Route.get_packages_for_morning_route_with_earliest( hub, earliest, morning_packages, any_time_packages, loc_dis_list, [False, None], [False, None]) # O(n^2) # If a package id is in the route of truck 1s morning run delete packaged from its container list for key in morning_run_truck1: if key in morning_packages_keys: morning_packages.pop(key) if key in any_time_packages_keys: any_time_packages.pop(key) # O(3n) # Runs the route and collects delivery data then returns that data [miles, datetime, visited, deliveries obj] truck1_deliveries = Route.new_run_route(morning_run_truck1, packages, START_TIME, loc_dis_list, [True, 'Truck 1'], [False, 'Truck 2'], deliveries) total_miles = total_miles + truck1_deliveries[0] # print('total miles:', total_miles, 'packages delivered:', len(truck1_deliveries[3]), 'double check:', # truck1_deliveries[2]) ###################### # fill morning run truck2 with packages from list based on greedy route # O(n^2) # The route of truck 2s morning run. Based on greedy algorithm morning_run_truck2 = Route.get_packages_for_morning_route_with_earliest( hub, [], aux_packages, packages_for_truck2, loc_dis_list, [False, None], [True, any_time_packages]) # O(n^2) # If a package id is in the route of truck 2s morning run delete packaged from its container list for key in morning_run_truck2: if key in any_time_packages_keys: any_time_packages.pop(key) if key in packages_for_truck2_keys: packages_for_truck2.pop(key) # O(3n) # Runs the route and collects delivery data then returns that data [miles, datetime, visited, deliveries obj] truck2_deliveries = Route.new_run_route(morning_run_truck2, packages, DELAYED_START_TIME, loc_dis_list, [False, 'Truck 1'], [True, 'Truck 2'], deliveries) total_miles = total_miles + truck2_deliveries[0] # print('total miles:', total_miles, 'packages delivered:', len(truck2_deliveries[3]), 'double check:', # truck2_deliveries[2]) ################################# # truck 2 second run in the afternoon # get the time truck 2 last delivered its last package curr_time = truck2_deliveries[1] # add miles from return trip back to hub from last package location return_miles = Route.get_dist_from_to( loc_dis_list, packages.find(morning_run_truck2[-1]).getValue().get_distances(), hub) total_miles = total_miles + return_miles # add time it took for the truck to go back to hub curr_time = curr_time + datetime.timedelta(minutes=(return_miles / 18) * 60) load_2_start_time = curr_time # 410 S State St., Salt Lake City, UT 84111 / Third District Juvenile Court 410 S State St update_package_after_init(packages.find(9), [ '410 S State St.', 'Salt Lake City', 'UT', '84111', 'Third District Juvenile Court 410 S State St' ], curr_time, late_run_only_list, time_of_update) # O(n^2) # The route of truck 2s afternoon run. Based on greedy algorithm afternoon_run_truck2 = Route.get_packages_for_morning_route_with_earliest( hub, [], late_run_only_list, any_time_packages, loc_dis_list, [False, None], [False, None]) # O(n^2) # If a package id is in the route of truck 2s afternoon run delete packaged from its container list for key in afternoon_run_truck2: if key in any_time_packages_keys: any_time_packages.pop(key) if key in late_run_only_list_keys: late_run_only_list.pop(key) # O(3n) # Runs the route and collects delivery data then returns that data [miles, datetime, visited, deliveries obj] truck2_afternoon_deliveries = Route.new_run_route( afternoon_run_truck2, packages, curr_time, loc_dis_list, [False, 'Truck 1'], [True, 'Truck 2'], deliveries) total_miles = total_miles + truck2_afternoon_deliveries[0] curr_time = truck2_afternoon_deliveries[1] # print('total miles:', total_miles, 'packages delivered:', len(truck2_afternoon_deliveries[3]), 'double check:', # truck2_afternoon_deliveries[2]) ############################################################ # O(n) # merge all deliveries into one big dictionary deliveries = merge(truck1_deliveries[3], truck2_deliveries[3], truck2_afternoon_deliveries[3]) # print('truck 1 morning miles:', truck1_deliveries[0], 'truck 2 morning miles:', truck2_deliveries[0], 'truck 2 afternoon miles:', truck2_afternoon_deliveries[0]) return [ deliveries, total_miles, curr_time, load_2_start_time.time(), morning_run_truck1, morning_run_truck2, afternoon_run_truck2, START_TIME.time(), DELAYED_START_TIME.time() ]