def evolution_search(f, para_b):
    begin_time = datetime.now()
    Timestamps_list = []
    Target_list = []
    Parameters_list = []
    keys = list(para_b.keys())
    dim = len(keys)
    plog = PrintLog(keys)

    min = np.ones(dim)
    max = np.ones(dim)
    value_list = list(parameters.values())
    for i_v in range(dim):
        min[i_v] = value_list[i_v][0]
        max[i_v] = value_list[i_v][1]
    bounds = (min, max)
    plog.print_header(initialization=True)

    my_topology = Star()
    my_options ={'c1': 0.6, 'c2': 0.3, 'w': 0.4}
    my_swarm = P.create_swarm(n_particles=20, dimensions=dim, options=my_options, bounds=bounds)  # The Swarm Class

    iterations = 30  # Set 100 iterations
    for i in range(iterations):
        # Part 1: Update personal best

        # for evaluated_result in map(evaluate, my_swarm.position):
        #     my_swarm.current_cost = np.append(evaluated_result)
        # for best_personal_result in map(evaluate, my_swarm.pbest_pos):  # Compute personal best pos
        #     my_swarm.pbest_cost = np.append(my_swarm.pbest_cost, best_personal_result)
        my_swarm.current_cost = np.array(list(map(evaluate, my_swarm.position)))
        #print(my_swarm.current_cost)
        my_swarm.pbest_cost = np.array(list(map(evaluate, my_swarm.pbest_pos)))
        my_swarm.pbest_pos, my_swarm.pbest_cost = P.compute_pbest(my_swarm)  # Update and store

        # Part 2: Update global best
        # Note that gbest computation is dependent on your topology
        if np.min(my_swarm.pbest_cost) < my_swarm.best_cost:
            my_swarm.best_pos, my_swarm.best_cost = my_topology.compute_gbest(my_swarm)

        # Let's print our output
        #if i % 2 == 0:
        #    print('Iteration: {} | my_swarm.best_cost: {:.4f}'.format(i + 1, my_swarm.best_cost))

        # Part 3: Update position and velocity matrices
        # Note that position and velocity updates are dependent on your topology
        my_swarm.velocity = my_topology.compute_velocity(my_swarm)
        my_swarm.position = my_topology.compute_position(my_swarm)

        Parameters_list.append(my_swarm.best_pos.tolist())
        Target_list.append(1-my_swarm.best_cost)
        elapse_time = (datetime.now() - begin_time).total_seconds()
        Timestamps_list.append(elapse_time)
#        print("The best candidate: ", my_swarm.best_pos)
#        print("The best result: ", res[1])
        plog.print_step(my_swarm.best_pos, 1 - my_swarm.best_cost)
        if i == 0:
            plog.print_header(initialization=False)

    return Timestamps_list, Target_list, Parameters_list
Esempio n. 2
0
def test_compute_pbest_return_values(swarm):
    """Test if compute_pbest() gives the expected return values"""
    expected_cost = np.array([1, 2, 2])
    expected_pos = np.array([[1, 2, 3], [4, 5, 6], [1, 1, 1]])
    pos, cost = P.compute_pbest(swarm)
    assert (pos == expected_pos).all()
    assert (cost == expected_cost).all()
