示例#1
0
def generate_test_data():
    for str_problem in ["osy"]:
        problem = get_problem(str_problem)

        X = []

        # define a callback function that prints the X and F value of the best individual
        def my_callback(algorithm):
            pop = algorithm.pop
            _X = pop.get("X")[np.random.permutation(len(pop))[:10]]
            X.append(_X)

        minimize(problem,
                 method='nsga2',
                 method_args={'pop_size': 100},
                 termination=('n_gen', 100),
                 callback=my_callback,
                 pf=problem.pareto_front(),
                 disp=True,
                 seed=1)

        np.savetxt("%s.x" % str_problem,
                   np.concatenate(X, axis=0),
                   delimiter=",")
示例#2
0
        asf = np.eye(F.shape[1])
        asf[asf == 0] = 1e6
        F_asf = np.max(F * asf[:, None, :], axis=2).T / 1e6
        for k in range(n_obj):
            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()
               },
from pymoo.optimize import minimize
from pymoo.algorithms.nsga2 import nsga2
from pymoo.util import plotting
import numpy as np

from pymop.factory import get_problem

# create the algorithm object
method = nsga2(pop_size=100, elimate_duplicates=True)

# execute the optimization
res = minimize(get_problem("zdt1"), method, termination=('n_gen', 200))

print("Best solution found: %s" % res.X)
print("Function value: %s" % res.F)
print("Constraint violation: %s" % res.CV)

plotting.plot(res.F, no_fill=True)
示例#4
0
from pymop.factory import get_problem, get_uniform_weights

# for some problems the pareto front does not need any parameters
pf = get_problem("tnk").pareto_front()
pf = get_problem("osy").pareto_front()

# for other problems the number of non-dominated points can be defined
pf = get_problem("zdt1").pareto_front(n_pareto_points=100)

# for DTLZ for example the reference direction should be provided, because the pareto front for the
# specific problem will depend on the factory for the reference lines
ref_dirs = get_uniform_weights(100, 3)
pf = get_problem("dtlz1", n_var=7, n_obj=3).pareto_front(ref_dirs)
示例#5
0
import numpy as np

from pymop.factory import get_problem

problem = get_problem("zdt1")

F, dF, CV = problem.evaluate(np.random.random((100, 30)),
                             return_values_of=["F", "dF", "CV"])
示例#6
0
from pymoo.optimize import minimize
from pymoo.util import plotting
from pymop.factory import get_problem, UniformReferenceDirectionFactory

# create the optimization problem
problem = get_problem("dtlz2")
ref_dirs = UniformReferenceDirectionFactory(3, n_points=100).do()
pf = problem.pareto_front(ref_dirs)

res = minimize(problem,
               method='moead',
               method_args={
                   'ref_dirs': ref_dirs,
                   'n_neighbors': 15,
                   'decomposition': 'pbi',
                   'prob_neighbor_mating': 0.7
               },
               termination=('n_gen', 200),
               pf=pf,
               save_history=False,
               disp=True)
plotting.plot(pf, res.F, labels=["Pareto-front", "F"])
示例#7
0
    return {
        'ref_dirs': ref_dirs,
        'pop_size': pop_size,
        'crossover': SimulatedBinaryCrossover(1.0, 30),
        'mutation': PolynomialMutation(20)
    }


setup = {

    # ==========================================
    # DTLZ1
    # ==========================================
    'dtlz1_3obj': {
        'termination': ('n_gen', 400),
        'problem': get_problem("dtlz1", None, 3, k=5),
        **get_setup(3)
    },
    'dtlz1_5obj': {
        'termination': ('n_gen', 600),
        'problem': get_problem("dtlz1", None, 5, k=5),
        **get_setup(5)
    },
    'dtlz1_8obj': {
        'termination': ('n_gen', 750),
        'problem': get_problem("dtlz1", None, 8, k=5),
        **get_setup(8)
    },
    'dtlz1_10obj': {
        'termination': ('n_gen', 1000),
        'problem': get_problem("dtlz1", None, 10, k=5),
# create the optimization problem
import numpy as np

from pymoo.model.population import Population
from pymoo.optimize import minimize
from pymop.factory import get_problem

problem = get_problem("rastrigin")

pop_size = 100

pop = Population(pop_size)
pop.set("X", np.random.random((pop_size, problem.n_var)))

res = minimize(problem,
               method='ga',
               method_args={
                   'pop_size': pop_size,
                   'sampling': pop
               },
               termination=('n_gen', 200),
               disp=True)
示例#9
0
from pymoo.util import plotting

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))
import numpy as np

