Ejemplo n.º 1
0
def get_ref_dirs(n_obj):
    if n_obj == 2:
        ref_dirs = UniformReferenceDirectionFactory(2, n_points=100).do()
    elif n_obj == 3:
        ref_dirs = UniformReferenceDirectionFactory(3, n_partitions=15).do()
    else:
        raise Exception(
            "Please provide reference directions for more than 3 objectives!")
    return ref_dirs
Ejemplo n.º 2
0
def get_setup(n_obj):
    if n_obj == 3:
        pop_size = 92
        ref_dirs = UniformReferenceDirectionFactory(n_obj, n_partitions=12).do()
    elif n_obj == 5:
        pop_size = 212
        ref_dirs = UniformReferenceDirectionFactory(n_obj, n_partitions=6).do()
    elif n_obj == 8:
        pop_size = 156
        ref_dirs = MultiLayerReferenceDirectionFactory([
            UniformReferenceDirectionFactory(n_obj, n_partitions=3, scaling=1.0),
            UniformReferenceDirectionFactory(n_obj, n_partitions=2, scaling=0.5)]).do()
    elif n_obj == 10:
        pop_size = 276
        ref_dirs = MultiLayerReferenceDirectionFactory([
            UniformReferenceDirectionFactory(n_obj, n_partitions=3, scaling=1.0),
            UniformReferenceDirectionFactory(n_obj, n_partitions=2, scaling=0.5)]).do()
    elif n_obj == 15:
        pop_size = 136
        ref_dirs = MultiLayerReferenceDirectionFactory([
            UniformReferenceDirectionFactory(n_obj, n_partitions=2, scaling=1.0),
            UniformReferenceDirectionFactory(n_obj, n_partitions=1, scaling=0.5)]).do()

    return {
        'ref_dirs': ref_dirs,
        'pop_size': pop_size,
        'crossover': SimulatedBinaryCrossover(1.0, 30),
        'mutation': PolynomialMutation(20)
    }
Ejemplo n.º 3
0
    def _do(self):
        ref_dirs = MultiLayerReferenceDirectionFactory([
            UniformReferenceDirectionFactory(n_dim=self.n_dim,
                                             n_partitions=12,
                                             scaling=1),
            UniformReferenceDirectionFactory(n_dim=self.n_dim,
                                             n_partitions=12,
                                             scaling=0.7)
        ]).do()

        #UniformReferenceDirectionFactory(n_dim=self.n_dim,n_points=self.n_points, n_partitions=self.n_partitions, scaling=self.scaling).do()
        self.n_points = ref_dirs.shape[0]
        self.seq = np.tile(self.seq, [ref_dirs.shape[0], 1])
        ref_dirs = np.multiply(ref_dirs, self.seq)
        sum = np.sum(ref_dirs, axis=1)
        sum = np.tile(sum, [ref_dirs.shape[1], 1]).transpose()
        ref_dirs = np.divide(ref_dirs, sum)
        return ref_dirs
Ejemplo n.º 4
0
def plot_test_problem(axarr, F, problem, type=1):

    F1 = F[:, 0].flatten()
    F2 = F[:, 1].flatten()

    c = list([1, 4, 3])
    constr_func = dict()
    for i in c:
        if i == 1:
            constr_func[str(i)] = constraint_c1
        elif i == 2:
            constr_func[str(i)] = constraint_c2
        elif i == 3:
            constr_func[str(i)] = constraint_c3
        elif i == 4:
            constr_func[str(i)] = constraint_c4
    # plt.clf()
    index = np.ones(F.shape[0], dtype=bool)

    for i in range(len(constr_func)):
        G = constr_func[str(c[i])](F, dtlz_type=type)
        cv = np.copy(G)  # np.zeros(G.shape)

        light_grey = np.array([220, 220, 220]) / 256
        dark_grey = np.array([169, 169, 169]) / 256
        cv[G <= 0] = 0
        if G.ndim > 1:
            cv = np.sum(cv, axis=1)

        temp_index = cv <= 0
        index = index & temp_index
        # axarr[index].plot(x, y)
        # cmaps = OrderedDict()
    plt.plot(F1, F2, 'o', color='#DCDCDC')  #'#A9A9A9'
    plt.plot(F1[index], F2[index], 'o', color='b')
    # F_all = np.concatenate((F, np.vstack(cv)),axis=1)
    # heatmap, xedges, yedges = np.histogram2d(F1, F2, weights=cv, )
    # extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
    # plt.hexbin(F1[index], F2[index], C=cv, cmap='Greys')

    # ax.clf()
    # plt.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys')
    ref_dirs = UniformReferenceDirectionFactory(n_dim=2, n_points=21)._do()
    PF = problem._calc_pareto_front(ref_dirs)
    plt.plot(PF[:, 0], PF[:, 1], 'o', color='r')
    plt.show()
