Ejemplo n.º 1
0
    async def start(self):
        future_launches = []
        future_connections = []
        for i in range(self._n_cores):
            simulator_supervisor = DynamicSimSupervisor(
                world_file=newpath + "/" + self._settings.world,
                simulator_cmd=self._settings.simulator_cmd,
                simulator_args=["--verbose"],
                plugins_dir_path=os.path.join(newpath, 'build', 'lib'),
                models_dir_path=os.path.join(newpath, 'models'),
                simulator_name='gazebo_{}'.format(i))
            simulator_future_launch = simulator_supervisor.launch_simulator(
                port=11345 + i)

            future_launches.append(simulator_future_launch)
            self._supervisors.append(simulator_supervisor)

        for i, future_launch in enumerate(future_launches):
            await future_launch
            connection_future = World.create(self._settings,
                                             world_address=("127.0.0.1",
                                                            11345 + i))
            future_connections.append(connection_future)

        for i, future_conn in enumerate(future_connections):
            self._connections.append(await future_conn)
            self._workers.append(
                asyncio.create_task(self._simulator_queue_worker(i)))
Ejemplo n.º 2
0
async def run():
    logger.info('Hello World!')
    settings = parser.parse_args()

    # Start Simulator
    if settings.simulator_cmd != 'debug':
        simulator_supervisor = DynamicSimSupervisor(
            world_file=settings.world,
            simulator_cmd=settings.simulator_cmd,
            simulator_args=["--verbose"],
            plugins_dir_path=os.path.join('.', 'build', 'lib'),
            models_dir_path=os.path.join('.', 'models'),
            simulator_name='gazebo'
        )
        await simulator_supervisor.launch_simulator(port=settings.port_start)
        await asyncio.sleep(0.1)

    connection = await World.create()
    if connection:
        logger.info("Connected to the simulator world.")

    await connection.pause(True)

    while True:
        await asyncio.sleep(10.0)
Ejemplo n.º 3
0
async def run():
    """
    The main coroutine, which is started below
    """
    log = logger.create_logger('experiment',
                               handlers=[
                                   logging.StreamHandler(sys.stdout),
                               ])

    # Set debug level to DEBUG
    log.setLevel(logging.DEBUG)

    # Parse command line / file input arguments
    settings = parser.parse_args()

    # Start Simulator
    if settings.simulator_cmd != 'debug':
        simulator_supervisor = DynamicSimSupervisor(
            world_file=settings.world,
            simulator_cmd=settings.simulator_cmd,
            simulator_args=["--verbose"],
            plugins_dir_path=os.path.join('.', 'build', 'lib'),
            models_dir_path=os.path.join('.', 'models'),
            simulator_name='gazebo')
        await simulator_supervisor.launch_simulator(port=settings.port_start)
        await asyncio.sleep(0.1)

    # Connect to the simulator and pause
    connection = await World.create(settings,
                                    world_address=('127.0.0.1',
                                                   settings.port_start))
    await asyncio.sleep(1)

    # initialization finished

    # load robot file
    robot = RevolveBot(_id=settings.test_robot)
    robot.load_file("/Users/nihed/Desktop/nihedssnakes/nihedssnake6.yaml",
                    conf_type='yaml')
    robot.save_file(
        f'{"/Users/nihed/Desktop/nihedssnakes/nihedssnake6.yaml"}.sdf',
        conf_type='sdf')

    # insert robot into the simulator
    robot_manager = await connection.insert_robot(robot,
                                                  Vector3(0, 0, 0.25),
                                                  life_timeout=None)
    await asyncio.sleep(1.0)

    # Start the main life loop
    while True:
        # Print robot fitness every second
        status = 'dead' if robot_manager.dead else 'alive'
        print(
            f"Robot fitness ({status}) is \n"
            f" OLD:     {fitness.online_old_revolve(robot_manager)}\n"
            f" DISPLAC: {fitness.displacement(robot_manager, robot)}\n"
            f" DIS_VEL: {fitness.displacement_velocity(robot_manager, robot)}")
        await asyncio.sleep(1.0)
