Exemplo n.º 1
0
 def __init__(self):
     self.videos_folder = "videos"
     self.current_experiment_video_folder = ""
     self.tracking_path = "/maze/agent_tracking/cmake-build-release/agent_tracker"
     self.robot_controller_path = "/maze/agent_tracking/cmake-build-release/robot_controller"
     self.experiment = Experiment()
     self.doors = Doors()
     self.feeders = Feeders()
     self.door_2_open = False
     self.tracker = App_comm([self.tracking_path, "experiment", "view"],
                             self.process_tracking)
     self.robot = App_comm([self.robot_controller_path],
                           self.process_robot_controller)
Exemplo n.º 2
0
def main():
  parser = argparse.ArgumentParser(description='SM Room Timer')
  parser.add_argument('-f', '--file', dest='filename', default=None)
  parser.add_argument('--rooms', dest='rooms_filename', default='rooms.json')
  parser.add_argument('--doors', dest='doors_filename', default='doors.json')
  parser.add_argument('--segment', dest='segments', action='append', default=[])
  parser.add_argument('--split', dest='splits', action='append', default=[])
  parser.add_argument('--splits', dest='splits_filename')
  parser.add_argument('--brief', action='store_true')
  args = parser.parse_args()

  rooms = Rooms.read(args.rooms_filename)
  doors = Doors.read(args.doors_filename, rooms)
  history = read_transition_log(args.filename, rooms, doors)

  # ids = build_route(history) if args.build_route else history.keys()
  route = build_route(history) # TODO: Needed?

  split_names = args.splits

  if args.splits_filename is not None:
    with open(args.splits_filename) as f:
      lines = [ line for line in f.readlines()
          if not line.startswith('#') and not line.isspace() ]
      split_names.extend([ line.strip() for line in lines ])

  segments = [ segment_from_name(name, rooms, route) for name in args.segments ]
  splits = [ transition_from_name(name, rooms, route) for name in split_names ]

  segments.extend(segments_from_splits(route, splits))

  if not args.brief:
    segment_history = build_segment_history(segments, history)
    print_room_stats(history, segment_history, segments)
  print_segment_stats(history, segments)
Exemplo n.º 3
0
def main():
    parser = argparse.ArgumentParser(description='SM Room Timer')
    parser.add_argument('-f', '--file', dest='filename', default=None)
    parser.add_argument('--rooms', dest='rooms_filename', default='rooms.json')
    parser.add_argument('--doors', dest='doors_filename', default='doors.json')
    parser.add_argument('--segment',
                        dest='segments',
                        action='append',
                        default=[])
    parser.add_argument('--split', dest='splits', action='append', default=[])
    parser.add_argument('--splits', dest='splits_filename')
    args = parser.parse_args()

    rooms = Rooms.read(args.rooms_filename)
    doors = Doors.read(args.doors_filename, rooms)

    with open(args.filename) as csvfile:
        tailer = Tailer(csvfile)
        history_reader = read_transition_log_csv_incrementally(
            tailer, rooms, doors)

        while not tailer.at_eof():
            history, transition = next(history_reader)

        # ids = build_route(history) if args.build_route else history.keys()
        route = build_route(history)  # TODO: Needed?

        split_names = args.splits

        if args.splits_filename is not None:
            with open(args.splits_filename) as f:
                lines = [
                    line for line in f.readlines()
                    if not line.startswith('#') and not line.isspace()
                ]
                split_names.extend([line.strip() for line in lines])

        segments = [
            segment_from_name(name, rooms, route) for name in args.segments
        ]
        splits = [
            transition_from_name(name, rooms, route) for name in split_names
        ]

        segments.extend(segments_from_splits(route, splits))

        old_stats = SegmentStats(history, segments)
        old_rendered_stats = None

        while True:
            stats = SegmentStats(history, segments)
            rendered_stats = render_segment_stats(old_stats, stats)
            if rendered_stats != old_rendered_stats:
                print()
                print(rendered_stats)
                old_rendered_stats = rendered_stats
            old_stats = stats
            history, transition = next(history_reader)
