コード例 #1
0
ファイル: quicktest2.py プロジェクト: ElteHupkes/tol-revolve
def run(conf):
    """

    :param conf:
    :return:
    """
    conf.evaluation_time = 5.0
    conf.output_directory = 'output'
    world = yield From(World.create(conf))
    yield From(world.pause(True))

    for i in range(3):
        ta, _, _ = yield From(world.generate_valid_robot())
        tb, _, _ = yield From(world.generate_valid_robot())
        ra = yield From(wait_for(world.insert_robot(ta, pose=Pose(position=Vector3(0, 3*i, 0.5)))))
        rb = yield From(wait_for(world.insert_robot(tb, pose=Pose(position=Vector3(0, 3*i + 1, 0.5)))))

        while True:
            # Attempt reproduction
            mate = yield From(world.attempt_mate(ra, rb))

            if mate:
                break

        tree, bbox = mate
        yield From(wait_for(world.insert_robot(tree, pose=Pose(position=Vector3(0, 3*i + 2, 0.5)))))
コード例 #2
0
    def run(self, conf):
        conf.min_parts = 1
        conf.max_parts = 3
        conf.arena_size = (3, 3)
        conf.max_lifetime = 99999
        conf.initial_age_mu = 99999
        conf.initial_age_sigma = 1
        conf.age_cutoff = 99999

        self.body_spec = get_body_spec(conf)
        self.brain_spec = get_brain_spec(conf)
        self.nn_parser = NeuralNetworkParser(self.brain_spec)

        print "OPENING FILES!!!!!!!!!!!!!!!!!!!"
        with open("body/{0}".format(self.body_file), 'r') as robot_file:
            robot_yaml = robot_file.read()

        for filename in self.brain_files:
            with open("brains/{0}".format(filename, 'r')) as brain_file:
                br_yaml = brain_file.read()
                self.brain_genotypes.append(
                    yaml_to_genotype(br_yaml, self.brain_spec))

        yield From(wait_for(self.pause(True)))

        pose = Pose(position=Vector3(0, 0, 0.5), rotation=rotate_vertical(0))

        robot_pb = yaml_to_robot(self.body_spec, self.brain_spec, robot_yaml)
        tree = Tree.from_body_brain(robot_pb.body, robot_pb.brain,
                                    self.body_spec)

        print "INSERTING ROBOT!!!!!!!!!!!!!!!!!!!!!!"
        robot = yield From(wait_for(self.insert_robot(tree, pose)))
        self.robot_name = robot.name

        self.modify_nn_publisher = yield From(
            self.manager.advertise(
                '/gazebo/default/{0}/modify_neural_network'.format(
                    self.robot_name),
                'gazebo.msgs.ModifyNeuralNetwork',
            ))
        # Wait for connections
        yield From(self.modify_nn_publisher.wait_for_listener())

        brain_num = 0
        num_of_brains = len(self.brain_genotypes)
        print "Number of brains = {0}".format(num_of_brains)

        yield From(wait_for(self.pause(False)))
        while (True):
            if self.timers.is_it_time('evaluate', self.time_period,
                                      self.get_world_time()):
                n = brain_num % num_of_brains
                print "Switching brain to #{0}!!!!!!!!!".format(n)
                yield From(self.insert_brain(self.brain_genotypes[n]))
                self.timers.reset('evaluate', self.get_world_time())
                brain_num += 1

            yield From(trollius.sleep(0.1))
