def initCity(dao,trip_pickle = True,cam_pickle=True): """ Initialize all data for following object: - Roads - Grids - Trips - Cameras Link/map data: - Trips --> Cells - Trip/Cells --> Roads - Cameras --> Roads - Roads --> Cameras :param read_pickle: If true, read ALL data from pickle. Otherwise initialize from scratch: can be slow :return: """ # Initialize roads RoadNode.init(dao) # Initialize grids GridCell.init(dao) # Initialize Trips Trip.init(dao,read_pickle=trip_pickle) # create traffic cameras TrafficCam.init(dao,read_pickle=cam_pickle)
def book_trip(self, trip: Trip): if trip.train.seats == 0: print("No Seats You Can Not Book") elif trip in self.trips: print(f"Already Booked") else: trip.train.seats -= 1 trip.show_trip_details() self.trips.append(trip) print(f"Your {trip} Was Booked!") self.__save_activity(trip, self.BOOK)
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 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
class TestTrip(unittest.TestCase): @classmethod def setUp(self): print("setUp") self.tripST7726 = Trip("20191205-ST-7726", "ST - Lincolnville GO") def test_id(self): print("test_id") self.assertEqual(self.tripST7726.get_id(), "20191205-ST-7726") def test_head_sign(self): print("test_head_sign") self.assertEqual(self.tripST7726.get_head_sign(), "ST - Lincolnville GO")
def _find_canonical_trips(self): sys.stdout.write("\nCreating Canonical Trips ... ") sys.stdout.flush() trips = [] for trip in self.all_trips: canonical_trip = Trip() for _location in trip.locations: location_node = self.location_index.containing_node(_location) canonical_trip.add_location(location_node) trips.append(canonical_trip) return trips
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_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_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 _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 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 main(dao, batch_size, embedding_size, skip_window, num_skips, num_sampled, num_steps): Trip.setDao(dao) Trip.getTripsPickle() trips_raw = [] # use road ID sequence to represent trips for t in Trip.all_trips: trips_raw.append(t.trajectory["road_node"].apply( lambda x: -1 if np.isnan(x) else int(x)).tolist()) # missing road segments is mapped to -1 trips, num_segments, road_seq, seq_road = prepare_data(trips_raw) # Build and train a skip-gram model execute_w2v(dao, batch_size, embedding_size, skip_window, num_skips, num_sampled, num_steps, trips, num_segments, road_seq, seq_road)
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 my_trips(self): # trippies = [] # for going in Trip.all(): # if going.driver == self: # trippies.append(going) # return trippies return [going for going in Trip.all() if going.driver == self]
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 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 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
class Tsp2Opt: def __init__(self, t, G): self.G = G self.t = t self.w = G.m self.nt = Trip(G) def execute(self): while True: n = len(self.t.trip)-1 maxVariation = 0 best = None for a in range(n-3): b = a+1 if a != 0: lim = n else: lim = n-1 for c in range(a+2, lim): if c != n: d = c+1 else: d = 0 variation = self.w[self.t.trip[a]-1][self.t.trip[b]-1] + self.w[self.t.trip[c]-1][self.t.trip[d]-1] \ - self.w[self.t.trip[a]-1][self.t.trip[c]-1] - self.w[self.t.trip[b]-1][self.t.trip[d]-1] if variation > maxVariation: maxVariation = variation best = a, b, c, d if maxVariation != 0: a, b, c, d = best aux = self.t.trip[b] self.t.trip[b] = self.t.trip[c] self.t.trip[c] = aux else: self.calculateNewTrip() break def calculateNewTrip(self): for v in self.t.trip: self.nt.addVertex(self.G.V[v-1])
class TspMst: def __init__(self, G): self.G = G self.r = self.G.V[0] self.mstPrim = MstPrim(self.G, self.r) self.trip = Trip(G) def execute(self): self.mstPrim.execute() self.preOrder(self.r) self.trip.addVertex(self.r) def preOrder(self, u): self.trip.addVertex(u) for v in self.G.V: if v.pi == u: self.preOrder(v)
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 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 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 get_graphql_data(dct): """ Fetches the GraphQL data for the current trip from the HSL GraphQL API. The trip must be populated with real time data from HSL, which is used to make a GraphQL query. :param dct: A dictionary containing real time trip data :return: The dictionary updated with GraphQL data about the trip. :raise: ValueError if the query returns null. This means the query was most likely invalid. """ date = Trip.trip_date(dct["tst"]) start = Trip.secs_past_midnight(dct["start"]) query = """{{ fuzzyTrip(route: "HSL:{0}", direction: {1}, date: "{2}", time: {3}) {{ gtfsId tripHeadsign stops {{ code gtfsId name lat lon }} route {{ longName }} geometry }} }}""".format(dct["line"], dct["dir"], date, start) headers = {'Content-type': "application/graphql"} r = requests.post(config.HSL_API, data=query, headers=headers) r.raise_for_status() # Let the controller handle that d = json.loads(r.text, object_hook=hook) if d is not None: dct.update(d) else: raise NetworkError("Data not received from GraphQL API") return dct
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 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
class TspNn: def __init__(self, G): self.G = G self.r = self.G.V[0] self.trip = Trip(G) self.V = self.G.V def execute(self): self.trip.addVertex(self.r) self.V.remove(self.r) v = self.r while self.V: u = self.nearest(v) self.trip.addVertex(u) self.V.remove(u) v = u self.trip.addVertex(self.r) def nearest(self, u): Min = maxint for v in self.G.V: if self.G.m[u.n-1][v.n-1] < Min: nearest = v Min = self.G.m[u.n-1][v.n-1] return nearest
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 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
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
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 __init__(self, t, G): self.G = G self.t = t self.w = G.m self.nt = Trip(G)
class Tsp3Opt: def __init__(self, t, G): self.G = G self.t = t self.w = G.m self.nt = Trip(G) def execute(self): while True: n = len(self.t.trip)-1 maxVariation = 0 best = None variation = [0, 0, 0, 0] for a in range(n-5): b = a + 1 for c in range(a+2, n-3): d = c + 1 if a != 0: lim = n else: lim = n-1 for e in range(c+2, lim): if e != n: f = e+1 else: f = 0 oldWeight = self.w[self.t.trip[a]-1][self.t.trip[b]-1] \ + self.w[self.t.trip[c]-1][self.t.trip[d]-1] \ + self.w[self.t.trip[e]-1][self.t.trip[f]-1] newWeight1 = self.w[self.t.trip[a]-1][self.t.trip[e]-1] \ + self.w[self.t.trip[d]-1][self.t.trip[b]-1] \ + self.w[self.t.trip[c]-1][self.t.trip[f]-1] newWeight2 = self.w[self.t.trip[a]-1][self.t.trip[d]-1] \ + self.w[self.t.trip[e]-1][self.t.trip[b]-1] \ + self.w[self.t.trip[c]-1][self.t.trip[f]-1] \ newWeight3 = self.w[self.t.trip[a]-1][self.t.trip[d]-1] \ + self.w[self.t.trip[e]-1][self.t.trip[c]-1] \ + self.w[self.t.trip[b]-1][self.t.trip[f]-1] \ newWeight4 = self.w[self.t.trip[a]-1][self.t.trip[c]-1] \ + self.w[self.t.trip[b]-1][self.t.trip[e]-1] \ + self.w[self.t.trip[d]-1][self.t.trip[f]-1] \ variation[0] = oldWeight - newWeight1 variation[1] = oldWeight - newWeight2 variation[2] = oldWeight - newWeight3 variation[3] = oldWeight - newWeight4 for i in range(4): var = variation[i] if var > maxVariation: maxVariation = var best = (a, b, c, d, e, f) nVariation = i if maxVariation != 0: a, b, c, d, e, f = best if nVariation == 0: self.swap1(a, b, c, d, e, f) elif nVariation == 1: self.swap2(a, b, c, d, e, f) elif nVariation == 2: self.swap3(a, b, c, d, e, f) elif nVariation == 3: self.swap4(a, b, c, d, e, f) else: self.calculateNewTrip() break def swap1(self, a, b, c, d, e, f): aux = self.t.trip[b] self.t.trip[b] = self.t.trip[e] self.t.trip[e] = self.t.trip[c] self.t.trip[c] = self.t.trip[d] self.t.trip[d] = aux def swap2(self, a, b, c, d, e, f): aux = self.t.trip[b] self.t.trip[b] = self.t.trip[d] self.t.trip[d] = aux aux = self.t.trip[e] self.t.trip[e] = self.t.trip[c] self.t.trip[c] = aux def swap3(self, a, b, c, d, e, f): aux = self.t.trip[b] self.t.trip[b] = self.t.trip[d] self.t.trip[d] = self.t.trip[c] self.t.trip[c] = self.t.trip[e] self.t.trip[e] = aux def swap4(self, a, b, c, d, e, f): aux = self.t.trip[b] self.t.trip[b] = self.t.trip[c] self.t.trip[c] = aux aux = self.t.trip[e] self.t.trip[e] = self.t.trip[d] self.t.trip[d] = aux def calculateNewTrip(self): for v in self.t.trip: self.nt.addVertex(self.G.V[v-1])
from route_finder import get_directions from trip import Trip if __name__ == '__main__': # Begin testing d = raw_input("Please enter destination address:") s = raw_input("Please enter start address:") dest = [] start = [] url = 'http://maps.googleapis.com/maps/api/geocode/json?' for location, point in zip([s, d],[start, dest]): location = location.replace(' ', '+') address = 'address=' + location address_url = url + address + "&sensor=true" address_response = urlopen(address_url) json_address = load(address_response) lat = json_address['results'][0]['geometry']['location']['lat'] lng = json_address['results'][0]['geometry']['location']['lng'] point.append(lat) point.append(lng) trip = Trip(get_directions(start, dest)) trip.walking_directions(start, dest) print trip
def __init__(self, G): self.G = G self.r = self.G.V[0] self.mstPrim = MstPrim(self.G, self.r) self.trip = Trip(G)
def __init__(self, G): self.G = G self.r = self.G.V[0] self.trip = Trip(G) self.V = self.G.V
def get_new_vehicles(): """hit the vehicleLocations API and get all vehicles that have updated since the last check. Associate each vehicle with a trip_id (tid) and send the trips for processing when it is determined that they have ended""" global fleet global next_trip_id global next_bid global last_update # UNIX time the request was sent request_time = time.time() try: response = requests.get( 'http://webservices.nextbus.com/service/publicXMLFeed', params={'command':'vehicleLocations','a':conf['agency'],'t':last_update}, headers={'Accept-Encoding':'gzip, deflate'}, timeout=3 ) except: print ('connection problem at',time.strftime("%b %d %Y %H:%M:%S") ) return # UNIX time the response was received response_time = time.time() # estimated UNIX time the server generated it's report # (halfway between send and reply times) server_time = (request_time + response_time) / 2 # list of trips to send for processing ending_trips = [] # this is the whole big ol' parsed XML document XML = ET.fromstring(response.text) # get values from the XML last_update = int(XML.find('./lastTime').attrib['time']) vehicles = XML.findall('.//vehicle') # prevent simulataneous editing with fleet_lock: # check to see if there's anything we just haven't heard from at all lately for vid in list(fleet.keys()): # if it's been more than 3 minutes if server_time - fleet[vid].last_seen > 180: # it has ended ending_trips.append(fleet[vid]) del fleet[vid] # Now, for each reported vehicle for v in vehicles: # if it's not predictable, it's not operating a route if v.attrib['predictable'] == 'false': continue try: # if it has no direction, it's invalid v.attrib['dirTag'] except: continue # get values from XML vid, rid, did = int(v.attrib['id']),v.attrib['routeTag'],v.attrib['dirTag'] lon, lat = float(v.attrib['lon']), float(v.attrib['lat']) report_time = server_time - int(v.attrib['secsSinceReport']) try: # have we seen this vehicle recently? fleet[vid] except: # haven't seen it! create a new trip fleet[vid] = Trip.new(next_trip_id,next_bid,did,rid,vid,report_time) # add this vehicle to the trip fleet[vid].add_point(lon,lat,report_time) # increment the trip and block counters next_trip_id += 1 next_bid += 1 # done with this vehicle continue # we have a record for this vehicle, and it's been heard from recently # see if anything else has changed that makes this a new trip if ( fleet[vid].route_id != rid or fleet[vid].direction_id != did ): # get the block_id from the previous trip last_bid = fleet[vid].block_id # this trip is ending ending_trips.append( fleet[vid] ) # create the new trip in it's place fleet[vid] = Trip.new(next_trip_id,last_bid,did,rid,vid,report_time) # add this vehicle to it fleet[vid].add_point(lon,lat,report_time) # increment the trip counter next_trip_id += 1 else: # not a new trip, just add the vehicle fleet[vid].add_point(lon,lat,report_time) # then update the time and sequence fleet[vid].last_seen = report_time fleet[vid].seq += 1 # release the fleet lock print ( len(fleet),'in fleet,',len(ending_trips),'ending trips at',time.strftime("%b %d %Y %H:%M:%S") ) # store the trips which are ending for some_trip in ending_trips: if len(some_trip.vehicles) > 1: some_trip.save() # look for new route information with 10% probability if getRoutes and random.random() < 0.1: fetch_route(some_trip.route_id) # process the trips that are ending? if doMatching: for some_trip in ending_trips: # start each in it's own process thread = threading.Thread(target=some_trip.process) thread.start()
def process_trip(valid_trip_id): """worker process called when using multiprocessing""" print( 'starting trip:',valid_trip_id ) db.reconnect() t = Trip.fromDB(valid_trip_id) t.process()
print( len(trip_ids),'trips in that range' ) # how many parallel processes to use? max_procs = int(input('max processes --> ')) # create a pool of workers and pass them the data p = mp.Pool(max_procs) p.map(process_trip,trip_ids,chunksize=3) print( 'COMPLETED!' ) # single mode enters one trip at a time and stops when # a non-integer is entered if mode in ['single','s']: trip_id = input('trip_id to process--> ') while trip_id.isdigit(): if db.trip_exists(trip_id): # create a trip object this_trip = Trip.fromDB(trip_id) # process this_trip.process() else: print( 'no such trip' ) # ask for another trip and continue trip_id = input('trip_id to process --> ') # 'range' mode does all valid ids in the given range elif mode in ['all','a']: # get a list of all trip id's in the range trip_ids = db.get_trip_ids_by_range(-float('inf'),float('inf')) process_trips(trip_ids) # process only a certain route elif mode in ['route','r']: route_id = input('route_id --> ') trip_ids = db.get_trip_ids_by_route(route_id)