示例#1
0
    def __init__(self, **kwargs):
        set_if_none(kwargs, 'pop_size', 100)
        set_if_none(kwargs, 'sampling', RandomSampling())
        set_if_none(kwargs, 'selection',
                    TournamentSelection(func_comp=comp_by_cv_and_fitness))
        set_if_none(kwargs, 'crossover',
                    SimulatedBinaryCrossover(prob_cross=0.9, eta_cross=3))
        set_if_none(kwargs, 'mutation',
                    PolynomialMutation(prob_mut=None, eta_mut=5))
        set_if_none(kwargs, 'survival', FitnessSurvival())
        set_if_none(kwargs, 'eliminate_duplicates', True)

        super().__init__(**kwargs)
        self.func_display_attrs = disp_single_objective
示例#2
0
文件: nsga3.py 项目: yidan3166/pymoo
    def __init__(self, ref_dirs, **kwargs):
        self.ref_dirs = ref_dirs
        kwargs['individual'] = Individual(rank=np.inf, niche=-1, dist_to_niche=np.inf)
        set_if_none(kwargs, 'pop_size', len(ref_dirs))
        set_if_none(kwargs, 'sampling', RandomSampling())
        set_if_none(kwargs, 'crossover', SimulatedBinaryCrossover(prob=1.0, eta=30))
        set_if_none(kwargs, 'mutation', PolynomialMutation(prob=None, eta=20))
        set_if_none(kwargs, 'selection', TournamentSelection(func_comp=comp_by_cv_then_random))
        set_if_none(kwargs, 'survival', ReferenceDirectionSurvival(ref_dirs))
        set_if_none(kwargs, 'eliminate_duplicates', True)

        super().__init__(**kwargs)

        self.func_display_attrs = disp_multi_objective
示例#3
0
    def __init__(
            self,
            ref_dirs,
            sampling=FloatRandomSampling(),
            selection=RestrictedMating(func_comp=comp_by_cv_dom_then_random),
            crossover=SimulatedBinaryCrossover(n_offsprings=1,
                                               eta=30,
                                               prob=1.0),
            mutation=PolynomialMutation(eta=20, prob=None),
            eliminate_duplicates=True,
            display=MultiObjectiveDisplay(),
            **kwargs):
        """

        Parameters
        ----------

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

        """

        self.ref_dirs = ref_dirs
        pop_size = len(ref_dirs)

        kwargs['individual'] = Individual(rank=np.inf, niche=-1, FV=-1)

        if 'survival' in kwargs:
            survival = kwargs['survival']
            del kwargs['survival']
        else:
            survival = CADASurvival(ref_dirs)

        # Initialize diversity archives
        self.da = None

        super().__init__(pop_size=pop_size,
                         sampling=sampling,
                         selection=selection,
                         crossover=crossover,
                         mutation=mutation,
                         survival=survival,
                         eliminate_duplicates=eliminate_duplicates,
                         n_offsprings=pop_size,
                         display=display,
                         **kwargs)
def calculate_pareto_front(
    state_space_equation,
    tau,
    y_measured,
    x0,
    xl: Union[np.ndarray, None],
    xu: Union[np.ndarray, None],
    n_var: int,
    n_obj: int,
    normalize_quaternions: bool,
    n_constr=0,
    pop_size=100,
    n_max_gen=1000,
    verbose=True,
    display=MyDisplay(),
) -> Result:

    # calculate pareto frontier
    problem = UUVParameterProblem(
        state_space_equation,
        tau,
        y_measured,
        x0,
        n_var=n_var,
        n_obj=n_obj,
        n_constr=n_constr,
        xl=xl,
        xu=xu,
        normalize_quaternions=normalize_quaternions,
    )
    algorithm = NSGA2(
        pop_size=pop_size,
        # n_offsprings=int(pop_size / 2),
        crossover=SimulatedBinaryCrossover(eta=15, prob=0.9),
        mutation=PolynomialMutation(prob=None, eta=15),
    )
    termination_default = MultiObjectiveDefaultTermination(n_max_gen=n_max_gen)
    termination_design_space = DesignSpaceToleranceTermination(n_max_gen=n_max_gen)
    termination_generations = get_termination("n_gen", 100)

    res = minimize(
        problem,
        algorithm,
        termination_default,
        verbose=verbose,
        display=display,
    )

    return res
