Ejemplo n.º 1
0
    def __init__(self,
                 xmin,
                 ymin,
                 xmax,
                 ymax,
                 img_size,
                 installation: Installation,
                 spawner=True):
        """:param img_size (width, height)"""
        assert ymax > ymin
        assert xmax > xmin

        self.xmin = xmin
        self.ymin = ymin

        self.xmax = xmax
        self.ymax = ymax

        self.img_size_x, self.img_size_y = img_size

        self.xscale = self.img_size_x / (self.xmax - self.xmin)
        self.yscale = self.img_size_y / (self.xmax - self.xmin)

        self._grids = {}

        self.inst = installation
        self._focal_points: List[_FocalPoint] = []

        self.tracelib = ctypes.cdll.LoadLibrary("./trace.so")

        if spawner:
            util.create_task(self.background_processor())

        if platform.system() == "Darwin":
            util.create_task(self.publish_loop())
Ejemplo n.º 2
0
async def setup(
    port: int,
    config_endpoint: Optional[str] = "http://127.0.0.1:8500",
):
    cfg = await get_config(port, config_endpoint)

    app = web.Application()
    app['cfg'] = cfg

    observer = Observer()
    app['observer'] = observer

    ws_manager = ws.WebsocketManager(broadcast=observer.notify_observers)

    json_inst = await build_installation(cfg['cfg'])
    inst = Installation.unmarshal(json_inst)

    app['inst'] = inst
    hm = HeadManager()

    app['head_manager'] = hm

    app['grid'] = Grid(-10, -10, 10, 10, (400, 400),
                       installation=inst)  # TODO: not global!
    asyncio.ensure_future(app['grid'].decay())

    boss_routes.setup_routes(app, ws_manager)

    orchestrator = Orchestrator(
        inst=inst,
        head_manager=hm,
        broadcast=observer.notify_observers,
    )

    fp_manager = FocalPointManager(
        broadcast=observer.notify_observers,
        inst=inst,
        grid=app['grid'],
    )

    observer.register_observer(orchestrator)
    observer.register_observer(fp_manager)  # perhaps not the best place
    observer.register_observer(ws_manager)

    tm = text_manager.text_manager(
        head_manager=hm,
        broadcast=observer.notify_observers,
    )
    util.create_task(tm)

    for redis in cfg['redis_servers']:
        asyncio.ensure_future(
            run_redis(redis, broadcast=observer.notify_observers))

    return app
Ejemplo n.º 3
0
 def __init__(
     self,
     inst: Installation,
     head_manager: HeadManager,
     broadcast: Callable,
 ):
     self.inst = inst
     self.head_manager = head_manager
     self.broadcast = broadcast
     util.create_task(self._dj())
     self._current_orch = None
     self.focal_points = {}
     self.texts = list()
Ejemplo n.º 4
0
def worker_init(config_file, device_type, num_devices):
    global task, solution
    gin.parse_config_file(config_file)
    task = util.create_task(logger=None)
    worker_id = int(mp.current_process().name.split('-')[-1])
    device = '{}:{}'.format(device_type, (worker_id - 1) % num_devices)
    solution = util.create_solution(device=device)
Ejemplo n.º 5
0
async def follow_evade(orchestrator: "Orchestrator"):
    tasks = []
    for head in orchestrator.inst.heads.values():
        task = util.create_task(
            follow_closest_focal_point(head, orchestrator, -1.0),
            allow_cancel=True,
        )
        tasks.append(task)
    await asyncio.gather(*tasks)
Ejemplo n.º 6
0
    async def _run_scenes(self, scenes):
        for scene in scenes:
            log.info(f"running scene", scene=scene.__name__)
            task: asyncio.Task = util.create_task(scene(self),
                                                  allow_cancel=True)

            timeout = timeouts(scene)

            try:
                await asyncio.wait_for(task, timeout=timeout)
            except asyncio.TimeoutError:
                pass
            except Exception as e:
                log.critical("scene caused exception", exception=str(e))
Ejemplo n.º 7
0
def main(config):
    logger = util.create_logger(name='test_solution', log_dir=config.log_dir)
    task = util.create_task(logger=logger)
    task.seed(config.seed)

    solution = util.create_solution(device='cpu:0')
    model_file = os.path.join(config.log_dir, config.model_filename)
    solution.load(model_file)

    rewards = []
    time_costs = []
    for ep in range(config.n_episodes):
        start_time = time.perf_counter()
        reward = task.rollout(solution=solution, evaluation=True)
        time_cost = time.perf_counter() - start_time
        rewards.append(reward)
        time_costs.append(time_cost)
        logger.info('Episode: {0}, reward: {1:.2f}'.format(ep + 1, reward))

    logger.info('Avg reward: {0:.2f}, sd: {1:.2f}'.format(
        np.mean(rewards), np.std(rewards)))
    logger.info('Time per rollout: {}s'.format(np.mean(time_costs)))