Esempio n. 3
0
    async def attack(self, phys_swarm):
        if phys_swarm.amount > 5:
            orders = []
            # reinitialize swarm if needed
            if phys_swarm.amount != self.swarm_size:
                self.swarm_size = phys_swarm.amount
                self.phys_swarm_pos = []
                for unit in phys_swarm:
                    self.phys_swarm_pos.append(
                        [unit.position.x, unit.position.y])
                self.phys_swarm_pos = np.array(self.phys_swarm_pos)

                self.logical_swarm = P.create_swarm(
                    n_particles=phys_swarm.amount,
                    dimensions=2,
                    options=self.my_options,
                    bounds=([0, 0], [
                        self.game_info.map_size[0], self.game_info.map_size[1]
                    ]),
                    init_pos=self.phys_swarm_pos,
                    clamp=(0, 5.6))

            self.logical_swarm.current_cost = self.fitness(
                self.logical_swarm.position, phys_swarm)
            self.logical_swarm.pbest_cost = self.fitness(
                self.logical_swarm.pbest_pos, phys_swarm)
            self.logical_swarm.pbest_pos, self.logical_swarm.pbest_cost = P.compute_pbest(
                self.logical_swarm)

            if np.min(self.logical_swarm.pbest_cost
                      ) < self.logical_swarm.best_cost:
                self.logical_swarm.best_pos, self.logical_swarm.best_cost = self.my_topology.compute_gbest(
                    self.logical_swarm)

            self.logical_swarm.velocity = self.my_topology.compute_velocity(
                self.logical_swarm)
            self.logical_swarm.position = self.my_topology.compute_position(
                self.logical_swarm)
            # Extract positions from above and issue movement/attack orders
            # loop through np array compiling positions and appending them to orders list.

            # The mutas are still ignoring nearby enemies.
            for row, unit in zip(self.logical_swarm.position, phys_swarm):
                if self.known_enemy_units.closer_than(unit.radar_range,
                                                      unit.position).exists:
                    orders.append(
                        unit.attack(
                            self.known_enemy_units.closest_to(unit.position)))
                else:
                    orders.append(
                        unit.move(Point2(Pointlike((row[0], row[1])))))
            await self.do_actions(orders)
Esempio n. 4
0
    async def attack(self, phys_swarm, iteration):
        if phys_swarm.amount > 10:
            orders = []
            # reinitialize swarm if needed
            if phys_swarm.amount > self.swarm_size + 3 or iteration > self.iter_of_last_update + 75:
                self.swarm_size = phys_swarm.amount
                self.phys_swarm_pos = []
                for unit in phys_swarm:
                    self.phys_swarm_pos.append([unit.position.x, unit.position.y])
                self.phys_swarm_pos = np.array(self.phys_swarm_pos)
                self.logical_swarm = P.create_swarm(n_particles=phys_swarm.amount, dimensions=2, options=self.my_options, bounds=([0,0], [self.game_info.map_size[0], self.game_info.map_size[1]]) , init_pos=self.phys_swarm_pos, clamp=(0,4.0))
                self.iter_of_last_update = iteration


            self.logical_swarm.current_cost = self.fitness(self.logical_swarm.position, phys_swarm)
            self.logical_swarm.pbest_cost = self.fitness(self.logical_swarm.pbest_pos, phys_swarm)
            self.logical_swarm.pbest_pos, self.logical_swarm.pbest_cost = P.compute_pbest(self.logical_swarm)

            if np.min(self.logical_swarm.pbest_cost) < self.logical_swarm.best_cost:
                self.logical_swarm.best_pos, self.logical_swarm.best_cost = self.my_topology.compute_gbest(self.logical_swarm)

            self.logical_swarm.velocity = self.my_topology.compute_velocity(self.logical_swarm)
            self.logical_swarm.position = self.my_topology.compute_position(self.logical_swarm)
            # Extract positions from above and issue movement/attack orders
            # loop through np array compiling positions and appending them to orders list.
          
            wounded_units = phys_swarm.filter(lambda u: u.health_percentage <= .7)
            phys_swarm = phys_swarm.filter(lambda u: u.health_percentage > .7)

            for unit in wounded_units:
                unit.move(self.townhalls.first.position)

            # The mutas are still ignoring nearby enemies.
            for row, unit in zip(self.logical_swarm.position, phys_swarm):
                if self.known_enemy_units.closer_than(unit.radar_range, unit.position).exists:
                    orders.append(unit.stop())
                    orders.append(unit.attack(self.known_enemy_units.closest_to(unit.position).position))
                elif self.known_enemy_units.exists:
                    orders.append(unit.attack(self.known_enemy_units.closest_to(Point2(Pointlike((row[0], row[1]))))))
                else:
                    orders.append(unit.move(Point2(Pointlike((row[0], row[1])))))

            await self.do_actions(orders)