Exemplo n.º 4
0
def main():
    parser = argparse.ArgumentParser(description='SM Room Timer')
    parser.add_argument('-f', '--file', dest='filename', default=None)
    parser.add_argument('--rooms', dest='rooms_filename', default='rooms.json')
    parser.add_argument('--doors', dest='doors_filename', default='doors.json')
    parser.add_argument('--debug', dest='debug', action='store_true')
    parser.add_argument('--debug-log', dest='debug_log_filename')
    parser.add_argument('--verbose', dest='verbose', action='store_true')
    parser.add_argument('--usb2snes', action='store_true')
    parser.add_argument('--route', action='store_true')
    parser.add_argument('--rebuild', action='store_true')
    # parser.add_argument('--segment', action='append', required=True)
    args = parser.parse_args()

    rooms = Rooms.read(args.rooms_filename)
    doors = Doors.read(args.doors_filename, rooms)
    route = Route() if args.route else DummyRoute()

    if args.filename and need_rebuild(args.filename):
        if not args.rebuild:
            print(
                "File needs to be rebuilt before it can be used; run rebuild_history.py or pass --rebuild to this script."
            )
            sys.exit(1)

        backup_and_rebuild(rooms, doors, args.filename)

    if args.debug_log_filename:
        debug_log = open(args.debug_log_filename, 'a')
        verbose = True
    elif args.debug:
        debug_log = sys.stdout
        verbose = True
    else:
        debug_log = None
        verbose = args.verbose

    frontend = SegmentTimerTerminalFrontend(verbose=verbose,
                                            debug_log=debug_log)

    if args.filename is not None and os.path.exists(args.filename):
        history = read_transition_log(args.filename, rooms, doors)
    else:
        history = History()

    for tid in history:
        route.record(tid)
        if route.complete: break

    print('Route is %s' % ('complete' if route.complete else 'incomplete'))

    transition_log = FileTransitionLog(
        args.filename) if args.filename is not None else NullTransitionLog()

    tracker = SegmentTimeTracker(history,
                                 transition_log,
                                 route,
                                 on_new_room_time=frontend.new_room_time)

    state_reader = ThreadedStateReader(rooms,
                                       doors,
                                       usb2snes=args.usb2snes,
                                       logger=frontend)
    state_reader.start()

    try:
        timer = SegmentTimer(frontend,
                             state_reader,
                             on_transitioned=tracker.transitioned,
                             on_state_change=frontend.state_changed,
                             on_reset=tracker.room_reset)

        while state_reader.is_alive():
            timer.poll()

    finally:
        state_reader.stop()