Ejemplo n.º 8
0
async def conversation(orchestrator: "Orchestrator"):
    heads = list(orchestrator.inst.heads.values())

    texts = orchestrator.texts
    if len(texts) == 0:
        log.info("no texts")
        await asyncio.sleep(5.0)
        return

    log.info("found texts", count=len(texts))
    parts = random.choice(texts)
    for p in parts:
        log.info("found part", part=p)

    for part in parts:
        # all point to the center
        log.info("saying", part=part)
        for head in heads:
            other_heads = [h for h in heads if h.name != head.name]
            assert len(heads) - len(other_heads) == 1
            positions = [h.global_pos for h in other_heads]
            center = (1.0 / len(positions)) * reduce(operator.add, positions)

            theta = head.point_to(center)
            path = f"/rotation/{theta:f}"
            orchestrator.head_manager.send("head", head.name, path)
        await asyncio.sleep(1.0)

        random.shuffle(heads)
        h0 = heads[0]

        if orchestrator.focal_points and random.random() < 0.66:
            # Follow the focal point
            coro = follow_closest_focal_point(h0, orchestrator)
            task = util.create_task(coro, allow_cancel=True)

            await asyncio.sleep(0.5)
            path = f"/play?text={part}&isSync=true"
            future = orchestrator.head_manager.send("voices", h0.name, path, return_future=True)

            await future
            task.cancel()
            await asyncio.sleep(0.5)

        else:
            # Point towards other head
            other_heads = heads[1:3] if random.random() < 0.20 else heads[1:2]
            first = other_heads[0]

            t0 = h0.point_to(first.global_pos)
            path = f"/rotation/{t0:f}"
            orchestrator.head_manager.send("head", h0.name, path)

            await asyncio.sleep(0.5)

            for other in other_heads:
                # Point other heads back towards speaker
                t1 = other.point_to(h0.global_pos)
                path = f"/rotation/{t1:f}"
                orchestrator.head_manager.send("head", other.name, path)
                await asyncio.sleep(0.5)

            path = f"/play?text={part}&isSync=true"
            future = orchestrator.head_manager.send("voices", h0.name, path, return_future=True)

            await future
            await asyncio.sleep(0.5)
Ejemplo n.º 9
0
 def __init__(self, broadcast: Callable, inst: Installation, grid: Grid):
     self.broadcast = broadcast
     self._focal_points: Dict[str, FocalPoint] = {}
     util.create_task(self._focal_point_garbage_collector())
     self.inst = inst
     self.grid = grid
Ejemplo n.º 10
0
async def setup(instance: str,
                config_endpoint: Optional[str] = None,
                port_override: Optional[int] = None):
    config_endpoint = config_endpoint or "http://127.0.0.1:8500"
    cfg = await get_config(config_endpoint, instance, port_override)

    redis_host, redis_port_str = cfg['redis_server'].split(":")
    redis_port = int(redis_port_str)

    log.info("connecting to redis", host=redis_host, port=redis_port)
    redis_connection = await asyncio_redis.Connection.create(host=redis_host,
                                                             port=redis_port)
    log.info("connected to redis", host=redis_host, port=redis_port)

    motor_data = [
        {
            "id": 1,
            "publish": True
        },
        {
            "id": 2,
            "publish": False
        },
    ]

    steppers = {}

    for m in motor_data:
        if cfg['head'].get('virtual', False):
            motor = motors.FakeStepper(m['id'])
            gpio = zero_detector.FakeGPIO()
        else:
            motor = motors.setup(m['id'])
            gpio = zero_detector.GPIO()

        stepper = Stepper(
            cfg,
            redis_connection,
            motor,
            Seeker(),
            Seeker(),
            gpio,
            publish=m['publish'],
        )
        util.create_task(stepper.redis_publisher())
        util.create_task(stepper.run())

        steppers[m['id']] = stepper

        util.create_task(stepper.publish_active_loop())

    app = web.Application()
    app['cfg'] = cfg
    app['steppers'] = steppers
    app['redis'] = redis_connection

    app.add_routes([
        web.get("/", home),
        web.get('/health', health_check),
        web.get('/metrics', handle_metrics),
        web.get("/position/{target}", position),
        web.get("/rotation/{theta}", rotation),
        web.get("/zero", zero),
        web.get("/find_zero", find_zero),
        web.get("/slow_rotate", slow_rotate),
        web.get("/seek", seek),
        web.get("/off", off),
        web.get("/status", status),
    ])

    return app