示例#5
0
    def test_pm(self):

        with open(os.path.join("resources", "mutation.json"), encoding='utf-8') as f:
            data = json.loads(f.read())

        for i, e in enumerate(data):

            Configuration.rand.random = MagicMock()
            Configuration.rand.random.side_effect = e['rnd']

            pm = PolynomialMutation(eta=20, prob=0.1)

            parents = np.array(e['ind'])
            children = pm.do(ZDT4(), parents)

            _children = np.array(e['off'])

            is_equal = np.all(np.abs(children - _children) < 0.1)

            if not is_equal:
                print(i)
                print(np.abs(children - _children))

            self.assertTrue(is_equal)
def get_setup(n_obj):
    if n_obj == 2:
        pop_size = 100
        ref_dirs = UniformReferenceDirectionFactory(n_obj, pop_size - 1).do()
    elif 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)
    }
示例#7
0
def set_default_if_none(var_type, kwargs):
    set_if_none(kwargs, 'pop_size', 100)
    set_if_none(kwargs, 'disp', False)
    set_if_none(kwargs, 'selection', RandomSelection())
    set_if_none(kwargs, 'survival', None)

    # values for mating
    if var_type == "real":
        set_if_none(kwargs, 'sampling', RandomSampling())
        set_if_none(kwargs, 'crossover', SimulatedBinaryCrossover(prob_cross=0.9, eta_cross=20))
        set_if_none(kwargs, 'mutation', PolynomialMutation(prob_mut=None, eta_mut=15))
    elif var_type == "binary":
        set_if_none(kwargs, 'sampling', RandomSampling())
        set_if_none(kwargs, 'crossover', BinaryUniformCrossover())
        set_if_none(kwargs, 'mutation', BinaryBitflipMutation())
        set_if_none(kwargs, 'eliminate_duplicates', True)
示例#8
0
    def __init__(self, pop_size=100, **kwargs):
        # always store the individual to store rank and crowding
        kwargs['individual'] = Individual(rank=np.inf, crowding=-1)

        # default settings for nsga2 - not overwritten if provided as kwargs
        set_if_none(kwargs, 'pop_size', pop_size)
        set_if_none(kwargs, 'sampling', RandomSampling())
        set_if_none(kwargs, 'selection', TournamentSelection(func_comp=binary_tournament))
        set_if_none(kwargs, 'crossover', SimulatedBinaryCrossover(prob_cross=0.9, eta_cross=15))
        set_if_none(kwargs, 'mutation', PolynomialMutation(prob_mut=None, eta_mut=20))
        set_if_none(kwargs, 'survival', RankAndCrowdingSurvival())
        set_if_none(kwargs, 'eliminate_duplicates', True)

        super().__init__(**kwargs)

        self.tournament_type = 'comp_by_dom_and_crowding'
        self.func_display_attrs = disp_multi_objective