コード例 #3
0
ファイル: benchmark2.py プロジェクト: ElteHupkes/tol-revolve
def run_server():
    conf = parser.parse_args()
    conf.analyzer_address = None

    world = yield From(World.create(conf))
    yield From(world.pause(True))

    with open("/home/elte/mt/tol/scripts/starfish.yaml", "rb") as f:
        robot_yaml = f.read()

    body_spec = world.builder.body_builder.spec
    brain_spec = world.builder.brain_builder.spec
    bot = yaml_to_robot(body_spec, brain_spec, robot_yaml)

    fname = conf.output_directory+"/revolve_benchmark.csv"
    exists = os.path.exists(fname)
    if exists:
        f = open(fname, 'ab', buffering=1)
    else:
        f = open(fname, 'wb', buffering=1)

    output = csv.writer(f, delimiter=',')

    if not exists:
        output.writerow(['run', 'population_size', 'step_size',
                         'sim_time', 'real_time', 'factor'])

    n_bots = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
    sim_time = 5.0
    runs = 20

    yield From(world.pause(False))

    for n in n_bots:
        poses = get_poses(n)
        trees = [Tree.from_body_brain(bot.body, bot.brain, body_spec) for _ in range(n)]

        for i in range(runs):
            yield From(wait_for(world.insert_population(trees, poses)))

            while world.last_time is None:
                yield From(trollius.sleep(0.1))

            sim_before = world.last_time
            before = time.time()

            while float(world.last_time - sim_before) < sim_time:
                yield From(trollius.sleep(0.1))

            sim_diff = float(world.last_time - sim_before)
            diff = time.time() - before

            output.writerow((i, n, conf.world_step_size, sim_diff,
                             diff, sim_diff / diff))

            yield From(wait_for(world.delete_all_robots()))
            yield From(trollius.sleep(0.3))
コード例 #4
0
ファイル: benchmark.py プロジェクト: karinemiras/tol-revolve
def run():
    """
    :return:
    """
    conf = parser.parse_args()
    conf.world_step_size = 0.004

    fname = conf.output_directory + "/benchmark.csv"
    exists = os.path.exists(fname)
    if exists:
        f = open(fname, 'ab', buffering=1)
    else:
        f = open(fname, 'wb', buffering=1)

    output = csv.writer(f, delimiter=',')

    if not exists:
        output.writerow([
            'run', 'population_size', 'step_size', 'sim_time', 'real_time',
            'factor'
        ])

    world = yield From(OnlineEvoManager.create(conf))
    yield From(wait_for(world.pause(False)))

    population_sizes = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
    sim_time = 5
    runs = 20

    for n in population_sizes:
        for i in range(runs):
            trees, bboxes = yield From(world.generate_population(n))
            for tree, bbox in zip(trees, bboxes):
                res = yield From(world.birth(tree, bbox, None))
                yield From(res)
                yield From(trollius.sleep(0.05))

            while world.last_time is None:
                yield From(trollius.sleep(0.1))

            sim_before = world.last_time
            before = time.time()

            while float(world.last_time - sim_before) < sim_time:
                yield From(trollius.sleep(0.1))

            sim_diff = float(world.last_time - sim_before)
            diff = time.time() - before

            output.writerow(
                (i, n, conf.world_step_size, sim_diff, diff, sim_diff / diff))

            yield From(wait_for(world.delete_all_robots()))
            yield From(trollius.sleep(0.3))

    f.close()
コード例 #5
0
ファイル: benchmark.py プロジェクト: ElteHupkes/tol-revolve
def run():
    """
    :return:
    """
    conf = parser.parse_args()
    conf.world_step_size = 0.004

    fname = conf.output_directory+"/benchmark.csv"
    exists = os.path.exists(fname)
    if exists:
        f = open(fname, 'ab', buffering=1)
    else:
        f = open(fname, 'wb', buffering=1)

    output = csv.writer(f, delimiter=',')

    if not exists:
        output.writerow(['run', 'population_size', 'step_size',
                         'sim_time', 'real_time', 'factor'])

    world = yield From(OnlineEvoManager.create(conf))
    yield From(wait_for(world.pause(False)))

    population_sizes = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
    sim_time = 5
    runs = 20

    for n in population_sizes:
        for i in range(runs):
            trees, bboxes = yield From(world.generate_population(n))
            for tree, bbox in zip(trees, bboxes):
                res = yield From(world.birth(tree, bbox, None))
                yield From(res)
                yield From(trollius.sleep(0.05))

            while world.last_time is None:
                yield From(trollius.sleep(0.1))

            sim_before = world.last_time
            before = time.time()

            while float(world.last_time - sim_before) < sim_time:
                yield From(trollius.sleep(0.1))

            sim_diff = float(world.last_time - sim_before)
            diff = time.time() - before

            output.writerow((i, n, conf.world_step_size, sim_diff,
                             diff, sim_diff / diff))

            yield From(wait_for(world.delete_all_robots()))
            yield From(trollius.sleep(0.3))

    f.close()