Exemplo n.º 5
0
class Habitat:
    def __init__(self):
        self.videos_folder = "videos"
        self.current_experiment_video_folder = ""
        self.tracking_path = "/maze/agent_tracking/cmake-build-release/agent_tracker"
        self.robot_controller_path = "/maze/agent_tracking/cmake-build-release/robot_controller"
        self.experiment = Experiment()
        self.doors = Doors()
        self.feeders = Feeders()
        self.door_2_open = False
        self.tracker = App_comm([self.tracking_path, "experiment", "view"],
                                self.process_tracking)
        self.robot = App_comm([self.robot_controller_path],
                              self.process_robot_controller)

    def process_robot_controller(self, content):
        pass

    def process_tracking(self, content):
        try:
            tracking = json.loads(content)
            frame = tracking["frame"]
            time_stamp = tracking["time_stamp"]
            coordinates = tracking["detection_coordinates"]["coordinates"]
            agent = tracking["detection_coordinates"]["detection_location"][
                "profile"]["agent_name"]
            location = tracking["detection_coordinates"]["detection_location"][
                "location"]
            msg = "%s,%f,%f,%f" % (agent, location["x"], location["y"],
                                   tracking["theta"])
            self.robot.write(msg)
            self.experiment.track_agent(agent, coordinates, location, frame,
                                        time_stamp)
        except:
            pass

    def enable_feeder(self, n):
        return self.feeders.enable(n)

    def disable_feeder(self, n):
        return self.feeders.disable(n)

    def open_door(self, n):
        return self.doors.open(n)

    def close_door(self, n):
        return self.doors.close(n)

    def quit(self):
        global app
        app.stop()
        return Result(0, "good bye!")

    def status(self):
        s = self.experiment.status()
        if s.code == 0:
            message = s.message
            for pi in Pi.get_pis():
                message += "\nPi at %s: " % pi.address
                ps = pi.get("status")
                if ps.code:
                    message += "error\n"
                else:
                    message += "ok\n"
                    for door_status in ps.content["door_status"]:
                        message += ("door %d: " % door_status["door_number"]
                                    ) + door_status["state"] + "\n"
                    message += ("feeder %d: " %
                                ps.content["feeder_status"]["feeder_number"]
                                ) + ps.content["feeder_status"]["state"]
            return Result(0, message)
        else:
            return s

    def feeder_reached(self, feeder_number):
        if feeder_number not in [1, 2]:
            return Result(1, "wrong feeder number (%d)" % feeder_number)
        if feeder_number == 1:
            if not self.experiment.is_active():
                self.doors.close(1)
                self.doors.close(2)
                self.doors.close(0)
                self.doors.close(3)
                return self.experiment.experiment_ended()
            else:
                self.tracker.write(self.current_experiment_video_folder + "/" +
                                   self.experiment.name + "_ep" +
                                   ('%02d' % len(self.experiment.episodes)))
                r = self.experiment.start_episode()
                self.experiment.check = self.doors.close
                self.doors.close(1)
                self.doors.open(2)
                self.doors.close(0)
                self.doors.open(3)
                self.feeders.enable(2)
                return r
        else:
            self.tracker.write("end")
            r = self.experiment.finish_episode()
            self.doors.close(3)
            self.doors.open(0)
            self.doors.close(2)
            self.doors.open(1)
            self.feeders.enable(1)
            return r

    def start_experiment(self, experiment_name, world_name, duration=0):
        self.experiment = Experiment(experiment_name, world_name, duration)
        self.experiment.start()
        if experiment_name != "":
            self.current_experiment_video_folder = self.videos_folder + "/" + experiment_name
            if not os.path.exists(self.current_experiment_video_folder):
                os.makedirs(self.current_experiment_video_folder)
        message = "experiment '%s'" % experiment_name
        if duration > -1:
            message += " for %d minutes" % duration
        self.doors.close(0)
        self.doors.close(1)
        self.doors.close(2)
        self.doors.close(3)
        self.feeders.enable(1)
        return Result(0, message)

    def test_feeder(self, feeder_number, duration, repetitions, wait_time):
        return self.feeders.test(feeder_number, duration, repetitions,
                                 wait_time)

    def calibrate_door(self, door_number, direction, opening_time,
                       closing_time):
        return self.doors.calibrate(door_number, direction, opening_time,
                                    closing_time)

    def save_doors_calibration(self):
        return self.doors.save_calibration()

    def load_doors_calibration(self):
        return self.doors.load_calibration()

    def update_background(self):
        self.tracker.write("update_background")
        return Result(0, "Background updated")

    def finish_experiment(self):
        return self.experiment.finish()

    def track(self, agent, x, y):  # do better
        return self.experiment.track_agent(agent, {
            "x": x,
            "y": y
        }, {
            "x": 0,
            "y": 0
        })

    def test_door(self, door_number, repetitions):
        return self.doors.test_door(door_number, repetitions)

    def end(self):
        self.tracker.write("exit")
        self.tracker.stop()
        self.robot.write("exit")
        self.robot.stop()