示例#9
0
    def _step(self):
        pop = self.pop
        X, F, V = pop.get("X", "F", "V")

        # get the personal best of each particle
        pbest = Population.create(*pop.get("pbest"))
        P_X, P_F = pbest.get("X", "F")

        # get the best for each solution - could be global or local or something else - (here: Global)
        best = self._social_best()
        G_X = best.get("X")

        # get the inertia weight of the individual
        inerta = self.w * V

        # calculate random values for the updates
        r1 = np.random.random((len(pop), self.problem.n_var))
        r2 = np.random.random((len(pop), self.problem.n_var))

        cognitive = self.c1 * r1 * (P_X - X)
        social = self.c2 * r2 * (G_X - X)

        # calculate the velocity vector
        _V = inerta + cognitive + social
        _V = set_to_bounds_if_outside(_V, -self.V_max, self.V_max)

        # update the values of each particle
        _X = X + _V
        _X = InversePenaltyOutOfBoundsRepair().do(self.problem, _X, P=X)

        # evaluate the offspring population
        off = Population(len(pop)).set("X", _X, "V", _V, "pbest", pbest,
                                       "best", best)

        # try to improve the current best with a pertubation
        if self.pertube_best:
            pbest = Population.create(*pop.get("pbest"))
            k = FitnessSurvival().do(self.problem,
                                     pbest,
                                     1,
                                     return_indices=True)[0]
            eta = int(np.random.uniform(20, 30))
            mutant = PolynomialMutation(eta).do(self.problem, pbest[[k]])[0]
            off[k].set("X", mutant.X)

        return off
示例#10
0
文件: moead.py 项目: zyhuster1/pymoo
    def __init__(self,
                 ref_dirs,
                 n_neighbors=20,
                 decomposition='auto',
                 prob_neighbor_mating=0.9,
                 display=MultiObjectiveDisplay(),
                 **kwargs):
        """

        Parameters
        ----------
        ref_dirs
        n_neighbors
        decomposition
        prob_neighbor_mating
        display
        kwargs
        """

        self.n_neighbors = n_neighbors
        self.prob_neighbor_mating = prob_neighbor_mating
        self.decomposition = decomposition

        set_if_none(kwargs, 'pop_size', len(ref_dirs))
        set_if_none(kwargs, 'sampling', FloatRandomSampling())
        set_if_none(kwargs, 'crossover',
                    SimulatedBinaryCrossover(prob=1.0, eta=20))
        set_if_none(kwargs, 'mutation', PolynomialMutation(prob=None, eta=20))
        set_if_none(kwargs, 'survival', None)
        set_if_none(kwargs, 'selection', None)

        super().__init__(display=display, **kwargs)

        # initialized when problem is known
        self.ref_dirs = ref_dirs

        if self.ref_dirs.shape[0] < self.n_neighbors:
            print("Setting number of neighbours to population size: %s" %
                  self.ref_dirs.shape[0])
            self.n_neighbors = self.ref_dirs.shape[0]

        # neighbours includes the entry by itself intentionally for the survival method
        self.neighbors = np.argsort(cdist(self.ref_dirs, self.ref_dirs),
                                    axis=1,
                                    kind='quicksort')[:, :self.n_neighbors]
示例#11
0
def nsganet(
    pop_size=100,
    sampling=RandomSampling(var_type=np.int),
    selection=TournamentSelection(func_comp=binary_tournament),
    crossover=TracedPointCrossover(n_points=2),
    mutation=PolynomialMutation(eta=3, var_type=np.int),
    eliminate_duplicates=True,
    n_offsprings=None,
    save_to=None,
    continue_from=None,
    **kwargs,
):
    """

    Parameters
    ----------
    pop_size : {pop_size}
    sampling : {sampling}
    selection : {selection}
    crossover : {crossover}
    mutation : {mutation}
    eliminate_duplicates : {eliminate_duplicates}
    n_offsprings : {n_offsprings}

    Returns
    -------
    nsganet : :class:`~pymoo.model.algorithm.Algorithm`
        Returns an NSGANet algorithm object.


    """
    logger.info("new version")
    return NSGANet(
        pop_size=pop_size,
        sampling=sampling,
        selection=selection,
        crossover=crossover,
        mutation=mutation,
        survival=RankAndCrowdingSurvival(),
        eliminate_duplicates=eliminate_duplicates,
        n_offsprings=n_offsprings,
        save_to=save_to,
        continue_from=continue_from,
        **kwargs,
    )