Esempio n. 5
0
    async def attack(self, phys_swarm, iteration):
        if phys_swarm.amount > 10:
            orders = []

            # I should be able to dynamically add and subtract particles from the swarm... should only init once at beginning...
            if # The business of adding/subrtracting from swarm should be done in on created/destroyed methods...
            # do a comprehension that deletes matches positions and alive units?

            
            # calcuate the current
            self.log_swarm.current_cost = self.fitness(  self.log_swarm.position,  phys_swarm  )
            self.log_swarm.pbest_cost = self.fitness(  self.log_swarm.pbest_pos,  phys_swarm  )
            self.log_swarm.pbest_pos, self.log_swarm.pbest_cost = P.compute_pbest(  self.log_swarm  )


            #
            if np.min(  self.log_swarm.pbest_cost  ) < self.log_swarm.best_cost:
                self.log_swarm.best_pos, self.log_swarm.best_cost = self.my_topology.compute_gbest(  self.log_swarm  )



            #
            self.logical_swarm.velocity = self.my_topology.compute_velocity(  self.log_swarm  )
            self.logical_swarm.position = self.my_topology.compute_position(  self.log_swarm  )
            

            #this should be parameterized as aggression...
            wounded_units = phys_swarm.filter(lambda u: u.health_percentage <= .7)

            for unit in wounded_units:
                unit.move(self.townhalls.first.position)

            
            phys_swarm = phys_swarm.filter(lambda u: u.health_percentage > .7)

            for row, unit in zip(self.logical_swarm.position, phys_swarm):
                orders.append(unit.attack(Point2(Pointlike((row[0], row[1])))))
            # might need to get the nearest unit to do this... also check to make sure nearest unit not already assigned a task


            await self.do_actions(orders)
Esempio n. 6
0
    if np.all(my_swarm.options['feasibility'] == False) == False:
        break

    my_swarm.best_cost = min(x for x in my_swarm.pbest_cost if x is not None)
    min_pos_id = np.where(my_swarm.pbest_cost == my_swarm.best_cost)[0][0]
    my_swarm.options['best_position'] = my_swarm.pbest_pos[min_pos_id]
    my_swarm.best_pos = my_topology.compute_gbest(my_swarm, p = 2, k = N)
    new_best_pos = np.empty([N, dim])
    for n in range(N):
        for d in range(dim):
            new_best_pos[n][d] = my_swarm.best_pos[n][d]
    my_swarm.best_pos = new_best_pos
    my_swarm.velocity = my_topology.compute_velocity(my_swarm)
    my_swarm.position = my_topology.compute_position(my_swarm)
    my_swarm.options['feasibility'] = cop.constraints(my_swarm.position)
    my_swarm.current_cost = cop.sum_violations(my_swarm.position)
    my_swarm.pbest_pos, my_swarm.pbest_cost = P.compute_pbest(my_swarm)

    if i%50==0:
        print('Iteration: {} | my_swarm.best_cost: {:.4f}'.format(i+1, my_swarm.best_cost))


if np.all(my_swarm.options['feasibility'] == False) == False:
    print('The feasible region was found!')
    print('The following are all the known feasible points:')
    print(my_swarm.position[my_swarm.options['feasibility'] == True])
