def direct_trips(source, destination, car_mpg, max_cost, max_time, depart_time, user_prefs, key_vault): global source_airport_code global destination_airport_code return_list = [] if user_prefs[0] or user_prefs[1] or user_prefs[2] == True: ground_cost = total_ground_cost(source, destination, car_mpg, key_vault) if user_prefs[0] and ground_cost[0][0] > 0: car_trip = Trip(source) car_trip_step = TripStep(destination, TripStep.CAR, ground_cost[0][0], ground_cost[0][1], ground_cost[0][2]) car_trip.cities.append(car_trip_step) car_trip.carbon_cost += ground_cost[0][0] car_trip.money_cost += ground_cost[0][1] car_trip.time_cost += ground_cost[0][2] return_list.append(car_trip) if user_prefs[1] and ground_cost[1][0] > 0: bus_trip = Trip(source) bus_trip_step = TripStep(destination, TripStep.BUS, ground_cost[1][0], ground_cost[1][1], ground_cost[1][2]) bus_trip.cities.append(bus_trip_step) bus_trip.carbon_cost += ground_cost[1][0] bus_trip.money_cost += ground_cost[1][1] bus_trip.time_cost += ground_cost[1][2] return_list.append(bus_trip) if user_prefs[2] and ground_cost[2][0] > 0: train_trip = Trip(source) train_trip_step = TripStep(destination, TripStep.TRAIN, ground_cost[2][0], ground_cost[2][1], ground_cost[2][2]) train_trip.cities.append(train_trip_step) train_trip.carbon_cost += ground_cost[2][0] train_trip.money_cost += ground_cost[2][1] train_trip.time_cost += ground_cost[2][2] return_list.append(train_trip) if user_prefs[3]: plane_trip = Trip(source) plane_cost = total_air_cost(source_airport_code, destination_airport_code, depart_time) if plane_cost[0] > 0: plane_trip_step = TripStep(destination, TripStep.PLANE, plane_cost[0], plane_cost[1], plane_cost[2]) plane_trip.cities.append(plane_trip_step) plane_trip.carbon_cost += plane_cost[0] plane_trip.money_cost += plane_cost[1] plane_trip.time_cost += plane_cost[2] return_list.append(plane_trip) return return_list
def adapt_file(file: str, dest: str): wb = load_workbook(filename=file) ws = Workbook() for i_col, title in enumerate(titles): ws.active.cell(row=1, column=i_col + 1).value = title curr_row = 2 for sheet in wb.sheetnames: max_row = wb[sheet].max_row max_col = wb[sheet].max_column for i_col, col in enumerate(wb[sheet].iter_cols(min_row=2, min_col=2, max_col=max_col, max_row=max_row)): for i_row, cell in enumerate(col): if cell.value is not None: date = wb[sheet].cell(row=1, column=i_col + 2).value date_with_day = datetime(year=date.year, month=date.month, day=i_row + 1) places = get_trip(cell.value) for place in places: current_trip = Trip(boat=sheet, date=date_with_day, start=place[0]) if len(place) > 1: current_trip.end = place[1] if cell.comment is not None: current_trip.comment = cell.comment.text current_trip.write_to_ws(ws, row=curr_row) curr_row += 1 ws.save(dest)
def read_file(filename): map = None with open(filename) as f: lines = f.readlines() first_line = True counter = 0 for line in lines: elements = line.split(" ") int_elements = [int(el) for el in elements] if first_line: first_line = False map = Map(int_elements[0], int_elements[1], int_elements[2], int_elements[3], int_elements[4], int_elements[5]) else: trip = Trip(counter, Pos(int_elements[0], int_elements[1]), Pos(int_elements[2], int_elements[3]), int_elements[4], int_elements[5]) map.add_trip(trip) counter += 1 return map
def generateInitialTripListPopulation(gift_list,initial_population_size): count = 0 trip_list = list([]) master_trip_population = list([]) gift_trip_list = list([]) while count < initial_population_size: random.shuffle(gift_list) total_weight = 0 i = 0 trip_list = list([]) while i < len(gift_list): while i < len(gift_list) and (total_weight + gift_list[i].weight) <= SLEIGH_CAPACITY: gift_trip_list.append(gift_list[i]) total_weight = total_weight + gift_list[i].weight i = i + 1 trip_order = Trip(gift_trip_list,SantaUtil.tripCost(gift_trip_list)) total_weight = 0 gift_trip_list = list([]) trip_list.append(trip_order) count = count+1 master_trip_population.append(trip_list) return master_trip_population
def read_trips(abs_file_path: string) -> List[Trip]: try: data = pd.read_csv(abs_file_path) samples_no = data.shape[0] columns_no = data.shape[1] trips = [] print("samples_no: " + str(samples_no)) print("columns_no: " + str(columns_no)) for i in range(samples_no): sample = data.iloc[i, :] start_time = parser.parse(sample["start_time"]) start_lat = float(sample["start_latitude"]) start_lon = float(sample["start_longitude"]) end_time = parser.parse(sample["end_time"]) end_lat = float(sample["end_latitude"]) end_lon = float(sample["end_longitude"]) trip = Trip(start_time, start_lat, start_lon, end_time, end_lat, end_lon) trips.append(trip) except Exception as e: print("Error: dataset could not be read: {}".format(e)) return [] return trips
def init_vehicles(): ## Set of vehicles moving in the car. global level global trafficInjection global vehicles global time_units global trip global path_mode global commander if level == 0: trafficInjection = UniformTrafficInjection() else: trafficInjection = RandomTrafficInjection() vehicles = trafficInjection.getVehicles() if path_constraints[path_mode] == "FREE": commander = nn_manual_commander() else: print("PHYSICS") commander = physics_commander() ## Adding the target vehicle vehicles.append( Vehicle(4, (1, 2, 1), (-5, -40, 0), (1, 1, 0), 0, [0, 0.2, 0], False, "manual" if path_mode == 0 else "physics")) trip = Trip(vehicles[-1]) time_units = 0
def test_invalid_trip_lt_five_mph(self): try: trip = Trip(self.validStartTime, self.validEndTime, self.invalidDurationFiveMph) self.assertEqual(1, 2) except Exception as ex: self.assertEqual(str(ex), 'Skip trip: Less than 5mph')
def test_invalid_trip_gt_one_hundred_mph(self): try: trip = Trip(self.validStartTime, self.validEndTime, self.invalidDurationOneHundredMph) self.assertEqual(1, 2) except Exception as ex: self.assertEqual(str(ex), 'Skip trip: Greater than 100mph')
def test_invalid_trip_negative_distance(self): try: trip = Trip(self.validStartTime, self.validEndTime, self.invalidDistance) self.assertEqual(1, 2) except Exception as ex: self.assertEqual(str(ex), 'Distance must be a positive number')
def test_invalid_trip_end_before_start(self): try: trip = Trip(self.validEndTime, self.validStartTime, self.validDistance) self.assertEqual(1, 2) except Exception as ex: self.assertEqual(str(ex), 'End Time must be after Start Time')
def test_valid_trip(self): try: trip = Trip(self.validStartTime, self.validEndTime, self.validDistance) self.assertEqual(trip.distance, self.validDistance) except Exception as ex: self.assertEqual(1, 2)
def refresh_trains(): threading.Timer(30.0, refresh_trains).start() r = requests.get(positionUrl, auth=(auth.username, auth.password)) page = r.json() for p in page: trip_id = p['vehicle']['trip']['trip_id'] train_number = ''.join([i for i in trip_id.split('_V')[0] if i.isdigit()]) if int(train_number) % 2 == 0: # inbound trains numbered even inbound_or_outbound = '_IB' else: inbound_or_outbound = '_OB' # outbound trains numbered odd if trip_id not in current_trips: # make a Trip object with the trip ID and the Route of the trip new_trip = Trip(trip_id, routes[trip_id.split('_')[0] + inbound_or_outbound]) current_trips[new_trip.trip_id] = new_trip trip = current_trips[trip_id] upd_array = trip.update_position(p['vehicle']['position']['latitude'], p['vehicle']['position']['longitude']) with open('results.csv', 'a') as resTable: writer = csv.writer(resTable) for row in upd_array: if len(row) > 0: writer.writerow(row)
def _create_trip_object_list(list_of_parks, state_code, month): parks_in_state = [] try: # Since the api has a limit of 50 parks, we have to have multiple urls to run after each other. This line loops through all the 400 data in the api for park in list_of_parks: state = park['states'] if state == state_code: address = park['addresses'][1] park_name = park['fullName'] park_city = address['city'] park_state = park['states'] park_description = park['description'] latitude = park['latitude'] longitude = park['longitude'] trip = Trip(month=month, park_name=park_name, park_city=park_city, park_state=park_state, park_description=park_description, latitude=latitude, longitude=longitude) parks_in_state.append(trip) return parks_in_state except KeyError: return "There are no parks for that state."
def start_ground_trips(source, destination, car_mpg, user_prefs, key_vault): global source_airport_code src_airports = nearby_airports(source, key_vault) source_airport_code = src_airports[0][1] trips = [] for airport, code in src_airports: ground_paths = total_ground_cost(source, airport, car_mpg, key_vault) if user_prefs[0]: car_trip = Trip(source) car_costs = ground_paths[0] car_trip.carbon_cost += float(car_costs[0]) car_trip.money_cost += car_costs[1] car_trip.time_cost += car_costs[2] car_trip.cities.append( TripStep(airport, TripStep.CAR, car_costs[0], car_costs[1], car_costs[2])) car_trip.prev_airport_code = code if car_trip.carbon_cost >= 0: trips.append(car_trip) if user_prefs[1]: bus_trip = Trip(source) bus_costs = ground_paths[1] bus_trip.carbon_cost += float(bus_costs[0]) bus_trip.money_cost += bus_costs[1] bus_trip.time_cost += bus_costs[2] bus_trip.cities.append( TripStep(airport, TripStep.BUS, bus_costs[0], bus_costs[1], bus_costs[2])) bus_trip.prev_airport_code = code if bus_trip.carbon_cost >= 0: trips.append(bus_trip) if user_prefs[2]: train_trip = Trip(source) train_costs = ground_paths[2] train_trip.carbon_cost += float(train_costs[0]) train_trip.money_cost += train_costs[1] train_trip.time_cost += train_costs[2] train_trip.cities.append( TripStep(airport, TripStep.TRAIN, train_costs[0], train_costs[1], train_costs[2])) train_trip.prev_airport_code = code if train_trip.carbon_cost >= 0: trips.append(train_trip) return trips
def addTrip(self, startTime, endTime, distance): try: trip = Trip(startTime, endTime, float(distance)) self.trips.append(trip) self.milesDriven = self.milesDriven + trip.distance self.timeDriven += trip.duration except Exception as ex: self.__errorLog.log(str(ex))
def BuildTrip(self, expectedTripTime, batteryCapacity, vehicle, timeBlockConstant, tripName=''): self.TimeBlockConstant = timeBlockConstant self.Vehicle = self.GetVehicle(batteryCapacity, vehicle) numberOfStops = self.GetNumberOfStops() hasDestinationCharger = self.GetHasDestinationCharger() route = self.GetRoute() return Trip(numberOfStops=numberOfStops, expectedTripTime=expectedTripTime, batteryCapacity=self.Vehicle.BatteryCapacity\ , hasDestinationCharger=hasDestinationCharger, route=route, vehicle=self.Vehicle, tripName=tripName)
def test_return_trips_if_users_are_friends(self, mock_get_user, mock_get_trips_from_user): friend_one = User() friend_one.add_friend(self.A_USER) friend_one.add_trip(Trip()) trip_service = TripService() result = trip_service.get_trips_by_user(friend_one) self.assertEquals(len(result), 1)
def __init__(self, filename, keys): ''' Initializes driver with features of 200 trips. ''' npy_file = '%s/%d.npy' % (ROOT_NAME, filename) load_data = np.load(npy_file) self.drive_data = [] for i in range(len(load_data)): trip = Trip(load_data[i]) trip.comp_features() trip_features = trip.get_features(keys) self.drive_data.append(trip_features)
def read_train_data(self, to_read_count=-1): self.data = [] """Reads data file""" read_count = 0 with open(self.train_file, 'r') as train_f: reader = csv.DictReader(train_f) for row in reader: trip = Trip(row) read_count += 1 self.data.append(trip) if to_read_count > 0 and read_count >= to_read_count: break
def calculate(): data = request.get_json() try: if len(data["points"]) < 2 or len(data["points"]) > 5 or data["carType"] not in ["econom", "economPlus", "business", "premium"] or type(data["baby"]) != bool or type(data["animal"]) != bool: return jsonify({"error": "Validation error"}), 500 except KeyError: return jsonify({"error": "Validation error"}), 500 trip = Trip(data['points'], data['carType'], data['baby'], data['animal']) trip.get_overall_length_of_route() trip.calculate_price() if trip.price == 0: return jsonify({"error": "Request error"}), 500 else: return jsonify({"price": trip.price}), 200
def generate(self): numOfTrips = random.randint(1, parameters.customers) numOfDrones = random.randint(1, min(numOfTrips, parameters.maxDrones)) #create deliveries for each customer (node) self.deliveries = [Delivery(x) for x in self.customers] #assign random delivery time to each delivery for delivery in self.deliveries: delivery.time = random.randint(parameters.minimumDeliveryTime, parameters.dayLength) #ensure each drone has at least one delivery for idx in range(numOfDrones): self.droneDeliveryAllocation[idx] = [self.deliveries[idx]] #populate rest of delivery assignment dictionary for idx in range(numOfDrones, len(self.deliveries)): droneAllocation = random.randrange(numOfDrones) self.droneDeliveryAllocation[droneAllocation].append( self.deliveries[idx]) #create trips for each drone for droneNo, assignedDeliveries in self.droneDeliveryAllocation.items( ): assignedDeliveries.sort( key=lambda x: x.time ) #sort each drones deliveries so trips are in order #create trips within drone and add deliveries to trips trips = [] startTime = 0 while len(assignedDeliveries) > 0: if parameters.droneCargoSlots > len(assignedDeliveries): maxNumber = len(assignedDeliveries) else: maxNumber = parameters.droneCargoSlots numberInTrip = random.randint( 1, maxNumber ) #randomly choose a number of packages to be in the trip, min = 1, max = cargoSize trips.append(Trip(*assignedDeliveries[:numberInTrip])) del assignedDeliveries[:numberInTrip] self.drones.insert(droneNo, Drone(*trips)) self.values = self.stringBuilder( ) #called last for problem file to be accurate
def get_trips(self): """Get all trips corresponding to this itinerary (from the database).""" if not self.DB_trips: if not self.is_walking: self.DB_trips = db.all_itinerary_trips(self) else: # create a single walking trip at the start of the time window from trip import Trip walk_seconds = self.total_walk_distance / config.walk_speed unix_trip_start = config.tz.localize( datetime.combine( config.window_start_date,config.window_start_time )).timestamp() self.DB_trips = [Trip( unix_trip_start, unix_trip_start + walk_seconds, self.otp_string )] return self.DB_trips
def get_trips_from_file(self): """Check files for trips data and read it into a list. Remove any trips outside the time window as well as any suboptimal trips.""" # directories to check directories = ['17476','17477','17478','17479','17480'] trips = [] for d in directories: csvpath = config.input_dir+d+'/'+str(self.orig)+'/'+str(self.dest)+'.csv' if not os.path.exists(csvpath): continue with open(csvpath) as f: reader = csv.DictReader(f) trips.extend( [ Trip(r['depart'],r['arrive'],r['itinerary']) for r in reader ] ) # we now have all the data from the files but need to clean it triptools.clip_trips_to_window(trips) triptools.remove_premature_departures(trips) return trips
class TestGetTripsByUser(unittest.TestCase): GUEST_USER = None A_USER = User() ANOTHER_USER = User() @mock.patch.object(TripService, '_get_logged_user_from_session', side_effect=UserNotLoggedInException, autospec=True) def test_raise_exception_if_user_not_logged_in(self, mock_get_user): trip_service = TripService() with self.assertRaises(UserNotLoggedInException): trip_service.get_trips_by_user(self.A_USER) mock_get_user.assert_called_once_with(trip_service) @mock.patch.object(TripService, '_get_logged_user_from_session', return_value=A_USER, autospec=True) def test_no_trips_returned_if_users_are_not_friends(self, mock_get_user): trip_service = TripService() result = trip_service.get_trips_by_user(self.ANOTHER_USER) self.assertListEqual(result, []) mock_get_user.assert_called_once_with(trip_service) @mock.patch.object(TripService, '_get_trips_of_user', return_value=[Trip()], autospec=True) @mock.patch.object(TripService, '_get_logged_user_from_session', return_value=A_USER, autospec=True) def test_return_trips_if_users_are_friends(self, mock_get_user, mock_get_trips_from_user): friend_one = User() friend_one.add_friend(self.A_USER) friend_one.add_trip(Trip()) trip_service = TripService() result = trip_service.get_trips_by_user(friend_one) self.assertEquals(len(result), 1)
def _create_trips(self): """Returns an array of Trip objects for each trip option in this query response. Args: None. Returns: Trip[]: an array of Trip objects corresponding to each trip option in this query response. """ trips = [] data = self.query_response["trips"]["data"] if "tripOption" in self.query_response["trips"]: trip_options = self.query_response["trips"]["tripOption"] for option in trip_options: trip = Trip(data, option) trips.append(trip) return trips
def postTripsByRoute(self, origin, dest): flights_schedules, searchUrl = self.getFlightSchedulesFromUrl( origin, dest) trips = [] origin = str(flights_schedules['summary']['from']['iata']) dest = str(flights_schedules['summary']['to']['iata']) try: route = session.query(Route).filter_by(origin=origin, destination=dest).one() except Exception as error: print('Error: ' + repr(error)) else: for trip in flights_schedules['options']: aircraft_model = str(trip['aircraft']['model']) aircraft_manufacturer = str(trip['aircraft']['manufacturer']) aircraft = AircraftController().searchForAircraft( aircraft=aircraft_model, manufacturer=aircraft_manufacturer) arrival_time = datetime.strptime(trip['arrival_time'], "%Y-%m-%dT%H:%M:%S") departure_time = datetime.strptime(trip['departure_time'], "%Y-%m-%dT%H:%M:%S") duration = arrival_time - departure_time trip = Trip(route=route.route_id, departure_time=str(trip['departure_time']), arrival_time=str(trip['arrival_time']), price=str(trip['fare_price']), aircraft=aircraft.aircraft_id, duration=duration, search_url=searchUrl.search_url_id) session.add(trip) trips.append(trip) session.commit() return trips
def BuildTrip(self, name, route, polyline, expectedTripTime, carBattery): # Compute distances, time to travel, energy expended, etc. stops = route[1:-1] startPoint = route[0] endPoint = route[-1] tripRoute = [ Start(startPoint.AddressInfo.Title, startPoint.AddressInfo) ] for stop in stops: tripRoute.append( self.GetCharger(stop, route[route.index(stop) - 1], carBattery)) tripRoute.append(self.GetDestination(endPoint, route[-2], carBattery)) # Package the trip object. trip = Trip(name, tripRoute, polyline, expectedTripTime, carBattery) # Return the trip object. return trip
from threads import MQTTListener, LocationFetcher from api import get_trip_data, NetworkError from rpi import RPIController from trip import Trip from queue import Queue from config import Config config = Config() # Initialization if __name__ == '__main__': # Create Raspberry Pi controller rpi = RPIController() # Create trip try: trip = Trip(get_trip_data(str(config.VEH_ID))) print("Trip ID: %s" % (trip.gtfsId)) except NetworkError as e: print(e.value + ", exiting") exit() # Queue is used for all MQTT messages and API call results q = Queue() # Start MQTT listener in its own thread m = MQTTListener(q, config.MQTT_BROKER, config.MQTT_CHANNEL + "/" + trip.gtfsId, trip.gtfsId) m.setDaemon(True) m.start() # Start real time api caller in its own thread
class TestOneToManyRelationships(unittest.TestCase): global driver_1 driver_1 = Driver("Dwight Schrute") global trip_1 trip_1 = Trip("11 Broadway, NY, NY", "123 Smith Street, BK, NY", driver_1) global trip_2 trip_2 = Trip("Pier 11 Ferry", "Battery Park", driver_1) global trip_3 trip_3 = Trip("Wall Street", "Lincoln Center", driver_1) global owner_1 owner_1 = Owner("Michael Scott", 38) global car_1 car_1 = Car("Ford", "Aerostar Minivan", 1997, owner_1) global car_2 car_2 = Car("Toyota", "Corolla", 2000, owner_1) global car_3 car_3 = Car("Chrysler", "300C", 2008, owner_1) def test_owner_property_methods(self): self.assertEqual(owner_1._name, "Michael Scott") self.assertEqual(owner_1.name, "Michael Scott") self.assertEqual(owner_1._age, 38) self.assertEqual(owner_1.age, 38) def test_driver_property_methods(self): self.assertEqual(driver_1._name, "Dwight Schrute") self.assertEqual(driver_1.name, "Dwight Schrute") def test_car_property_methods(self): self.assertEqual(car_1._make, "Ford") self.assertEqual(car_1.make, "Ford") self.assertEqual(car_1._model, "Aerostar Minivan") self.assertEqual(car_1.model, "Aerostar Minivan") self.assertEqual(car_1._year, 1997) self.assertEqual(car_1.year, 1997) self.assertEqual(car_1._owner, owner_1) self.assertEqual(car_1.owner, owner_1) def test_trip_property_methods(self): self.assertEqual(trip_3._start, "Wall Street") self.assertEqual(trip_3.start, "Wall Street") self.assertEqual(trip_3._destination, "Lincoln Center") self.assertEqual(trip_3.destination, "Lincoln Center") self.assertEqual(trip_3._driver, driver_1) self.assertEqual(trip_3.driver, driver_1) def test_car_class_method(self): self.assertItemsEqual(Car._all, [car_1, car_2, car_3]) self.assertItemsEqual(Car.all(), [car_1, car_2, car_3]) def test_trip_class_method(self): self.assertItemsEqual(Trip._all, [trip_1, trip_2, trip_3]) self.assertItemsEqual(Trip.all(), [trip_1, trip_2, trip_3]) def test_find_my_cars_instance_method(self): self.assertItemsEqual( owner_1.find_my_cars(), ["Ford Aerostar Minivan", "Toyota Corolla", "Chrysler 300C"]) def test_my_trips_instance_method(self): self.assertItemsEqual(driver_1.my_trips(), [trip_1, trip_2, trip_3]) def test_find_my_cars_instance_method(self): self.assertItemsEqual(driver_1.my_trip_summaries(), [ "11 Broadway, NY, NY to 123 Smith Street, BK, NY", "Pier 11 Ferry to Battery Park", "Wall Street to Lincoln Center" ])
1: f1, 2: f2, 3: f3, 4: f4, 5: f5, 6: f6, 7: f7, 8: f8, 9: f9, 10: f10 } f, side = switcher.get(fnumber), int(argv[sideidx]) (first_xys, first_zs) = train_data(side, f, False) if argv[1] == "view": points = first_xys + ast.literal_eval(argv[4]) trip = Trip(f, (0, 0), points, probe(f, points), 100, Plotter('surface'), 0) trip.select_kernel() trip.fit(n_restarts_optimizer=100) trip.plot_pred(argv[5]) exit(0) plot, seedval, time_limit, nb, budget, alg, online = argv[1].startswith( 'plot'), int(argv[2]), float(argv[3]), int(argv[4]), int( argv[6]), argv[8], argv[9] == 'on' # Initial settings. seed(seedval) (TSxy, TSz), depot = test_data(f), (-0.00001, -0.00001) plotter = Plotter('surface') if plot else None # Create initial model with kernel selected by cross-validation. trip = Trip(f, depot, first_xys, first_zs, budget, plotter)