Ejemplo n.º 4
0
 def _simulator_supervisor(self, simulator_name_postfix):
     return DynamicSimSupervisor(
         world_file='worlds/' + self._settings.world + '.world',
         simulator_cmd=self._simulator_cmd,
         simulator_args=["--verbose"],
         plugins_dir_path=os.path.join('.', 'build', 'lib'),
         models_dir_path=os.path.join('.', 'models'),
         simulator_name=f'gazebo_{simulator_name_postfix}')
Ejemplo n.º 5
0
async def run():
    """
    The main coroutine, which is started below.
    """
    robot_file_path = "experiments/examples/yaml/spider.yaml"

    # Parse command line / file input arguments
    settings = parser.parse_args()

    # Start Simulator
    if settings.simulator_cmd != 'debug':
        simulator_supervisor = DynamicSimSupervisor(
            world_file=settings.world,
            simulator_cmd=settings.simulator_cmd,
            simulator_args=["--verbose"],
            plugins_dir_path=os.path.join('.', 'build', 'lib'),
            models_dir_path=os.path.join('.', 'models'),
            simulator_name='gazebo')
        await simulator_supervisor.launch_simulator(port=settings.port_start)
        await asyncio.sleep(0.1)

    # Load a robot from yaml
    robot = revolve_bot.RevolveBot()
    robot.load_file(robot_file_path)
    robot.update_substrate()
    # robot._brain = BrainRLPowerSplines()

    # Connect to the simulator and pause
    connection = await World.create(settings,
                                    world_address=('127.0.0.1',
                                                   settings.port_start))
    await asyncio.sleep(1)

    # Starts the simulation
    await connection.pause(False)

    # Insert the robot in the simulator
    robot_manager = await connection.insert_robot(
        robot, Vector3(0, 0, settings.z_start))

    # Start a run loop to do some stuff
    while True:
        # Print robot fitness every second
        status = 'dead' if robot_manager.dead else 'alive'
        print(
            f"Robot fitness ({status}) is \n"
            f" OLD:     {fitness.online_old_revolve(robot_manager)}\n"
            f" DISPLAC: {fitness.displacement(robot_manager, robot)}\n"
            f" DIS_VEL: {fitness.displacement_velocity(robot_manager, robot)}")
        await asyncio.sleep(1.0)
Ejemplo n.º 6
0
async def run():
    # Start Simulator
    settings = parser.parse_args()
    if settings.simulator_cmd != 'debug':
        simulator_supervisor = DynamicSimSupervisor(
            world_file=settings.world,
            simulator_cmd=settings.simulator_cmd,
            simulator_args=["--verbose"],
            plugins_dir_path=os.path.join('.', 'build', 'lib'),
            models_dir_path=os.path.join('.', 'models'),
            simulator_name='gazebo')
        await simulator_supervisor.launch_simulator(port=settings.port_start)
        await asyncio.sleep(0.1)

    world = await World.create()
    if world:
        print("Connected to the simulator world.")

    sdf_model = """
    <sdf version ='1.5'>
        <model name ='sphere'>
            <pose>1 0 0 0 0 0</pose>
            <link name ='link'>
                <pose>0 0 .5 0 0 0</pose>
                <collision name ='collision'>
                    <geometry>
                        <sphere>
                            <radius>0.5</radius>
                        </sphere>
                    </geometry>
                </collision>
                <visual name ='visual'>
                    <geometry>
                        <sphere>
                            <radius>0.5</radius>
                        </sphere>
                    </geometry>
                </visual>
            </link>
        </model>
    </sdf>"""

    await world.insert_model(sdf_model)
    await world.pause(True)

    while True:
        await asyncio.sleep(10.0)