コード例 #6
0
ファイル: world.py プロジェクト: egdman/tol-revolve
    def place_birth_clinic(self, diameter, height, angle=None):
        """
        CURRENTLY NOT USED.

        Places the birth clinic. Since we're lazy and rotating appears to cause errors,
        we're just deleting the old birth clinic and inserting a new one every time.
        Inserts the birth clinic
        :param height:
        :param diameter:
        :param angle:
        :return:
        """
        if self.birth_clinic_model:
            # Delete active birth clinic and place new
            yield From(wait_for(self.delete_model(self.birth_clinic_model.name)))
            self.birth_clinic_model = None

        if angle is None:
            angle = random.random() * 2 * math.pi

        name = "birth_clinic_"+str(self.get_robot_id())
        self.birth_clinic_model = bc = BirthClinic(name=name, diameter=diameter, height=height)
        bc.rotate_around(Vector3(0, 0, 1), angle)
        future = yield From(self.insert_model(SDF(elements=[bc])))
        raise Return(future)
コード例 #7
0
ファイル: world.py プロジェクト: huub8/tol-revolve
    def place_birth_clinic(self, diameter, height, angle=None):
        """
        CURRENTLY NOT USED.

        Places the birth clinic. Since we're lazy and rotating appears to cause errors,
        we're just deleting the old birth clinic and inserting a new one every time.
        Inserts the birth clinic
        :param height:
        :param diameter:
        :param angle:
        :return:
        """
        if self.birth_clinic_model:
            # Delete active birth clinic and place new
            yield From(
                wait_for(self.delete_model(self.birth_clinic_model.name)))
            self.birth_clinic_model = None

        if angle is None:
            angle = random.random() * 2 * math.pi

        name = "birth_clinic_" + str(self.get_robot_id())
        self.birth_clinic_model = bc = BirthClinic(name=name,
                                                   diameter=diameter,
                                                   height=height)
        bc.rotate_around(Vector3(0, 0, 1), angle)
        future = yield From(self.insert_model(SDF(elements=[bc])))
        raise Return(future)
コード例 #8
0
def run():
    """
    The main coroutine, which is started below.
    """
    # Parse command line / file input arguments
    conf = parser.parse_args()

    # Adding brain configuration
    with open(conf.brain_conf_path, 'r') as f:
        s = f.read()
        brain_conf = ast.literal_eval(s)
    if conf.load_controller != "None":
        brain_conf["policy_load_path"] = conf.load_controller
    conf.brain_conf = brain_conf

    # This disables the analyzer; enable it if you want to generate valid robots
    # Can also do this using arguments of course, just pass an empty string
    # conf.analyzer_address = None

    with open("{}.yaml".format(conf.robot_name), 'r') as yamlfile:
        bot_yaml = yamlfile.read()

    # Create the world, this connects to the Gazebo world
    world = yield From(World.create(conf))

    # These are useful when working with YAML
    body_spec = world.builder.body_builder.spec
    brain_spec = world.builder.brain_builder.spec

    # Create a robot from YAML
    robot = yaml_to_robot(body_spec, brain_spec, bot_yaml)

    # Create a revolve.angle `Tree` representation from the robot, which
    # is what is used in the world manager.
    robot_tree = Tree.from_body_brain(robot.body, robot.brain, body_spec)

    # Insert the robot into the world. `insert_robot` resolves when the insert
    # request is sent, the future it returns resolves when the robot insert
    # is actually confirmed and a robot manager object has been created
    pose = Pose(position=Vector3(0, 0, 0.05))
    future = yield From(world.insert_robot(robot_tree, pose, "{}-{}".format(conf.robot_name, conf.experiment_round)))
    robot_manager = yield From(future)

    # I usually start the world paused, un-pause it here. Note that
    # pause again returns a future for when the request is sent,
    # that future in turn resolves when a response has been received.
    # This is the general convention for all message actions in the
    # world manager. `wait_for` saves the hassle of grabbing the
    # intermediary future in this case.
    yield From(wait_for(world.pause(True)))

    # Start a run loop to do some stuff
    while True:
        # Print robot fitness every second
        print("Robot fitness: %f" % robot_manager.fitness())
        yield From(trollius.sleep(1.0))
