Пример #1
0
def minimize_(problem,
              evaluator,
              method='auto',
              method_args={},
              seed=None,
              callback=None,
              disp=False):
    """
        See :func:`~pymoo.optimize.minimize` for description. Instead of a function the parameter is a problem class.
    """

    # try to find a good algorithm if auto is selected
    if method == 'auto':
        method = 'nsga2'

    # choose the algorithm implementation given the string
    if method == 'nsga2':
        algorithm = NSGA2("real", disp=disp, **method_args)
    elif method == 'nsga3':
        algorithm = NSGA3("real", disp=disp, **method_args)
    elif method == 'moead':
        algorithm = MOEAD("real", disp=disp, **method_args)
    elif method == 'de':
        algorithm = DifferentialEvolution(disp=disp, **method_args)
    elif method == 'ga':
        algorithm = SingleObjectiveGeneticAlgorithm("real",
                                                    disp=disp,
                                                    **method_args)
    else:
        raise Exception('Unknown method: %s' % method)

    X, F, G = algorithm.solve(problem, evaluator)

    return {'problem': problem, 'X': X, 'F': F, 'G': G}
Пример #2
0
    def generate_solution(self):

        if self.rescheduling:
            n_obj = 6
        else:
            n_obj = 5

        ref_dirs = get_reference_directions("das-dennis",
                                            n_obj,
                                            n_partitions=8)

        selection = get_selection('tournament',
                                  func_comp=feasability_tournament,
                                  pressure=self.tournament_size)

        algorithm = NSGA3(pop_size=self.population_size,
                          sampling=DockSampling(),
                          selection=selection,
                          crossover=DockCrossover(),
                          mutation=DockMutation(),
                          ref_dirs=ref_dirs,
                          eliminate_duplicates=func_is_duplicate)
        res = minimize(DockProblem(n_obj, self),
                       algorithm,
                       seed=1,
                       verbose=True,
                       save_history=True,
                       termination=('n_gen', self.max_generations))

        return res.X.flatten(), res.history
Пример #3
0
def Get_Algorithm_Instance(reference_directions,
                           pop_size=None,
                           crossover_probability=1.0,
                           mutation_probability=None):
    crossover = get_crossover("real_sbx", prob=crossover_probability, eta=30)
    mutation = get_mutation("real_pm", prob=mutation_probability, eta=20)
    return NSGA3(ref_dirs=reference_directions,
                 pop_size=pop_size,
                 crossover=crossover,
                 mutation=mutation)
Пример #4
0
def unsga3(**kwargs):
    """
    This is an implementation of the Unified NSGA3 algorithm :cite:`unsga3`. The same options as for
    :class:`pymoo.algorithms.nsga3.nsga3` are available.

    Returns
    -------
    unsga3 : :class:`~pymoo.model.algorithm.Algorithm`
        Returns an UNSGA3 algorithm object.


    """

    return NSGA3(selection=TournamentSelection(func_comp=comp_by_rank_and_ref_line_dist), **kwargs)
Пример #5
0
    def test_equal_during_run(self):
        class MyCallback(Callback):

            def notify(self, algorithm):
                F = algorithm.pop.get("F")

                python_fast_nds = load_function("fast_non_dominated_sort", _type="python")(F)
                cython_fast_nds = load_function("fast_non_dominated_sort", _type="cython")(F)
                assert_fronts_equal(python_fast_nds, cython_fast_nds)

                python_efficient_fast_nds = load_function("efficient_non_dominated_sort", _type="python")(F,
                                                                                                          strategy="binary")
                assert_fronts_equal(python_fast_nds, python_efficient_fast_nds)

                cython_efficient_fast_nds = load_function("efficient_non_dominated_sort", _type="cython")(F,
                                                                                                          strategy="binary")
                assert_fronts_equal(python_efficient_fast_nds, cython_efficient_fast_nds)

                python_efficient_fast_nds_bin = load_function("efficient_non_dominated_sort", _type="python")(F)
                assert_fronts_equal(python_fast_nds, python_efficient_fast_nds_bin)

                cython_efficient_fast_nds_bin = load_function("efficient_non_dominated_sort", _type="cython")(F)
                assert_fronts_equal(python_efficient_fast_nds_bin, cython_efficient_fast_nds_bin)

                python_tree_based_nds = load_function("tree_based_non_dominated_sort", _type="python")(F)
                assert_fronts_equal(python_fast_nds, python_tree_based_nds)

        for n_obj in [3, 5, 10]:
            # create the reference directions to be used for the optimization
            ref_dirs = get_reference_directions("energy", n_obj, n_points=100)

            # create the algorithm object
            algorithm = NSGA3(pop_size=92,
                              ref_dirs=ref_dirs)

            print(f"NDS with {n_obj} objectives.")

            # execute the optimization
            minimize(DTLZ2(n_obj=n_obj),
                     algorithm,
                     callback=MyCallback(),
                     seed=1,
                     termination=('n_gen', 600),
                     verbose=True)