# this will be the evaluation function that is called each time
from pymop.factory import get_problem

from pymop.problem import Problem

def my_evaluate_func(x, out, *args, **kwargs):  
 f1 = 31*x[:,0] + 38*x[:,1] + 19*x[:,2] + 37*x[:,3] + 45*x[:,4] + 23*x[:,5] + 23*x[:,6])
 f2 = 27*x[:,0] + 35*x[:,1] + 74*x[:,2] + 62*x[:,3] + 22*x[:,4] + 27*x[:,5] + 33*x[:,6])
 f3 = 61*x[:,0] + 56*x[:,1] + 55*x[:,2] + 84.6*x[:,3] + 65*x[:,4] + 73*x[:,5] + 62*x[:,6]
 g1 = x[:,0] + x[:,1] + x[:,2] + x[:,3] + x[:,4] + x[:,5] + x[:,6] - 1
 g2 = 1 - x[:,0] - x[:,1] - x[:,2] - x[:,3] - x[:,4] - x[:,5] - x[:,6]
 out["F"] = anp.column_stack([f1])
 out["G"] = anp.column_stack([g1, g2])
 mask = ["int", "int", "int", "int", "int", "int", "int"]

problem = get_problem(my_evaluate_func, np.array([0, 0 , 0, 0, 0, 0, 0, 0]), np.array([1, 1, 1, 1, 1, 1, 1]))
F, CV = problem.evaluate(np.random.rand(100, 7))



示例#11
0
from pymoo.optimize import minimize
from pymop.factory import get_problem

problem = get_problem("g01")

res = minimize(problem,
               method='ga',
               method_args={
                   'pop_size': 100,
                   'eliminate_duplicates': False,
               },
               termination=('n_gen', 50),
               disp=True)

print("Best solution found: %s" % res.X)
print("Function value: %s" % res.F)

示例#12
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("dtlz2", n_var=12, 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='unsga3',
               method_args={
                   'pop_size': 100,
                   'ref_dirs': ref_dirs
               },
               termination=('n_gen', 200),
               pf=pf,
               disp=True)
plotting.plot(res.F)
示例#13
0
    __F = _F - ideal_point
    __F[__F < 1e-3] = 0

    # update the extreme points for the normalization having the highest asf value each
    F_asf = np.max(__F * asf[:, None, :], axis=2)
    I = np.argmin(F_asf, axis=1)
    return I


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("carside")

#problem = ConvexProblem(DTLZ2(n_var=12, n_obj=3))

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(
    UniformReferenceDirectionFactory(3, n_partitions=70, scaling=1.0).do())

res = minimize(
    problem,
    method='nsga3',
示例#14
0
import numpy as np

from pymoo.optimize import minimize
from pymoo.util import plotting
from pymop.factory import get_problem, UniformReferenceDirectionFactory

problem = get_problem("zdt1")
pf = problem.pareto_front()

# create the reference directions to be used for the optimization
ref_points = np.array([[0.3, 0.4], [0.8, 0.5]])

res = minimize(problem,
               method='rnsga3',
               method_args={
                   'ref_points': ref_points,
                   'pop_per_ref_point': 50,
                   'mu': 0.1
               },
               termination=('n_gen', 400),
               pf=pf,
               disp=True)
plotting.plot(pf,
              res.F,
              ref_points,
              show=True,
              labels=['pf', 'F', 'ref_points'])

problem = get_problem("dtlz4", n_var=12, n_obj=3)
ref_dirs = UniformReferenceDirectionFactory(3, n_points=91).do()
pf = problem.pareto_front(ref_dirs)
        'mutation': PolynomialMutation(20)
    }