else:
    print('The feasible region was not found :(')
    print('The best sum of violations found by our swarm is: {:.4f}'.format(my_swarm.best_cost))
    print('The best position found by our swarm is: {}'.format(my_swarm.options['best_position']))
    def optimize(self,
                 objective_func,
                 iters,
                 print_step=1,
                 verbose=1,
                 **kwargs):

        ub = 1
        lb = 0

        for i in range(iters):

            w = 0.9 - i * ((0.9 - 0.4) / iters)

            my_c = 0.1 - i * ((0.1 - 0) / (iters / 2))

            if my_c < 0:
                my_c = 0
            # print(my_c)
            s = 2 * random.random() * my_c  # Seperation weight
            a = 2 * random.random() * my_c  # Alignment weight
            c = 2 * random.random() * my_c  # Cohesion weight
            f = 2 * random.random()  # Food attraction weight
            e = my_c  # Enemy distraction weight

            # Compute cost for current position and personal best
            self.swarm.current_cost = objective_func(self.swarm.position,
                                                     **kwargs)
            self.swarm.pbest_cost = objective_func(self.swarm.pbest_pos,
                                                   **kwargs)
            self.swarm.pbest_pos, self.swarm.pbest_cost = compute_pbest(
                self.swarm)
            self.swarm.pworst_pos, self.swarm.pworst_cost = self.compute_pworst(
                self.swarm)

            pmin_cost_idx = np.argmin(self.swarm.pbest_cost)
            pmax_cost_idx = np.argmax(self.swarm.pworst_cost)
            # pmax_cost_idx = np.argmax(self.swarm.pbest_cost)
            # Update gbest from neighborhood

            # self.swarm.best_cost = np.min(self.swarm.pbest_cost)
            # self.swarm.pbest_pos = self.swarm.pbest_pos[np.argmin(self.swarm.pbest_cost)]

            # best_cost_yet_found = np.min(self.swarm.best_cost)

            self.swarm.best_pos, self.swarm.best_cost = self.top.compute_gbest(
                self.swarm, 2, self.n_particles)

            # Updating Food position
            if self.swarm.pbest_cost[pmin_cost_idx] < self.food_fitness:
                self.food_fitness = self.swarm.pbest_cost[pmin_cost_idx]
                self.food_pos = self.swarm.pbest_pos[pmin_cost_idx]

            # Updating Enemy position
            if self.swarm.pworst_cost[pmax_cost_idx] > self.enemy_fitness:
                self.enemy_fitness = self.swarm.pworst_cost[pmax_cost_idx]
                self.enemy_pos = self.swarm.pworst_pos[pmax_cost_idx]

            # best_cost_yet_found = np.min(self.swarm.best_cost)

            for j in range(self.n_particles):

                S = np.zeros(self.dimensions)
                A = np.zeros(self.dimensions)
                C = np.zeros(self.dimensions)
                F = np.zeros(self.dimensions)
                E = np.zeros(self.dimensions)

                # Calculating Separation(S)

                for k in range(self.n_particles):
                    S += (self.swarm.position[k] - self.swarm.position[j])

                S = -S

                # Calculating Allignment(A)

                for k in range(self.n_particles):
                    A += self.swarm.velocity[k]
                A = (A / self.n_particles)

                # Calculating Cohesion
                for k in range(self.n_particles):
                    C += self.swarm.position[k]
                C = (C / self.n_particles) - self.swarm.position[j]

                F = self.food_pos - self.swarm.position[
                    j]  # Calculating Food postion
                E = self.enemy_pos - self.swarm.position[
                    j]  # Calculating Enemy position

                self.swarm.velocity[j] = (s * S + a * A + c * C + f * F +
                                          e * E) + w * self.swarm.velocity[j]
                self.swarm.position[j] = self.compute_position(
                    self.swarm.velocity[j])

            # Print to console
            if i % print_step == 0:
                cli_print(
                    "Iteration {}/{}, cost: {}".format(
                        i + 1, iters, np.min(self.swarm.best_cost)),
                    verbose,
                    2,
                    logger=self.logger,
                )

        # Obtain the final best_cost and the final best_position
        # final_best_cost = np.min(self.swarm.pbest_cost)
        # final_best_pos = self.swarm.pbest_pos[np.argmin(self.swarm.pbest_cost)]

        final_best_cost = self.swarm.best_cost.copy()
        final_best_pos = self.swarm.best_pos.copy()

        print("==============================\nOptimization finished\n")
        print("Final Best Cost : ", final_best_cost, "\nBest Value : ",
              final_best_pos)

        # end_report(
        #     final_best_cost, final_best_pos, verbose, logger=self.logger
        # )
        return (final_best_cost, final_best_pos)
