def evaluate(problem, mu, population, bounds_lower, bounds_upper, pen_alpha):
    for n in range(0, mu):
        individual = population.variables[n, :]
        if valid(individual, bounds_lower, bounds_upper):

            solution = Individual(phenome=individual)
            problem.evaluate(solution)
        else:
            solution = wrapper(problem, individual, bounds_lower, bounds_upper,
                               pen_alpha)
            solution = Individual(objective_values=solution)

        population.objectives[n, :] = solution.objective_values[:]
    return population
예제 #2
0
    def resize_each_arm(self):
        for arm in self.arms:

            delta_population = len(cluster.population) - self.n_points
            if delta_population < 0:
                trans_positions = np.random.uniform(
                    0, 1, (abs(delta_population), self.dimension))
                positions = cluster.transform_inverse(trans_positions)
                new_population = [
                    Individual(position) for position in positions
                ]
                self.problem.batch_evaluate(new_population)
                cluster.population.extend(new_population)

            cluster.population = sorted(cluster.population,
                                        key=attrgetter('objective_values'))
            cluster.population = cluster.population[:self.n_points]

        ranks = self.get_ranks(self.clusters)
        for i, cluster in enumerate(self.clusters):
            cluster.ranks = ranks[i]
            #print [p.objective_values for p in self.clusters[i].population]
            if self.verbose:
                print('cluster%d: %r' % (i, self.clusters[i].ranks))
        '''
예제 #3
0
def draw_original_contour(function_id, **kwargs):
    dim = 2
    func = CEC2005(dim)[function_id]
    population = kwargs.get('population', [])
    angle = kwargs.get('angle', 240)
    rotate = kwargs.get('rotate', False)
    fig_name = kwargs.get('fig_name', None)
    fig_title = kwargs.get('fig_title', str(func))
    cmap = cm.coolwarm
    scatter_cmap = cm.jet(np.linspace(0.1, 0.9, len(population)))
    boundary = Boundary(dim, function_id)
    step = (boundary.max_bounds[0] - boundary.min_bounds[0]) / 100
    X = np.arange(boundary.min_bounds[0], boundary.max_bounds[0] + step, step)
    Y = np.arange(boundary.min_bounds[1], boundary.max_bounds[1] + step, step)
    (X, Y) = np.meshgrid(X, Y)
    positions = (lambda .0: continue[ [
x,
y] for (x, y) in .0 ])(zip(X.ravel(), Y.ravel()))
    solutions = (lambda .0: continue[ Individual(position) for position in .0 ])(positions)
    problem = Problem(func.objective_function)
    problem.batch_evaluate(solutions)
    Z = np.array((lambda .0: continue[ solution.objective_values for solution in .0 ])(solutions))
    vmin = min(Z)
    vmax = max(Z)
    vmin = vmin - (vmax - vmin) * 0.2
    vmax = vmax + (vmax - vmin) * 0.2
    Z = Z.reshape(X.shape)
    inch_size = 4
    fig_w = 1
    fig_h = 1
    fig = plt.figure(figsize = (fig_w * inch_size, fig_h * inch_size))
    ax = fig.add_subplot(fig_h, fig_w, 1)
    ax.set_xlim([
        boundary.min_bounds[0],
        boundary.max_bounds[0]])
    ax.set_ylim([
        boundary.min_bounds[1],
        boundary.max_bounds[1]])
    cset = ax.contourf(X, Y, Z, cmap = cmap, vmin = vmin, vmax = vmax)
    fig.colorbar(cset, aspect = 20)
    colors = iter(scatter_cmap)
    color = next(colors)
    x = np.array((lambda .0: continue[ individual.phenome[0] for individual in .0 ])(population))
    y = np.array((lambda .0: continue[ individual.phenome[1] for individual in .0 ])(population))
    ax.scatter(x, y, color = color, marker = 'o', s = 10)
    for opt in func.get_optimal_solutions():
        optimal_pos = opt.phenome
        ax.scatter(optimal_pos[0], optimal_pos[1], color = 'w', marker = 'x', s = 100)
    
    fig.tight_layout()
    st = fig.suptitle(fig_title, fontsize = 16)
    st.set_y(0.95)
    fig.subplots_adjust(top = 0.85)
    if fig_name is not None:
        plt.savefig(fig_name)
    else:
        plt.show()
        input('Press Enter to continue...')
    plt.close(fig)
예제 #4
0
def evaluateWFG(WFG: wfg.WFG, x: np.ndarray, obj: int) -> np.ndarray:
    k: int = 2 * (obj - 1)
    if k >= len(x):
        logger.fatal("#dim must be less than 2*(#obj-1) on WFG problems")
        logger.fatal("--- forced termination ---")
        sys.exit()
    prob: wfg.WFG = WFG(obj, len(x), k)
    indiv: Individual = Individual(x)
    prob.evaluate(indiv)
    val = np.array(indiv.objective_values) / refP[:obj]
    return val
예제 #5
0
def draw_surface3d(function_id, **kwargs):
    dim = 2
    func = CEC2005(dim)[function_id]
    clusters = kwargs.get('clusters', [])
    angle = kwargs.get('angle', 240)
    rotate = kwargs.get('rotate', False)
    fig_name = kwargs.get('fig_name', None)
    boundary = Boundary(func)
    step = (boundary.max_bounds[0] - boundary.min_bounds[0]) / 100
    X = np.arange(boundary.min_bounds[0], boundary.max_bounds[0] + step, step)
    Y = np.arange(boundary.min_bounds[1], boundary.max_bounds[1] + step, step)
    (X, Y) = np.meshgrid(X, Y)
    positions = (lambda .0: continue[ [
x,
y] for (x, y) in .0 ])(zip(X.ravel(), Y.ravel()))
    solutions = (lambda .0: continue[ Individual(position) for position in .0 ])(positions)
    problem = Problem(func.objective_function)
    problem.batch_evaluate(solutions)
    Z = np.array((lambda .0: continue[ solution.objective_values for solution in .0 ])(solutions))
    Z = Z.reshape(X.shape)
    fig = plt.figure(figsize = plt.figaspect(0.5))
    fig.suptitle(str(func))
    ax = fig.add_subplot(1, 2, 1)
    cset = ax.contourf(X, Y, Z, cmap = cm.coolwarm)
    colors = iter(cm.rainbow(np.linspace(0, 1, len(clusters))))
    for cluster in clusters:
        color = next(colors)
        x = np.array((lambda .0: continue[ individual.phenome[0] for individual in .0 ])(cluster.population))
        y = np.array((lambda .0: continue[ individual.phenome[1] for individual in .0 ])(cluster.population))
        ax.scatter(x, y, color = color, marker = 'o', s = 10)
        x_border = (lambda .0: continue[ vertice[0] for vertice in .0 ])(cluster.border)
        x_border.append(x_border[0])
        y_border = (lambda .0: continue[ vertice[1] for vertice in .0 ])(cluster.border)
        y_border.append(y_border[0])
        ax.plot(x_border, y_border, color = color)
    
    optimal_pos = func.get_optimal_solutions()[0].phenome
    ax.scatter(optimal_pos[0], optimal_pos[1], color = 'w', marker = 'x', s = 100)
    ax = fig.add_subplot(1, 2, 2, projection = '3d')
    surf = ax.plot_surface(X, Y, Z, alpha = 0.8, zorder = -1, cmap = cm.coolwarm, linewidth = 0, edgecolors = 'k', antialiased = False)
    fig.colorbar(surf, shrink = 0.5, aspect = 5)
    cset = ax.contourf(X, Y, Z, zdir = 'z', zorder = -2, offset = np.amin(Z), cmap = cm.coolwarm)
    if rotate:
        for ang in range(angle, angle + 360, 10):
            ax.view_init(30, ang)
            plt.draw()
            plt.pause(0.001)
        
    else:
        ax.view_init(30, angle)
        plt.show()
        if fig_name is not None:
            plt.savefig(fig_name)
        input('Press Enter to continue...')
예제 #6
0
    def init_population(self, n_points, dim):
        positions = np.zeros((n_points, dim))
        for d in range(dim):
            positions[:, d] = np.random.uniform(self.boundary.min_bounds[d],
                                                self.boundary.max_bounds[d],
                                                self.n_points)

        population = [Individual(position) for position in positions]
        self.problem.batch_evaluate(population)
        population = sorted(population, key=attrgetter('objective_values'))
        population = population[:len(population) / 2]
        ranks = range(1, len(population) + 1)
        return [Cluster(population, ranks)]
예제 #7
0
    def run(self):
        self.iteration = self.iteration + 1
        if self.algo_type == 'CMA':

            positions = self.algo.ask()

            solutions = [Individual(position) for position in positions]
            try:
                self.problem.batch_evaluate(solutions)
            except ResourcesExhausted:
                self.should_terminate = True
                return

            self.algo.tell([p.phenome for p in solutions],
                           [p.objective_values for p in solutions])
            self.population = sorted(solutions,
                                     key=attrgetter('objective_values'))

        self.best_solution = min(self.population,
                                 key=attrgetter('objective_values'))
        self.update_statistics()
def wrapper(problem, individual, MIN_BOUND, MAX_BOUND, pen_alpha):
    fitness_weights = np.empty(problem.num_objectives)
    fitness_weights.fill(-1.0)

    f_ind = closest_feasible(individual, MIN_BOUND, MAX_BOUND)
    solution = Individual(phenome=f_ind)
    problem.evaluate(solution)
    f_fbl = solution.objective_values[:]
    weights = tuple(1.0 if w >= 0 else -1.0 for w in fitness_weights)

    if len(weights) != len(f_fbl):
        raise IndexError(
            "Fitness weights and computed fitness are of different size.")

    dists = tuple(0 for w in fitness_weights)
    dist = distance(f_ind, individual)

    if not isinstance(dists, Sequence):
        dists = repeat(dists)

    pen_fbl = tuple(f - w * pen_alpha * dist
                    for f, w, d in zip(f_fbl, weights, dists))

    return pen_fbl
예제 #9
0
def draw( obj, fig_name, **kwargs ):

    import os
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from optproblems import Individual, Problem

    # Parameters
    problem = Problem( obj )
    angle = kwargs.get( 'angle', 240 )
    optimal = kwargs.get( 'optimal', None )
    scatter = kwargs.get( 'scatter', None )
    xlim = kwargs.get( 'xlim', [-100,100] )
    ylim = kwargs.get( 'ylim', [-100,100] )
    fig_title = kwargs.get( 'fig_title', fig_name )
    fig_dir = kwargs.get( 'fig_dir', './' )
    if not os.path.exists(fig_dir):
        os.makedirs(fig_dir)

    fig = plt.figure(figsize=plt.figaspect(0.85))
    ax = fig.add_subplot(111, aspect=1)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    cmap = cm.coolwarm
    #scatter_cmap = cm.jet( np.linspace(0.1, 0.9, len(clusters_positions)) )
    fig.tight_layout()
    st = fig.suptitle( fig_title, fontsize=16 )
    st.set_y(0.95)
    fig.subplots_adjust(top=0.85)

    # Generate mesh solutions
    step = (xlim[1] - xlim[0])/100.0
    X = np.arange( xlim[0], xlim[1]+step, step )
    Y = np.arange( ylim[0], ylim[1]+step, step )

    X, Y = np.meshgrid(X, Y)
    positions = [ [x,y] for x, y in zip(X.ravel(), Y.ravel()) ]
    solutions = [ Individual(position) for position in positions ]

    # Evaluate solutions
    problem.batch_evaluate(solutions)
    Z = np.array( [solution.objective_values for solution in solutions] )
    vmin, vmax = min(Z), max(Z)
    vmin = vmin - (vmax-vmin)*0.2
    vmax = vmax + (vmax-vmin)*0.2
    Z = Z.reshape(X.shape)


    # Draw contour
    cset = ax.contourf(X, Y, Z, cmap=cmap, vmin=vmin, vmax=vmax)
    fig.colorbar(cset, aspect=20)
    if optimal:
        ax.scatter( optimal[0], optimal[1], color='w', marker='x', s=100 )

    if scatter is not None:
        color = 'r'
        ax.scatter( scatter[:,0], scatter[:,1], color=color, s=10 )


    plt.savefig('%s/%s' % (fig_dir, fig_name))
    plt.close(fig)
예제 #10
0
def draw_cluster(function_id, clusters, k, **kwargs):
    dim = 2
    func = CEC2005(dim)[function_id]
    angle = kwargs.get('angle', 240)
    fig_name = kwargs.get('fig_name', None)
    cluster = clusters[k]
    color = cm.rainbow(np.linspace(0, 1, len(clusters)))[k]
    X = np.arange(0, 1.01, 0.01)
    Y = np.arange(0, 1.01, 0.01)
    (X, Y) = np.meshgrid(X, Y)
    positions = (lambda .0: continue[ [
x,
y] for (x, y) in .0 ])(zip(X.ravel(), Y.ravel()))
    original_positions = cluster.transform_inverse(positions)
    solutions = (lambda .0: continue[ Individual(position) for position in .0 ])(original_positions)
    problem = Problem(func.objective_function)
    problem.batch_evaluate(solutions)
    Z = np.array((lambda .0: continue[ solution.objective_values for solution in .0 ])(solutions))
    Z = Z.reshape(X.shape)
    fig = plt.figure(figsize = plt.figaspect(0.5))
    fig.suptitle(str(func))
    ax = fig.add_subplot(1, 2, 1)
    cset = ax.contourf(X, Y, Z, cmap = cm.coolwarm)
    positions = np.array((lambda .0: continue[ p.phenome for p in .0 ])(cluster.population))
    transformed_positions = cluster.transform(positions)
    x = transformed_positions.T[0]
    y = transformed_positions.T[1]
    ax.scatter(x, y, color = color, marker = 'o', s = 10)
    cord = np.array([
        [
            0,
            0],
        [
            1,
            0],
        [
            1,
            1],
        [
            0,
            1]])
    ax.plot(cord[([
        0,
        1,
        2,
        3,
        0], 0)], cord[([
        0,
        1,
        2,
        3,
        0], 1)], color = color)
    ax = fig.add_subplot(1, 2, 2, projection = '3d')
    surf = ax.plot_surface(X, Y, Z, alpha = 0.8, zorder = -1, cmap = cm.coolwarm, linewidth = 0, edgecolors = 'k', antialiased = False)
    fig.colorbar(surf, shrink = 0.5, aspect = 5)
    cset = ax.contourf(X, Y, Z, zdir = 'z', zorder = -2, offset = np.amin(Z), cmap = cm.coolwarm)
    ax.view_init(30, angle)
    plt.show()
    if fig_name is not None:
        plt.savefig(fig_name)
    input('Press Enter to continue...')
예제 #11
0
def draw_all(function_id, **kwargs):
    dim = 2
    func = CEC2005(dim)[function_id]
    clusters = kwargs.get('clusters', [])
    angle = kwargs.get('angle', 240)
    rotate = kwargs.get('rotate', False)
    fig_name = kwargs.get('fig_name', None)
    cmap = cm.coolwarm
    scatter_cmap = cm.jet(np.linspace(0.1, 0.9, len(clusters)))
    boundary = Boundary(func)
    step = (boundary.max_bounds[0] - boundary.min_bounds[0]) / 100
    X = np.arange(boundary.min_bounds[0], boundary.max_bounds[0] + step, step)
    Y = np.arange(boundary.min_bounds[1], boundary.max_bounds[1] + step, step)
    (X, Y) = np.meshgrid(X, Y)
    positions = (lambda .0: continue[ [
x,
y] for (x, y) in .0 ])(zip(X.ravel(), Y.ravel()))
    solutions = (lambda .0: continue[ Individual(position) for position in .0 ])(positions)
    problem = Problem(func.objective_function)
    problem.batch_evaluate(solutions)
    Z = np.array((lambda .0: continue[ solution.objective_values for solution in .0 ])(solutions))
    Z = Z.reshape(X.shape)
    fig_w = len(clusters) + 1
    fig_h = 2
    fig = plt.figure(figsize = plt.figaspect(float(fig_h) / fig_w))
    fig.suptitle(str(func))
    ax = fig.add_subplot(fig_h, fig_w, 1, projection = '3d')
    surf = ax.plot_surface(X, Y, Z, alpha = 0.8, zorder = -1, cmap = cmap, linewidth = 0, edgecolors = 'k', antialiased = False)
    fig.colorbar(surf, shrink = 0.5, aspect = 5)
    cset = ax.contourf(X, Y, Z, zdir = 'z', zorder = -2, offset = np.amin(Z), cmap = cmap)
    ax.view_init(30, angle)
    ax = fig.add_subplot(fig_h, fig_w, fig_w + 1)
    cset = ax.contourf(X, Y, Z, cmap = cmap)
    colors = iter(scatter_cmap)
    for cluster in clusters:
        color = next(colors)
        x = np.array((lambda .0: continue[ individual.phenome[0] for individual in .0 ])(cluster.population))
        y = np.array((lambda .0: continue[ individual.phenome[1] for individual in .0 ])(cluster.population))
        ax.scatter(x, y, color = color, marker = 'o', s = 10)
        x_border = (lambda .0: continue[ vertice[0] for vertice in .0 ])(cluster.border)
        x_border.append(x_border[0])
        y_border = (lambda .0: continue[ vertice[1] for vertice in .0 ])(cluster.border)
        y_border.append(y_border[0])
        ax.plot(x_border, y_border, color = color)
    
    optimal_pos = func.get_optimal_solutions()[0].phenome
    ax.scatter(optimal_pos[0], optimal_pos[1], color = 'w', marker = 'x', s = 100)
    for k in range(len(clusters)):
        cluster = clusters[k]
        color = scatter_cmap[k]
        X = np.arange(0, 1.01, 0.01)
        Y = np.arange(0, 1.01, 0.01)
        (X, Y) = np.meshgrid(X, Y)
        positions = (lambda .0: continue[ [
x,
y] for (x, y) in .0 ])(zip(X.ravel(), Y.ravel()))
        original_positions = cluster.transform_inverse(positions)
        solutions = (lambda .0: continue[ Individual(position) for position in .0 ])(original_positions)
        problem = Problem(func.objective_function)
        problem.batch_evaluate(solutions)
        Z = np.array((lambda .0: continue[ solution.objective_values for solution in .0 ])(solutions))
        Z = Z.reshape(X.shape)
        ax = fig.add_subplot(fig_h, fig_w, k + 2, projection = '3d')
        surf = ax.plot_surface(X, Y, Z, alpha = 0.8, zorder = -1, cmap = cmap, linewidth = 0, edgecolors = 'k', antialiased = False)
        fig.colorbar(surf, shrink = 0.5, aspect = 5)
        cset = ax.contourf(X, Y, Z, zdir = 'z', zorder = -2, offset = np.amin(Z), cmap = cmap)
        ax.view_init(30, angle)
        ax = fig.add_subplot(fig_h, fig_w, fig_w + k + 2)
        cset = ax.contourf(X, Y, Z, cmap = cmap)
        positions = np.array((lambda .0: continue[ p.phenome for p in .0 ])(cluster.population))
        transformed_positions = cluster.transform(positions)
        x = transformed_positions.T[0]
        y = transformed_positions.T[1]
        ax.scatter(x, y, color = color, marker = 'o', s = 10)
        cord = np.array([
            [
                0,
                0],
            [
                1,
                0],
            [
                1,
                1],
            [
                0,
                1]])
        ax.plot(cord[([
            0,
            1,
            2,
            3,
            0], 0)], cord[([
            0,
            1,
            2,
            3,
            0], 1)], color = color)
    
    fig.tight_layout()
    plt.show()
    if fig_name is not None:
        plt.savefig(fig_name)
    input('Press Enter to continue...')
예제 #12
0
        input('Press Enter to continue...')
    plt.close(fig)


if __name__ == '__main__':
    nPoints = 40
    dim = 2
    function_id = 8
    n_clusters = 3
    func = CEC2005(dim)[function_id]
    positions = np.zeros((nPoints, dim))
    boundary = Boundary(dim, function_id)
    for d in range(dim):
        positions[(:, d)] = np.random.uniform(boundary.min_bounds[d], boundary.max_bounds[d], nPoints)
    
    population = (lambda .0: continue[ Individual(position) for position in .0 ])(positions)
    problem = Problem(func.objective_function)
    problem.batch_evaluate(population)
    population = sorted(population, key = (lambda p: p.objective_values))
    population = population[:len(population) // 2]
    X = np.array((lambda .0: continue[ individual.phenome for individual in .0 ])(population))
    labels = KMeans(n_clusters = n_clusters).fit_predict(X)
    clusters = []
    for k in range(n_clusters):
        cluster_population = []
        for i in range(len(population)):
            if labels[i] == k:
                cluster_population.append(population[i])
                continue
        clusters.append(Cluster(cluster_population, boundary))
    
예제 #13
0
    def run(self):
        self.iteration = self.iteration + 1

        # Choose best cluster to update
        ranks = self.get_ranks(self.clusters)
        remain_f_allocation = Combination(self.problem.remaining_evaluations,
                                          len(self.clusters),
                                          self.n_points,
                                          ranks,
                                          model='linear',
                                          debug=False).combination

        self.remain_f_allocation += np.array(remain_f_allocation)
        best_arm = np.argmax(self.remain_f_allocation)
        remain_f = np.amax(remain_f_allocation)

        if self.algo_type == 'CMA':
            if self.algos[best_arm].stop():
                self.remain_f_allocation[
                    best_arm] = -self.remain_f_allocation[best_arm]
                if self.verbose:
                    print('CMA-ES at cluster %d stops!!' % (best_arm))
                #draw_contour( function_id, clusters=bandit.clusters )
                return

        print('Update cluster %d' % best_arm)

        # TODO
        #self.remain_f_allocation[best_arm] = 0
        self.remain_f_allocation[best_arm] -= len(
            self.clusters[best_arm].population)

        # Transform data points to [0-1] space and resume algorithm
        original_points = [
            p.phenome for p in self.clusters[best_arm].population
        ]
        trans_points = self.clusters[best_arm].transform(original_points).clip(
            0, 1)
        fitness_values = [
            p.objective_values for p in self.clusters[best_arm].population
        ]

        new_trans_positions = self.update_positions(best_arm, trans_points,
                                                    fitness_values)

        # Update cluster.population
        new_positions = self.clusters[best_arm].transform_inverse(
            new_trans_positions)
        solutions = [Individual(position) for position in new_positions]

        try:
            self.problem.batch_evaluate(solutions)
        except ResourcesExhausted:
            self.should_terminate = True
            return

        self.clusters[best_arm].population = sorted(
            solutions, key=attrgetter('objective_values'))
        ranks = self.get_ranks(self.clusters)
        for i, cluster in enumerate(self.clusters):
            cluster.ranks = ranks[i]

        self.best_solution = self.update_best_solution()

        # Check if need to recluster
        trans_mean_position = np.mean(new_trans_positions, axis=0)
        best_point = self.clusters[best_arm].population[0].phenome
        trans_best_point = self.clusters[best_arm].transform([best_point
                                                              ]).clip(0, 1)[0]
        margin = 0.05
        if ((trans_best_point < margin).any() or (trans_best_point > 1-margin).any()) and \
           ((trans_mean_position < 2*margin).any() or (trans_mean_position > 1-2*margin).any()):

            if self.verbose:
                print('Reclustering...')
                print('due to best_point of cluster %d at: %r' %
                      (best_arm, trans_best_point))
                print('                      and mean at: %r' %
                      (trans_mean_position))
            if args.draw_contour > 0:
                draw_contour(self.function_id, clusters=self.clusters)
            self.shift_matrix(best_arm, best_point)
            if args.draw_contour > 0:
                draw_contour(self.function_id, clusters=self.clusters)
            self.recluster(len(self.clusters))
            if args.draw_contour > 0:
                draw_contour(self.function_id, clusters=self.clusters)

        self.update_statistics(best_arm)
예제 #14
0
    def estimate_k_clusters(self, X, max_n_clusters):
        score = np.zeros(max_n_clusters + 1)
        score[0] = -1.0
        for k in range(2, max_n_clusters + 1):
            km = KMeans(n_clusters=k)
            labels = km.fit_predict(X)
            score[k] = silhouette_score(X, labels)
        return np.argmax(score)

        population = [Individual(position) for position in positions]
        self.problem.batch_evaluate(population)
        population = sorted(population, key=attrgetter('objective_values'))
        selected_population = population[:len(population) // 2]
        X = np.array([p.phenome for p in selected_population])

        if self.verbose:
            print('popsize:%d, k:%d' % (len(selected_population), k))
        ranks = range(1, len(selected_population) + 1)
        self.clusters = [Cluster(selected_population, ranks)]

        min_k = k

        while True:
            positions = np.zeros((population_step, self.dimension))
            for d in range(self.dimension):
                positions[:,
                          d] = np.random.uniform(self.boundary.min_bounds[d],
                                                 self.boundary.max_bounds[d],
                                                 population_step)
            new_population = [Individual(position) for position in positions]
            self.problem.batch_evaluate(new_population)
            population.extend(new_population)
            population = sorted(population, key=attrgetter('objective_values'))
            selected_population = population[:len(population) // 2]
            X = np.array([p.phenome for p in selected_population])

            k = self.estimate_n_clusters(X, self.max_n_clusters)
            if self.verbose:
                print('popsize:%d, k:%d' % (len(selected_population), k))
            if k <= min_k: break
            min_k = k

            ### Should delete
            #self.clusters = self.k_means(k)
            #draw_contour( self.function_id, clusters=self.clusters )
            ###########

        self.clusters = self.k_means(k)
        #draw_contour( self.function_id, clusters=self.clusters )

        #self.update_borders()
        #for i in range(k):
        #    self.update_matrix(i)

        if args.draw_contour > 0 and args.figure_directory:
            draw_contour(self.function_id,
                         clusters=self.clusters,
                         fig_name="%sF%d_init" %
                         (args.figure_directory, self.function_id + 1),
                         fig_title="F%d_init" % (self.function_id + 1))
        #draw_contour( self.function_id, clusters=self.clusters )

        self.resize_each_cluster()
예제 #15
0
def draw_quiver(aco, obj, fig_name, **kwargs):

    import os
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from optproblems import Individual, Problem

    # Parameters
    problem = Problem(obj)
    angle = kwargs.get('angle', 240)
    optimal = kwargs.get('optimal', None)
    xlim = kwargs.get('xlim', [-100, 100])
    ylim = kwargs.get('ylim', [-100, 100])
    fig_title = kwargs.get('fig_title', fig_name)
    fig_dir = kwargs.get('fig_dir', 'test_pso')
    if not os.path.exists(fig_dir):
        os.makedirs(fig_dir)

    fig = plt.figure(figsize=plt.figaspect(0.85))
    ax = fig.add_subplot(111, aspect=1)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    cmap = cm.coolwarm
    fig.tight_layout()
    st = fig.suptitle(fig_title, fontsize=16)
    st.set_y(0.95)
    fig.subplots_adjust(top=0.85)

    # Generate mesh solutions
    step = (xlim[1] - xlim[0]) / 100.0
    X = np.arange(xlim[0], xlim[1] + step, step)
    Y = np.arange(ylim[0], ylim[1] + step, step)

    X, Y = np.meshgrid(X, Y)
    positions = [[x, y] for x, y in zip(X.ravel(), Y.ravel())]
    solutions = [Individual(position) for position in positions]

    # Evaluate solutions
    problem.batch_evaluate(solutions)
    Z = np.array([solution.objective_values for solution in solutions])
    vmin, vmax = min(Z), max(Z)
    vmin = vmin - (vmax - vmin) * 0.2
    vmax = vmax + (vmax - vmin) * 0.2
    Z = Z.reshape(X.shape)

    # Draw contour
    cset = ax.contourf(X, Y, Z, cmap=cmap, vmin=vmin, vmax=vmax)
    fig.colorbar(cset, aspect=20)
    if optimal:
        ax.scatter(optimal[0], optimal[1], color='w', marker='x', s=100)

    # Draw arrow
    X = np.array([p.current.position[0] for p in pso.swarm])
    Y = np.array([p.current.position[1] for p in pso.swarm])
    U = np.array([p.velocity[0] for p in pso.swarm])
    V = np.array([p.velocity[1] for p in pso.swarm])
    M = np.hypot(U, V)
    Q = ax.quiver(X, Y, U, V, color='m', units='x', pivot='tip', scale=1)

    # Draw scatter
    ax.scatter(X, Y, color='r', s=10)

    plt.savefig('%s/%s' % (fig_dir, fig_name))
    plt.close(fig)
예제 #16
0
 def _evaluate(self, x, out, *args, **kwargs):
     solutions = [Individual(s) for s in x]
     self.func.batch_evaluate(solutions)
     out["F"] = anp.array([s.objective_values for s in solutions])