Example #1
0
def test_async(capsys):
    async def open_and_close_doors(ele):
        await ele.open_doors()
        await ele.close_doors()

    elevator_1 = Elevator(name="Elevator 1")
    elevator_2 = Elevator(name="Elevator 2")
    expected_messages_order = [
        Elevator.MESSAGE_TEMPLATES["doors_opening"].format(elevator_1.name),
        Elevator.MESSAGE_TEMPLATES["doors_opening"].format(elevator_2.name),
        Elevator.MESSAGE_TEMPLATES["doors_closing"].format(elevator_1.name),
        Elevator.MESSAGE_TEMPLATES["doors_closing"].format(elevator_2.name)
    ]

    async def main():
        await asyncio.gather(open_and_close_doors(elevator_1),
                             open_and_close_doors(elevator_2))

    time_1 = time.time()
    asyncio.run(main())

    stdout = capsys.readouterr().out.split("\n")
    delta_time = time.time() - time_1
    # assuming door_action duration is the same
    assert delta_time > elevator_1.door_action_duration * 2 and delta_time < elevator_2.door_action_duration * 4
    check_stdout(expected_messages_order, stdout)
    def test_closest_elevator_to_floor(self):
        elevators = [Elevator(current_floor=0), Elevator(current_floor=2), Elevator(current_floor=5)]
        behaviour = ClosestCallPrepend()

        result = behaviour.closest_elevator_to_floor(elevators, 3)

        self.assertEqual(result, 1)
    def test_least_busy_elevator(self):
        behaviour = LeastBusyAppend()

        elevator1 = Elevator()
        elevator1.destinations = [1, 2, 3, 4]
        elevator2 = Elevator()
        elevator2.destinations = [5, 6]
        elevator3 = Elevator()
        elevator3.destinations = [7, 8, 9]

        elevators = [elevator1, elevator2, elevator3]

        result = behaviour.least_busy_elevator(elevators)

        self.assertEqual(result, 1)
Example #4
0
    def __init__(self,
                 nbElevator,
                 typeAlgo,
                 lamb=0.5,
                 expo=60,
                 typeIdle="noMoveIdle"):
        self.elevators = []
        self.users = {
            '1': [],
            '2': [],
            '3': [],
            '4': [],
            '5': [],
            '6': [],
            '7': []
        }
        self.totalUsers = 0
        self.totalTravels = 0
        self.totalWaitingTime = 0
        self.meanWaitingTime = 0
        self.calls = []
        self.expo = expo
        self.exp = exponnorm(expo)
        self.lamb = lamb
        self.typeIdle = typeIdle
        self.tpsAttendu = []

        for i in range(nbElevator):
            newElevator = Elevator(False, False, [], 1, typeAlgo,
                                   self.typeIdle)
            self.elevators.append(newElevator)

        userT = userThread(self)
        userT.start()
def main():
    """Точка входа в программу"""
    args = parse_args()

    elevator = Elevator(**args)
    events_to_output = ['passed_floor', 'opened_doors', 'closed_doors']
    for event in events_to_output:
        elevator.subscribe(event, print_elevator_event)

    stop = Event()
    elevator.start(stop)

    for line in sys.stdin:
        try:
            name, floor = line.split(SEPARATOR, 2)
            if int(floor) not in range(1, int(args['n']) + 1):
                print(_('< ERROR: Wrong floors number: min=%d, max=%d' % (1, args['n'])))
                continue
            elevator.perform(name, int(floor))
        except ValueError:
            print(_('< ERROR: Wrong input format. Expected: action_name floor_number'))
        except WrongActionError:
            print(_('< ERROR: Wrong action'))
        else:
            print(_('< OK'))

    stop.set()
Example #6
0
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"
Example #7
0
 def test_num_floors_traveled_up_down(self):
     """should keep track of the number of floors traveled going up then down"""
     elevator = Elevator(num_floors=5, starting_floor=3)
     elevator.request_floor(5)
     elevator.request_floor(1)
     elevator.travel()
     self.assertEqual(elevator.num_floors_traveled, 6)
Example #8
0
 def test_select_up(self):
     info("Test: {0}".format("test_select_up"))
     elevator = Elevator(10)
     floor = 3
     elevator.select(floor)
     elevator.act()
     self.assertEqual(elevator.current, floor)
Example #9
0
 def test_current_floor_after_travel(self):
     """should set current floor to last visited floor"""
     elevator = Elevator(num_floors=6, starting_floor=4)
     elevator.request_floor(5)
     elevator.request_floor(2)
     elevator.travel()
     self.assertEqual(elevator.current_floor, 2)