Exemplo n.º 6
0
                        l = by_room_and_exit.get(key)
                        if l:
                            if len(l) == 1:
                                print("Fixing entry door on line %d" % n)
                                transition.id.entry_door = list(
                                    l.keys())[0].entry_door
                            else:
                                print(
                                    "More than one entry door found for %s to $s (line %d): %s"
                                    % (transition.id.room,
                                       transition.id.exit_room, n, repr(l)))
                        else:
                            # print("No entry door found for %s to %s (line %d)" %
                            #     (transition.id.room, transition.id.exit_room, n))
                            pass
                    writer.writerow(transition.as_csv_row())


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='SM Room Timer')
    parser.add_argument('-i', '--input', dest='inputs', action='append')
    parser.add_argument('-o', '--output', dest='output', default=None)
    parser.add_argument('--rooms', dest='rooms_filename', default='rooms.json')
    parser.add_argument('--doors', dest='doors_filename', default='doors.json')
    args = parser.parse_args()

    rooms = Rooms.read(args.rooms_filename)
    doors = Doors.read(args.doors_filename, rooms)

    rebuild_history(rooms, doors, args.inputs, args.output)
Exemplo n.º 7
0
def main():
    parser = argparse.ArgumentParser(description='SM Room Timer')
    parser.add_argument('-f', '--file', dest='filename', default=None)
    parser.add_argument('--rooms', dest='rooms_filename', default='rooms.json')
    parser.add_argument('--doors', dest='doors_filename', default='doors.json')
    parser.add_argument('--debug', dest='debug', action='store_true')
    parser.add_argument('--debug-log', dest='debug_log_filename')
    parser.add_argument('--verbose', dest='verbose', action='store_true')
    parser.add_argument('--usb2snes', action='store_true')
    parser.add_argument('--route', action='store_true')
    parser.add_argument('--rebuild', action='store_true')
    parser.add_argument('--port', type=int, default=15000)
    parser.add_argument('--headless', action='store_true')
    # parser.add_argument('--segment', action='append', required=True)
    args = parser.parse_args()

    rooms = Rooms.read(args.rooms_filename)
    doors = Doors.read(args.doors_filename, rooms)
    route = Route() if args.route else DummyRoute()

    if args.filename and need_rebuild(args.filename):
        if not args.rebuild:
            print(
                "File needs to be rebuilt before it can be used; run rebuild_history.py or pass --rebuild to this script."
            )
            sys.exit(1)

        backup_and_rebuild(rooms, doors, args.filename)

    if args.debug_log_filename:
        debug_log = open(args.debug_log_filename, 'a')
        verbose = True
    elif args.debug:
        debug_log = sys.stdout
        verbose = True
    else:
        debug_log = None
        verbose = args.verbose

    shutdown = []

    try:
        server = WebsocketServer(port=args.port)
        server.start()
        shutdown.append(server.stop)

        json_generator = JsonEventGenerator(verbose=verbose,
                                            debug_log=debug_log,
                                            on_event=server.broadcast)

        if args.filename is not None and os.path.exists(args.filename):
            history = read_transition_log(args.filename, rooms, doors)
        else:
            history = History()

        for tid in history:
            route.record(tid)
            if route.complete: break
        print('Route is %s' % ('complete' if route.complete else 'incomplete'))

        transition_log = FileTransitionLog(
            args.filename) if args.filename is not None else NullTransitionLog(
            )

        tracker = SegmentTimeTracker(
            history,
            transition_log,
            route,
            on_new_room_time=json_generator.new_room_time)

        timer_thread = TimerThread(history,
                                   rooms,
                                   doors,
                                   transition_log,
                                   route,
                                   json_generator,
                                   server,
                                   usb2snes=args.usb2snes)
        timer_thread.start()
        shutdown.append(timer_thread.stop)

        if args.headless:
            timer_thread.join()

        else:
            dirname = os.path.dirname(os.path.realpath(__file__))
            filename = 'sm_web_timer.html'
            port = args.port
            url = 'file://%s/%s?port=%s' % (dirname, filename, port)
            browser = Browser(sys.argv, url)
            sys.exit(browser.run())

    finally:
        for f in reversed(shutdown):
            try:
                f()
            except Exception as e:
                print(e)