コード例 #9
0
    def evaluate_pair(self, tree, bbox, parents=None):
        """
        Evaluates a single robot tree.
        :param tree:
        :param bbox:
        :param parents:
        :return: Evaluated Robot object
        """
        # Pause the world just in case it wasn't already
        yield From(wait_for(self.pause(True)))

        pose = Pose(position=Vector3(0, 0, -bbox.min.z))
        fut = yield From(self.insert_robot(tree, pose, parents=parents))
        robot = yield From(fut)

        max_age = self.conf.evaluation_time + self.conf.warmup_time

        # Unpause the world to start evaluation
        yield From(wait_for(self.pause(False)))

        before = time.time()

        while True:
            if robot.age() >= max_age:
                break

            # Sleep for the pose update frequency, which is about when
            # we expect a new age update.
            yield From(trollius.sleep(1.0 / self.state_update_frequency))

        yield From(wait_for(self.delete_robot(robot)))
        yield From(wait_for(self.pause(True)))

        diff = time.time() - before
        if diff > self.conf.evaluation_threshold:
            sys.stderr.write(
                "Evaluation threshold exceeded, shutting down with nonzero status code.\n"
            )
            sys.stderr.flush()
            sys.exit(15)

        raise Return(robot)
コード例 #10
0
    def evaluate_pair(self, tree, bbox, parents=None):
        """
        Evaluates a single robot tree.
        :param tree:
        :param bbox:
        :param parents:
        :return: Evaluated Robot object
        """
        # Pause the world just in case it wasn't already
        yield From(wait_for(self.pause(True)))

        pose = Pose(position=Vector3(0, 0, -bbox.min.z))
        fut = yield From(self.insert_robot(tree, pose, parents=parents))
        robot = yield From(fut)

        max_age = self.conf.evaluation_time + self.conf.warmup_time

        # Unpause the world to start evaluation
        yield From(wait_for(self.pause(False)))

        before = time.time()

        while True:
            if robot.age() >= max_age:
                break

            # Sleep for the pose update frequency, which is about when
            # we expect a new age update.
            yield From(trollius.sleep(1.0 / self.state_update_frequency))

        yield From(wait_for(self.delete_robot(robot)))
        yield From(wait_for(self.pause(True)))

        diff = time.time() - before
        if diff > self.conf.evaluation_threshold:
            sys.stderr.write("Evaluation threshold exceeded, shutting down with nonzero status code.\n")
            sys.stderr.flush()
            sys.exit(15)

        raise Return(robot)
コード例 #11
0
ファイル: quicktest2.py プロジェクト: karinemiras/tol-revolve
def run(conf):
    """

    :param conf:
    :return:
    """
    conf.evaluation_time = 5.0
    conf.output_directory = 'output'
    world = yield From(World.create(conf))
    yield From(world.pause(True))

    for i in range(3):
        ta, _, _ = yield From(world.generate_valid_robot())
        tb, _, _ = yield From(world.generate_valid_robot())
        ra = yield From(
            wait_for(
                world.insert_robot(ta,
                                   pose=Pose(position=Vector3(0, 3 *
                                                              i, 0.5)))))
        rb = yield From(
            wait_for(
                world.insert_robot(
                    tb, pose=Pose(position=Vector3(0, 3 * i + 1, 0.5)))))

        while True:
            # Attempt reproduction
            mate = yield From(world.attempt_mate(ra, rb))

            if mate:
                break

        tree, bbox = mate
        yield From(
            wait_for(
                world.insert_robot(
                    tree, pose=Pose(position=Vector3(0, 3 * i + 2, 0.5)))))