Ejemplo n.º 5
0
    def __init__(self, ref_points, pop_per_ref_point, mu=0.05, **kwargs):
        n_obj = ref_points.shape[1]

        # add the aspiration point lines
        aspiration_ref_dirs = UniformReferenceDirectionFactory(
            n_dim=n_obj, n_points=pop_per_ref_point).do()

        kwargs['ref_dirs'] = aspiration_ref_dirs
        super().__init__(**kwargs)

        self.pop_size = ref_points.shape[0] * aspiration_ref_dirs.shape[
            0] + aspiration_ref_dirs.shape[1]

        # create the survival strategy
        self.survival = AspirationPointSurvival(ref_points,
                                                aspiration_ref_dirs,
                                                mu=mu)
Ejemplo n.º 6
0
    def test_no_exception(self):

        for problem in self.problems:

            for algorithm in self.algorithms:

                try:
                    minimize(problem,
                             method=algorithm['name'],
                             method_args={**algorithm, 'ref_dirs': UniformReferenceDirectionFactory(n_dim=problem.n_obj, n_points=100).do()},
                             termination=('n_eval', algorithm['n_eval']),
                             seed=2,
                             save_history=True,
                             disp=False)

                except:
                    print(problem)
                    print(algorithm)
                    self.fail("minimize() raised ExceptionType unexpectedly!")
Ejemplo n.º 7
0
            f1 = np.vstack(xv.flatten())
            f2 = np.vstack(yv.flatten())
            F = np.hstack((f1, f2))
            n = F.shape[0]

        # plot_test_problem(F, problem, type=dtlz_type)

        F1 = F[:, 0].flatten()
        F2 = F[:, 1].flatten()

        G[G <= 0] = 0
        if G.ndim > 1:
            G = np.sum(G, axis=1)
        index = G > 0

        ref_dirs = UniformReferenceDirectionFactory(n_dim=problem.n_obj,
                                                    n_points=21)._do()
        PF = problem._calc_pareto_front(ref_dirs)

        plt.title(name)
        plt.plot(F1, F2, 'o', color='#DCDCDC')  # '#A9A9A9'
        plt.plot(F1[index], F2[index], 'o', color='b')
        plt.plot(PF[:, 0], PF[:, 1], 'o', color='r')
        # ax[count].set_title(name)
        # ax[count].plot(F1, F2, 'o', color='#DCDCDC')  # '#A9A9A9'
        # ax[count].plot(F1[index], F2[index], 'o', color='b')
        # ax[count].plot(PF[:, 0], PF[:, 1], 'o', color='r')
        # ax[count].set_xlim([np.min(F1), np.max(F1)])
        count += 1
    plt.show()

# if __name__ == '__main__':
Ejemplo n.º 8
0
aggregation['l'].append('asf')
aggregation['G'].append('acv')
aggregation['fg_M5'].append('asfcv')
aggregation['fg_M6'].append('asfcv')
metamodel_list = ['dacefit']

init_pop_size = 100
pop_size_per_epoch = 21
pop_size_per_algorithm = 21
pop_size_lf = 100

problem_name = 'tnk'
# problem = get_problem(problem_name, n_var=10, n_obj=2)
problem = get_problem(problem_name)
# problem = get_problem(problem_name, n_var=10)
ref_dirs = UniformReferenceDirectionFactory(problem.n_obj, n_points=pop_size_per_epoch).do()
if problem_name.__contains__('dtlz'):
    pf = problem.pareto_front(ref_dirs=ref_dirs)
else:
    pf = np.loadtxt("../data/IGD/TNK.2D.pf")  # problem.pareto_front()


acq_list, framework_acq_dict = get_acq_function(framework_id=framework_id,
                                                aggregation=aggregation,
                                                problem=problem,
                                                n_dir=pop_size_per_epoch)