示例#12
0
    def __init__(self,
                 pop_size=100,
                 sampling=FloatRandomSampling(),
                 selection=RandomSelection(),
                 crossover=SimulatedBinaryCrossover(prob=0.9, eta=3),
                 mutation=PolynomialMutation(prob=None, eta=5),
                 eliminate_duplicates=True,
                 n_offsprings=None,
                 display=SingleObjectiveDisplay(),
                 **kwargs):
        """

        Parameters
        ----------
        pop_size : {pop_size}
        sampling : {sampling}
        selection : {selection}
        crossover : {crossover}
        mutation : {mutation}
        eliminate_duplicates : {eliminate_duplicates}
        n_offsprings : {n_offsprings}

        """

        super().__init__(pop_size=pop_size,
                         sampling=sampling,
                         selection=selection,
                         crossover=crossover,
                         mutation=mutation,
                         survival=NichingSurvival(),
                         eliminate_duplicates=eliminate_duplicates,
                         n_offsprings=n_offsprings,
                         display=display,
                         **kwargs)

        # self.mating = NeighborBiasedMating(selection,
        #                                    crossover,
        #                                    mutation,
        #                                    repair=self.mating.repair,
        #                                    eliminate_duplicates=self.mating.eliminate_duplicates,
        #                                    n_max_iterations=self.mating.n_max_iterations)

        self.default_termination = SingleObjectiveDefaultTermination()
示例#13
0
文件: nsga3.py 项目: yidan3166/pymoo
def nsga3(
        ref_dirs,
        pop_size=None,
        sampling=RandomSampling(),
        selection=TournamentSelection(func_comp=comp_by_cv_then_random),
        crossover=SimulatedBinaryCrossover(prob=1.0, eta=30),
        mutation=PolynomialMutation(prob=None, eta=20),
        eliminate_duplicates=True,
        n_offsprings=None,
        **kwargs):
    """

    Parameters
    ----------
    ref_dirs : {ref_dirs}
    pop_size : int (default = None)
        By default the population size is set to None which means that it will be equal to the number of reference
        line. However, if desired this can be overwritten by providing a positve number.
    sampling : {sampling}
    selection : {selection}
    crossover : {crossover}
    mutation : {mutation}
    eliminate_duplicates : {eliminate_duplicates}
    n_offsprings : {n_offsprings}

    Returns
    -------
    nsga3 : :class:`~pymoo.model.algorithm.Algorithm`
        Returns an NSGA3 algorithm object.


    """

    return NSGA3(ref_dirs,
                 pop_size=pop_size,
                 sampling=sampling,
                 selection=selection,
                 crossover=crossover,
                 mutation=mutation,
                 survival=ReferenceDirectionSurvival(ref_dirs),
                 eliminate_duplicates=eliminate_duplicates,
                 n_offsprings=n_offsprings,
                 **kwargs)
示例#14
0
    def __init__(self, m_nEs, typeC, local_search_on_n_vars,
                 using_surrogate_model, update_model_after_n_gens, path,
                 **kwargs):

        set_if_none(kwargs, 'individual', Individual(rank=np.inf, crowding=-1))
        set_if_none(kwargs, 'sampling', RandomSampling())
        set_if_none(kwargs, 'crossover',
                    SimulatedBinaryCrossover(prob=1.0, eta=20))
        set_if_none(kwargs, 'mutation', PolynomialMutation(prob=None, eta=20))
        super().__init__(**kwargs)

        self.tournament_type = 'comp_by_dom_and_crowding'
        self.func_display_attrs = disp_multi_objective
        ''' Custom '''
        self.typeC = typeC

        self.alpha = 1

        self.DS = []
        self.A_X, self.A_hashX, self.A_F = [], [], []
        self.tmp_A_X, self.tmp_A_hashX, self.tmp_A_F = [], [], []

        self.dpfs = []
        self.no_eval = []

        self.m_nEs = m_nEs

        self.n_vars = local_search_on_n_vars
        self.using_surrogate_model = using_surrogate_model
        self.update_model_after_n_gens = update_model_after_n_gens
        self.surrogate_model = None
        self.update_model = True
        self.n_updates = 0
        self.training_data = []

        self.nEs = 0
        self.path = path

        self.F_total = []
        self.worst_f0 = -np.inf
        self.worst_f1 = -np.inf