コード例 #12
0
ファイル: online_evolve.py プロジェクト: egdman/tol-revolve
    def run(self):
        """
        :return:
        """
        conf = self.conf
        insert_queue = []

        if not self.do_restore:
            # Build the arena
            yield From(wait_for(self.build_arena()))

            # Generate a starting population
            trees, bboxes = yield From(
                self.generate_population(conf.initial_population_size))
            insert_queue = zip(trees, bboxes,
                               [None for _ in range(len(trees))])

        # Simple loop timing mechanism
        timers = {
            k: Time()
            for k in ['reproduce', 'death', 'snapshot', 'log_fitness', 'rtf']
        }
        this = self

        def timer(name, t):
            """
            :param t:
            :param name:
            :return:
            """
            if this.last_time is not None and float(this.last_time -
                                                    timers[name]) > t:
                timers[name] = this.last_time
                return True

            return False

        # Start the world
        real_time = time.time()
        yield From(wait_for(self.pause(False)))
        while True:
            if insert_queue:
                tree, bbox, parents = insert_queue.pop()
                yield From(wait_for(self.birth(tree, bbox, parents)))

            # Perform operations only if there are no items
            # in the insert queue, makes snapshotting easier.
            if insert_queue:
                yield From(trollius.sleep(0.2))
                continue

            if timer('snapshot', 10.0):
                # Snapshot the world every 10 simulation seconds
                yield From(self.create_snapshot())
                yield From(wait_for(self.pause(False)))

            if timer('death', 5.0):
                # Kill off robots over their age every 5 simulation seconds
                futs = yield From(self.kill_old_robots())
                if futs:
                    yield From(multi_future(futs))

            if len(self.robots) <= 1:
                print("Less than two robots left in population - extinction.")
                break

            if timer('reproduce',
                     3.0) and len(self.robots) < conf.max_population_size:
                # Attempt a reproduction every 3 simulation seconds
                potential_mates = self.select_mates()
                if potential_mates:
                    ra, rb = random.choice(potential_mates)
                    result = yield From(self.attempt_mate(ra, rb))

                    if result:
                        ra.did_mate_with(rb)
                        rb.did_mate_with(ra)
                        child, bbox = result
                        insert_queue.append((child, bbox, (ra, rb)))

            if timer('log_fitness', 2.0):
                # Log overall fitness every 2 simulation seconds
                self.log_fitness()

            if timer('rtf', 1.0):
                # Print RTF to screen every second
                nw = time.time()
                diff = nw - real_time
                real_time = nw
                print("RTF: %f" % (1.0 / diff))

            yield From(trollius.sleep(0.2))
コード例 #13
0
def run():
    """
    The main coroutine, which is started below.
    """
    # Parse command line / file input arguments
    conf = parser.parse_args()

    conf.output_directory = "output"
    conf.restore_directory = "restore"
    with open("models/robot_26.yaml", 'r') as yamlfile:
        bot_yaml1 = yamlfile.read()

    with open("models/robot_150.yaml", 'r') as yamlfile:
        bot_yaml2 = yamlfile.read()

    # Create the world, this connects to the Gazebo world

    world = yield From(World.create(conf))

    # These are useful when working with YAML
    body_spec = world.builder.body_builder.spec
    brain_spec = world.builder.brain_builder.spec

    # Create a robot from YAML
    protobot1 = yaml_to_robot(body_spec=body_spec,
                              nn_spec=brain_spec,
                              yaml=bot_yaml1)

    # Create a robot from YAML
    protobot2 = yaml_to_robot(body_spec=body_spec,
                              nn_spec=brain_spec,
                              yaml=bot_yaml2)

    # Create a revolve.angle `Tree` representation from the robot, which
    # is what is used in the world manager.
    robot_tree1 = Tree.from_body_brain(body=protobot1.body,
                                       brain=protobot1.brain,
                                       body_spec=body_spec)
    # Create a revolve.angle `Tree` representation from the robot, which
    # is what is used in the world manager.
    robot_tree2 = Tree.from_body_brain(body=protobot2.body,
                                       brain=protobot2.brain,
                                       body_spec=body_spec)
    # Insert the robot into the world. `insert_robot` resolves when the insert
    # request is sent, the future it returns resolves when the robot insert
    # is actually confirmed and a robot manager object has been created
    pose1 = Pose(position=Vector3(0, 0, 0.05))
    pose2 = Pose(position=Vector3(0, 2, 0.05))
    future1 = yield From(
        world.insert_robot(
            tree=robot_tree1,
            pose=pose1,
            # name="robot_26"
        ))
    future2 = yield From(
        world.insert_robot(
            tree=robot_tree2,
            pose=pose2,
            # name="robot_26"
        ))
    robot_manager1 = yield From(future1)
    robot_manager2 = yield From(future2)

    # I usually start the world paused, un-pause it here. Note that
    # pause again returns a future for when the request is sent,
    # that future in turn resolves when a response has been received.
    # This is the general convention for all message actions in the
    # world manager. `wait_for` saves the hassle of grabbing the
    # intermediary future in this case.
    yield From(wait_for(world.pause(True)))

    # Start a run loop to do some stuff
    while True:
        # Print robot fitness every second
        print("Robot fitness is {fitness}".format(
            fitness=robot_manager1.fitness()))
        yield From(trollius.sleep(1.0))
