Example #1
0
def create_builder():
    # Some BW4T settings
    block_colours = ['#ff0000', '#ffffff', '#ffff00', '#0000ff', '#00ff00', '#ff00ff']
    block_sense_range = 10  # the range with which agents detect blocks
    other_sense_range = np.inf  # the range with which agents detect other objects (walls, doors, etc.)
    agent_memory_decay = (10 / tick_duration)  # we want to memorize states for (seconds / tick_duration ticks) ticks

    # Set numpy's random generator
    np.random.seed(random_seed)

    # The world size, with plenty of space for agents to move between rooms
    world_size = (30, 44)

    # Create our world builder
    builder = WorldBuilder(shape=world_size, tick_duration=tick_duration, random_seed=random_seed, run_matrx_api=True,
                           run_matrx_visualizer=True, verbose=verbose, visualization_bg_clr="#f0f0f0",
                           visualization_bg_img="")

    # Add the world bounds (not needed, as agents cannot 'walk off' the grid, but for visual effect)
    builder.add_room(top_left_location=(0, 0), width=world_size[0], height=world_size[1], name="world_bounds")

    # Create the rooms
    room_locations = add_rooms(builder)

    # Add the blocks the agents need to collect, we do so probabilistically so each world will contain different blocks
    add_blocks(builder, room_locations, block_colours)

    # Create the drop-off zones, this includes generating the random colour/shape combinations to collect.
    add_drop_off_zone(builder, world_size, block_colours, nr_blocks_to_collect=2)

    # Add the agents and human agents to the top row of the world
    add_agents(builder, block_sense_range, other_sense_range, agent_memory_decay)

    # Return the builder
    return builder
Example #2
0
    def __init__(self,
                 agents: List[dict],
                 worldsettings: dict = DEFAULT_WORLDSETTINGS):
        '''
           @param agents a list like 
            [
            {'name':'agent1', 'botclass':PatrollingAgent, 'settings':{'slowdown':3}},
            {'name':'human1', 'botclass':Human, 'settings':{'slowdown':1}}
            ]
            Names must all be unique.
            Check BW4TBrain for more on the agents specification.
        '''
        self._worldsettings = worldsettings
        self._agents = agents

        np.random.seed(worldsettings['random_seed'])
        world_size = self.world_size()

        # Create the goal
        goal = CollectionGoal(worldsettings['deadline'])

        # Create our world builder
        self._builder = WorldBuilder(
            shape=world_size,
            tick_duration=worldsettings['tick_duration'],
            random_seed=worldsettings['random_seed'],
            run_matrx_api=worldsettings['run_matrx_api'],
            run_matrx_visualizer=worldsettings['run_matrx_visualizer'],
            verbose=worldsettings['verbose'],
            simulation_goal=goal)

        # Hacky? But this is apparently the way to do this.
        # Also note the extra underscore, maybe that's a buig in matrx?
        self._builder.api_info['_matrx_paused'] = worldsettings['matrx_paused']

        # Add the world bounds (not needed, as agents cannot 'walk off' the grid, but for visual effects)
        self._builder.add_room(top_left_location=(0, 0),
                               width=world_size[0],
                               height=world_size[1],
                               name="world_bounds")
        room_locations = self._addRooms()
        self._addBlocks(room_locations)
        self._addDropOffZones(world_size)

        # Add the agents and human agents to the top row of the world
        self._addAgents()

        media_folder = os.path.dirname(
            os.path.join(os.path.realpath(__file__), "media"))
        self._builder.startup(media_folder=media_folder)
        self._builder.add_logger(BW4TLogger, save_path='.')

        self._gridworld = self._builder.worlds(nr_of_worlds=1).__next__()