res = minimize(problem=problem,
               method='samoo',
               method_args={'seed': 53,
                            'method': 'samoo',
Ejemplo n.º 9
0
    def __init__(
            self,
            ref_points,
            pop_per_ref_point,
            mu=0.05,
            sampling=FloatRandomSampling(),
            selection=TournamentSelection(func_comp=comp_by_cv_then_random),
            crossover=SimulatedBinaryCrossover(eta=30, prob=1.0),
            mutation=PolynomialMutation(eta=20, prob=None),
            eliminate_duplicates=True,
            n_offsprings=None,
            **kwargs):
        """

        Parameters
        ----------

        ref_points : {ref_points}
        pop_per_ref_point : int
            Size of the population used for each reference point.

        mu : float
            Defines the scaling of the reference lines used during survival selection. Increasing mu will result
            having solutions with a larger spread.

        Other Parameters
        -------

        n_offsprings : {n_offsprings}
        sampling : {sampling}
        selection : {selection}
        crossover : {crossover}
        mutation : {mutation}
        eliminate_duplicates : {eliminate_duplicates}

        """

        # number of objectives the reference lines have
        n_obj = ref_points.shape[1]

        # add the aspiration point lines
        aspiration_ref_dirs = UniformReferenceDirectionFactory(
            n_dim=n_obj, n_points=pop_per_ref_point).do()

        survival = AspirationPointSurvival(ref_points,
                                           aspiration_ref_dirs,
                                           mu=mu)
        pop_size = ref_points.shape[0] * aspiration_ref_dirs.shape[
            0] + aspiration_ref_dirs.shape[1]
        ref_dirs = None

        super().__init__(ref_dirs,
                         pop_size=pop_size,
                         sampling=sampling,
                         selection=selection,
                         crossover=crossover,
                         mutation=mutation,
                         survival=survival,
                         eliminate_duplicates=eliminate_duplicates,
                         n_offsprings=n_offsprings,
                         **kwargs)
Ejemplo n.º 10
0
from pymoo.optimize import minimize
from pymoo.util import plotting
from pymoo.util.reference_direction import UniformReferenceDirectionFactory
from pymop.factory import get_problem

problem = get_problem("dtlz1", n_var=7, n_obj=3)
# create the reference directions to be used for the optimization
ref_dirs = UniformReferenceDirectionFactory(3, n_points=91).do()

# create the pareto front for the given reference lines
pf = problem.pareto_front(ref_dirs)

res = minimize(problem,
               method='nsga3',
               method_args={
                   'pop_size': 92,
                   'ref_dirs': ref_dirs
               },
               termination=('n_gen', 400),
               pf=pf,
               seed=1,
               disp=True)
plotting.plot(res.F)
Ejemplo n.º 11
0
            crowding[np.argmin(F_asf[:, k])] = np.inf

        return crowding


def normalize(F, ideal_point, nadir_point, utopian_epsilon=0.0):
    utopian_point = ideal_point - utopian_epsilon
    N = (F - utopian_point) / (nadir_point - utopian_point)
    return N


problem = get_problem("dtlz2", n_var=None, n_obj=3, k=5)

n_gen = 400
pop_size = 91
ref_dirs = UniformReferenceDirectionFactory(3, n_partitions=12,
                                            scaling=1.0).do()

# create the pareto front for the given reference lines
pf = problem.pareto_front(ref_dirs)

res = minimize(problem,
               method='nsga2',
               method_args={
                   'pop_size': 100,
                   'survival': ASFSurvival()
               },
               termination=('n_gen', n_gen),
               pf=pf,
               save_history=True,
               seed=31,
               disp=True)
Ejemplo n.º 12
0
from pymoo.experimental.pbi import ReferenceDirectionSurvivalPBI
from pymoo.optimize import minimize
from pymoo.util.reference_direction import UniformReferenceDirectionFactory, MultiLayerReferenceDirectionFactory
from pymop.factory import get_problem

import matplotlib.pyplot as plt

import numpy as np

problem = get_problem("dtlz3", n_var=None, n_obj=15, k=10)

n_gen = 2000
pop_size = 136
ref_dirs = MultiLayerReferenceDirectionFactory([
    UniformReferenceDirectionFactory(15, n_partitions=2, scaling=1.0),
    UniformReferenceDirectionFactory(15, n_partitions=1, scaling=0.5)
]).do()

# create the pareto front for the given reference lines
pf = problem.pareto_front(ref_dirs)

ideal_point = []
nadir_point = []


def my_callback(algorithm):
    ideal_point.append(np.copy(algorithm.survival.ideal_point))
    nadir_point.append(np.copy(algorithm.survival.nadir_point))

Ejemplo n.º 13
0
class ScaledZDT1(ZDT1):
    def _calc_pareto_front(self, n_pareto_points=1000):
        pf = super()._calc_pareto_front(2000) * np.array([1.0, 10.0])
        #cd = calc_crowding_distance(pf)
        #pf = pf[np.argsort(cd)[::-1][:200]]
        return pf - 500

    def _evaluate(self, x, out, *args, **kwargs):
        super()._evaluate(x, out, *args, **kwargs)
        out["F"] = out["F"] * np.array([1.0, 10.0]) - 500


problem = ScaledZDT1()

ref_dirs = UniformReferenceDirectionFactory(2, n_points=100).do()

pf = problem.pareto_front()

res = minimize(
    problem,
    method='nsga3',
    method_args={
        'pop_size': 100,
        'ref_dirs': ref_dirs,
        #'survival': ReferenceDirectionSurvivalTrue(ref_dirs, np.array([[1.0, 0], [0, 1.0]]))
    },
    termination=('n_gen', 400),
    pf=pf,
    seed=1,
    disp=True)
Ejemplo n.º 14
0
        else:
            # already randomized through shuffling
            next_ind = next_ind[0]

        mask[next_ind] = False
        survivors.append(int(next_ind))

        niche_count[next_niche] += 1

    return survivors


if __name__ == "__main__":
    problem = get_problem("dtlz1", n_var=7, n_obj=3)
    # create the reference directions to be used for the optimization
    ref_dirs = UniformReferenceDirectionFactory(3, n_partitions=12).do()

    # create the pareto front for the given reference lines
    pf = problem.pareto_front(ref_dirs)

    res = minimize(problem,
                   method='nsga3',
                   method_args={
                       'pop_size': 92,
                       'ref_dirs': ref_dirs,
                       'survival': KKTPMReferenceSurvival(ref_dirs)
                   },
                   termination=('n_gen', 400),
                   pf=pf,
                   seed=31,
                   disp=True)