示例#15
0
def ga(
        pop_size=100,
        sampling=RandomSampling(),
        selection=TournamentSelection(func_comp=comp_by_cv_and_fitness),
        crossover=SimulatedBinaryCrossover(prob=0.9, eta=3),
        mutation=PolynomialMutation(prob=None, eta=5),
        eliminate_duplicates=True,
        n_offsprings=None,
        **kwargs):
    """

    Parameters
    ----------
    pop_size : {pop_size}
    sampling : {sampling}
    selection : {selection}
    crossover : {crossover}
    mutation : {mutation}
    eliminate_duplicates : {eliminate_duplicates}
    n_offsprings : {n_offsprings}

    Returns
    -------
    ga : :class:`~pymoo.model.algorithm.Algorithm`
        Returns an SingleObjectiveGeneticAlgorithm algorithm object.


    """

    return SingleObjectiveGeneticAlgorithm(pop_size=pop_size,
                                           sampling=sampling,
                                           selection=selection,
                                           crossover=crossover,
                                           mutation=mutation,
                                           survival=FitnessSurvival(),
                                           eliminate_duplicates=eliminate_duplicates,
                                           n_offsprings=n_offsprings,
                                           **kwargs)
示例#16
0
def nsga2(
        pop_size=100,
        sampling=RandomSampling(),
        selection=TournamentSelection(func_comp=binary_tournament),
        crossover=SimulatedBinaryCrossover(prob=0.9, eta=15),
        mutation=PolynomialMutation(prob=None, eta=20),
        eliminate_duplicates=True,
        n_offsprings=None,
        **kwargs):
    """

    Parameters
    ----------
    pop_size : {pop_size}
    sampling : {sampling}
    selection : {selection}
    crossover : {crossover}
    mutation : {mutation}
    eliminate_duplicates : {eliminate_duplicates}
    n_offsprings : {n_offsprings}

    Returns
    -------
    nsga2 : :class:`~pymoo.model.algorithm.Algorithm`
        Returns an NSGA2 algorithm object.


    """

    return NSGA2(pop_size=pop_size,
                 sampling=sampling,
                 selection=selection,
                 crossover=crossover,
                 mutation=mutation,
                 survival=RankAndCrowdingSurvival(),
                 eliminate_duplicates=eliminate_duplicates,
                 n_offsprings=n_offsprings,
                 **kwargs)
示例#17
0
    def __init__(self,
                 pop_size=100,
                 sampling=FloatRandomSampling(),
                 selection=TournamentSelection(func_comp=comp_by_cv_and_fitness),
                 crossover=SimulatedBinaryCrossover(prob=0.9, eta=3),
                 mutation=PolynomialMutation(prob=None, eta=5),
                 survival=FitnessSurvival(),
                 eliminate_duplicates=True,
                 n_offsprings=None,
                 display=SingleObjectiveDisplay(),
                 **kwargs):
        """

        Parameters
        ----------
        pop_size : {pop_size}
        sampling : {sampling}
        selection : {selection}
        crossover : {crossover}
        mutation : {mutation}
        eliminate_duplicates : {eliminate_duplicates}
        n_offsprings : {n_offsprings}

        """

        super().__init__(pop_size=pop_size,
                         sampling=sampling,
                         selection=selection,
                         crossover=crossover,
                         mutation=mutation,
                         survival=survival,
                         eliminate_duplicates=eliminate_duplicates,
                         n_offsprings=n_offsprings,
                         display=display,
                         **kwargs)

        self.default_termination = SingleObjectiveDefaultTermination()
