|
| 1 | +"""Asynchronous controller manager for multi-process control of multiple drones. |
| 2 | +
|
| 3 | +This module provides a controller manager that allows multiple controllers to run in separate |
| 4 | +processes without blocking other controllers or the main process. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import multiprocessing as mp |
| 10 | +from queue import Empty |
| 11 | +from typing import TYPE_CHECKING |
| 12 | + |
| 13 | +import numpy as np |
| 14 | + |
| 15 | +from lsy_drone_racing.control.controller import Controller |
| 16 | + |
| 17 | +if TYPE_CHECKING: |
| 18 | + from multiprocessing.synchronize import Event |
| 19 | + |
| 20 | + from numpy.typing import NDArray |
| 21 | + |
| 22 | + |
| 23 | +class ControllerManager: |
| 24 | + """Multi-process safe manager class for asynchronous/non-blocking controller execution. |
| 25 | +
|
| 26 | + Note: |
| 27 | + The controller manager currently does not support step and episode callbacks. |
| 28 | +
|
| 29 | + Todo: |
| 30 | + Implement an automated return mechanism for the controllers. |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__(self, controllers: list[Controller], default_action: NDArray): |
| 34 | + """Initialize the controller manager.""" |
| 35 | + assert all(isinstance(c, Controller) for c in controllers), "Invalid controller type(s)!" |
| 36 | + self._controllers_cls = controllers |
| 37 | + self._obs_queues = [mp.Queue(1) for _ in controllers] |
| 38 | + self._action_queues = [mp.Queue(1) for _ in controllers] |
| 39 | + self._ready = [mp.Event() for _ in controllers] |
| 40 | + self._shutdown = [mp.Event() for _ in controllers] |
| 41 | + self._actions = np.tile(default_action, (len(controllers), 1)) |
| 42 | + |
| 43 | + def start(self, init_args: tuple | None = None, init_kwargs: dict | None = None): |
| 44 | + """Start the controller manager.""" |
| 45 | + for i, c in enumerate(self._controllers_cls): |
| 46 | + args = ( |
| 47 | + c, |
| 48 | + tuple() if init_args is None else init_args, |
| 49 | + dict() if init_kwargs is None else init_kwargs, |
| 50 | + self._obs_queues[i], |
| 51 | + self._action_queues[i], |
| 52 | + self._ready[i], |
| 53 | + self._shutdown[i], |
| 54 | + ) |
| 55 | + self._controller_procs.append(mp.Process(target=self._control_loop, args=args)) |
| 56 | + self._controller_procs[-1].start() |
| 57 | + for ready in self._ready: # Wait for all controllers to be ready |
| 58 | + ready.wait() |
| 59 | + |
| 60 | + def update_obs(self, obs: dict, info: dict): |
| 61 | + """Pass the observation and info updates to all controller processes. |
| 62 | +
|
| 63 | + Args: |
| 64 | + obs: The observation dictionary. |
| 65 | + info: The info dictionary. |
| 66 | + """ |
| 67 | + for obs_queue in self._obs_queues: |
| 68 | + _clear_producing_queue(obs_queue) |
| 69 | + obs_queue.put((obs, info)) |
| 70 | + |
| 71 | + def latest_actions(self) -> NDArray: |
| 72 | + """Get the latest actions from all controllers.""" |
| 73 | + for i, action_queue in enumerate(self._action_queues): |
| 74 | + if not action_queue.empty(): # Length of queue is 1 -> action is ready |
| 75 | + # The action queue could be cleared in between the check and the get() call. Since |
| 76 | + # the controller processes immediately put the next action into the queue, this |
| 77 | + # minimum block time is acceptable. |
| 78 | + self._actions[i] = action_queue.get() |
| 79 | + return np.array(self._actions) |
| 80 | + |
| 81 | + @staticmethod |
| 82 | + def _control_loop( |
| 83 | + cls: type[Controller], |
| 84 | + init_args: tuple, |
| 85 | + init_kwargs: dict, |
| 86 | + obs_queue: mp.Queue, |
| 87 | + action_queue: mp.Queue, |
| 88 | + ready: Event, |
| 89 | + shutdown: Event, |
| 90 | + ): |
| 91 | + controller = cls(*init_args, **init_kwargs) |
| 92 | + ready.set() |
| 93 | + while not shutdown.is_set(): |
| 94 | + obs, info = obs_queue.get() # Blocks until new observation is available |
| 95 | + action = controller.compute_control(obs, info) |
| 96 | + _clear_producing_queue(action_queue) |
| 97 | + action_queue.put_nowait(action) |
| 98 | + |
| 99 | + |
| 100 | +def _clear_producing_queue(queue: mp.Queue): |
| 101 | + """Clear the queue if it is not empty and this process is the ONLY producer. |
| 102 | +
|
| 103 | + Warning: |
| 104 | + Only works for queues with a length of 1. |
| 105 | + """ |
| 106 | + if not queue.empty(): # There are remaining items in the queue |
| 107 | + try: |
| 108 | + queue.get_nowait() |
| 109 | + except Empty: # Another process could have consumed the last item in between |
| 110 | + pass # This is fine, the queue is empty |
0 commit comments