Example #10
0
 def __init__(self, parser, n_floors, n_elevators):
     self.parser = parser
     self.n_floors = n_floors
     self.elevators = []
     for i in range(n_elevators):
         self.elevators.append(Elevator(i, self.n_floors // 2))
     self.active_requests = []
Example #11
0
 def test_select_down(self):
     info("Test: {0}".format("test_select_down"))
     elevator = Elevator(10, 5)
     floor = 2
     elevator.select(floor)
     elevator.act()
     self.assertEqual(elevator.current, floor)
Example #12
0
	def __init__(self,n_,m_):
		self.n=n_
		self.m=m_
		print "Admin will handle " + str(self.n) + " elevators for "+ str(self.m)+ " Floors"
		for i in range(1,self.n+1):
			self.elevators.append(Elevator(i))
			print self.get_information_elevator(i)
Example #13
0
    def test_RunToNextTaskOrMaxTs_basic(self):
        conf = self._get_default_conf()
        elevator = Elevator(conf)
        next_tasks = [
            conf["INITIAL_FLOOR"] + 1, conf["INITIAL_FLOOR"] + 2,
            conf["INITIAL_FLOOR"] + 4, conf["INITIAL_FLOOR"] + 3
        ]
        elevator.register_next_tasks(next_tasks)

        elevator.run_to_next_task_or_max_ts(None)
        ts1, location1 = elevator.get_status()
        self.assertEqual(
            ts1, conf["TIME_TO_GO_UP_ONE_FLOOR"] + conf["TIME_TO_OPEN_DOORS"])
        self.assertEqual(location1, next_tasks[0])

        elevator.run_to_next_task_or_max_ts(None)
        ts2, location2 = elevator.get_status()
        self.assertEqual(
            ts2, ts1 + conf["TIME_TO_GO_UP_ONE_FLOOR"] +
            conf["TIME_TO_CLOSE_DOORS"] + conf["TIME_TO_OPEN_DOORS"])
        self.assertEqual(location2, next_tasks[1])

        elevator.run_to_next_task_or_max_ts(None)
        ts3, location3 = elevator.get_status()
        self.assertEqual(
            ts3, ts2 + (2 * conf["TIME_TO_GO_UP_ONE_FLOOR"]) +
            conf["TIME_TO_CLOSE_DOORS"] + conf["TIME_TO_OPEN_DOORS"])
        self.assertEqual(location3, next_tasks[2])

        elevator.run_to_next_task_or_max_ts(None)
        ts4, location4 = elevator.get_status()
        self.assertEqual(
            ts4, ts3 + conf["TIME_TO_GO_DOWN_ONE_FLOOR"] +
            conf["TIME_TO_CLOSE_DOORS"] + conf["TIME_TO_OPEN_DOORS"])
        self.assertEqual(location4, next_tasks[3])
Example #14
0
def test_elevator_can_open_doors_on_start(capsys):
    elevator = Elevator(name="Elevator 1")
    doors_opening_message = Elevator.MESSAGE_TEMPLATES["doors_opening"].format(
        elevator.name)
    elevator.open_doors()
    stdout = capsys.readouterr().out.split("\n")
    assert check_stdout([doors_opening_message], stdout)
Example #15
0
 def test_loading_to_moving(self):
     elevator = Elevator(lobby_load_delay=1, load_delay=1, verbosity="off")
     elevator.simulate_tick([Call(origin=1, destination=2, size=1, init_time=1)])
     self.assertEqual(elevator.state, 'LOADING')
     elevator.simulate_tick([])
     elevator.simulate_tick([])
     self.assertEqual(elevator.state, 'MOVING')
Example #16
0
 def test_visited_floors(self):
     """should register visited floors in order"""
     elevator = Elevator(num_floors=5, starting_floor=5)
     elevator.request_floor(4)
     elevator.request_floor(2)
     elevator.travel()
     self.assertListEqual(elevator.visited_floors, [4, 2])
 def __init__(self, env, floor_count, elevator_count):
     self.env = env
     self.floor_count = floor_count
     self.elevators = [
         Elevator(self.env, i) for i in range(1, elevator_count + 1)
     ]
     self.sectors = self.make_sectors(floor_count)
Example #18
0
 def init_elevators(self, **kwargs):
     self.elevators = []
     for idx in range(self.plan.n_els):
         self.elevators.append(Elevator(idx, self.plan.n_floors, **kwargs))
     self.plan.strategy.init_elevators(self.elevators)
     if self.debug:
         self.print_elevators_info()
Example #19
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-f", "--floors",
        help="number of floors in the building",
        type=int, choices=range(5, 21), default=12
    )
    parser.add_argument(
        "-H", "--height",
        help="height of the floor (meters)",
        type=float, default=2.65
    )
    parser.add_argument(
        "-v", "--velocity",
        help="velocity of the elevator cabin (meters per second)",
        type=float, default=3.0
    )
    parser.add_argument(
        "-d", "--doors_delay",
        help="time delay while cabin doors are open (seconds)",
        type=float, default=3.0
    )
    parser.add_argument(
        "-p", "--port",
        help="controller port",
        type=int, default=4455
    )
    args = parser.parse_args()

    print("Welcome to Elevator Simulator")
    print("Floors:\t\t{floors:>8}\nHeight:\t\t{height:>8}\nVelocity:\t{velocity:>8}\nDoors delay:{doors_delay:>8}"
          .format(**vars(args)))

    loop = asyncio.get_event_loop()
    controller = Controller('Elevator Controller', port=args.port, loop=loop)
    print("Elevator controller server is listening on port {}".format(args.port))

    elevator = Elevator(
        floors=args.floors,
        height=args.height,
        velocity=args.velocity,
        doors_delay=args.doors_delay
    )

    tasks = asyncio.gather(
        loop.create_task(elevator.handle_commands(controller.get_command_queue())),
        loop.create_task(elevator.run())
    )

    try:
        loop.run_until_complete(tasks)
    except KeyboardInterrupt:
        print("Shutdown requested")
        tasks.cancel()
        loop.run_forever()
    finally:
        loop.close()

    return 0
Example #20
0
 def test_duplicate_floor_requests(self):
     """gnore duplicate floor requests"""
     elevator = Elevator(num_floors=5, starting_floor=1)
     elevator.request_floor(3)
     elevator.request_floor(3)
     self.assertSetEqual(elevator.requested_floors, {3})
     elevator.travel()
     self.assertListEqual(elevator.visited_floors, [3])
Example #21
0
 def test_controller_select(self):
     info("Test: {0}".format("test_controller_select"))
     elevator = Elevator(10, 2)
     controller = Controller(elevator)
     controller.select(3, dt.datetime.now() + dt.timedelta(0, 1))
     sleep(2)
     self.assertEqual(elevator.current, 3)
     self.assertEqual(controller.state, 'door_closed')
Example #22
0
 def test_init(self):
     conf = defaultdict(lambda: 0)
     initial_floor = random.randint(1, 100000)
     conf["INITIAL_FLOOR"] = initial_floor
     elevator = Elevator(conf)
     current_ts, current_location = elevator.get_status()
     self.assertEqual(current_ts, 0)
     self.assertEqual(current_location, initial_floor)
Example #23
0
 def test_multiple_select_down(self):
     info("Test: {0}".format("test_multiple_select_down"))
     elevator = Elevator(10, 8)
     elevator.select(5)
     elevator.select(2)
     elevator.select(0)
     elevator.act()
     self.assertEqual(elevator.current, 0)
Example #24
0
    def test_properties(self):
        floors = [Floor(1, 7), Floor(2, 7)]
        elevators = [Elevator(id=1, size=10)]

        c = Controller(floors, elevators)

        self.assertTrue(type(c.signal_change_velocity) is Signal)
        self.assertTrue(type(c.signal_stop) is Signal)
Example #25
0
 def test_init_params(self):
     """should store correct initial parameters when elevator is initalized"""
     elevator = Elevator(5, 2)
     self.assertEqual(elevator.num_floors, 5)
     self.assertEqual(elevator.current_floor, 2)
     self.assertSetEqual(elevator.requested_floors, set())
     self.assertListEqual(elevator.visited_floors, [])
     self.assertEqual(elevator.num_floors_traveled, 0)
    def __init__(self, num_elevators, num_floors):
        if num_floors < 1:
            raise Exception('You need at least one elevator')

        self.n = num_elevators
        self.controllers = []
        for i in range(0, num_elevators):
            self.controllers.append(Controller(Elevator(num_floors)))
Example #27
0
def main():
    mybuilding = Building(floors=18,
                          floorheight=4.1)
    mybuilding.elevator = Elevator()
    print(mybuilding.elevator)
    mybuilding.populate()
    phys = Physics(building=mybuilding, hours=10)
    print(phys.building.elevator)
Example #28
0
def makeElevators(count=2, height=DEFAULT_HEIGHT):
    retval = list()
    floors = range(0, height)
    for _ in xrange(0, count):
        direction = choice(DIRECTIONS)
        floor = choice(floors)
        retval.append(Elevator(direction=direction, floor=floor)) 
    return retval
Example #29
0
 def test_changing_directions_no_furtherup(self):
     e = Elevator(ElevatorLogic())
     e.call(2, DOWN)
     e.call(4, UP)
     e.run_until_stopped()
     self.assertEqual(e._logic_delegate.debug_path, [1, 2, 3, 4])
     e.run_until_stopped()
     self.assertEqual(e._logic_delegate.debug_path, [1, 2, 3, 4, 3, 2])
def test_elevator_can_only_carry_passengers_when_door_is_open():
    elevator = Elevator(name="Elevator 1")
    assert elevator.door_status == "closed"
    passenger_1 = Passenger(destination=2)
    try:
        elevator.load_passengers([passenger_1])
        assert False, "No Exception was thrown"
    except Exception as ex:
        assert str(ex) == "You tried to load passengers into {} while it was in state {}!".format(elevator.name, elevator.state)