Ejemplo n.º 1
0
async def run():
    """
    The main coroutine, which is started below.
    """

    n_cores = 1

    experiment_conf = ExperimentConfig()
    settings = parser.parse_args()
    queue = SimulatorQueue(n_cores, settings)
    await queue.start()

    population = Population(experiment_conf.population_conf)
    await population.init_pop(queue)
    # population.simulator_connection.disconnect()

    # await simulator_supervisor.relaunch()

    gen_num = 0
    while gen_num < experiment_conf.num_generations:
        population = await population.next_gen(gen_num + 1, queue)
        # simulator_connection.disconnect()
        # simulator_supervisor.relaunch()
        # population.simulator_connection = await World.create(settings)
        gen_num += 1
Ejemplo n.º 2
0
def main():
    import traceback

    def handler(_loop, context):
        try:
            exc = context['exception']
        except KeyError:
            print(context['message'])
            return

        if isinstance(exc, ConnectionResetError):
            print("Got disconnect / connection reset - shutting down.")
            sys.exit(0)

        if isinstance(exc, OSError) and exc.errno == 9:
            print(exc)
            traceback.print_exc()
            return

        # traceback.print_exc()
        raise exc

    try:
        arguments = parser.parse_args()
        loop = asyncio.get_event_loop()
        loop.set_exception_handler(handler)
        run(loop, arguments)
    except KeyboardInterrupt:
        print("Got CtrlC, shutting down.")
Ejemplo n.º 3
0
async def run():
    """
    The main coroutine, which is started below.
    """
    # Parse command line / file input arguments
    settings = parser.parse_args()

    # Load a robot from yaml
    robot = revolve_bot.RevolveBot()
    if settings.robot_yaml is None:
        robot.load_file("experiments/bo_learner/yaml/spider.yaml")
    else:
        robot.load_file(settings.robot_yaml)
    robot.update_substrate()

    # Connect to the simulator and pause
    world = await World.create(settings)
    await world.pause(True)

    await world.delete_model(robot.id)
    await asyncio.sleep(2.5)

    # Insert the robot in the simulator
    robot_manager = await world.insert_robot(robot, Vector3(0, 0, 0.025))

    # Resume simulation
    await world.pause(False)

    # Start a run loop to do some stuff
    while True:
        await asyncio.sleep(5.0)
Ejemplo n.º 4
0
async def run():
    """
    The main coroutine, which is started below.
    """
    # Parse command line / file input arguments
    settings = parser.parse_args()

    # Load a robot from yaml
    robot = revolve_bot.RevolveBot()
    robot.load_file("experiments/examples/yaml/spider.yaml")

    # Connect to the simulator and pause
    world = await World.create(settings)
    await world.pause(True)

    # Insert the robot in the simulator
    robot_manager = await world.insert_robot(robot, Vector3(0, 0, 0.05))

    # Resume simulation
    await world.pause(False)

    # Start a run loop to do some stuff
    while True:
        # Print robot fitness every second
        print("Robot fitness is {fitness}".format(
            fitness=robot_manager.fitness()))
        await asyncio.sleep(1.0)
Ejemplo n.º 5
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.º 6
0
async def run():
    """
    The main coroutine, which is started below.
    """
    # Parse command line / file input arguments
    settings = parser.parse_args()

    # Load a robot from yaml
    robot = revolve_bot.RevolveBot()
    robot.load_file("experiments/examples/yaml/spider.yaml")
    robot.update_substrate()

    # Connect to the simulator and pause
    world = await World.create(settings)
    await world.pause(True)

    await (await world.delete_model(robot.id))
    await asyncio.sleep(2.5)

    # Insert the robot in the simulator
    insert_future = await world.insert_robot(robot, Vector3(0, 0, 0.25))
    robot_manager = await insert_future

    # Resume simulation
    await world.pause(False)

    # Start a run loop to do some stuff
    while True:
        # Print robot fitness every second
        print("Robot fitness is {fitness}".format(
                fitness=robot_manager.fitness()))
        await asyncio.sleep(1.0)
