def setUpClass(cls): print("setUpClass()") # Initialize airports cls.Logan = Airport() cls.JFK = Airport() cls.Logan.set_name("Logan") cls.JFK.set_name("JFK") # Initialize passengers cls.Ben = Passenger("Ben") cls.Julia = Passenger("Julia") cls.Jamie = Passenger("Jamie") # Initialize flights cls.flightLoganToJFK = Flight.airports_to_from(cls.Logan, cls.JFK) # Flight 1 cls.flightLoganToJFK.set_flight_number("UA1161") cls.flightLoganToJFK.set_flight_date("04-27-2020") cls.flightLoganToJFK.set_flight_time("4:30pm") cls.flightLoganToJFK.set_airline("United Airlines") # Add flights to airport cls.Logan.add_flight(cls.flightLoganToJFK) cls.JFK.add_flight(cls.flightLoganToJFK)
def schedule(self): count = 0 while True: count += 1 destination = random.choice(destinations) trip = Journey("A", destination) passenger = Passenger(count, self.env, trip) print("Sending passenger %d on the trip %s at %d" % (count, trip, self.env.now)) self.env.process(passenger.wait_for_train(self.train_stop)) yield self.env.timeout(5)
def group_AssignSeat(airplane, df, group_list, offset_dict): success = 0 # Filter from all groups to groups of this size group_df = find_members_in_group(df[df['group_size'] == len(group_list)], group_list) sort_on = ['number_of_flags', 'age'] group_df = group_df.sort_values(by=sort_on, ascending=False) group_df = group_df.reset_index(drop=True) # iterate through each member in this group for row in group_df.index: # this_row = group_df[group_df.index == row] pID = group_df.loc[row, 'pID'] this_psgr = Passenger(pID) age = group_df.loc[row, 'age'] group = group_df.loc[row, 'group'] has_travelled = group_df.loc[row, 'has_travelled'] has_precon = group_df.loc[row, 'has_preexisting_condition'] this_psgr.fill_questionare(age, group, has_travelled, has_precon) this_offset_detail = offset_selector(airplane, this_psgr, offset_dict) this_offset = this_offset_detail['offset'] group_df.loc[row, 'offset_order'] = this_offset_detail['order'] group_df.loc[row, 'offset_x'] = this_offset['x'] group_df.loc[row, 'offset_y'] = this_offset['y'] group_df.loc[row, 'offset_method'] = this_offset['method'] #group passenger seating method # Allowed Group Passenger Seat_State = 'G' blocked_seat_list = SocialDistance(airplane, this_offset, occupied_state='G') SeatPassenger(airplane, blocked_seat_list, occupied_state='G') #if prev_assigned_seat is not None and success < len(group_list)-1: # assert prev_assigned_seat != airplane.last_assigned_seat, "Unable to Seat" group_df.loc[row, 'seat'] = airplane.last_assigned_seat success += 1 group_find_next_seat(airplane) airplane.update() assert success == len(group_list), "NOT ALL PASSENGERS IN GROUP SEATED" group_ToggleState(airplane, group_df) group_find_next_seat(airplane) return group_df ###################################################################################################
def login(): url = request.url if "demo" not in url: session["demo"] = False passenger = Passenger({ "id_type": url.split("id_type=")[1].split("&")[0], "data": url.split("data=")[1], "demo": False }) else: session["demo"] = True passenger = Passenger({"demo": True}) session["passenger"] = passenger.uid with open("pickle/" + passenger.uid + ".pickle", "wb") as f: pickle.dump(passenger, f) return redirect(url_for("welcome"))
def init_synthethic_dataset(self): self.database = {} passengers = [Passenger(name) for name in ["john green", \ "louie anderson", \ "liza koshy"]] bookings = [Booking(*booking) for booking in [("AMS", "ZRH", "10-Dec-2018"), \ ("LHR", "AMS", "01-Jan-2019"), \ ("BER", "ARN", "02-Mar-2019")]] flights = [Flight(*flight) for flight in \ [("KLM", "AMS", "BSL", "10-Dec-2018", 200), \ ("SWISS", "BSL", "ZRH", "10-Dec-2018", 100), \ ("KLM", "LHR", "AMS", "01-Jan-2019", 300), \ ("Eurowings", "BER", "ARN", "02-Mar-2019", 300)]] tickets = [Ticket(*ticket) for ticket in \ [(passengers[0], flights[0], "economy"), (passengers[0], flights[1], "economy"), (passengers[1], flights[2], "business"), \ (passengers[2], flights[3], "economy")]] bookings[0].add_ticket(tickets[0]) bookings[0].add_ticket(tickets[1]) bookings[1].add_ticket(tickets[2]) bookings[2].add_ticket(tickets[3]) self.database["passengers"] = passengers self.database["bookings"] = bookings self.database["flights"] = flights self.database["tickets"] = tickets self.database["name_to_tickets"] = { passenger.name: [] for passenger in passengers } for ticket in tickets: self.database["name_to_tickets"][ticket.client.name] += [ticket]
def main(): num_passengers = int(input("How many passengers does the building have?")) num_floors = int(input("How many floors does the building have?")) strategy = int(input("Which strategy do you want to use? (1 for FIFO, 2 for move-to-max-min)")) building = Building(num_passengers, num_floors) elevator = Elevator(num_floors) passengers = [] for i in range(num_passengers): start_floor = random.choice(range(elevator.n_floors)) destination_floor = random.choice(range(elevator.n_floors)) while start_floor == destination_floor: destination_floor = random.choice(range(elevator.n_floors)) passenger = Passenger(start_floor, destination_floor) passengers.append(passenger) elevator.add_call(passenger.start_floor, passenger.destination, passenger) if strategy == 1: for passenger in passengers: elevator.FIFO() else: elevator.max_floor_strategy() print "\n" costs = [] for passenger in passengers: costs.append(passenger.time_cost) print "Average cost: ", np.mean(costs), " floors" print "Average squared cost: ", np.mean([i**2 for i in costs]), " floors" print "Median cost: ", np.median(costs), " floors" print "Maximum cost: ", max(costs), " floors"
def load_bus(self, name, boarding, destination,): if self.checkSeat(): passenger = Passenger(name, boarding, destination) self.buss_passangers.append(passenger) else: return self.buss_passangers return self.buss_passangers
def buildPassengers(count, result, lines): for i in range(count): p = Passenger( i, getRandomPath(result, [node.id for line in lines for node in line.nodes])) yield p
def main(): airport_names = ['JFK', 'LAX', 'ATL', 'DFW'] # string flight_num, string airline, string date, string time flight_info = [["UA1215", "United Airlines", "3/20/2020", "3:30pm"], ["UA1438", "United Airlines", "3/20/2020", "3:45pm"], ["UA3455", "United Airlines", "3/20/2020", "4:00pm"], ["UA4234", "United Airlines", "3/20/2020", "4:15pm"]] # read_csv of names df = pd.read_csv('baby_names.csv') # get name values names = df['NAME'].values # these will become Passenger()'s # Initialize airports airports = initialize_airports(airport_names) # Initialize flights initialize_flights(flight_info, airports) # Display the airport data created thus far print_data(airports) for airport in airports: for flight in airport.get_flights(): for i in range(25 + np.random.randint(0, 200)): passenger = Passenger(names[np.random.choice(len(names), 1)]) flight.add_passenger(passenger)
def tick(self): if (self.environment.get_clock() % self.environment.TICKS_NEEDED_TO_GENERATE_PASSENGER) == 0: for i in range(self.environment.PASSENGERS_TO_BE_GENERATED): # GET ID FROM ENVIRONMENT PASSENGER LIST i + 0 # HACK: fix unused variable warning p = Passenger(self.environment) self.environment.add_passenger(p)
def increment_time(self, request_json): requests_to_process = self.get_requests_to_process(request_json) new_pickups = [Passenger(person) for person in requests_to_process] self.car.pickup_requests.extend(new_pickups) next_destination = self.get_next_destination() self.car.move(next_destination.location) self.car.do_pickups() self.car.do_dropoffs() self.car.print_status()
def passengers(self): list_pass = [] for i in range(self.pass_count): flight = self.flights[random.randint(0, len(self.flights) - 1)] list_pass.append( Passenger(random.choice(self.first_names), random.choice(self.last_names), flight, random.randint(1, 100))) return list_pass
def add_passengers(self, stages_list): diff = self.max_num_of_passengers - len(self.passengers) if diff > 0: # Объекту пассажира передается объект его целевого этажа с использованием модуля random nbuilding = stages_list[:] nbuilding.remove(self) # Из списка исключается текущий этаж for _ in range(diff): self.passengers.append(Passenger(random.choice(nbuilding))) # Переинициализация состояния кнопок этажа self.initialize_floor_buttons()
def _handleArrival(self, curTime): """ Makes changes according to 1st rule. """ prob_number = random.random() if prob_number <= self._arriveProb: self._numPassengers += 1 passenger = Passenger(self._numPassengers, curTime) self._passengerQ.enqueue(passenger) print(f"Time {curTime}: Passenger {self._numPassengers} arrived.")
def generate_boarding(self, plane_length): passengers = list() seatList = set() while len(seatList) is not 6 * plane_length: seatList.add((randint(1, plane_length), chr(randint(65, 70)))) for seat in seatList: passengers.append(Passenger(seat[0], seat[1], randint(0, 2))) self.plane = Plane(plane_length) passengers.reverse() self.plane.add_passengers(passengers) return passengers
def read_passengers(in_file): passengers = {} with open(in_file, 'r') as file: reader = csv.reader(file) for row in reader: try: tmp = Passenger(int(row[0]), int(row[1]), int(row[2])) passengers[tmp.id] = tmp except: pass return passengers
def _handleArrive(self, curTime): """ Rule 1: If a customer arrives, he is added to the queue. At most, one customer can arrive during each time step. """ if random.random() <= self._arriveProb: self._numPassengers += 1 thePassenger = Passenger(self._numPassengers, curTime) print("Time {}: Passenger {} arrived.".format( curTime, self._numPassengers)) self._passengerQ.add(thePassenger)
def _get_states(self): states = {} state_to_no = {} no_to_state = {} state_count = 0 no_of_dests = self.no_of_rows * self.no_of_cols no_of_locs = no_of_dests + 1 #+ 1 for being in taxi #What a mess - think of a way to eliminate the nestedness for taxi_loc in range(no_of_dests): for pass1_loc in range(no_of_locs): for pass2_loc in range(no_of_locs): for pass1_dest in range(no_of_dests): for pass2_dest in range(no_of_dests): #if pass1_loc == pass1_dest == pass2_loc == pass2_dest: continue state = self.encode(taxi_loc, pass1_loc, pass2_loc, pass1_dest, pass2_dest) taxi = Taxi(taxi_loc, 0, self.taxi_max_capacity) pass1 = Passenger(1, pass1_loc, pass1_dest) pass2 = Passenger(2, pass2_loc, pass2_dest) if pass1_loc == self.position_in_taxi: taxi.pickup_passenger(pass1) if pass2_loc == self.position_in_taxi: taxi.pickup_passenger(pass2) if pass1_loc == pass1_dest: taxi.pickup_passenger(pass1) taxi.drop_passenger(pass1) if pass2_loc == pass2_dest: taxi.pickup_passenger(pass2) taxi.drop_passenger(pass2) states[state] = [taxi, pass1, pass2] state_to_no[state] = state_count no_to_state[state_count] = state state_count = state_count + 1 return states, state_to_no, no_to_state
def single_AssignSeat(airplane, df, offset_info): sort_on = ['number_of_flags', 'age'] df = df.sort_values(by=sort_on, ascending=False) for row in df.index: pID = df.loc[row, 'pID'] this_psgr = Passenger(pID) age = df.loc[row, 'age'] group = [] has_travelled = df.loc[row, 'has_travelled'] has_precon = df.loc[row, 'has_preexisting_condition'] this_psgr.fill_questionare(age, group, has_travelled, has_precon) condition_count = len(df[df['has_preexisting_condition'] == True]) this_offset_detail = offset_selector(airplane, this_psgr, offset_info, limiter=condition_count) this_offset = this_offset_detail['offset'] df.loc[row, 'offset_order'] = this_offset_detail['order'] df.loc[row, 'offset_x'] = this_offset['x'] df.loc[row, 'offset_y'] = this_offset['y'] df.loc[row, 'offset_method'] = this_offset['method'] blocked_seat_list = SocialDistance(airplane, this_offset, occupied_state='P') SeatPassenger(airplane, blocked_seat_list, occupied_state='P') # assert prev_assigned_seat != airplane.last_assigned_seat, "Unsuccessful Seating!" df.loc[row, 'seat'] = airplane.last_assigned_seat single_find_next_seat(airplane) airplane.update() return df
def load_data(): with open("titanic/test.csv") as file: data = csv.reader(file) count = 0 for row in data: if count > 0: try: PASSENGERS[int(row[0])] = Passenger( int(row[0]), int(row[1]), float(row[8])) except: pass count = count + 1 file.close()
def generate_boarding(self, plane_length): passengers = list() seatList = list() for count in range(1, 4): seats = set() while len(seats) < plane_length * 2: seats.add((randint(1, plane_length), chr(64 + count))) seats.add((randint(1, plane_length), chr(71 - count))) seatList.extend(list(seats)) for seat in seatList: passengers.append(Passenger(seat[0], seat[1], randint(0, 2))) self.plane = Plane(plane_length) self.plane.add_passengers(passengers) return passengers
def generate_boarding(self, plane_length): passengers = list() seatList = list() for number in range(1, plane_length, plane_length // 4): seats = set() while len(seats) < plane_length * 6 / 4: seats.add((randint(number, number + (plane_length // 4) - 1), chr(randint(65, 70)))) seatList.extend(list(seats)) for seat in seatList: passengers.append(Passenger(seat[0], seat[1], randint(0, 2))) self.plane = Plane(plane_length) self.plane.add_passengers(passengers) return passengers
def reset(self): """ Initializes/resets the simulation to its initial state """ # Generate a list of passengers based on total number of passengers self.passenger_list = [ Passenger(i, self.num_floors) for i in range(1, self.total_passengers + 1) ] self.elevator = ElevatorFactory.get_elevator(self.num_floors, self.elevator_type, self.passenger_list, self.elevator_capacity) self.building = Building(self.num_floors, self.passenger_list)
def generate_boarding(self, plane_length): passengers = list() seatList = list() for count in range(0, 3): for i in range(plane_length, 0, -2): seatList.append((i, chr(65 + count))) for i in range(plane_length, 0, -2): seatList.append((i, chr(70 - count))) for i in range(plane_length - 1, 0, -2): seatList.append((i, chr(65 + count))) for i in range(plane_length - 1, 0, -2): seatList.append((i, chr(70 - count))) for seat in seatList: passengers.append(Passenger(seat[0], seat[1], randint(0, 2))) self.plane = Plane(plane_length) self.plane.add_passengers(passengers) return passengers
def add_passenger(self, num_passengers): assert num_passengers <= self.size[0] * self.size[ 1], 'number of passengers is larger than number of grids' passenger_set = set() while True: if len(passenger_set) == num_passengers: break p = (random.randint(0, self.size[0] - 1), random.randint(0, self.size[1] - 1)) if p not in passenger_set: passenger_set.add(p) for s in passenger_set: # generate destination point while True: d = (random.randint(0, self.size[0] - 1), random.randint(0, self.size[1] - 1)) if d != s: break self.passengers.append(Passenger(s, d))
def getPassengers(self): filename = self.testPath if self.useTest else self.trainPath passengers = [] with open(filename, 'r', newline='\n') as file: reader = csv.reader(file) for row in reader: cells = row if len(cells) != 12: raise Exception('Fields missing in dataset!') passengerId, survived, pClass, name, sex, age, sibSp, parch, ticket, fare, cabin, embarked = cells passenger = Passenger(passengerId, survived, pClass, name, sex, age, sibSp, parch, ticket, fare, cabin, embarked) passengers.append(passenger) return passengers
# Stats MISC coachQueueSTATS = { 'duration': 0.0, 'maxSize': 0, 'maxWait': 0, 'nPass': 0 } firstQueueSTATS = { 'duration': 0.0, 'maxSize': 0, 'maxWait': 0, 'nPass': 0 } # Stats Service Stations busyStation = { 'coach':{'001':0.0, '002':0.0, '003':0.0, }, 'first':{'001':0.0, '002':0.0,} } duration = 0 while ongoingSimulation(duration, checkInDuration): # Handle New Arrivals # First Class if newArrival(checkInDuration, fcAvgArrivalRate, duration): psgr = Passenger('First', duration, fcAvgSvcRate) firstClassQueue.enqueue(psgr) firstQueueSTATS['nPass'] += 1 # Increments total number of passengers in queue # Checks Queue Max size if firstClassQueue.size() > firstQueueSTATS['maxSize']: firstQueueSTATS['maxSize'] = firstClassQueue.size() # Coach if newArrival(checkInDuration, coachAvgArrivalRate, duration): psgr = Passenger('Coach', duration, coachAvgSvcRate) coachQueue.enqueue(psgr) coachQueueSTATS['nPass'] += 1 # Increments total number of passengers in queue # Checks Queue Max size if coachQueue.size() > coachQueueSTATS['maxSize']: coachQueueSTATS['maxSize'] = coachQueue.size() # Handle BUSY Service Stations
class TestOneToManyRelationships(unittest.TestCase): global driver_1 driver_1 = Driver("Daniel", "fast and furious") global driver_2 driver_2 = Driver("Alice", "faster and furiouser") global passenger_1 passenger_1 = Passenger("Michael Scott", 38) global passenger_2 passenger_2 = Passenger("Anna", 25) global passenger_3 passenger_3 = Passenger("Katie", 20) global trip_1 trip_1 = Trip(driver_1, passenger_1) global trip_2 trip_2 = Trip(driver_1, passenger_2) global trip_3 trip_3 = Trip(driver_1, passenger_3) global trip_4 trip_4 = Trip(driver_2, passenger_3) global trip_5 trip_5 = Trip(driver_2, passenger_2) def test_passenger_property_methods(self): self.assertEqual(passenger_1._name, "Michael Scott") self.assertEqual(passenger_1.name, "Michael Scott") self.assertEqual(passenger_1._age, 38) self.assertEqual(passenger_1.age, 38) def test_driver_property_methods(self): self.assertEqual(driver_1._name, "Daniel") self.assertEqual(driver_1.name, "Daniel") self.assertEqual(driver_1._driving_style, "fast and furious") self.assertEqual(driver_1.driving_style, "fast and furious") def test_trip_property_methods(self): self.assertEqual(trip_1._driver, driver_1) self.assertEqual(trip_1.driver, driver_1) self.assertEqual(trip_1._passenger, passenger_1) self.assertEqual(trip_1.passenger, passenger_1) def test_trip_class_method(self): self.assertItemsEqual(Trip._all, [trip_1, trip_2, trip_3, trip_4, trip_5]) self.assertItemsEqual(Trip.all(), [trip_1, trip_2, trip_3, trip_4, trip_5]) def test_driver_instance_methods(self): self.assertItemsEqual(driver_1.trips(), [trip_1, trip_2, trip_3]) self.assertItemsEqual(driver_1.passengers(), [passenger_1, passenger_2, passenger_3]) self.assertEqual(driver_1.trip_count(), 3) def test_passenger_instance_methods(self): self.assertItemsEqual(passenger_2.trips(), [trip_2, trip_5]) self.assertItemsEqual(passenger_2.drivers(), [driver_1, driver_2]) self.assertEqual(passenger_2.trip_count(), 2) global artist_1 artist_1 = Artist("Lady Gaga") global artist_2 artist_2 = Artist("Vulfpeck") global genre_1 genre_1 = Genre("Pop") global genre_2 genre_2 = Genre("Indie") global genre_3 genre_3 = Genre("Alternative") global song_1 song_1 = Song("Joanne", artist_1, genre_1) global song_2 song_2 = Song("Conscious Club", artist_2, genre_2) global song_3 song_3 = Song("Back Pocket", artist_2, genre_1) global song_4 song_4 = Song("El Chepe", artist_2, genre_3) global song_5 song_5 = Song("Sinner's Prayer", artist_1, genre_3) def test_genre_property_methods(self): self.assertEqual(genre_1._name, "Pop") self.assertEqual(genre_1.name, "Pop") def test_artist_property_methods(self): self.assertEqual(artist_1._name, "Lady Gaga") self.assertEqual(artist_1.name, "Lady Gaga") def test_song_property_methods(self): self.assertEqual(song_1._name, "Joanne") self.assertEqual(song_1.name, "Joanne") self.assertEqual(song_1._artist, artist_1) self.assertEqual(song_1.artist, artist_1) self.assertEqual(song_1._genre, genre_1) self.assertEqual(song_1.genre, genre_1) def test_song_class_method(self): self.assertItemsEqual(Song._all, [song_1, song_2, song_3, song_4, song_5]) self.assertItemsEqual(Song.all(), [song_1, song_2, song_3, song_4, song_5]) def test_artist_instance_methods(self): self.assertItemsEqual(artist_1.songs(), [song_1, song_5]) self.assertItemsEqual(artist_1.genres(), [genre_1, genre_3]) def test_genre_instance_methods(self): self.assertItemsEqual(genre_3.songs(), [song_4, song_5]) self.assertItemsEqual(genre_3.artists(), [artist_1, artist_2])
from plane_class import Plane from FlightTrip import FlightTrip from passenger import Passenger from people import People plane = Plane("AirSparta",20,20,15,10) seats = plane.get_seats() flight = FlightTrip(1,"Peru","12/06/2020","2:00PM",20,20) michael = Passenger("Michael", "111", 21, "21/12/1992") samir = Passenger("Samir", "122", 23, "21/12/1999") flight.add_passenger(michael) flight.add_passenger(samir) # print(flight.return_passenger_list()) flight = FlightTrip(1, 'Bora Bora', '01/01/2022', '10:00', 3, 3) samir = Passenger("Samir", "15503", 122, "24/08/1999") stefan = Passenger('Stefan', '123A', 100, '10/12/96') ryan = Passenger('Ryan', '2468B', 555, '08/06/20', True) mergim = Passenger('Mergim', '101010X', 777, '01/01/2077') print(flight.add_passenger(samir)) print(flight.add_passenger(stefan)) print(flight.add_passenger(ryan)) print(flight.add_passenger(mergim)) flight.flight_attendee_report()
while True: pass_or_staff = input("Passenger or Staff? ") if pass_or_staff.lower() == 'staff': break elif pass_or_staff.lower() == 'passenger': name = input("Enter name: ") tax_no = input('Enter tax number: ') passport_no = input("Enter passport number: ") dob = input("Enter date of birth: ") with_child = input("Are you travelling with infant? [True/False]") if with_child == 'True': with_child = True elif with_child == 'False': with_child = False pass1 = Passenger(name, tax_no, passport_no, dob, with_child) flight_options = input("Where do you want to go? ") if flight_options.capitalize() == flight_cannes.destination: print(flight_cannes.add_passenger(pass1)) else: print('Invalid response') break flight_cannes.flight_attendee_report() print(flight_cannes.ticket_revenue())
def menu(): texts = Texts() passenger = Passenger() dao = BusDao() if os.path.exists(dao.path): dao.set_passenger(passenger, texts) choice = "" while choice != "0": views = Views(texts) choice = multipy_input(texts.show_menutext()) if choice == "1": passenger.set_bus_lines(multipy_input(texts.busline_input_text)) elif choice == "2": views.show_near_lines(passenger, dao) elif choice == "3": views.show_bus_lines(passenger, dao) elif choice == "4": passenger.bus_lines_del(multipy_input(texts.busline_input_text)) elif choice == "5": views.show_near(passenger, dao) elif choice == "6": passenger.show_bus_lines() elif choice == "7": views.open_map(passenger, dao, (multipy_input(texts.busid_input_text))) elif choice == "8": views.show_by_id(passenger, dao, (multipy_input(texts.busid_input_text))) elif choice == "9": views.show_fastests(passenger, dao) elif choice == "10": views.show_all(passenger, dao) elif choice == "11": views.open_map_manually(multipy_input(texts.latitude_input_text), multipy_input(texts.longitude_input_text)) elif choice == "12": try: passenger.set_latitude(multipy_input(texts.latitude_input_text)) passenger.set_longitude(multipy_input(texts.longitude_input_text)) except: print("=(") elif choice == "13": try: passenger.maxdistance = multipy_input(texts.max_distance_intext) except: print("=(") elif choice == "14": try: passenger.minspeed = multipy_input(texts.min_speed_text) except: print("=(") elif choice == "97": print("%s %s" % (texts.language_text, texts.language)) passenger.show(texts.passenger_text) elif choice == "98": dao.write_user_config(passenger, texts) elif choice == "99": texts.language = multipy_input(texts.lang_chtext) print(texts.language) else: if choice != "0": print("\n=(\n") else: print("\n=)\n")