コード例 #14
0
    def run(self):
        """
        :return:
        """
        conf = self.conf
        insert_queue = []

        if not self.do_restore:
            # Build the arena
            yield From(wait_for(self.build_arena()))

            # Generate a starting population
            trees, bboxes = yield From(self.generate_population(conf.initial_population_size))
            insert_queue = zip(trees, bboxes, [None for _ in range(len(trees))])

        # Simple loop timing mechanism
        timers = {k: Time() for k in ['reproduce', 'death', 'snapshot',
                                      'log_fitness', 'rtf']}
        this = self

        def timer(name, t):
            """
            :param t:
            :param name:
            :return:
            """
            if this.last_time is not None and float(this.last_time - timers[name]) > t:
                timers[name] = this.last_time
                return True

            return False

        # Start the world
        real_time = time.time()
        yield From(wait_for(self.pause(False)))
        while True:
            if insert_queue:
                tree, bbox, parents = insert_queue.pop()
                yield From(wait_for(self.birth(tree, bbox, parents)))

            # Perform operations only if there are no items
            # in the insert queue, makes snapshotting easier.
            if insert_queue:
                yield From(trollius.sleep(0.2))
                continue

            if timer('snapshot', 10.0):
                # Snapshot the world every 10 simulation seconds
                yield From(self.create_snapshot())
                yield From(wait_for(self.pause(False)))

            if timer('death', 5.0):
                # Kill off robots over their age every 5 simulation seconds
                futs = yield From(self.kill_old_robots())
                if futs:
                    yield From(multi_future(futs))

            if len(self.robots) <= 1:
                print("Less than two robots left in population - extinction.")
                break

            if timer('reproduce', 3.0) and len(self.robots) < conf.max_population_size:
                # Attempt a reproduction every 3 simulation seconds
                potential_mates = self.select_mates()
                if potential_mates:
                    ra, rb = random.choice(potential_mates)
                    result = yield From(self.attempt_mate(ra, rb))

                    if result:
                        ra.did_mate_with(rb)
                        rb.did_mate_with(ra)
                        child, bbox = result
                        insert_queue.append((child, bbox, (ra, rb)))

            if timer('log_fitness', 2.0):
                # Log overall fitness every 2 simulation seconds
                self.log_fitness()

            if timer('rtf', 1.0):
                # Print RTF to screen every second
                nw = time.time()
                diff = nw - real_time
                real_time = nw
                print("RTF: %f" % (1.0 / diff))

            yield From(trollius.sleep(0.2))