Пример #6
0
    def _nsga3(self) -> object:
        sampling = get_sampling("int_random")
        crossover = get_crossover("int_sbx")
        mutation = get_mutation("int_pm")
        # create the reference directions to be used for the optimization
        if self._nome_of_mono is None:
            ref_dirs = get_reference_directions("das-dennis",
                                                len(self._nomes_direcoes_of),
                                                n_partitions=len(
                                                    self._variaveis))
        else:
            ref_dirs = get_reference_directions("das-dennis",
                                                1,
                                                n_partitions=len(
                                                    self._variaveis))

        algorithm = NSGA3(pop_size=self._tamanho_populacao,
                          sampling=sampling,
                          crossover=crossover,
                          mutation=mutation,
                          ref_dirs=ref_dirs,
                          eliminate_duplicates=True)

        return algorithm
    method_name = "pynsga3-true"
    n_runs = 50
    problems = setup.keys()

    for e in problems:

        s = setup[e]
        problem = s['problem']

        s = setup[e]
        problem = s['problem']
        pf = problem.pareto_front(s['ref_dirs'])

        algorithm = NSGA3(s['ref_dirs'],
                          pop_size=s['pop_size'],
                          crossover=s['crossover'],
                          mutation=s['mutation'],
                          survival=ReferenceDirectionSurvivalTrue(
                              s['ref_dirs'], pf))

        for run in range(n_runs):
            fname = "%s_%s_%s.run" % (method_name, e, (run + 1))

            data = {
                'problem':
                problem,
                'algorithm':
                algorithm,
                'seed':
                run,
                'termination':
                MaximumGenerationTermination(s['termination'][1]),
Пример #8
0
import numpy as np

from pymoo.algorithms.nsga3 import NSGA3
from pymoo.factory import get_problem, get_reference_directions
from pymoo.optimize import minimize
from pymoo.visualization.scatter import Scatter

# create the reference directions to be used for the optimization
ref_dirs = get_reference_directions("das-dennis", 3, n_partitions=40)
print("ref_dirs.shape =", ref_dirs.shape)

# create the algorithm object
algorithm = NSGA3(pop_size=ref_dirs.shape[0], ref_dirs=ref_dirs)

# execute the optimization
res = minimize(get_problem("carside"),
               algorithm,
               seed=1,
               termination=('n_gen', 1000),
               verbose=True)

# save the results
np.savetxt("x.csv", res.X, delimiter=',', fmt='%1.4e')
np.savetxt("f.csv", res.F, delimiter=',', fmt='%1.4e')
np.savetxt("g.csv", res.G, delimiter=',', fmt='%1.4e')
np.savetxt("cv.csv", res.CV, delimiter=',', fmt='%1.4e')
Пример #9
0
    plt.scatter(res['F'][:,0], res['F'][:,1])
    plt.show()

    exit()

    # load the problem instance
    # from pymop.problems.zdt import ZDT4
    # problem = ZDT4()
    # problem = Rastrigin(n_var=30)
    problem = DTLZ2(n_var=10)

    # create the algorithm instance by specifying the intended parameters
    from pymoo.algorithms.nsga3 import NSGA3

    algorithm = NSGA3("real", pop_size=100, verbose=True)

    start_time = time.time()

    # save the history in an object to observe the convergence over generations
    history = []

    # number of generations to run it
    n_gen = 200

    # solve the problem and return the results
    X, F, G = algorithm.solve(problem,
                              evaluator=(100 * n_gen),
                              seed=2,
                              return_only_feasible=False,
                              return_only_non_dominated=False,
Пример #10
0
algorithm = UNSGA3(ref_dirs, pop_size=100)

# execute the optimization
res = minimize(problem,
               algorithm,
               termination=('n_gen', 150),
               save_history=True,
               seed=1)

print("UNSGA3: Best solution found: \nX = %s\nF = %s" % (res.X, res.F))
# END unsga3


# START no_unsga3
_res = minimize(problem,
                NSGA3(ref_dirs, pop_size=100),
                termination=('n_gen', 150),
                save_history=True,
                seed=1)
print("NSGA3: Best solution found: \nX = %s\nF = %s" % (res.X, res.F))
# END no_unsga3


# START unsga3_comp

import numpy as np
import matplotlib.pyplot as plt

ret = [np.min(e.pop.get("F")) for e in res.history]
_ret = [np.min(e.pop.get("F")) for e in _res.history]
Пример #11
0
from pymoo.factory import get_reference_directions
from pymoo.optimize import minimize
from pymoo.problems.multi.sympart import SYMPART, SYMPARTRotated
from pymoo.visualization.scatter import Scatter
import matplotlib.pyplot as plt

for problem, name in zip([SYMPART(), SYMPARTRotated()],
                         ["SYM-PART", "SYM-PART rotated"]):

    ref_dirs = get_reference_directions("das-dennis",
                                        problem.n_obj,
                                        n_partitions=20)
    PS = problem.pareto_set(500)
    PF = problem.pareto_front(500)

    algorithm = NSGA3(ref_dirs=ref_dirs)

    res = minimize(problem, algorithm, ('n_gen', 500), seed=1, verbose=False)

    fig_name = f"{algorithm.__class__.__name__} on {name}"
    # visualize decision space
    plot = Scatter(title="Decision Space")
    plot.add(PS, s=10, color='r', label="PS")
    plot.add(res.X, s=30, color='b', label="Obtained solutions")
    plot.do()
    plt.legend()

    # visualize objective space
    plot = Scatter(title="Objective Space")
    plot.add(PF, s=10, color='r', label="PF")
    plot.add(res.F, s=30, color='b', label="Obtained solutions")
Пример #12
0
    for _problem in problems:

        s = setup[_problem]
        problem = s['problem']

        if s["algorithm"] == "nsga2":
            method = NSGA2(pop_size=s['pop_size'],
                           crossover=s['crossover'],
                           mutation=s['mutation'],
                           eliminate_duplicates=True)

        elif s["algorithm"] == "nsga3":
            method = NSGA3(s['ref_dirs'],
                           pop_size=s['pop_size'],
                           crossover=s['crossover'],
                           mutation=s['mutation'],
                           eliminate_duplicates=True)

        for run in range(1, n_runs + 1):

            fname = "%s_%s.run" % (_problem, run)
            _in = os.path.join(path, fname)
            _out = "results/%s/%s/%s_%s.out" % (name, _problem.replace(
                "_", "/"), _problem, run)

            data = {
                'args': [problem, method],
                'kwargs': {
                    'seed': run,
                },
Пример #13
0
from pymoo.algorithms.nsga3 import NSGA3
from pymoo.factory import get_problem, get_reference_directions, get_termination
from pymoo.optimize import minimize
from pymoo.visualization.scatter import Scatter

problem = get_problem("dtlz3", None, 3, k=10)

# create the reference directions to be used for the optimization
ref_dirs = get_reference_directions("das-dennis", 3, n_partitions=12)

# create the algorithm object
algorithm = NSGA3(pop_size=92, ref_dirs=ref_dirs)

res = minimize(problem,
               algorithm,
               get_termination("default", n_last=25),
               pf=True,
               seed=2,
               verbose=True)

print(res.algorithm.n_gen)
plot = Scatter(title="DTLZ3")
plot.add(res.F, color="red", alpha=0.8, s=20)
plot.show()

Пример #14
0
def get_algorithms(X_current, max_changed_vars, categorical_columns, \
                   upper_bounds, lower_bounds, immutable_column_indexes, \
                   integer_columns, pop_size, prob_mating, seed):
    """Retrieve the list of algorithms to be used in the optimization process.
    Do not use this method directly. Instead, use the methods starting with
    `generate_counterfactuals_*`.

    :param X_current: the original individual
    :type X_current: numpy.array
    :param max_changed_vars: the maximum number of attributes to be
        modified. Default is None, where all variables may be modified.
    :type max_changed_vars: Integer
    :param categorical_columns: dictionary containing the categorical columns
        and their allowed values. The keys are the i-th position of the indexes
        and the values are the allowed categories. The minimum and maximum categories
        must respect the values in lower_bounds and upper_bounds since this variable
        is called after it in code.
    :type categorical_columns: dict
    :param upper_bounds: the maximum values allowed per attribute. It must
        have the same length of x_original. Its values must be different from the
        values informed in lower_bounds. For the categorical columns ordinally
        encoded it represents the category with the minimum value.
    :type upper_bounds: numpy.array
    :param lower_bounds: the minimum values allowed per attribute. It must
        have the same length of x_original. Its values must be different from the
        values informed in upper_bounds. For the categorical columns ordinally
        encoded it represents the category with the maximum value.
    :type lower_bounds: numpy.array
    :param immutable_column_indexes: lists columns that are not allowed to
        be modified.
    :type immutable_column_indexes: numpy.array
    :param integer_columns: lists the columns that allows only integer values.
        It is used by xMOAI in rounding operations.
    :type integer_columns: numpy.array
    :param pop_size: the number of counterfactuals to be generated per algorithm
        and per generation..
    :type pop_size: Integer
    :param prob_mating: the probability of mating by individuals in a given
        generation to be used by the evolutionary algorithms.
    :type prob_mating: Float
    :param seed: the seed to be used by the algorithms.
    :type seed: Integer
    
    :return: the list of algorithms to be used in the optimization as well as
        the upper and lower bounds to be used.
    :rtype: np.array, np.array, np.array
    """
    # fixing cases where the upper and lower bounds are the same value
    # in these cases, these columns are also added to the immutable
    # column list
    for index in np.where(upper_bounds == lower_bounds)[0]:
        immutable_column_indexes.append(index)

        if np.issubdtype(upper_bounds[index], np.integer):
            upper_bounds[index] += 1
        else:
            upper_bounds[index] += 1e-21

    immutable_column_indexes = list(set(immutable_column_indexes))

    repair = xMOAIRepair(X_current, max_changed_vars, \
                         categorical_columns, integer_columns, immutable_column_indexes)

    #ref_dirs = get_reference_directions("das-dennis", num_objectives, \
    #                                    n_partitions=num_objectives * 4)
    ref_dirs = get_reference_directions(
        "multi-layer",
        get_reference_directions("das-dennis", num_objectives, \
                                 n_partitions=num_objectives * 4, scaling=1.0),
        get_reference_directions("das-dennis", num_objectives, \
                                 n_partitions=num_objectives * 4, scaling=0.5)
    )

    ref_points = np.zeros((1, num_objectives))

    algorithms = {
        "NSGA-II": NSGA2(pop_size=pop_size, repair=repair),
        "NSGA-III": NSGA3(pop_size=pop_size*3, ref_dirs=ref_dirs, \
                          repair=repair),
        "UNSGA-III": UNSGA3(pop_size=pop_size*3, ref_dirs=ref_dirs, \
                            repair=repair),
        "RNSGA-II": RNSGA2(pop_size=pop_size*3, \
                           ref_points=ref_points, repair=repair)
    }

    return algorithms, upper_bounds, lower_bounds
Пример #15
0
import multiprocessing

from pymoo.algorithms.nsga3 import NSGA3
from pymoo.factory import get_reference_directions
from pymoo.optimize import minimize
from pymoo.visualization.scatter import Scatter

from modact.interfaces.pymoo import PymopProblem

if __name__ == "__main__":
    n_proccess = 8
    pool = multiprocessing.Pool(n_proccess)
    problem = PymopProblem("cts2", parallelization=('starmap', pool.starmap))

    mu = 92
    ref_dirs = get_reference_directions("das-dennis",
                                        problem.n_obj,
                                        n_partitions=12)

    algorithm = NSGA3(ref_dirs, pop_size=mu, eliminate_duplicates=True)

    res = minimize(problem, algorithm, ('n_gen', 200), seed=1, verbose=True)

    plot = Scatter()
    plot.add(problem.pareto_front(),
             plot_type="line",
             color="black",
             alpha=0.7)
    plot.add(res.F, color="red")
    plot.save("test.png")