Ejemplo n.º 7
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.º 8
0
async def test_collision_robot(robot_file_path: str):
    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()

    assert (settings.test_robot_collision is not None)
    robot = RevolveBot(_id=settings.test_robot_collision)
    robot.load_file(robot_file_path, conf_type='yaml')
    robot.save_file(f'{robot_file_path}.sdf', conf_type='sdf')

    def simulator_died_callback(_process, _ret_code):
        pass

    # Start Simulator
    if settings.simulator_cmd != 'debug':
        simulator_supervisor = CollisionSimSupervisor(
            world_file=os.path.join('tools', 'analyzer', 'analyzer-world.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_died_callback,
        )
        await simulator_supervisor.launch_simulator(port=settings.port_start)
        await asyncio.sleep(0.1)

    log.debug("simulator ready")

    # Connect to the simulator and pause
    analyzer = await BodyAnalyzer.create('127.0.0.1', settings.port_start)
    log.debug("connection ready")
    await asyncio.sleep(1)

    log.info("Sending robot to the analyzer simulator")
    start = time.time()
    result = await analyzer.analyze_robot(robot)
    end = time.time()

    log.debug(f'Analyzer finished in {end-start}')
    log.debug('result:')
    log.debug(result)

    await analyzer.disconnect()
    log.debug("disconnected")

    if settings.simulator_cmd != 'debug':
        await simulator_supervisor.stop()

    log.debug("simulator killed")
Ejemplo n.º 9
0
async def run():

    settings = parser.parse_args()
    yaml_file = 'experiments/'+ settings.experiment_name sla+'/data_fullevolution/phenotypes/'+'phenotype_'+settings.test_robot+'.yaml'

    r = RevolveBot(_id=settings.test_robot)
    r.load_file(yaml_file, conf_type='yaml')
    #r.save_file('experiments/'+ settings +'/data_fullevolution/phenotype_35.sdf.xml', conf_type='sdf')
    #r.render_body('experiments/'+ settings +'/data_fullevolution/phenotypes/phenotype_35.body.png')

    connection = await World.create(settings, world_address=("127.0.0.1", settings.port_start))
    await connection.insert_robot(r)
Ejemplo n.º 10
0
async def run():
    print('Hello World from `{}`'.format(rvpath))
    settings = parser.parse_args()

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

    await world.pause(True)

    while True:
        await asyncio.sleep(10.0)
Ejemplo n.º 11
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.º 12
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.º 13
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.º 14
0
async def run():
    """
    The main coroutine, which is started below.
    """
    # Parse command line / file input arguments

    genotype_conf = PlasticodingConfig(max_structural_modules=100, )

    mutation_conf = MutationConfig(
        mutation_prob=0.8,
        genotype_conf=genotype_conf,
    )

    crossover_conf = CrossoverConfig(crossover_prob=0.8, )

    settings = parser.parse_args()
    experiment_management = ExperimentManagement(settings)

    population_conf = PopulationConfig(
        population_size=100,
        genotype_constructor=random_initialization,
        genotype_conf=genotype_conf,
        fitness_function=fitness.displacement_velocity_hill,
        mutation_operator=standard_mutation,
        mutation_conf=mutation_conf,
        crossover_operator=standard_crossover,
        crossover_conf=crossover_conf,
        selection=lambda individuals: tournament_selection(individuals, 2),
        parent_selection=lambda individuals: multiple_selection(
            individuals, 2, tournament_selection),
        population_management=steady_state_population_management,
        population_management_selector=tournament_selection,
        evaluation_time=settings.evaluation_time,
        offspring_size=50,
        experiment_name=settings.experiment_name,
        experiment_management=experiment_management,
    )

    settings = parser.parse_args()
    simulator_queue = SimulatorQueue(settings.n_cores, settings,
                                     settings.port_start)
    await simulator_queue.start()

    population = Population(population_conf, simulator_queue, 0)

    # choose a snapshot here. and the maximum best individuals you wish to watch
    generation = 100
    max_best = 10
    await population.load_snapshot(generation)

    fitnesses = []
    for ind in population.individuals:
        fitnesses.append(ind.fitness)
    fitnesses = np.array(fitnesses)

    ini = len(population.individuals) - max_best
    fin = len(population.individuals)
    population.individuals = np.array(population.individuals)
    population.individuals = population.individuals[np.argsort(fitnesses)
                                                    [ini:fin]]

    await population.evaluate(population.individuals, generation)
Ejemplo n.º 15
0
        """
        :param data:
        :return:
        """
        if 'ODE Message 3' in data:
            self.ode_errors += 1
        elif data.strip():
            sys.stderr.write(data)

        if self.ode_errors >= 100:
            self.ode_errors = 0
            sys.stderr.write('ODE Message 3 (100)\n')


if __name__ == "__main__":
    settings = parser.parse_args()
    manager_settings = sys.argv[1:]
    supervisor = OnlineEvolutionSupervisor(
        manager_cmd=settings.manager,
        manager_args=manager_settings,
        world_file=settings.world,
        simulator_cmd=settings.simulator_cmd,
        simulator_args=["--verbose"],
        plugins_dir_path=os.path.join(rvpath, 'build', 'lib'),
        models_dir_path=os.path.join(rvpath, 'models'))

    if settings.manager is None:
        ret = supervisor.launch_simulator()
    else:
        ret = supervisor.launch()
    sys.exit(ret)
Ejemplo n.º 16
0
        """
        :param data:
        :return:
        """
        if 'ODE Message 3' in data:
            self.ode_errors += 1
        elif data.strip():
            sys.stderr.write(data)

        if self.ode_errors >= 100:
            self.ode_errors = 0
            sys.stderr.write('ODE Message 3 (100)\n')


if __name__ == "__main__":
    settings = parser.parse_args()
    manager_settings = sys.argv[1:]
    supervisor = OnlineEvolutionSupervisor(
        manager_cmd=settings.manager,
        manager_args=manager_settings,
        world_file=settings.world,
        simulator_cmd=settings.simulator_cmd,
        simulator_args=["--verbose"],
        plugins_dir_path=os.path.join(rvpath, 'build', 'lib'),
        models_dir_path=os.path.join(rvpath, 'models')
    )

    if settings.manager is None:
        ret = supervisor.launch_simulator()
    else:
        ret = supervisor.launch()
Ejemplo n.º 17
0
async def run():
    """
    The main coroutine, which is started below.
    """

    # experiment params #
    num_generations = 200
    population_size = 100
    offspring_size = 100
    front = 'slaves'

    # environment world and z-start
    environments = {'plane': 0.03,
                    'tilted5': 0.1
                    }

    genotype_conf = PlasticodingConfig(
        max_structural_modules=15,
        plastic=True,
    )

    mutation_conf = MutationConfig(
        mutation_prob=0.8,
        genotype_conf=genotype_conf,
    )

    crossover_conf = CrossoverConfig(
        crossover_prob=0.8,
    )
    # experiment params #

    # Parse command line / file input arguments
    settings = parser.parse_args()
    experiment_management = ExperimentManagement(settings, environments)
    do_recovery = settings.recovery_enabled and not experiment_management.experiment_is_new()

    logger.info('Activated run '+settings.run+' of experiment '+settings.experiment_name)

    if do_recovery:
        gen_num, has_offspring, next_robot_id = experiment_management.read_recovery_state(population_size,
                                                                                          offspring_size)

        if gen_num == num_generations-1:
            logger.info('Experiment is already complete.')
            return
    else:
        gen_num = 0
        next_robot_id = 1

    def fitness_function_plane(robot_manager, robot):
        return fitness.displacement_velocity_hill(robot_manager, robot, False)

    fitness_function = {'plane': fitness_function_plane,
                        'tilted5': fitness_function_plane}

    population_conf = PopulationConfig(
        population_size=population_size,
        genotype_constructor=random_initialization,
        genotype_conf=genotype_conf,
        fitness_function=fitness_function,
        mutation_operator=standard_mutation,
        mutation_conf=mutation_conf,
        crossover_operator=standard_crossover,
        crossover_conf=crossover_conf,
        selection=lambda individuals: tournament_selection(individuals, environments, 2),
        parent_selection=lambda individuals: multiple_selection(individuals, 2, tournament_selection, environments),
        population_management=steady_state_population_management,
        population_management_selector=tournament_selection,
        evaluation_time=settings.evaluation_time,
        offspring_size=offspring_size,
        experiment_name=settings.experiment_name,
        experiment_management=experiment_management,
        environments=environments,
        front=front
    )


    settings = parser.parse_args()

    simulator_queue = {}
    analyzer_queue = None

    previous_port = None
    for environment in environments:

        settings.world = environment
        settings.z_start = environments[environment]

        if previous_port is None:
            port = settings.port_start
            previous_port = port
        else:
            port = previous_port+settings.n_cores
            previous_port = port

        simulator_queue[environment] = SimulatorQueue(settings.n_cores, settings, port)
        await simulator_queue[environment].start()

    analyzer_queue = AnalyzerQueue(1, settings, port+settings.n_cores)
    await analyzer_queue.start()

    population = Population(population_conf, simulator_queue, analyzer_queue, next_robot_id)

    if do_recovery:

        if gen_num >= 0:
            # loading a previous state of the experiment
            await population.load_snapshot(gen_num)
            logger.info('Recovered snapshot '+str(gen_num)+', pop with ' + str(len(population.individuals))+' individuals')

        if has_offspring:
            individuals = await population.load_offspring(gen_num, population_size, offspring_size, next_robot_id)
            gen_num += 1
            logger.info('Recovered unfinished offspring '+str(gen_num))

            if gen_num == 0:
                await population.init_pop(individuals)
            else:
                population = await population.next_gen(gen_num, individuals)

            experiment_management.export_snapshots(population.individuals, gen_num)
    else:
        # starting a new experiment
        experiment_management.create_exp_folders()
        await population.init_pop()
        experiment_management.export_snapshots(population.individuals, gen_num)

    while gen_num < num_generations-1:
        gen_num += 1
        population = await population.next_gen(gen_num)
        experiment_management.export_snapshots(population.individuals, gen_num)
Ejemplo n.º 18
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)))
Ejemplo n.º 19
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.º 20
0
async def run():
    """
    The main coroutine, which is started below.
    """

    # experiment params #
    num_generations = 100
    population_size = 100
    offspring_size = 50

    genotype_conf = PlasticodingConfig(
        max_structural_modules=100,
    )

    mutation_conf = MutationConfig(
        mutation_prob=0.8,
        genotype_conf=genotype_conf,
    )

    crossover_conf = CrossoverConfig(
        crossover_prob=0.8,
    )
    # experiment params #

    # Parse command line / file input arguments
    settings = parser.parse_args()
    experiment_management = ExperimentManagement(settings)
    do_recovery = settings.recovery_enabled and not experiment_management.experiment_is_new()

    logger.info('Activated run '+settings.run+' of experiment '+settings.experiment_name)

    if do_recovery:
        gen_num, has_offspring, next_robot_id = experiment_management.read_recovery_state(population_size, offspring_size)

        if gen_num == num_generations-1:
            logger.info('Experiment is already complete.')
            return
    else:
        gen_num = 0
        next_robot_id = 1

    def fitness_function(robot_manager, robot):
        contacts = measures.contacts(robot_manager, robot)
        assert(contacts != 0)
        return fitness.displacement_velocity_hill(robot_manager, robot)

    population_conf = PopulationConfig(
        population_size=population_size,
        genotype_constructor=random_initialization,
        genotype_conf=genotype_conf,
        fitness_function=fitness_function,
        mutation_operator=standard_mutation,
        mutation_conf=mutation_conf,
        crossover_operator=standard_crossover,
        crossover_conf=crossover_conf,
        selection=lambda individuals: tournament_selection(individuals, 2),
        parent_selection=lambda individuals: multiple_selection(individuals, 2, tournament_selection),
        population_management=steady_state_population_management,
        population_management_selector=tournament_selection,
        evaluation_time=settings.evaluation_time,
        offspring_size=offspring_size,
        experiment_name=settings.experiment_name,
        experiment_management=experiment_management,
    )

    settings = parser.parse_args()
    simulator_queue = SimulatorQueue(settings.n_cores, settings, settings.port_start)
    await simulator_queue.start()

    population = Population(population_conf, simulator_queue, next_robot_id)

    if do_recovery:
        # loading a previous state of the experiment
        await population.load_snapshot(gen_num)
        if gen_num >= 0:
            logger.info('Recovered snapshot '+str(gen_num)+', pop with ' + str(len(population.individuals))+' individuals')
        if has_offspring:
            individuals = await population.load_offspring(gen_num, population_size, offspring_size, next_robot_id)
            gen_num += 1
            logger.info('Recovered unfinished offspring '+str(gen_num))

            if gen_num == 0:
                await population.init_pop(individuals)
            else:
                population = await population.next_gen(gen_num, individuals)

            experiment_management.export_snapshots(population.individuals, gen_num)
    else:
        # starting a new experiment
        experiment_management.create_exp_folders()
        await population.init_pop()
        experiment_management.export_snapshots(population.individuals, gen_num)

    while gen_num < num_generations-1:
        gen_num += 1
        population = await population.next_gen(gen_num)
        experiment_management.export_snapshots(population.individuals, gen_num)