コード例 #15
0
    def run_single(self):
        """
        :return:
        """
        conf = self.conf
        insert_queue = []

        if not self.do_restore:
            if self.current_run == 0:
                # Only build arena on first run
                yield From(wait_for(self.build_arena()))

            # Set initial battery charge
            self.current_charge = self.conf.initial_charge
            self.last_charge_update = 0.0
            self.births = 0
            self.deaths = 0

            # Generate a starting population
            trees, bboxes = yield From(self.generate_population(conf.initial_population_size))
            insert_queue = zip(trees, bboxes, [None for _ in range(len(trees))])

        # Simple loop timing mechanism
        timers = {k: Time() for k in ['reproduce', 'death', 'snapshot',
                                      'log_fitness', 'rtf', 'insert_queue']}
        this = self

        def timer(name, t):
            """
            :param t:
            :param name:
            :return:
            """
            if this.last_time is not None and float(this.last_time - timers[name]) > t:
                timers[name] = this.last_time
                return True

            return False

        # Some variables
        real_time = time.time()
        rtf_interval = 10.0
        sleep_time = 0.1
        run_result = 'unknown'
        started = False

        while True:
            if insert_queue and (not started or timer('insert_queue', 1.0)):
                tree, bbox, parents = insert_queue.pop()
                res = yield From(self.birth(tree, bbox, parents))
                if res:
                    yield From(res)

            if not started:
                # Start the world
                yield From(wait_for(self.pause(False)))
                started = True

            # Perform operations only if there are no items
            # in the insert queue, makes snapshotting easier.
            if insert_queue:
                # Space out robot inserts with one simulation second
                # to allow them to drop in case they are too close.
                # Sleep for a very small interval every time until
                # all inserts are done
                yield From(trollius.sleep(0.01))
                continue

            if timer('snapshot', 100.0):
                # Snapshot the world every 100 simulation seconds
                yield From(self.create_snapshot())
                yield From(wait_for(self.pause(False)))

            if timer('death', 3.0):
                # Kill off robots over their age every 5 simulation seconds
                futs = yield From(self.kill_old_robots())
                if futs:
                    yield From(multi_future(futs))

            if timer('reproduce', 3.0):
                # Attempt a reproduction every 3 simulation seconds
                potential_parents = self.select_parents()
                if potential_parents:
                    ra = random.choice(potential_parents)
                    rb = self.select_optimal_mate(ra)
                    result = yield From(self.attempt_mate(ra, rb))

                    if result:
                        child, bbox = result
                        insert_queue.append((child, bbox, (ra, rb)))

            if timer('log_fitness', 2.0):
                # Log overall fitness every 2 simulation seconds
                self.log_fitness()
                self.log_summary()

            if timer('rtf', rtf_interval):
                # Print RTF to screen every so often
                nw = time.time()
                diff = nw - real_time
                real_time = nw
                print("RTF: %f" % (rtf_interval / diff))

            # Stop conditions
            num_bots = len(self.robots)
            age = float(self.age())

            if num_bots <= conf.extinction_cutoff:
                print("%d or fewer robots left in population - extinction." %
                      conf.extinction_cutoff)
                run_result = 'extinction'
                break
            elif age > conf.stability_cutoff:
                print("World older than %f seconds, stable." % conf.stability_cutoff)
                run_result = 'stable'
                break

            yield From(trollius.sleep(sleep_time))

        # Delete all robots and reset the world, just in case a new run
        # will be started.
        self.write_result(run_result)
        yield From(wait_for(self.delete_all_robots()))
        yield From(wait_for(self.reset()))
        yield From(wait_for(self.pause(True)))
        yield From(trollius.sleep(0.5))