示例#18
0
文件: nsga2.py 项目: zyhuster1/pymoo
    def __init__(self,
                 pop_size=100,
                 sampling=FloatRandomSampling(),
                 selection=TournamentSelection(func_comp=binary_tournament),
                 crossover=SimulatedBinaryCrossover(eta=15, prob=0.9),
                 mutation=PolynomialMutation(prob=None, eta=20),
                 eliminate_duplicates=True,
                 n_offsprings=None,
                 display=MultiObjectiveDisplay(),
                 **kwargs):
        """

        Parameters
        ----------
        pop_size : {pop_size}
        sampling : {sampling}
        selection : {selection}
        crossover : {crossover}
        mutation : {mutation}
        eliminate_duplicates : {eliminate_duplicates}
        n_offsprings : {n_offsprings}

        """

        kwargs['individual'] = Individual(rank=np.inf, crowding=-1)
        super().__init__(pop_size=pop_size,
                         sampling=sampling,
                         selection=selection,
                         crossover=crossover,
                         mutation=mutation,
                         survival=RankAndCrowdingSurvival(),
                         eliminate_duplicates=eliminate_duplicates,
                         n_offsprings=n_offsprings,
                         display=display,
                         **kwargs)

        self.tournament_type = 'comp_by_dom_and_crowding'
示例#19
0
from pymoo.algorithms.nsga2 import NSGA2
from pymoo.factory import get_problem, get_termination
from pymoo.operators.crossover.simulated_binary_crossover import SimulatedBinaryCrossover
from pymoo.operators.mutation.polynomial_mutation import PolynomialMutation
from pymoo.optimize import minimize
from pymoo.visualization.scatter import Scatter

problem = get_problem("welded_beam")
algorithm = NSGA2(
    pop_size=200,
    crossover=SimulatedBinaryCrossover(eta=20, prob=0.9),
    mutation=PolynomialMutation(prob=0.25, eta=40),
)
termination = get_termination("f_tol", n_last=60)

res = minimize(
    problem,
    algorithm,
    # ("n_gen", 800),
    pf=False,
    seed=10,
    verbose=True)

print(res.algorithm.n_gen)
Scatter().add(res.F, s=20).add(problem.pareto_front(),
                               plot_type="line",
                               color="black").show()
示例#20
0
        self.crossover = random.choice(self.crossovers)
        self.mutation = random.choice(self.mutations)
        self.repair = random.choice(self.repairs)

        off = super().do(problem, pop, n_offsprings, **kwargs)
        return off


selections = [RandomSelection()]

# define all the crossovers to be tried
crossovers = [SimulatedBinaryCrossover(10.0), SimulatedBinaryCrossover(30.0), DifferentialEvolutionCrossover()]
# COMMENT out this line to only use the SBX crossover with one eta value
# crossovers = [SimulatedBinaryCrossover(30)]

mutations = [NoMutation(), PolynomialMutation(10.0), PolynomialMutation(30.0)]
repairs = []

ensemble = EnsembleMating(selections, crossovers, mutations, repairs)

problem = Rastrigin(n_var=30)

algorithm = GA(
    pop_size=100,
    mating=ensemble,
    eliminate_duplicates=True)

res = minimize(problem,
               algorithm,
               seed=1,
               verbose=True)
    def _calc_pareto_front(self):
        return -15

    def _calc_pareto_set(self):
        return anp.array([
            1,
            1,
        ])


myProblem = myProblem()

method = nsga2(pop_size=50,
               sampling=RandomSampling(var_type=np.int),
               crossover=SimulatedBinaryCrossover(prob=0.9,
                                                  eta=15,
                                                  var_type=np.int),
               mutation=PolynomialMutation(prob=None, eta=20),
               elimate_duplicates=True)

res = minimize(myProblem, method, termination=('n_gen', 50), disp=False)

# print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F))
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)
np.save('Best_sol.npy', res.X)
np.save('Func_val.npy', res.F)
示例#22
0
    def _evaluate(self, x, out, *args, **kwargs):
        out["F"] = -np.min(x * [3, 1], axis=1)
        out["G"] = x[:, 0] + x[:, 1] - 10


