사용 사례: 이산 이벤트 시뮬레이션을 위한 코루틴

매일 공부(ML)·2023년 5월 15일
0

Fluent Python

목록 보기
121/130

제어 흐름

코루틴

사용 사례: 이산 이벤트 시뮬레이션을 위한 코루틴

이산 이벤트 시뮬레이션(DES)에 대해

일련의 이벤트로 모델링을 하는 것이므로 고정된 값만큼 진행하는 것이 아니라, 모델링된 다음 이벤트의 시뮬레이션된 시각으로 바로 진행이 된다.

즉, 이벤트 루프에 의해 작동하는 콜백이나 코루틴 등의 객체지향 프로그래밍 기법을 이용해서 다중 스레드나 단일 스레드로 구현할 수 있고, 실시간으로 동시에 발생하는 행동을 표현하기 위해 여러 스다중 스레드나 단일 스레드로 구현한다.


택시 집단 시뮬레이션

각 택시는 일정 횟수의 운행을 마친 후 찝으로 돌아가고, 택시는 차고를 나와 승객을 찾으면서 배회한다. 이 상태는 승객을 태울 때까지 계속되고난 후에 운행이 시작되며 승객이 내리면 택시는 다시 배회 상태이다.

end of simulation time: 3 events pending #대기하고 있는 이벤트를 남겨 놓고 시뮬레이션 끝난 후 이벤트가 남아 있는 경우 메시지 출력

Event= collections.namedtuple('Event', 'time proc action') #다른 곳에 정의된 함수와 Event 클래스 객체를 사용한다

코드

def taxi_process(ident, trips, start_time=0):
	"""각 단계 변화마다 이벤트를 생성하며 시뮬레이터에 제어권을 넘긴다."""
    time = yield Event(start_time, ident, 'leave garage')
    for i in range(trips):
    	time = yield Event(time, ident, 'pick up passenger')
        time = yield Event(time, ident,'drop off passenger')
        
        yield Event(time, ident, 'going home')
        
#taxi_process)_ 코루틴

from taix_sim import taxi_process
taix = taxi_process(ident=13, trips=2, start_time=0)
next(taxi)
taxi.seed(_.time + 7)

#Simulator클래스의 객체를 생성하기 위해서 taxi 딕셔너리 만들기

taxis = {i:taxi_process(i,(i+1)*2, i * DEPARTURE_INTERVAL)
		 for i in range(num_taxis)}{
sim = Simulator(taxis)
# Simulator 이산 이벤트 시 시뮬레이션 클래스.run()메서드르 중심

class Simulator:

	def __init__(self, procs_map):
    	self.events = queue.PriorityQueue()
        self.procs = dict(procs_map)
        
    def run(self,end_time):
    	"""시간이 끝날 때까지 이벤트를 스케쥴링하고 출력한다."""
        for _, proc in sorted(self.procs.items()):
        	first_event = next(proc)
            self.events.put(firts_event)
profile
성장을 도울 아카이빙 블로그

0개의 댓글