コード例 #16
0
def run_server():
    conf = parser.parse_args()
    conf.analyzer_address = None

    world = yield From(World.create(conf))
    yield From(world.pause(True))

    with open("/home/elte/mt/tol/scripts/starfish.yaml", "rb") as f:
        robot_yaml = f.read()

    body_spec = world.builder.body_builder.spec
    brain_spec = world.builder.brain_builder.spec
    bot = yaml_to_robot(body_spec, brain_spec, robot_yaml)

    fname = conf.output_directory + "/revolve_benchmark.csv"
    exists = os.path.exists(fname)
    if exists:
        f = open(fname, 'ab', buffering=1)
    else:
        f = open(fname, 'wb', buffering=1)

    output = csv.writer(f, delimiter=',')

    if not exists:
        output.writerow([
            'run', 'population_size', 'step_size', 'sim_time', 'real_time',
            'factor'
        ])

    n_bots = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
    sim_time = 5.0
    runs = 20

    yield From(world.pause(False))

    for n in n_bots:
        poses = get_poses(n)
        trees = [
            Tree.from_body_brain(bot.body, bot.brain, body_spec)
            for _ in range(n)
        ]

        for i in range(runs):
            yield From(wait_for(world.insert_population(trees, poses)))

            while world.last_time is None:
                yield From(trollius.sleep(0.1))

            sim_before = world.last_time
            before = time.time()

            while float(world.last_time - sim_before) < sim_time:
                yield From(trollius.sleep(0.1))

            sim_diff = float(world.last_time - sim_before)
            diff = time.time() - before

            output.writerow(
                (i, n, conf.world_step_size, sim_diff, diff, sim_diff / diff))

            yield From(wait_for(world.delete_all_robots()))
            yield From(trollius.sleep(0.3))
コード例 #17
0
    def run_single(self):
        """
        :return:
        """
        conf = self.conf
        insert_queue = []

        if not self.do_restore or not self.do_restore['running']:
            # Set initial battery charge
            self.births = 0
            self.deaths = 0

            # Generate a starting population
            trees, bboxes = yield From(self.generate_population(conf.population_size))
            insert_queue = zip(trees, bboxes, [None for _ in range(len(trees))])

        # Simple loop timing mechanism
        timers = {}
        this = self

        def timer(name, t):
            """
            :param t:
            :param name:
            :return:
            """
            if this.last_time is None:
                return False

            if name not in timers:
                timers[name] = this.last_time
                return False

            if float(this.last_time - timers[name]) > t:
                timers[name] = this.last_time
                return True

            return False

        # Some variables
        real_time = time.time()
        rtf_interval = 10.0
        sleep_time = 0.1
        started = False
        t_eval = self.conf.evaluation_time + self.conf.warmup_time
        robot_limit = self.conf.population_limit

        birth_interval = t_eval
        kill_interval = 2 * birth_interval

        while True:
            if insert_queue and (not started or timer('insert_queue', 1.0)):
                tree, bbox, parents = insert_queue.pop()
                res = yield From(self.birth(tree, bbox, parents))
                if res:
                    yield From(res)

            if not started:
                # Start the world
                yield From(wait_for(self.pause(False)))
                started = True

            # Perform operations only if there are no items
            # in the insert queue, makes snapshotting easier.
            if insert_queue:
                # Space out robot inserts with one simulation second
                # to allow them to drop in case they are too close.
                # Sleep for a very small interval every time until
                # all inserts are done
                yield From(trollius.sleep(0.01))
                continue

            # Book keeping
            if timer('snapshot', 100.0):
                # Snapshot the world every 100 simulation seconds
                yield From(self.create_snapshot())
                yield From(wait_for(self.pause(False)))

            if timer('log_fitness', 5.0):
                # Log overall fitness every 5 simulation seconds
                self.log_fitness()
                self.log_summary()

            if timer('rtf', rtf_interval):
                # Print RTF to screen every so often
                nw = time.time()
                diff = nw - real_time
                real_time = nw
                print("RTF: %f" % (rtf_interval / diff))

            if timer('death', kill_interval):
                futs = yield From(self.kill_robots())

                if futs:
                    yield From(multi_future(futs))

            if timer('birth', birth_interval) and len(self.robots) < robot_limit:
                if self.births >= self.conf.birth_limit:
                    # Stop the experiment
                    break

                triplet = yield From(self.produce_individual())
                if triplet:
                    insert_queue.append(triplet)

            yield From(trollius.sleep(sleep_time))

        # Delete all robots and reset the world, just in case a new run
        # will be started.
        yield From(wait_for(self.delete_all_robots()))
        yield From(wait_for(self.reset()))
        yield From(wait_for(self.pause(True)))
        yield From(trollius.sleep(0.5))