def make_rider_queue(self, riders_text): self._total_cabs = int(riders_text.readline()) i = 0 while i < self._total_cabs: new_cab_line = riders_text.readline() new_cab_list = new_cab_line.strip('\n').split(' ') self._cabs.append(Car(new_cab_list[0], int(new_cab_list[1]), float('0' + new_cab_list[2]), int(new_cab_list[3]))) i+=1 self._total_riders = int(riders_text.readline()) rider_list = {} count = 0 for line in riders_text: r_info = line.strip('\n').split(' ') r_name = r_info[0] r_time = int(r_info[1]) r_start = int(r_info[2]) r_end = int(r_info[3]) if len(rider_list.keys()) > 0 and r_name in rider_list.keys(): rider_list[r_name].add_ride(r_time, r_start, r_end) if r_start not in self._rider_queue.keys(): self._rider_queue.update({r_start:Queue.PriorityQueue()}) else: rider = Rider(r_name, r_time, r_start, r_end) rider_list.update({rider.get_rider_name():rider}) if r_start in self._rider_queue.keys(): self._rider_queue[rider.get_rider_list()[0].get_starting_point()].put((rider.get_rider_list()[0].get_time_point(),rider)) else: new_floor = Queue.PriorityQueue() new_floor.put((rider.get_rider_list()[0].get_time_point(),rider)) self._rider_queue.update({rider.get_rider_list()[0].get_starting_point():new_floor})
class TestRider(unittest.TestCase): def setUp(self): self.rider = Rider(0, 2, 10, (1, 1), (4, 4), 2) self.next_rider = Rider(0, 9, 15, (2, 2), (3, 3), 2) self.vehicle = Vehicle(0, 2) def test_distance_to_vehicle(self): self.assertEqual(self.rider.distance_to_vehicle(self.vehicle), 2) def test_critical_time(self): self.assertEqual(self.rider.critical_time(), 4)
def create_event_list(filename): """Return a list of Events based on raw list of events in <filename>. Precondition: the file stored at <filename> is in the format specified by the assignment handout. @param filename: str The name of a file that contains the list of events. @rtype: list[Event] """ events = [] with open(filename, "r") as file: for line in file: line = line.strip() if not (line or line.startswith("#")): continue # Skip lines that are blank or start with #. # Create a list of words in the line, e.g. # Note that these are strings, and you'll need to convert some # of them to a different type. tokens = line.split() timestamp = int(tokens[0]) event_type = tokens[1] # HINT: Use Location.deserialize to convert the location string to # a location. if event_type == "DriverRequest": # TODO # Create a DriverRequest event. driver_id = tokens[2] origin_location = deserialize_location(tokens[3]) speed = int(tokens[4]) is_idle = True driver = Driver(driver_id, origin_location, speed, is_idle) events.append(DriverRequest(timestamp, driver)) elif event_type == "RiderRequest": # TODO # Create a RiderRequest event. rider_id = tokens[2] origin_location = deserialize_location(tokens[3]) destination_location = deserialize_location(tokens[4]) paitence = int(tokens[5]) Status = WAITING rider = Rider(rider_id, origin_location, destination_location, Status, paitence) event = RiderRequest(timestamp, rider) events.append(event) return events
def create_event_list(filename): """Return a list of Events based on raw list of events in <filename>. Precondition: the file stored at <filename> is in the format specified by the assignment handout. @param filename: str The name of a file that contains the list of events. @rtype: list[Event] >>> x = create_event_list("events.txt") >>> isinstance(x, list) True """ events = [] with open(filename, "r") as file: for line in file: line = line.strip() if not line or line.startswith("#"): # Skip lines that are blank or start with #. continue # Create a list of words in the line, e.g. # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15']. # Note that these are strings, and you'll need to convert some # of them to a different type. tokens = line.split() timestamp = int(tokens[0]) event_type = tokens[1] id = tokens[2] location = deserialize_location(tokens[3]) # HINT: Use Location.deserialize to convert the location string to # a location. if event_type == "DriverRequest": # TODO # Create a DriverRequest event. speed = int(tokens[4]) driver = Driver(id, location, speed) event = DriverRequest(timestamp, driver) else: # TODO # Create a RiderRequest event. destination = deserialize_location(tokens[4]) patience = int(tokens[5]) rider = Rider(id, location, destination, patience) event = RiderRequest(timestamp, rider) events.append(event) return events
def create_event_list(filename): """Return a list of Events based on raw list of events in <filename>. Precondition: the file stored at <filename> is in the format specified by the assignment handout. @param filename: str The name of a file that contains the list of events. @rtype: list[Event] >>> event = create_event_list("events_small.txt") >>> r = Rider("Dan", Location(1,1), Location(6,6), 15) >>> d = Driver("Arnold", Location(3,3), 2) >>> my_list = [] >>> my_list.append(RiderRequest(1, r)) >>> my_list.append(DriverRequest(10,d )) >>> event == my_list True """ events = [] with open(filename, "r") as file: for line in file: line = line.strip() if not line or line.startswith("#"): # Skip lines that are blank or start with #. continue # Create a list of words in the line, e.g. # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15']. # Note that these are strings, and you'll need to convert some # of them to a different type. tokens = line.split() timestamp = int(tokens[0]) event_type = tokens[1] # HINT: Use Location.deserialize to convert the location string to # a location. event = None if event_type == "DriverRequest": # Create a DriverRequest event. driver = Driver(tokens[2], deserialize_location(tokens[3]), int(tokens[4])) event = DriverRequest(timestamp, driver) elif event_type == "RiderRequest": # Create a RiderRequest event. rider = Rider(tokens[2], deserialize_location(tokens[3]), deserialize_location(tokens[4]), int(tokens[5])) event = RiderRequest(timestamp, rider) if event is not None: events.append(event) return events
def create_event_list(filename): """Return a list of Events based on raw list of events in <filename>. Precondition: the file stored at <filename> is in the format specified by the assignment handout. @param filename: str The name of a file that contains the list of events. @rtype: list[Event] >>> l = create_event_list('events_small.txt') >>> len(l) 2 >>> [print(event) for event in l] 1 -- Dan: Request a driver 10 -- Arnold: Request a rider [None, None] """ events = [] with open(filename, "r") as file: for line in file: line = line.strip() if not line or line.startswith("#"): # Skip lines that are blank or start with #. continue # Create a list of words in the line, e.g. # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15']. # Note that these are strings, and you'll need to convert some # of them to a different type. tokens = line.split() timestamp = int(tokens[0]) event_type = tokens[1] # HINT: Use Location.deserialize to convert the location string to # a location. if event_type == "DriverRequest": id = tokens[2] location = deserialize_location(tokens[3]) speed = int(tokens[4]) # Create a DriverRequest event. event = DriverRequest(timestamp, Driver(id, location, speed)) elif event_type == "RiderRequest": id = tokens[2] origin = deserialize_location(tokens[3]) destination = deserialize_location(tokens[4]) patience = int(tokens[5]) # Create a RiderRequest event. event = RiderRequest(timestamp, Rider(id, origin, destination, patience)) events.append(event) return events
def getListOfRiders(): html = requests.get(LIST_RIDERS_URL).content soup = BeautifulSoup(html, 'html.parser') listOfRiders = [] for tableRows in soup.find_all('tr')[1:]: tableCels = tableRows.find_all('td') # Some games do not use the Class of the rider if (len(tableCels) > 5): listOfRiders.append( Rider(tableCels[1].text, tableCels[2].text, tableCels[3].text, int(tableCels[4].text), int(tableCels[5].text))) else: listOfRiders.append( Rider(tableCels[1].text, tableCels[2].text, "", int(tableCels[3].text), int(tableCels[4].text))) return listOfRiders
def create_event_list(filename): """Return a list of Events based on raw list of events in <filename>. Precondition: the file stored at <filename> is in the format specified by the assignment handout. @param filename: str The name of a file that contains the list of events. @rtype: list[Event] """ events = [] with open(filename, "r") as file: for line in file: line = line.strip() if not line or line.startswith("#"): # Skip lines that are blank or start with #. continue # Create a list of words in the line, e.g. # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15']. # Note that these are strings, and you'll need to convert some # of them to a different type. tokens = line.split() timestamp = int(tokens[0]) event_type = tokens[1] # Append the event when the event is DriverRequest if event_type == "DriverRequest": identification = tokens[2] location = deserialize_location(tokens[3]) speed = int(tokens[4]) event = DriverRequest(timestamp, Driver(identification, location, speed)) events.append(event) # Append the event when the event is RiderRequest elif event_type == "RiderRequest": identification = tokens[2] origin = deserialize_location(tokens[3]) destination = deserialize_location(tokens[4]) patience = int(tokens[5]) event = RiderRequest( timestamp, Rider(identification, origin, destination, patience)) events.append(event) return events
def new_rider(self, start_floor_num, destination_floor_num, elapsed): if not (0 <= start_floor_num < len(self.floors) and 0 <= destination_floor_num < len(self.floors)): raise ValueError( f'scenario wanted ride between floors {start_floor_num} and {destination_floor_num}; ' f'building is {len(self.floors)} tall') if start_floor_num == destination_floor_num: raise ValueError( f'scenario wanted ride from floor {start_floor_num} to itself') rider = Rider(start_floor_num, destination_floor_num) self._all_riders.append(rider) self.floors[start_floor_num].add_waiting_rider(rider) if self._trace_riders: self.add_message( 'RDR', elapsed, f'new rider R{rider.number} wants to go from {start_floor_num} to {destination_floor_num}' ) return rider
def create_event_list(filename): """Return a list of Events based on raw list of events in <filename>. Precondition: the file stored at <filename> is in the format specified by the assignment handout. @param filename: str The name of a file that contains the list of events. @rtype: list[Event] """ events = [] with open(filename, "r") as file: for line in file: line = line.strip() if not line or line.startswith("#"): # Skip lines that are blank or start with #. continue # Create a list of words in the line, e.g. # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15']. tokens = line.split() timestamp = int(tokens[0]) event_type = tokens[1] if event_type == "DriverRequest": #Create DriverRequest event. driverObject = Driver(tokens[2], deserialize_location(tokens[3]), int(tokens[4])) event = DriverRequest(timestamp, driverObject) elif event_type == "RiderRequest": # Create a RiderRequest event. riderObject = Rider(tokens[2], deserialize_location(tokens[3]), deserialize_location(tokens[4]), int(tokens[5])) event = RiderRequest(timestamp, riderObject) events.append(event) return events
def read(self, file): lines = [list(map(int, l.split(' '))) for l in file] self.num_row = lines[0][0] self.num_col = lines[0][1] self.bonus = lines[0][4] self.max_step = lines[0][5] self.vehicles = [Vehicle(i, bonus=self.bonus, bonus_weigth=self.bonus_weight) for i in range(lines[0][2])] rider_index = 0 for l in lines[1:]: r = Rider( index=rider_index, start_intersection=(l[0], l[1]), ending_intersection=(l[2], l[3]), earliest=l[4], latest=l[5], bonus=self.bonus ) self.riders.append(r) rider_index += 1
def __init__(self, number, rider=None, horse=None): self.number = number self.rider = rider if rider else Rider() self.horse = horse if horse else Horse()
def setUp(self): self.rider = Rider("Koichi Oguri", 86) self.horse = Horse("Oguri Cap", 25, self.rider)
def setUp(self): self.rider = Rider("Koichi Oguri", 86)
def createRider(color, square, lane, specialist): rider = Rider(specialist.name, Cards(specialist.deck, random.shuffle), riderMove.Rider(square, lane)) rider.shade = specialist.shade rider.color = color return rider
def load_riders(self): self.riders = list() for req in self.req_handler.request_dict[self.current_time]: self.riders.append(Rider(req['start'], req['end'], req['name']))
def createRider(square, lane): return Rider("Tac", Cards([]), riderMove.Rider(square, lane))
def setUp(self): self.rider = Rider(0, 2, 10, (1, 1), (4, 4), 2) self.next_rider = Rider(0, 9, 15, (2, 2), (3, 3), 2) self.vehicle = Vehicle(0, 2)
from rider import Rider team_names = [ "Wrocław", "Leszno", "Grudziądz", "Częstochowa", "Tarnów", "Zielona Góra", "Gorzów Wlkp.", "Toruń" ] league = [[[0, 1], [2, 3], [4, 5], [6, 7]], [[3, 4], [7, 0], [5, 2], [1, 6]], [[2, 1], [5, 3], [4, 7], [0, 6]], [[1, 5], [7, 2], [6, 4], [3, 0]], [[2, 6], [4, 0], [5, 7], [1, 3]], [[7, 1], [4, 2], [0, 5], [6, 3]], [[5, 6], [0, 2], [3, 7], [1, 4]], [[6, 5], [4, 1], [2, 0], [7, 3]], [[5, 0], [2, 4], [1, 7], [3, 6]], [[0, 4], [7, 5], [6, 2], [3, 1]], [[0, 3], [5, 1], [4, 6], [2, 7]], [[6, 0], [1, 2], [3, 5], [7, 4]], [[6, 1], [4, 3], [0, 7], [2, 5]], [[5, 4], [1, 0], [3, 2], [7, 6]]] rider_1 = Rider("Piotr", "Pawlicki", 150) rider_2 = Rider("Niki", "Pedersen", 150) rider_3 = Rider("Fredrik", "Lindgren", 149) rider_4 = Rider("Bartosz", "Zmarzlik", 149) rider_5 = Rider("Janusz", "Kołodziej", 148) rider_6 = Rider("Patryk", "Dudek", 148) rider_7 = Rider("Tai", "Woffinden", 147) rider_8 = Rider("Krzysztof", "Kasprzak", 147) rider_9 = Rider("Emil", "Sajfutdinow", 146) rider_10 = Rider("Maksym", "Drabik", 146) rider_11 = Rider("Maciej", "Janowski", 145) rider_12 = Rider("Leon", "Madsen", 145) rider_13 = Rider("Artiom", "Łaguta", 144) rider_14 = Rider("Kenneth", "Bjerre", 144) rider_15 = Rider("Jarosław", "Hampel", 143) rider_16 = Rider("Grzegorz", "Zengota", 143)
def test_is_not_the_same(self): another_rider = Rider("Koichi Oguri", 86) self.assertEqual(False, i.is_the_same(self.rider, another_rider))
def simulation(env, db_name, debug_, obf_class_size, num_riders, num_drivers, gen_utility, obf_level, env_time, eta_tolerance, dd_surge_neg, dd_surge_less_than_one, dd_surge_more_than_one, req_delay, mech_name, privacy_level, regression_data_file, d_regression_data_file, mech_number, count, exp_folder, z_qlg, g_res, alpha, geo_lat, geo_lon, uniform_eta=1, uniform_dm=1, uniform=1, r_uniform=1, g_remap=0): # Name of file to save data to gen_utility_name = 'NA' if gen_utility == None else str( int(1000 * gen_utility)) privacy_level_name = str(privacy_level) obf_level_name = 'NA' if obf_level == None else str(obf_level) foldername = exp_folder + '/results_' + str( eta_tolerance ) + '_' + dd_surge_neg + '_' + dd_surge_less_than_one + '_' + dd_surge_more_than_one + '_' + str( num_riders) + '_' + str(num_drivers) + '_' + str(gen_utility) if not os.path.exists(foldername): os.makedirs(foldername) filename = foldername + '/rider_results_' + mech_name + '_' + str( obf_class_size ) + '_' + str(num_riders) + '_' + str(num_drivers) + '_' + str( env_time ) + '_' + gen_utility_name + '_' + privacy_level_name + '_' + obf_level_name + '_' + str( eta_tolerance) + '_' + str(count) + '.csv' filename_d = foldername + '/driver_results_' + mech_name + '_' + str( obf_class_size ) + '_' + str(num_riders) + '_' + str(num_drivers) + '_' + str( env_time ) + '_' + gen_utility_name + '_' + privacy_level_name + '_' + obf_level_name + '_' + str( eta_tolerance) + '_' + str(count) + '.csv' # Connect to mongodb database client = MongoClient() mongoClient = MongoClient('mongodb://localhost', 27017) # Create server, riders, drivers, globals database = mongoClient[db_name] server = Server(database, debug_, z_qlg) riderIDs = list(mongoClient[db_name].riders.distinct("userID")) for i in range(num_riders): server.riderObjects.append( Rider(i, server, debug_, gen_utility, obf_level, req_delay, mech_name, privacy_level, z_qlg, g_res, alpha, geo_lat, geo_lon, r_uniform, g_remap)) for i in range(num_drivers): server.driverObjects.append( Driver(i, server, debug_, eta_tolerance, dd_surge_neg, dd_surge_less_than_one, dd_surge_more_than_one, gen_utility, mech_name, privacy_level, z_qlg, g_res, uniform_eta, uniform_dm, uniform)) env.process(server.run(env)) for i in range(num_riders): env.process(server.riderObjects[i].run(env)) for i in range(num_drivers): env.process(server.driverObjects[i].run(env)) # driver_ops = threading.Thread(target=manage_drivers, args=(server, env)) # driver_ops.daemon = True while True: if env.now == env_time - 1: print( '============== Calculating utility loss due to incomplete rides ==============' ) etaEstimate(server, env_time, database, uniform_eta) if env.now != 0 and (env.now % 20 == 0 or env.now % (env_time - 1) == 0): driverUtilCSV(server, foldername, filename_d, dd_surge_neg, dd_surge_less_than_one, dd_surge_more_than_one, gen_utility, mech_name) generateCSV(server, foldername, filename, obf_class_size, num_riders, num_drivers, dd_surge_neg, dd_surge_less_than_one, dd_surge_more_than_one, mech_name, count, gen_utility) # if env.now == env_time - 1: # generate_regression_data(server, num_riders, num_drivers, regression_data_file, eta_tolerance, mech_number, dd_surge_neg, dd_surge_less_than_one, dd_surge_more_than_one) # d_generate_regression_data(server, num_riders, num_drivers, d_regression_data_file, eta_tolerance, mech_number, dd_surge_neg, dd_surge_less_than_one, dd_surge_more_than_one) num_requests = int(num_riders / 50) # num_requests=4 if env.now <= (env_time / 4): # print('check ',env.now,env_time) if server.serviceActive == False: server.serviceActive = True if env.now == 0: pass # print('Num request are ',num_requests) rider_ids = np.random.randint(0, (num_riders - 1), num_requests) for t in range(len(rider_ids)): server.pendingRiders.append(rider_ids[t]) yield env.timeout(1) print("Time: {}".format(env.now))
def create_event_list(filename): """Return a list of Events based on raw list of events in <filename>. Precondition: the file stored at <filename> is in the format specified by the assignment handout. @param filename: str The name of a file that contains the list of events. @rtype: list[Event] """ events = [] with open(filename, "r") as file: for line in file: line = line.strip() if not line or line.startswith("#"): # Skip lines that are blank or start with #. continue # Create a list of words in the line, e.g. # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15']. # Note that these are strings, and you'll need to convert some # of them to a different type. tokens = line.split() timestamp = int(tokens[0]) event_type = tokens[1] # HINT: Use Location.deserialize to convert the location string to # a location. if event_type == "DriverRequest": # Create a DriverRequest event. driver = Driver(tokens[2], deserialize_location(tokens[3]), int(tokens[4])) event = DriverRequest(timestamp, driver) events.append(event) elif event_type == "RiderRequest": # Create a RiderRequest event. rider = Rider(tokens[2], deserialize_location(tokens[3]), deserialize_location(tokens[4]), int(tokens[5])) event = RiderRequest(timestamp, rider) events.append(event) return events # Sample Event List # The parser will skip empty lines, lines with whitespace only, # or those that start with '#'. # The format for DriverRequest events is: # <timestamp> DriverRequest <driver id> <location> <speed> # <location> is <row>,<col> 0 DriverRequest Amaranth 1,1 1 0 DriverRequest Bergamot 1,2 1 0 DriverRequest Crocus 3,1 1 0 DriverRequest Dahlia 3,2 1 0 DriverRequest Edelweiss 4,2 1 0 DriverRequest Foxglove 5,2 1 # The format for RiderRequest events is: # <timestamp> RiderRequest <rider id> <origin> <destination> <patience> # <origin>, <destination> are <row>,<col> 0 RiderRequest Almond 1,1 5,5 10 5 RiderRequest Bisque 3,2 2,3 5 10 RiderRequest Cerise 4,2 1,5 15 15 RiderRequest Desert 5,1 4,3 5 20 RiderRequest Eggshell 3,4 3,1 1 25 RiderRequest Fallow 2,1 2,5 10 #At time 1, Dan exists #Dan is at location 1,1, requests a driver, and is willing #to wait 15 units of time for pickup before he cancels 1 RiderRequest Dan 1,1 6,6 15 #At time 10, Arnold exists #Arnold is at location 3,3, requests a rider, #and Arnold's car moves 2 units of distance per unit time 10 DriverRequest Arnold 3,3 2 class Location: """ Our simulation plays out on a simplified grid of city blocks. Each location is specified by a pair of (row, column) Attribute: ========== @type row: non-negative integer number of blocks from the bottom @type column: non-negative integer number of blocks from the left """ def __init__(self, row, column): """Initialize a location. @type self: Location @type row: int @type column: int @rtype: None """ self.row = row self.column = column def __str__(self): """Return a string representation. @type self: Location @rtype: str >>> l = Location (2,3) >>> print(l) 2,3 """ return "{},{}".format(self.row, self.column) def __eq__(self, other): """Return True if self equals other, and false otherwise. @type self:Location @type other: Location | Any @rtype: bool >>> l1 = Location (3,4) >>> l2 = Location (3, 4) >>> l3 = Location (5,6) >>> l1 == l2 True >>> l1 == l3 False """ return (type(self) == type(other) and self.column == other.column and self.row == other.row) def manhattan_distance(origin, destination): """Return the Manhattan distance between the origin and the destination. @type origin: Location @type destination: Location @rtype: int >>> manhattan_distance(Location(2,3),Location(5,7)) 7 >>> manhattan_distance(Location(2,3),Location(2,7)) 4 """ return (abs(origin.column - destination.column) + abs(origin.row - destination.row)) def deserialize_location(location_str): """Deserialize a location. @type location_str: str A location in the format 'row,col' @rtype: Location >>> d1 = deserialize_location('24,35') >>> print (d1) 24,35 >>> d2 = deserialize_location('6,4') >>> print(d2) 6,4 """ l = Location(0, 0) index_comma = location_str.find(',') l.row = int(location_str[:index_comma]) l.column = int(location_str[index_comma+1:]) return l if __name__ == "__main__": import doctest doctest.testmod() from location import Location from location import manhattan_distance """ The Monitor module contains the Monitor class, the Activity class, and a collection of constants. Together the elements of the module help keep a record of activities that have occurred. Activities fall into two categories: Rider activities and Driver activities. Each activity also has a description, which is one of request, cancel, pickup, or dropoff. === Constants === @type RIDER: str A constant used for the Rider activity category. @type DRIVER: str A constant used for the Driver activity category. @type REQUEST: str A constant used for the request activity description. @type CANCEL: str A constant used for the cancel activity description. @type PICKUP: str A constant used for the pickup activity description. @type DROPOFF: str A constant used for the dropoff activity description. """ RIDER = "rider" DRIVER = "driver" REQUEST = "request" CANCEL = "cancel" PICKUP = "pickup" DROPOFF = "dropoff" class Activity: """An activity that occurs in the simulation. === Attributes === @type timestamp: int The time at which the activity occurred. @type description: str A description of the activity. @type identifier: str An identifier for the person doing the activity. @type location: Location The location at which the activity occurred. """ def __init__(self, timestamp, description, identifier, location): """Initialize an Activity. @type self: Activity @type timestamp: int @type description: str @type identifier: str @type location: Location @rtype: None """ self.description = description self.time = timestamp self.id = identifier self.location = location class Monitor: """A monitor keeps a record of activities that it is notified about. When required, it generates a report of the activities it has recorded. """ # === Private Attributes === # @type _activities: dict[str, dict[str, list[Activity]]] # A dictionary whose key is a category, and value is another # dictionary. The key of the second dictionary is an identifier # and its value is a list of Activities. def __init__(self): """Initialize a Monitor. @type self: Monitor """ self._activities = { RIDER: {}, DRIVER: {} } """@type _activities: dict[str, dict[str, list[Activity]]]""" def __str__(self): """Return a string representation. @type self: Monitor @rtype: str >>> m = Monitor() >>> A1 = Activity(1,"request","Chris",Location(0,0)) >>> A2 = Activity(3,"pickup","Chris",Location(10,2)) >>> A3 = Activity(5,"request","Jack",Location(1,3)) >>> A4 = Activity(6,"pickup","Louis",Location(6,7)) >>> A5 = Activity(2,"request","Chen",Location(3,3)) >>> A6 = Activity(6,"cancel","Chen",Location(3,3)) >>> A7 = Activity(10,"pickup","LK",Location(0,0)) >>> m._activities = {RIDER:{"Chen":[A5,A6],"Jack":[A3]},\ DRIVER:{"Chris":[A1,A2],"Louis":[A4],"LK":[A7]}} >>> print(m) Monitor (3 drivers, 2 riders) """ return "Monitor ({} drivers, {} riders)".format( len(self._activities[DRIVER]), len(self._activities[RIDER])) def notify(self, timestamp, category, description, identifier, location): """Notify the monitor of the activity. @type self: Monitor @type timestamp: int The time of the activity. @type category: DRIVER | RIDER The category for the activity. @type description: REQUEST | CANCEL | PICKUP | DROP_OFF A description of the activity. @type identifier: str The identifier for the actor. @type location: Location The location of the activity. @rtype: None """ if identifier not in self._activities[category]: self._activities[category][identifier] = [] activity = Activity(timestamp, description, identifier, location) self._activities[category][identifier].append(activity) def report(self): """Return a report of the activities that have occurred. @type self: Monitor @rtype: dict[str, object] """ return {"rider_wait_time": self._average_wait_time(), "driver_total_distance": self._average_total_distance(), "driver_ride_distance": self._average_ride_distance()} def _average_wait_time(self): """Return the average wait time of riders that have either been picked up or have cancelled their ride. @type self: Monitor @rtype: float >>> m1 = Monitor() >>> A1 = Activity(1,"request","Chris",Location(0,0)) >>> A2 = Activity(3,"pickup","Chris",Location(10,2)) >>> A3 = Activity(5,"request","Jack",Location(1,3)) >>> A4 = Activity(6,"request","Louis",Location(6,7)) >>> A5 = Activity(2,"request","Chen",Location(3,3)) >>> A6 = Activity(6,"cancel","Chen",Location(3,3)) >>> A7 = Activity(9,"pickup","Louis",Location(0,0)) >>> m1._activities = {RIDER:{"Chris":[A1,A2],"Jack":[A3],\ "Louis":[A4,A7],"Chen":[A5,A6]},DRIVER:{}} >>> m1.average_wait_time() 3.0 """ wait_time = 0 count = 0 for activities in self._activities[RIDER].values(): # A rider that has less than two activities hasn't finished # waiting (they haven't cancelled or been picked up). if len(activities) >= 2: # The first activity is REQUEST, and the second is PICKUP # or CANCEL. The wait time is the difference between the two. wait_time += activities[1].time - activities[0].time count += 1 return wait_time / count @property def average_wait_time(self): return self._average_wait_time() def _average_total_distance(self): """Return the average distance drivers have driven. @type self: Monitor @rtype: float >>> m2 = Monitor() >>> A1 = Activity(1,"request","Chris",Location(0,0)) >>> A2 = Activity(3,"pickup","Chris",Location(10,2)) >>> A3 = Activity(5,"dropoff","Chris",Location(1,3)) >>> A4 = Activity(6,"request","Louis",Location(6,7)) >>> A5 = Activity(2,"request","Chen",Location(3,3)) >>> A6 = Activity(6,"cancel","Chen",Location(4,3)) >>> A7 = Activity(9,"cancel","Louis",Location(0,0)) >>> m2._activities = {RIDER:{},DRIVER:{"Chris":[A1,A2,A3],\ "Louis":[A4,A7],"Chen":[A5,A6]}} >>> m2.average_total_distance() 12.0 """ total_distance = 0 num_drivers = len(self._activities[DRIVER]) for activities in self._activities[DRIVER].values(): i = 1 while i < len(activities): total_distance += manhattan_distance(activities[i].location, activities[i- 1].location) i += 1 return total_distance / num_drivers @property def average_total_distance(self): return self._average_total_distance() def _average_ride_distance(self): """Return the average distance drivers have driven on rides. @type self: Monitor @rtype: float >>> m3 = Monitor() >>> A1 = Activity(1,"request","Chris",Location(0,0)) >>> A2 = Activity(3,"pickup","Chris",Location(10,2)) >>> A3 = Activity(5,"dropoff","Chris",Location(1,3)) >>> A4 = Activity(6,"request","Louis",Location(6,7)) >>> A5 = Activity(2,"request","Chen",Location(3,3)) >>> A6 = Activity(6,"pickup","Chen",Location(4,0)) >>> A7 = Activity(10,"dropoff","Chen",Location(13,20)) >>> A8 = Activity(9,"cancel","Louis",Location(0,0)) >>> m3._activities = {RIDER:{},DRIVER:{"Chris":[A1,A2,A3],\ "Louis":[A4,A8],"Chen":[A5,A6,A7]}} >>> m3.average_ride_distance() 13.0 """ ride_distance = 0 num_drivers = len(self._activities[DRIVER]) for activities in self._activities[DRIVER].values(): for activity in activities: if activity.description == PICKUP: i = activities.index(activity) ride_distance += manhattan_distance( activities[i + 1].location, activities[i].location) return ride_distance / num_drivers @property def average_ride_distance(self): return self._average_ride_distance() from location import Location """ The rider module contains the Rider class. It also contains constants that represent the status of the rider. === Constants === @type WAITING: str A constant used for the waiting rider status. @type CANCELLED: str A constant used for the cancelled rider status. @type SATISFIED: str A constant used for the satisfied rider status """ WAITING = "waiting" CANCELLED = "cancelled" SATISFIED = "satisfied" class Rider: """A rider for a ride-sharing service. === Attributes === @type id: str A unique identifier for the rider. @type origin: Location The starting location @type destination: Location The ending location @type status: str WAITING, CANCELLED or SATISFIED @type patience: int The number of time units the rider will wait to be picked up before they cancel their ride """ def __init__(self, identifier, origin, destination, patience): """Initialize a Driver. @type self:Rider @type identifier: str @type origin: Location @type destination: Location @type patience: int @rtype: None """ self.id = identifier self.origin = origin self.destination = destination self.patience = patience self.status = WAITING def __str__(self): """Return a string representation. @type self: Rider @rtype: str >>> r = Rider("Alex",Location(1,2),Location(3,4), 12) >>> print(r) Alex 1,2 3,4 12 """ return "{} {} {} {}".format(self.id, self.origin, self.destination, self.patience) def __eq__(self, other): """Return True if self equals other, and false otherwise. @type self: Rider @type other: Rider | Any @rtype:bool >>> r1 = Rider("Alex",Location(1,2),Location(3,4), 10) >>> r2 = Rider("Alex",Location(1,2),Location(3,4),10) >>> r3 = Rider("Shawn",Location(3,2),Location(2,4), 15) >>> r1 == r2 True >>> r1 == r3 False """ return (type(self) == type(other) and self.id == other.id and self.origin == other.origin and self.destination == other.destination and self.patience == other.patience) if __name__ == "__main__": import doctest doctest.testmod() from container import PriorityQueue from dispatcher import Dispatcher from event import create_event_list from monitor import Monitor class Simulation: """A simulation. This is the class which is responsible for setting up and running a simulation. The API is given to you: your main task is to implement the run method below according to its docstring. Of course, you may add whatever private attributes and methods you want. But because you should not change the interface, you may not add any public attributes or methods. This is the entry point into your program, and in particular is used for auto-testing purposes. This makes it ESSENTIAL that you do not change the interface in any way! """ # === Private Attributes === # @type _events: PriorityQueue[Event] # A sequence of events arranged in priority determined by the event # sorting order. # @type _dispatcher: Dispatcher # The dispatcher associated with the simulation. def __init__(self): """Initialize a Simulation. @type self: Simulation @rtype: None """ self._events = PriorityQueue() self._dispatcher = Dispatcher() self._monitor = Monitor() def run(self, initial_events): """Run the simulation on the list of events in <initial_events>. Return a dictionary containing statistics of the simulation, according to the specifications in the assignment handout. @type self: Simulation @type initial_events: list[Event] An initial list of events. @rtype: dict[str, object] """ # Add all initial events to the event queue. for event in initial_events: self._events.add(event) while self._events.is_empty() is False: executed_event = self._events.remove() result_events = executed_event.do(self._dispatcher, self._monitor) # this warning can be ignored if result_events is not None: for result_event in result_events: self._events.add(result_event) # Until there are no more events, remove an event # from the event queue and do it. Add any returned # events to the event queue. return self._monitor.report() if __name__ == "__main__": events = create_event_list("events.txt") sim = Simulation() final_stats = sim.run(events) print(final_stats)
origin = deserialize_location(tokens[3]) destination = deserialize_location(tokens[4]) patience = int(tokens[5]) status = 'waiting' rider = Rider(_id, status, patience, origin, destination) event = RiderRequest(timestamp, rider) events.append(event) return events if __name__ == "__main__": import doctest doctest.testmod() dispatcher = Dispatcher() monitor = Monitor() rider_Bathe = Rider('Bathe', WAITING, 5, Location(1, 2), Location(5, 8)) driver_Atom = Driver('Atom', Location(0, 0), 1) rider_rq = RiderRequest(0, rider_Bathe) print(rider_rq) cancellation = rider_rq.do(dispatcher, monitor)[0] driver_rq = DriverRequest(1, driver_Atom) print(driver_rq) pickup = driver_rq.do(dispatcher, monitor)[0] print(pickup) print(cancellation) dropoff = pickup.do(dispatcher, monitor)[0] print(dropoff) driver_rq1 = dropoff.do(dispatcher, monitor)[0] print(driver_rq1)
@param self: Dispatcher @param rider: Rider @rtype: None >>> rider_Bathe = Rider('Bathe','waiting', 5, Location(1,2), Location(5,8)) >>> dispatcher = Dispatcher() >>> print(dispatcher.request_driver(rider_Bathe)) None >>> print(dispatcher.cancel_ride(rider_Bathe)) None """ try: self.waiting_riders.remove(rider) except IndexError: print('No waiting riders!!!') except ValueError: print('The rider is not waiting!!!') if __name__ == "__main__": import doctest doctest.testmod() dispatcher = Dispatcher() rider1 = Rider('rider1', 'waiting', 5, Location(1, 2), Location(5, 8)) driver1 = Driver('driver1', Location(10, 9), 1) print(dispatcher.request_driver(rider1)) print(dispatcher.request_rider(driver1)) dispatcher.cancel_ride(rider1) print(dispatcher)