Ejemplo n.º 21
0
async def run():
    """
    The main coroutine, which is started below.
    """

    # experiment params #
    num_generations = 100
    population_size = 100
    offspring_size = 50
    front = 'slaves'

    # environment world and z-start
    environments = {'plane': 0.03, 'tilted5': 0.1}

    genotype_conf = PlasticodingConfig(
        max_structural_modules=15,
        plastic=True,
    )

    mutation_conf = MutationConfig(
        mutation_prob=0.8,
        genotype_conf=genotype_conf,
    )

    crossover_conf = CrossoverConfig(crossover_prob=0.8, )
    # experiment params #load_individual

    # Parse command line / file input arguments
    settings = parser.parse_args()
    experiment_management = ExperimentManagement(settings, environments)
    do_recovery = settings.recovery_enabled and not experiment_management.experiment_is_new(
    )

    logger.info('Activated run ' + settings.run + ' of experiment ' +
                settings.experiment_name)

    def fitness_function(robot_manager, robot):
        #contacts = measures.contacts(robot_manager, robot)
        #assert(contacts != 0)
        return fitness.displacement_velocity_hill(robot_manager, robot, False)

    population_conf = PopulationConfig(
        population_size=population_size,
        genotype_constructor=random_initialization,
        genotype_conf=genotype_conf,
        fitness_function=fitness_function,
        mutation_operator=standard_mutation,
        mutation_conf=mutation_conf,
        crossover_operator=standard_crossover,
        crossover_conf=crossover_conf,
        selection=lambda individuals: tournament_selection(
            individuals, environments, 2),
        parent_selection=lambda individuals: multiple_selection(
            individuals, 2, tournament_selection, environments),
        population_management=steady_state_population_management,
        population_management_selector=tournament_selection,
        evaluation_time=settings.evaluation_time,
        offspring_size=offspring_size,
        experiment_name=settings.experiment_name,
        experiment_management=experiment_management,
        environments=environments,
        front=front)

    settings = parser.parse_args()

    simulator_queue = {}
    analyzer_queue = None

    previous_port = None
    for environment in environments:

        settings.world = environment
        settings.z_start = environments[environment]

        if previous_port is None:
            port = settings.port_start
            previous_port = port
        else:
            port = previous_port + settings.n_cores
            previous_port = port

        simulator_queue[environment] = SimulatorQueue(settings.n_cores,
                                                      settings, port)
        await simulator_queue[environment].start()

    analyzer_queue = AnalyzerQueue(1, settings, port + settings.n_cores)
    await analyzer_queue.start()

    population = Population(population_conf, simulator_queue, analyzer_queue,
                            1)

    # choose a snapshot here. and the maximum best individuals you wish to watch
    generation = 61  #99
    max_best = 3  #10
    await population.load_snapshot(generation)

    values = []
    for ind in population.individuals:
        # define a criteria here
        for environment in environments:
            ind[environment].evaluated = False
        values.append(ind[list(environments.keys())[-1]].consolidated_fitness)
        #values.append(ind['plane'].phenotype._behavioural_measurements.displacement_velocity_hill)

    values = np.array(values)

    ini = len(population.individuals) - max_best
    fin = len(population.individuals)

    population.individuals = np.array(population.individuals)
    # highest
    population.individuals = population.individuals[np.argsort(values)
                                                    [ini:fin]]
    # lowest
    #population.individuals = population.individuals[np.argsort(values)[0:max_best]]

    for ind in population.individuals:
        print(ind[list(environments.keys())[-1]].phenotype.id)
        print('consolidated_fitness',
              ind[list(environments.keys())[-1]].consolidated_fitness)

    for environment in environments:
        print(environment)
        await population.evaluate(new_individuals=population.individuals,
                                  gen_num=generation,
                                  environment=environment,
                                  type_simulation='watch')