def create_builder():
    # Create our builder, here we specify the world size and a nice background image
    builder = WorldBuilder(shape=[14, 13],
                           run_matrx_api=True,
                           run_matrx_visualizer=True,
                           visualization_bg_img="",
                           tick_duration=0.1)

    # Add the walls surrounding the maze
    builder.add_room(top_left_location=[0, 0],
                     width=14,
                     height=13,
                     name="Borders")

    # Add the walls to our maze
    builder.add_line(start=[2, 2], end=[6, 2], name="Maze wall")
    builder.add_line(start=[8, 2], end=[11, 2], name="Maze wall")
    builder.add_line(start=[2, 3], end=[2, 5], name="Maze wall")
    builder.add_line(start=[11, 3], end=[11, 5], name="Maze wall")
    builder.add_line(start=[6, 4], end=[8, 4], name="Maze wall")
    builder.add_line(start=[9, 4], end=[9, 7], name="Maze wall")
    builder.add_line(start=[6, 5], end=[6, 6], name="Maze wall")
    builder.add_line(start=[4, 4], end=[4, 8], name="Maze wall")
    builder.add_line(start=[5, 8], end=[9, 8], name="Maze wall")
    builder.add_line(start=[2, 7], end=[2, 9], name="Maze wall")
    builder.add_line(start=[11, 7], end=[11, 9], name="Maze wall")
    builder.add_line(start=[2, 10], end=[5, 10], name="Maze wall")
    builder.add_line(start=[7, 10], end=[11, 10], name="Maze wall")

    # Add our treasure chest!
    builder.add_object(location=[7, 5],
                       name="Treasure!",
                       visualize_colour="#fcba03",
                       is_traversable=True)

    # Add a human controllable agent with certain controls and a GIF
    key_action_map = {
        'w': MoveNorth.__name__,
        'd': MoveEast.__name__,
        's': MoveSouth.__name__,
        'a': MoveWest.__name__,
    }
    brain = HumanAgentBrain()
    builder.add_human_agent(location=[1, 1],
                            agent=brain,
                            name="Human",
                            key_action_map=key_action_map,
                            img_name="/static/images/agent.gif")

    # Return the builder
    return builder
def create_builder(test_subject_id=None):
    world_size = [24, 28]
    bg_color = "#ebebeb"
    wall_color = "#adadad"
    tdp = "tdp_decision_support_explained"
    timestamp = setTimestamp()

    config_path = os.path.join(os.path.realpath("mhc"), 'cases',
                               'experiment_3_tdp_dss.json')

    config = json.load(open(config_path))
    print("Loaded config file:", config_path)

    np.random.seed(config['random_seed'])
    print("Set random seed:", config['random_seed'])

    # Create our builder instance
    builder = WorldBuilder(shape=world_size,
                           run_matrx_api=True,
                           run_matrx_visualizer=False,
                           visualization_bg_clr=bg_color,
                           visualization_bg_img="",
                           tick_duration=config['world']['tick_duration'],
                           simulation_goal=AllPatientsTriaged(
                               config['patients']['max_patients']))

    #################################################################
    # Rooms
    ################################################################
    add_mhc_rooms(builder, config, world_size, wall_color)

    #################################################################
    # Beds
    ################################################################
    add_mhc_chairs_beds(builder)

    #################################################################
    # Other objects
    ################################################################
    add_mhc_extras(builder, config)

    # add settings object
    builder.add_object(location=[0, 0],
                       is_traversable=True,
                       is_movable=False,
                       name="Settings",
                       visualize_size=0,
                       tdp=tdp,
                       visualize_your_vs_patient_robots=True,
                       start_timestamp=timestamp,
                       show_agent_predictions=True,
                       trial_completed=False,
                       config=config,
                       end_message=config['world']['trial_end_message'],
                       customizable_properties=['trial_completed'])

    #################################################################
    # Loggers
    ################################################################
    log_folder = tdp + "_" + timestamp
    if test_subject_id is not None:
        log_folder = f"test_subject_{test_subject_id}_{log_folder}"

    builder.add_logger(
        LogPatientStatus,
        save_path=os.path.join('Results', log_folder),
        file_name_prefix="patient_status",
    )

    builder.add_logger(LogNewPatients,
                       save_path=os.path.join('Results', log_folder),
                       file_name_prefix="new_patients")

    builder.add_logger(LogTriageDecision,
                       save_path=os.path.join('Results', log_folder),
                       file_name_prefix="triage_decisions")

    #################################################################
    # Actors
    ################################################################

    # create the patient planner (god agent) that spawns patients over time, as described in the config
    builder.add_agent(location=[0, 0],
                      is_traversable=True,
                      is_movable=False,
                      agent_brain=PatientPlanner(config=config, tdp=tdp),
                      name="Patient planner",
                      visualize_size=0)

    # add the test subject: the human doctor
    builder.add_human_agent(location=config['human_doctor']['location'],
                            is_traversable=True,
                            is_movable=False,
                            agent=HumanDoctor(),
                            name="human_doctor",
                            visualize_size=0)

    # add the hospital manager (god agent) that takes care of removing deceased patients
    builder.add_agent(location=[0, 0],
                      is_traversable=True,
                      is_movable=False,
                      agent_brain=HospitalManager(),
                      name="hospital_manager",
                      visualize_size=0)

    # Return the builder
    return builder