setup = {

    # ==========================================
    # MISC
    # ==========================================

    # ==========================================
    # C1-DTLZ1
    # ==========================================
    'c1-dtlz1-3obj': {
        'termination': ('n_gen', 500),
        'problem': get_problem("c1dtlz1", n_obj=3),
        **get_setup(3),
    },
    'c1-dtlz1-5obj': {
        'termination': ('n_gen', 600),
        'problem': get_problem("c1dtlz1", n_obj=5),
        **get_setup(5),
    },

    # ==========================================
    # C1-DTLZ3
    # ==========================================
    'c1-dtlz3-3obj': {
        'termination': ('n_gen', 1000),
        'problem': get_problem("c1dtlz3", n_obj=3),
        **get_setup(3),
示例#16
0
文件: rnsga2.py 项目: lulzzz/pymoo
# ZDT 1
#
import numpy as np

from pymoo.optimize import minimize
from pymoo.util import plotting
from pymop.factory import get_problem

problem = get_problem("zdt1", n_var=30)
pf = problem.pareto_front()

# create the reference directions to be used for the optimization
ref_points = np.array([[0.5, 0.2], [0.1, 0.6]])

res = minimize(
    problem,
    method='rnsga2',
    method_args={
        'pop_size': 40,
        'ref_points': ref_points,
        'epsilon': 0.02,
        'normalization': 'no',
        'survival_type': "closest",
        'extreme_points_as_reference_points': True
        # 'weights': np.array([0.9, 0.1])
    },
    save_history=True,
    termination=('n_gen', 500),
    seed=1,
    pf=pf,
    disp=True)
示例#17
0
from pymop.factory import get_problem

# create a simple test problem from string
p = get_problem("Ackley")

# the input name is not case sensitive
p = get_problem("ackley")

# also input parameter can be provided directly
p = get_problem("dtlz1", n_var=20, n_obj=5)
示例#18
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)
from pymoo.optimize import minimize
from pymop.factory import get_problem

problem = get_problem("rastrigin", n_var=10)

res = minimize(problem,
               method='de',
               method_args={
                   'pop_size': 200,
                   'variant': "DE/rand+best/1/exp",
                   'CR': 0.5,
                   'F': 0.75,
                   # 'selection': RandomSelection(),
                   # 'survival': ConstraintHandlingSurvival(method="parameter_less"),
                   # 'survival': ConstraintHandlingSurvival(method="epsilon_constrained")
                   # 'survival': ConstraintHandlingSurvival(method="penalty", weight=0.25)
                   # 'survival': ConstraintHandlingSurvival(method="stochastic_ranking", prob=0.45)
               },
               termination=('n_gen', 1750),
               disp=True)

print("Best solution found: %s" % res.X)
print("Function value: %s" % res.F)
示例#20
0
config = configparser.ConfigParser()
config.read("configuration.ini")
PROBLEM = str(config['Properties']['PROBLEM'])
BOUND_LOW = float(config['Properties']['BOUND_LOW'])
BOUND_UP = float(config['Properties']['BOUND_UP'])
NDIM = int(config['Properties']['DIMENSIONS'])

ALGORITHM = str(config['Properties']['ALGORITHM'])
NGEN = int(config['Properties']['NGEN'])
MU = int(config['Properties']['POPULATION'])
CXPB = float(config['Properties']['CXPB'])
CXETA = float(config['Properties']['CXETA'])
MUTETA = float(config['Properties']['MUTETA'])

problem = factory.get_problem(PROBLEM, n_var=NDIM)

creator.create("FitnessMin", base.Fitness, weights=(-1.0, -1.0))
creator.create("Individual",
               array.array,
               typecode='d',
               fitness=creator.FitnessMin)


def uniform(low, up, size=None):
    try:
        return [random.uniform(a, b) for a, b in zip(low, up)]
    except TypeError:
        return [
            random.uniform(a, b) for a, b in zip([low] * size, [up] * size)
        ]
    }
}