def repair(problem, pop, **kwargs):
    pop.set("X", np.round(pop.get("X")).astype(np.int))
    return pop


res = minimize(MyProblem(),
               method='ga',
               method_args={
                   'pop_size':
                   20,
                   'crossover':
                   SimulatedBinaryCrossover(prob_cross=0.9, eta_cross=3),
                   'mutation':
                   PolynomialMutation(eta_mut=2),
                   'eliminate_duplicates':
                   True,
                   'func_repair':
                   repair
               },
               termination=('n_gen', 30),
               disp=True)

print("Best solution found: %s" % res.X)
print("Function value: %s" % res.F)
print("Constraint violation: %s" % res.CV)
示例#23
0
文件: rnsga3.py 项目: mbeza/pymoo-1
    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)
from pymoo.operators.sampling.random_sampling import RandomSampling
from pymoo.optimize import minimize
from pymoo.util import plotting
from pymop.factory import get_problem

# create the optimization problem
problem = get_problem("zdt1")
pf = problem.pareto_front()

# --------------------------------------------------------------------------------
# Here we define our evolutionary operators to be used by the algorithm
# --------------------------------------------------------------------------------

sampling = RandomSampling()
crossover = SimulatedBinaryCrossover(prob_cross=1.0, eta_cross=5)
mutation = PolynomialMutation(prob_mut=0.1, eta_mut=10)

# then provide the operators to the minimize method
res = minimize(problem,
               method='nsga2',
               method_args={
                   'pop_size': 100,
                   'sampling': sampling,
                   'crossover': crossover,
                   'mutation': mutation
               },
               termination=('n_gen', 200),
               pf=pf,
               save_history=False,
               disp=True)
plotting.plot(pf, res.F, labels=["Pareto-front", "F"])
示例#25
0
"""
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),
        'mutation': PolynomialMutation(20)
    },
示例#26
0
    def _step(self):
        pop = self.pop
        X, F, V = pop.get("X", "F", "V")

        # get the personal best of each particle
        pbest = Population.create(*pop.get("pbest"))
        P_X, P_F = pbest.get("X", "F")

        # get the GLOBAL best solution - other variants such as local best can be implemented here too
        best = self.opt.repeat(len(pop))
        G_X = best.get("X")

        # get the inertia weight of the individual
        inerta = self.w * V

        # calculate random values for the updates
        r1 = np.random.random((len(pop), self.problem.n_var))
        r2 = np.random.random((len(pop), self.problem.n_var))

        cognitive = self.c1 * r1 * (P_X - X)
        social = self.c2 * r2 * (G_X - X)

        # calculate the velocity vector
        _V = inerta + cognitive + social
        _V = repair_out_of_bounds_manually(_V, -self.V_max, self.V_max)

        # update the values of each particle
        _X = X + _V
        _X = repair_out_of_bounds(self.problem, _X)

        # evaluate the offspring population
        off = Population(len(pop)).set("X", _X, "V", _V, "pbest", pbest)
        self.evaluator.eval(self.problem, off, algorithm=self)

        # check whether a solution has improved or not - also consider constraints here
        has_improved = ImprovementReplacement().do(self.problem,
                                                   pbest,
                                                   off,
                                                   return_indices=True)

        # replace the personal best of each particle if it has improved
        off[has_improved].set("pbest", off[has_improved])
        off.set("best", best)
        pop = off

        # try to improve the current best with a pertubation
        if self.pertube_best:
            pbest = Population.create(*pop.get("pbest"))
            k = FitnessSurvival().do(self.problem,
                                     pbest,
                                     1,
                                     return_indices=True)[0]
            eta = int(np.random.uniform(5, 30))
            mutant = PolynomialMutation(eta).do(self.problem, pbest[[k]])[0]
            self.evaluator.eval(self.problem, mutant, algorithm=self)

            # if the mutant is in fact better - replace the personal best
            if is_better(mutant, pop[k]):
                pop[k].set("pbest", mutant)

        self.pop = pop