Esempio n. 8
0
    def optimize(self):
        results_2k = 0
        results_10k = 0
        results_20k = 0
        fes = 0 # Function evaluations
        l_lim = self.cop.l_lim
        u_lim = self.cop.u_lim
        if l_lim == None or u_lim == None:
            bounds = None
        else:
            l_lims = np.asarray([l_lim] * self.dim)
            u_lims = np.asarray([u_lim] * self.dim)
            bounds = (l_lims, u_lims)

        my_options = {'c1': self.c1, 'c2': self.c2, 'w': self.w,
                        'feasibility': np.zeros(self.N, dtype = bool),
                        'best_position': None}
        my_swarm = P.create_swarm(n_particles = self.N, dimensions = self.dim, options = my_options, bounds = bounds)

        my_swarm.options['feasibility'] = self.cop.constraints(my_swarm.position)
        my_swarm.current_cost = self.cop.sum_violations(my_swarm.position)
        fes += self.N
        my_swarm.pbest_pos = my_swarm.position
        my_swarm.pbest_cost = my_swarm.current_cost


        for i in range(self.iterations):
            if np.all(my_swarm.options['feasibility'] == False) == False:
                if i == 0:
                    my_swarm.best_cost = 0
                break

            my_swarm.best_cost = min(x for x in my_swarm.pbest_cost if x is not None)
            min_pos_id = np.where(my_swarm.pbest_cost == my_swarm.best_cost)[0][0]
            my_swarm.options['best_position'] = my_swarm.pbest_pos[min_pos_id]
            my_swarm.best_pos = self.my_topology.compute_gbest(my_swarm, p = 2, k = self.N)
            if fes == 2000:
                if self.verbose == True:
                    print('FES: {} | my_swarm.best_cost: {:.4f}'.format(fes, my_swarm.best_cost))
                results_2k = my_swarm.best_cost
            elif fes == 10000:
                if self.verbose == True:
                    print('FES: {} | my_swarm.best_cost: {:.4f}'.format(fes, my_swarm.best_cost))
                results_10k = my_swarm.best_cost
            elif fes == 20000:
                if self.verbose == True:
                    print('FES: {} | my_swarm.best_cost: {:.4f}'.format(fes, my_swarm.best_cost))
                results_20k = my_swarm.best_cost
                break
            new_best_pos = np.empty([self.N, self.dim])
            for n in range(self.N):
                for d in range(self.dim):
                    new_best_pos[n][d] = my_swarm.best_pos[n][d]
            my_swarm.best_pos = new_best_pos
            my_swarm.velocity = self.my_topology.compute_velocity(my_swarm)
            my_swarm.position = self.my_topology.compute_position(my_swarm)
            my_swarm.options['feasibility'] = self.cop.constraints(my_swarm.position)
            my_swarm.current_cost = self.cop.sum_violations(my_swarm.position)
            fes += self.N
            my_swarm.pbest_pos, my_swarm.pbest_cost = P.compute_pbest(my_swarm)

            if i%50==0:
                if self.verbose == True:
                    print('Iteration: {} | my_swarm.best_cost: {:.4f}'.format(i+1, my_swarm.best_cost))


        if np.all(my_swarm.options['feasibility'] == False) == False:
            self.success = True
            if self.verbose == True:
                print('The feasible region was found!')
                print('The following are all the known feasible points:')
                print(my_swarm.position[my_swarm.options['feasibility'] == True])
        else:
            if self.verbose == True:
                print('The feasible region was not found :(')
                print('The best sum of violations found by our swarm is: {:.4f}'.format(my_swarm.best_cost))
                print('The best position found by our swarm is: {}'.format(my_swarm.options['best_position']))

        return (my_swarm.best_cost, results_2k, results_10k, results_20k, self.success)
Esempio n. 9
0
 def test_input_swarm(self, swarm):
     """Test if method raises AttributeError with wrong swarm"""
     with pytest.raises(AttributeError):
         P.compute_pbest(swarm)