Ejemplo n.º 7
0
async def run():
    # Parse command line / file input arguments
    settings = parser.parse_args()

    # Start Simulator
    if settings.simulator_cmd != 'debug':
        simulator_supervisor = DynamicSimSupervisor(
            world_file=settings.world,
            simulator_cmd=settings.simulator_cmd,
            simulator_args=["--verbose"],
            plugins_dir_path=os.path.join('.', 'build', 'lib'),
            models_dir_path=os.path.join('.', 'models'),
            simulator_name='gazebo')
        await simulator_supervisor.launch_simulator(port=settings.port_start)
        # let there be some time to sync all initial output of the simulator
        await asyncio.sleep(5)

    # Connect to the simulator and pause
    connection = await World.create(settings,
                                    world_address=('127.0.0.1',
                                                   settings.port_start))
    await asyncio.sleep(1)
    await connection.disconnect()
    print("SIMULATOR STARTED")
Ejemplo n.º 8
0
async def run():
    # Parse command line / file input arguments
    settings = parser.parse_args()

    # create ata folder and logger
    data_folder = os.path.join(DATA_FOLDER_BASE, settings.experiment_name)
    data_folder = make_folders(data_folder)
    log = logger.create_logger('experiment',
                               handlers=[
                                   logging.StreamHandler(sys.stdout),
                                   logging.FileHandler(os.path.join(
                                       data_folder, 'experiment_manager.log'),
                                                       mode='w')
                               ])

    # Set debug level to DEBUG
    log.setLevel(logging.DEBUG)

    # Save settings
    experimental_settings = {
        'START': {
            'human': time.strftime("%a, %d %b %Y %H:%M:%S"),
            'seconds': time.time(),
        },
        'ROBOT_BATTERY': ROBOT_BATTERY,
        'ROBOT_STOP': ROBOT_STOP,
        'ROBOT_SELF_COLLIDE': ROBOT_SELF_COLLIDE,
        'REPRODUCE_LOCALLY_RADIUS': REPRODUCE_LOCALLY_RADIUS,
        'INDIVIDUAL_MAX_AGE': INDIVIDUAL_MAX_AGE,
        'INDIVIDUAL_MAX_AGE_SIGMA': INDIVIDUAL_MAX_AGE_SIGMA,
        'SEED_POPULATION_START': SEED_POPULATION_START,
        'MIN_POP': MIN_POP,
        'MAX_POP': MAX_POP,
        'Z_SPAWN_DISTANCE': Z_SPAWN_DISTANCE,
        'LIMIT_X': LIMIT_X,
        'LIMIT_Y': LIMIT_Y,
        'MATURE_AGE': MATURE_AGE,
        'MATE_DISTANCE': MATE_DISTANCE,
        'MATING_COOLDOWN': MATING_COOLDOWN,
        'COUPLE_MATING_LIMIT': COUPLE_MATING_LIMIT,
        'MATING_INCREASE_RATE': MATING_INCREASE_RATE,
        'RECENT_CHILDREN_DELTA_TIME': RECENT_CHILDREN_DELTA_TIME,
        'PLASTICODING_CONF.max_structural_modules':
        PLASTICODING_CONF.max_structural_modules,
        'CROSSOVER_PROBABILITY': CROSSOVER_CONF.crossover_prob,
        'MUTATION_PROBABILITY': MUTATION_CONF.mutation_prob,

        # FOLDER WHERE TO SAVE THE EXPERIMENT
        # {current_folder}/data/{arguments.experiment_name}
        # example ~/projects/revolve/experiments/unmanaged/data/default_experiment
        'DATA_FOLDER_BASE': DATA_FOLDER_BASE,
    }
    with open(os.path.join(data_folder, 'experimental_settings.yaml'),
              'w') as f:
        f.write(str(yaml.dump(experimental_settings)))

    # Start Simulator
    if settings.simulator_cmd != 'debug':

        def simulator_dead(_process, ret_code):
            log.error("SIMULATOR DIED BEFORE THE END OF THE EXPERIMENT")
            sys.exit(ret_code)

        simulator_supervisor = DynamicSimSupervisor(
            world_file=settings.world,
            simulator_cmd=settings.simulator_cmd,
            simulator_args=["--verbose"],
            plugins_dir_path=os.path.join('.', 'build', 'lib'),
            models_dir_path=os.path.join('.', 'models'),
            simulator_name='gazebo',
            process_terminated_callback=simulator_dead,
        )
        await simulator_supervisor.launch_simulator(port=settings.port_start)
        # let there be some time to sync all initial output of the simulator
        await asyncio.sleep(5)

    # Connect to the simulator and pause
    connection = await World.create(settings,
                                    world_address=('127.0.0.1',
                                                   settings.port_start))
    connection.output_directory = os.path.join(data_folder, 'snapshots')
    await asyncio.sleep(1)

    robot_population = Population(log, data_folder, connection)

    log.info("SEEDING POPULATION STARTED")
    await robot_population.seed_initial_population(pause_while_inserting=False)
    log.info("SEEDING POPULATION FINISHED")

    # Start the main life loop
    try:
        last_snapshot = connection.last_time

        log.info("creating initial snapshot")
        success = await robot_population.create_snapshot()

        while True:
            world_time = connection.last_time
            if float(world_time - last_snapshot) > SNAPSHOT_TIME:
                log.info(f"Creating snapshot at {world_time}")
                last_snapshot = world_time
                success = await robot_population.create_snapshot()
            await robot_population.death_season()
            await robot_population.mating_season()
            await robot_population.immigration_season()
            robot_population.adjust_mating_multiplier(connection.age())

            await asyncio.sleep(0.05)
    except Finish:
        await asyncio.wait_for(connection.disconnect(), 10)
        if settings.simulator_cmd != 'debug':
            await asyncio.wait_for(simulator_supervisor.stop(), 10)
        log.info("EVOLUTION finished successfully")