if __name__ == '__main__':

    run_files = []
    prefix = "runs"
    method_name = "pyde-rand+best-exp"
    n_runs = 31
    entries = setup.keys()

    for key in entries:

        s = setup[key]
        str_problem = s['problem']
        problem = get_problem(str_problem)

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

            data = {
                'args': [problem, "de"],
                'kwargs': {
                    'method_args': {
                        'pop_size': 200
                    },
                    'termination': s['termination'],
                    'seed': (run + 1)
                },
                'out':
                "%s/%s/%s_%s_%s.out" %
示例#22
0
"""
This is the experiment for nsga2.
"""
import os
import pickle

from pymoo.algorithms.nsga2 import nsga2
from pymoo.operators.crossover.simulated_binary_crossover import SimulatedBinaryCrossover
from pymoo.operators.mutation.polynomial_mutation import PolynomialMutation
from pymop.factory import get_problem

setup = {
    'zdt1': {
        'pop_size': 100,
        'termination': ('n_gen', 200),
        'problem': get_problem("zdt1", n_var=30),
        'crossover': SimulatedBinaryCrossover(0.9, 15),
        'mutation': PolynomialMutation(20),
    },
    'zdt2': {
        'pop_size': 100,
        'termination': ('n_gen', 200),
        'problem': get_problem("zdt2", n_var=30),
        'crossover': SimulatedBinaryCrossover(0.9, 15),
        'mutation': PolynomialMutation(20)
    },
    'zdt3': {
        'pop_size': 100,
        'termination': ('n_gen', 200),
        'problem': get_problem("zdt3", n_var=30),
        'crossover': SimulatedBinaryCrossover(0.9, 15),
示例#23
0
import matplotlib.pyplot as plt

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("c3dtlz4", n_var=12, n_obj=3)

# create the reference directions to be used for the optimization
ref_dirs = UniformReferenceDirectionFactory(3, n_points=91).do()
#ref_dirs = UniformReferenceDirectionFactory(2, n_points=100).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', 1000),
               pf=pf,
               seed=4,
               disp=True)

plotting.plot(res.F)
示例#24
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',
示例#25
0
    def test_correctness(self):

        np.random.seed(1)

        setup = {
            "zdt1": {
                'utopian_epsilon': 1e-3
            },
            "zdt2": {
                'utopian_epsilon': 1e-4
            },
            "zdt3": {
                'utopian_epsilon': 1e-4,
                "ideal_point": np.array([0.0, -1.0])
            },
            "osy": {
                'utopian_epsilon': 0.0,
                "ideal_point": np.array([-300, -0.05])
            }
        }

        for str_problem, parameter in setup.items():

            problem = get_problem(str_problem)

            import os
            X = np.loadtxt(os.path.join("resources", "kktpm",
                                        "%s.x" % str_problem),
                           delimiter=",")
            #F = np.loadtxt(os.path.join("resources", "kktpm", "%s.f" % str_problem))
            #G = np.loadtxt(os.path.join("resources", "kktpm", "%s.g" % str_problem))

            _F, _G, _dF, _dG = problem.evaluate(
                X, return_values_of=["F", "G", "dF", "dG"])

            #self.assertTrue(np.abs(F - _F).mean() < 1e-6)
            #self.assertTrue(np.abs(G - _G).mean() < 1e-6)

            #indices = np.random.permutation(X.shape[0])[:100]
            indices = np.arange(X.shape[0])

            # load the correct results
            correct = np.loadtxt(
                os.path.join("resources", "kktpm",
                             "%s.kktpm" % str_problem))[indices]

            # calculate the KKTPM measure
            kktpm, _ = KKTPM(var_bounds_as_constraints=True).calc(
                X[indices], problem, **parameter)
            error = np.abs(kktpm[:, 0] - correct)

            for i in range(len(error)):

                if error[i] > 0.0001:
                    print("Error for ", str_problem)
                    print("index: ", i)
                    print("Error: ", error[i])
                    print("X", ",".join(np.char.mod('%f', X[i])))
                    print("Python: ", kktpm[i])
                    print("Correct: ", correct[i])

                    import os
                    os._exit(1)

            # make sure the results are almost equal
            self.assertTrue(error.mean() < 1e-6)

            print(str_problem, error.mean())
from pymoo.algorithms.nsga3 import NSGA3
from pymoo.experimental.emo.max_non_dominated import ReferenceDirectionSurvivalNonDominated
from pymoo.experimental.emo.max_of_extremes import ReferenceDirectionSurvivalMaxExtremes
from pymoo.experimental.emo.true import ReferenceDirectionSurvivalTrue
from pymoo.model.termination import MaximumGenerationTermination
from pymop import ScaledProblem
from pymop.factory import get_problem

setup = {

    # ==========================================
    # DTLZ1
    # ==========================================
    'dtlz1_3obj': {
        'termination': ('n_gen', 400),
        'problem': get_problem("dtlz1", None, 3, k=5),
        **get_setup(3)
    },
    'dtlz1_5obj': {
        'termination': ('n_gen', 600),
        'problem': get_problem("dtlz1", None, 5, k=5),
        **get_setup(5)
    },
    'dtlz1_10obj': {
        'termination': ('n_gen', 1000),
        'problem': get_problem("dtlz1", None, 10, k=5),
        **get_setup(10)
    },

    # ==========================================
    # DTLZ2
示例#27
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")

# 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', 600),
               pf=pf,
               seed=4,
               disp=True)

# if desired we can filter out the solutions that are not close to ref_dirs
closest_to_ref_dir = res.opt.get("closest")
plotting.plot(res.F[closest_to_ref_dir, :], show=True)