def initRoutingDay(self): routingDay = RoutingDay(self.instance) for request in self.scheduleDay.deliveries: trip = Trip(self.instance, request) routingDay.addTrip(trip) for request in self.scheduleDay.pickups: trip = Trip(self.instance, request) routingDay.addTrip(trip) return routingDay
def test_order_hotel(): flights_data = flight_general.get_all_updated_data() data_in_range = [ flight for flight in flights_data if (4 <= flight.days <= 6) and flight.destination_value == 10 and ( flight.label == 4 or flight.label == 3) and datetime.strptime( flight.return_date, '%Y-%m-%d') < datetime(2021, 5, 1) ] data_in_range.sort() trip_list = [] time_start = time.time() i = 0 j = 0 my_set = set() while i < 2: flight = data_in_range[j] if flight.destination.city not in my_set: trip_list.append(Trip(flight)) my_set.update([flight.destination.city]) i += 1 j = j + 1 for trip in trip_list: trip.get_hotel_for_trip() trip_list.sort(reverse=True) for trip in trip_list: print(trip) time_end = time.time() print((time_end - time_start) / 60)
def __get_trip(self, trip): """ Gets the trip information out of the json returned from ITA This should only be called if the caller understands the json returned by ITA """ price = float(trip['ext']['price'][3:]) ppm = float(trip['ext']['pricePerMile'][3:]) ppm = round(ppm, 4) itin = trip['itinerary'] distance = int(itin['distance']['value']) flights = [] #get the flights out of the itinerary for flight in itin['slices']: stops = [] layovers = flight.get('stops') if not layovers is None: for layover in layovers: stops.append(layover['code']) fl = Flight(flight['origin']['code'], flight['destination']['code'], flight['departure'], flight['arrival'], flight['duration'], stops) flights.append(fl) return Trip(flights[0], flights[1], ppm, price, distance)
def trip_for_stopnames(self, stopnames=[]): """ :param: stopnames: array that hold name of the stops :return: Object of Trip """ matching_stations = [self.stations_by_name[name] for name in stopnames] return Trip(matching_stations)
def getRandomDriverTrips(self, numtrips, numNotDrivers, feat): #get list of drivers and shuffle notDrivers = os.listdir("../drivers/") copy = notDrivers[1:] random.shuffle(copy) notDrivers[1:] = copy #process number of 'other' drivers if numNotDrivers == 0 or numNotDrivers >= len(notDrivers): numNotDrivers = len(notDrivers) - 1 #if we are comparing to only one driver and that driver is the same as #the original driver if numNotDrivers == 1: while notDrivers[1] == self.name: copy = notDrivers[1:] random.shuffle(copy) notDrivers[1:] = copy #sample trips and output desired features tripList = [] for i in range(numtrips): dnum = notDrivers[random.randint( 1, numNotDrivers)] #sample a random driver #print self.name + " " + dnum while dnum == self.name: #don't sample from self dnum = notDrivers[random.randint(1, numNotDrivers)] tnum = random.randint(1, 200) #sample a random trip t = Trip("../drivers/" + str(dnum) + "/" + str(tnum) + ".csv", feat) tripList.append(t.printFeatures()) return tripList
def get_trips() -> List[Trip]: conn = get_db() res = conn.execute( 'SELECT * FROM position ORDER BY Timestamp').fetchall() trips = [] if len(res) > 1: start = res[0] end = res[1] tr = Trip() #res = list(map(dict,res)) for x in range(0, len(res) - 2): next_el = res[x + 2] if end["mileage"] - start["mileage"] == 0 or \ (end["Timestamp"] - start["Timestamp"]).total_seconds() / 3600 > 3: start = end tr = Trip() else: distance = next_el["mileage"] - end["mileage"] # km duration = (next_el["Timestamp"] - end["Timestamp"]).total_seconds() / 3600 if ( distance == 0 and duration > 0.08 ) or duration > 2: # check the speed to handle missing point tr.distance = end["mileage"] - start["mileage"] # km if tr.distance > 0: tr.start_at = start["Timestamp"] tr.end_at = end["Timestamp"] tr.add_points(end["longitude"], end["latitude"]) tr.duration = ( end["Timestamp"] - start["Timestamp"]).total_seconds() / 3600 tr.speed_average = tr.distance / tr.duration diff_level = start["level"] - end["level"] tr.consumption = diff_level / 100 * BATTERY_POWER # kw tr.consumption_km = 100 * tr.consumption / tr.distance # kw/100 km # logger.debug( # f"Trip: {start['Timestamp']} {tr.distance:.1f}km {tr.duration:.2f}h {tr.speed_average:.2f} km/h {tr.consumption:.2f} kw {tr.consumption_km:.2f}kw/100km") # filter bad value if tr.consumption_km < 70: trips.append(tr) start = next_el tr = Trip() else: tr.add_points(end["longitude"], end["latitude"]) end = next_el return trips
def _generate_all_combinations(self): logging.info("Generating trip candidates with {0} cities each".format( self.cities_per_trip_candidate)) if self.total_cities < self.cities_per_trip_candidate: only_trip = self.requested_cities.keys() trip_votes = self._get_trip_total_votes(only_trip) trip_votees = self._get_trip_total_votees(only_trip) self.all_combinations = [Trip(only_trip, trip_votes, trip_votees)] candidate_list = list( combinations(self.requested_cities.keys(), self.cities_per_trip_candidate)) self.all_combinations = [ Trip(trip_cities, self._get_trip_total_votes(trip_cities), self._get_trip_total_votees(trip_cities)) for trip_cities in candidate_list ]
def writeCSV_test(self): g = open("driver_stats/" + str(self.name) + "_test.csv", "w") #first trips from this driver for i in range(num_selfTrips + 1, num_selfTrips + num_testTrips + 1): t = Trip("../drivers/" + str(self.name) + "/" + str(i) + ".csv") g.write(t.printFeatures()) #trips from other drivers tripList = self.getRandomDriverTrips(num_testTrips) for other in tripList: g.write(other) g.close()
def load_trips(filename, limit=float('inf')): trips = [] with open(filename, "r") as f: reader = csv.reader(f) reader.next() for line in reader: trips.append(Trip(line)) if (len(trips) >= limit): break return trips
def writeCSV_training(self): g = open("driver_stats/" + str(self.name) + "_training.csv", "w") #a header and then the features for each trip #g.write("advSpeed,tripDist\n") #first trips from this driver for i in range(1, num_selfTrips + 1): t = Trip("../drivers/" + str(self.name) + "/" + str(i) + ".csv") g.write(t.printFeatures()) #trips from other drivers tripList = self.getRandomDriverTrips(num_NOTselfTrips) for other in tripList: g.write(other) g.close()
def getRandomDriverTrips(self, numtrips): notDrivers = os.listdir("../drivers/") numNotDrivers = len( notDrivers) #change this parameter to consider a different number tripList = [] for i in range(numtrips): dnum = notDrivers[random.randint(1, len(notDrivers) - 1)] #sample a random driver while dnum == self.name: #don't sample from self dnum = notDrivers[random.randint(1, numNotDrivers - 1)] tnum = random.randint(1, 200) #sample a random trip t = Trip("../drivers/" + str(dnum) + "/" + str(tnum) + ".csv") tripList.append(t.printFeatures()) return tripList
def request(self, rider_id, lat, lng): minDistance, minDriverId = float('inf'), None for dId, loc in self.driver2Location.items(): curDistance = Helper.get_distance(lat, lng, loc[0], loc[1]) if minDistance > curDistance: minDistance, minDriverId = curDistance, dId trip = Trip(rider_id, lat, lng) trip.driver_id = minDriverId if minDriverId: self.driver2Trip[minDriverId] = trip del self.driver2Location[minDriverId] return trip
def request(self, rider_id, lat, lng): # Write your code here dist = -1 driver = -1 for key, value in self.locs.items(): td = Helper.get_distance(value[0], value[1], lat, lng) if dist == -1 or td < dist: dist = td driver = key trip = Trip(rider_id, lat, lng) trip.driver_id = driver if dist != -1: del self.locs[driver] self.trips[driver] = trip return trip
def request(self, rider_id, lat, lng): # Write your code here minD = sys.maxsize closestD = None for driver in self.driverLocation.keys(): if driver in self.trip: continue lat1, lng1 = self.driverLocation[driver] dis = Helper.get_distance(lat1, lng1, lat, lng) if dis < minD: minD = dis closestD = driver trip = Trip(rider_id, lat, lng) trip.driver_id = closestD self.trip[closestD] = trip return trip
def request(self, rider_id, lat, lng): trip = Trip(rider_id, lat, lng) distance, driver_id = -1, -1 for key, value in self.driver2Location.items(): dis = Helper.get_distance(value.lat, value.lng, lat, lng) if distance < 0 or distance > dis: driver_id = key distance = dis if driver_id != -1: del self.driver2Location[driver_id] trip.driver_id = driver_id self.driver2Trip[driver_id] = trip return trip
def test_order_hotel(): flights_data = flight_general.get_all_updated_data() data_in_range = [ flight for flight in flights_data if (flight.days == 5 or flight.days == 6) and flight.destination_value < 25 and (flight.label == 4 or flight.label == 3) ] data_in_range.sort() trip_list = [] for i in range(0, 3): flight = data_in_range[i] trip = Trip(flight) trip.get_hotel_for_trip() trip_list.append(trip) trip_list.sort(reverse=True) return trip_list
def writeCSV(self, order, numNotDrivers, feat): g = open("driver_stats/" + str(self.name) + "_training.csv", "w") #first trips from this driver for i in range(0, num_selfTrips + num_testTrips): #print i t = Trip( "../drivers/" + str(self.name) + "/" + str(order[i]) + ".csv", feat) g.write(t.printFeatures()) #trips from other drivers tripList = self.getRandomDriverTrips(num_NOTselfTrips + num_testTrips, numNotDrivers, feat) for other in tripList: g.write(other) g.close()
def request(self, rider_id, lat, lng): trip = Trip(rider_id, lat, lng) min_dist = float('inf') closest_driver_id = -1 for driver_id, driver in self.drivers.items(): dist = Helper.get_distance(lat, lng, driver.lat, driver.lng) if dist < min_dist: min_dist = dist closest_driver_id = driver_id print(dist, closest_driver_id) trip.driver_id = closest_driver_id self.trip_serial_id += 1 self.trips[self.trip_serial_id] = trip self.drivers[closest_driver_id].trip_id = self.trip_serial_id return trip
def request(self, rider_id, lat, lng): # Write your code here t = Trip(rider_id, lat, lng) min_diff = sys.maxint match_driver = [] for driver in self.driver_id_to_location: driver_tuple = self.driver_id_to_location[driver] diff = Helper.get_distance(lat, lng, driver_tuple[0], driver_tuple[1]) if diff < min_diff: min_diff = diff match_driver = [driver, driver_tuple[0], driver_tuple[1]] if len(match_driver) != 0: del self.driver_id_to_location[match_driver[0]] t.driver_id = match_driver[0] self.driver_id_to_trip[match_driver[0]] = t return t else: return None
def request(self, rider_id, lat, lng): the_dvr_id = None min_distance = float("inf") for dvr_id, dvr in self.drivers.items(): if dvr[2]: continue distance = Helper.get_distance(lat, lng, dvr[0], dvr[1]) if distance < min_distance: min_distance = distance the_dvr_id = dvr_id if not the_dvr_id: return None trip = Trip(rider_id, lat, lng) trip.driver_id = the_dvr_id self.drivers[the_dvr_id][2] = trip return trip
def request(self, rider_id, lat, lng): # create a trip first # find the closest available driver from self.driver2Location # if no driver return none, if yes, fill in trip driver_id, # remove from driver2Location, add to driver2Trip trip = Trip(rider_id, lat, lng) driver_id, distance = -1, -1 for id, loc in self.driver2Location.items(): dis = Helper.get_distance(lat, lng, loc.lat, loc.lng) if distance == -1 or dis < distance: distance = dis driver_id = id if driver_id == -1: print("No available drivers") return None trip.driver_id = driver_id self.driver2Trip[driver_id] = trip del self.driver2Location[driver_id] return trip
def request(self, rider_id, lat, lng): if not rider_id: return trip = Trip(rider_id, lat, lng) _distance = distance = self.INFINITY driver_id = -1 for _driver_id, _loc in self.driver_to_locs.items(): _distance = Helper.get_distance(_loc['lat'], _loc['lng'], lat, lng) if _distance < distance: driver_id = _driver_id distance = _distance if driver_id == -1: return trip trip.driver_id = driver_id self.driver_to_trip[driver_id] = trip del self.driver_to_locs[driver_id] return trip
def plot_unique_trips(): from matplotlib import pyplot as plt trip_lookup = {} print("Loading map") road_map = Map("nyc_map4/nodes.csv", "nyc_map4/links.csv") print("Matching nodes") sizes = [] with open("sample.csv", "r") as f: reader = csv.reader(f) reader.next() for line in reader: trip = Trip(line) trip.num_occurrences = 1 trip.origin_node = road_map.get_nearest_node( trip.fromLat, trip.fromLon) trip.dest_node = road_map.get_nearest_node(trip.toLat, trip.toLon) if ((trip.origin_node, trip.dest_node) in trip_lookup): #Already seen this trip at least once trip_lookup[trip.origin_node, trip.dest_node].num_occurrences += 1 elif trip.origin_node != None and trip.dest_node != None: #Never seen this trip before trip_lookup[trip.origin_node, trip.dest_node] = trip sizes.append(len(trip_lookup)) plt.plot(range(len(sizes)), sizes) plt.xlabel("Inner Loop Iteration") plt.ylabel("L1 Error (sec)") fig = plt.gcf() fig.set_size_inches(20, 10) fig.savefig('test2png.png', dpi=100) #Make unique trips into a list and return new_trips = [trip_lookup[key] for key in trip_lookup] return new_trips
def request(self, rider_id, lat, lng): # @param rider_id an integer # @param lat, lng rider's location # return a trip # find a closest driver closest_driver, closest_dist = None, sys.maxsize for driver, location in self.drivers2location.items(): distance = Helper.get_distance(lat, lng, location[0], location[1]) if distance < closest_dist: closest_driver = driver closest_dist = distance # create a trip with rider's information. trip = Trip(rider_id, lat, lng) # fill driver_id into this trip. trip.driver_id = closest_driver # mark this driver not available. del self.drivers2location[closest_driver] self.drivers2trip[closest_driver] = trip return trip
def algorithm(self): self.routingDay = self.initRoutingDay() for pair, saving in self.savings: trip1 = self.routingDay.tripContainingRequest(pair[0], True) trip2 = self.routingDay.tripContainingRequest(pair[1], True) if trip1 and trip2: if not trip1.equals(trip2): newTrip = Trip(self.instance) newTrip.concatenateTrips(trip2, trip1, pair) if newTrip.isValid(): validChange = True benefit = True for toolID, tool in self.instance.tools.items(): if self.inventory[toolID] < 0: benefit = False newInventory = newTrip.inventoryChange() inventory1 = trip1.inventoryChange() inventory2 = trip2.inventoryChange() for toolID, tool in self.instance.tools.items(): change = newInventory[toolID] - inventory1[ toolID] - inventory2[toolID] if change < 0 and self.inventory[ toolID] + change < 0: validChange = False break if self.inventory[toolID] < 0 and change > 0: benefit = True if validChange and benefit: self.routingDay.addTrip(newTrip) self.routingDay.deleteTrip(trip1) self.routingDay.deleteTrip(trip2) for toolID, tool in self.instance.tools.items(): change = newInventory[toolID] - inventory1[ toolID] - inventory2[toolID] self.inventory[ toolID] = self.inventory[toolID] + change
from Trip import Trip from MaxMileageException import MaxMileageException try: miles = int(input("How many miles to your destination? \n")) trip = Trip() trip.setMiles(miles) hours = miles / 65 print("The trip will be {} hours.".format(hours)) trip.stop_for_food(hours) trip.rest_for_day(hours) # print(miles) loop = 0 while miles > 0: if loop == 350: print("You are getting low on gas. Please fill up.") loop += 1 # print(miles) miles -= 1 except MaxMileageException: print("You must not go on a trip over 500 miles.")
def writeCSV_selfDriver(self): g = open("driver_stats/" + str(self.name) + "_selfTrips.csv", "w") for i in range(1, 201): #get features for all driver trips t = Trip("../drivers/" + str(self.name) + "/" + str(i) + ".csv") g.write(t.printFeatures()) g.close()
result_dict['schedule'].append({ "job": j.job_id, "delivery time": j.find_delivery_time().strftime("%m/%d/%Y, %H:%M:%S"), "user company": j.user_company, "location": j.vessel_loading_location, "pick up": j.check_pickup_time(), "items": j.process_items(), "terminal": j.terminal }) pp = pprint.PrettyPrinter(indent=4) unassigned_jobs_list.sort(key=lambda x: x.find_delivery_time()) for i in range(len(unassigned_jobs_list) - 1): j = unassigned_jobs_list[i] for k in range(1, len(unassigned_jobs_list) - i): o = unassigned_jobs_list[i + k] print( str(j.job_id) + " and " + str(o.job_id) + ": " + str(j.use_same_truck(o))) if (j.use_same_truck(o)): trip = Trip(j, o) print(trip.get_truck()) pp.pprint(sorted(result_dict['schedule'], key=lambda x: x['delivery time']))
# Holds a set of random trips all_trips = [] header = True # Get 20000 trips for t in trip_file: if header: # First row is just descriptions of data, not data at all header = False continue if i > 20000: break i += 1 # This list is used to initialize a Trip object new_trip_list = [t[0], t[8], t[9], float(t[10]), float(t[11]), float(t[12]), float(t[13]), -1, -1, 1] new_trip = Trip(new_trip_list) all_trips.append(new_trip) grid_arcs = get_correct_nodes(n, "speeds_per_hour/0_0", "ArcFlags/20Regions0_0.csv") grid_a_star = get_correct_nodes(n, "speeds_per_hour/0_0", None) node_info = get_node_range(grid_a_star) max_speed = 0 # Iterates through every edge to find te fastest speed for column in grid_a_star: for region in column: for node in region.nodes: for connection in node.speed_connections: if node.speed_connections[connection] > max_speed: max_speed = node.speed_connections[connection] all_trips_arcs = [] all_trips_star = []