Ejemplo n.º 9
0
async def run():
    """
    The main coroutine, which is started below.
    """

    arguments = parser.parse_args()

    if arguments.robot_name is not None:
        # this split will give errors on windows
        robot_file_path = "experiments/bodies/" + arguments.robot_name + ".yaml"

    if arguments.iterations is not None:
        # this split will give errors on windows
        iterations = int(arguments.iterations)

    #robot_file_path = "experiments/examples/yaml/spider.yaml"

    # Parse command line / file input arguments
    settings = parser.parse_args()

    # Start Simulator
    if settings.simulator_cmd != 'debug':
        simulator_supervisor = DynamicSimSupervisor(
            world_file=settings.world,
            simulator_cmd=settings.simulator_cmd,
            simulator_args=["--verbose"],
            plugins_dir_path=os.path.join('.', 'build', 'lib'),
            models_dir_path=os.path.join('.', 'models'),
            simulator_name='gazebo')
        await simulator_supervisor.launch_simulator(port=settings.port_start)
        await asyncio.sleep(0.1)

    # Load a robot from yaml
    robot = revolve_bot.RevolveBot()
    robot.load_file(robot_file_path)
    robot.update_substrate()
    # robot._brain = BrainRLPowerSplines()

    # Connect to the simulator and pause
    connection = await World.create(settings,
                                    world_address=('127.0.0.1',
                                                   settings.port_start))
    await asyncio.sleep(1)

    # Starts the simulation
    await connection.pause(False)

    # Insert the robot in the simulator
    #life_timeout = Fixed time a robot stays in the simulator
    robot_manager = await connection.insert_robot(
        robot, Vector3(0, 0, settings.z_start))

    robot_fitness = []
    for x in range(1, iterations):
        # Print robot fitness every second
        robot_fitness.append(
            fitness.displacement_velocity(robot_manager, robot))
        await asyncio.sleep(0.1)

    print("**The Robot Fitness is: ",
          str(sum(robot_fitness) / len(robot_fitness)))