コード例 #1
0
    def _do(self, pop, n_select, n_parents, **kwargs):
        _type = pop.get("type")
        elites = np.where(_type == "elite")[0]
        non_elites = np.where(_type == "non_elite")[0]

        # do the mating selection - always one elite and one non-elites
        s_elite = elites[RandomSelection().do(elites, n_select, 1)[:, 0]]
        s_non_elite = non_elites[RandomSelection().do(non_elites, n_select,
                                                      1)[:, 0]]

        return np.column_stack([s_elite, s_non_elite])
コード例 #2
0
    def __init__(self, variant="DE/rand/1/exp", CR=0.1, F=0.75, **kwargs):
        set_default_if_none("real", kwargs)
        super().__init__(**kwargs)
        self.selection = RandomSelection()

        self.crossover = DifferentialEvolutionCrossover(weight=F)

        _, self.var_selection, self.var_n, self.var_mutation, = variant.split(
            "/")

        self.mutation = DifferentialEvolutionMutation(self.var_mutation, CR)
        self.func_display_attrs = disp_single_objective
コード例 #3
0
    def _do(self, pop, n_select, n_parents, **kwargs):
        _type = pop.get("type")
        elites = np.where(_type == "elite")[0]
        non_elites = np.where(_type == "non_elite")[0]

        # if through duplicate elimination no non-elites exist
        if len(non_elites) == 0:
            non_elites = elites

        # do the mating selection - always one elite and one non-elites
        s_elite = elites[RandomSelection().do(elites, n_select, 1)[:, 0]]
        s_non_elite = non_elites[RandomSelection().do(non_elites, n_select, 1)[:, 0]]

        return np.column_stack([s_elite, s_non_elite])
コード例 #4
0
ファイル: rnsga2.py プロジェクト: wavesresearch/pymoo
    def __init__(self,
                 ref_points,
                 epsilon=0.001,
                 normalization="front",
                 weights=None,
                 extreme_points_as_reference_points=False,
                 **kwargs):
        """

        Parameters
        ----------

        ref_points : {ref_points}
        epsilon : float
        weights : np.array
        normalization : {{'no', 'front', 'ever'}}
        extreme_points_as_reference_points : bool

        """

        self.epsilon = epsilon
        self.weights = weights
        self.normalization = normalization
        self.selection = RandomSelection()

        super().__init__(**kwargs)

        self.survival = RankAndModifiedCrowdingSurvival(
            ref_points, epsilon, weights, normalization,
            extreme_points_as_reference_points)
コード例 #5
0
    def _do(self, pop, n_select, n_parents, **kwargs):
        variant = self.variant

        # create offsprings and add it to the data of the algorithm
        P = RandomSelection().do(pop, n_select, n_parents)

        F, CV = pop.get("F", "CV")
        fitness = parameter_less(F, CV)[:, 0]
        sorted_by_fitness = fitness.argsort()
        best = sorted_by_fitness[0]

        if variant == "best":
            P[:, 0] = best
        elif variant == "current-to-best":
            P[:, 0] = np.arange(len(pop))
            P[:, 1] = best
            P[:, 2] = np.arange(len(pop))
        elif variant == "current-to-rand":
            P[:, 0] = np.arange(len(pop))
            P[:, 2] = np.arange(len(pop))
        elif variant == "rand-to-best":
            P[:, 1] = best
            P[:, 2] = np.arange(len(pop))
        elif variant == "current-to-pbest":
            n_pbest = int(np.ceil(0.1 * len(pop)))
            pbest = sorted_by_fitness[:n_pbest]

            P[:, 0] = np.arange(len(pop))
            P[:, 1] = np.random.choice(pbest, len(pop))
            P[:, 2] = np.arange(len(pop))

        return P
コード例 #6
0
def de(
        pop_size=100,
        sampling=LatinHypercubeSampling(criterion="maxmin", iterations=100),
        variant="DE/rand+best/1/bin",
        CR=0.5,
        F=0.75,
        **kwargs):
    """

    Parameters
    ----------
    pop_size : {pop_size}
    sampling : {sampling}
    variant : str

    CR : float

    F : float

    Returns
    -------
    de : :class:`~pymoo.model.algorithm.Algorithm`
        Returns an DifferentialEvolution algorithm object.

    """

    _, _selection, _n, _mutation, = variant.split("/")

    return DifferentialEvolution(pop_size=pop_size,
                                 sampling=sampling,
                                 selection=RandomSelection(),
                                 crossover=DifferentialEvolutionCrossover(weight=F),
                                 mutation=DifferentialEvolutionMutation(_mutation, CR),
                                 **kwargs)
コード例 #7
0
    def __init__(self,
                 pop_size=100,
                 sampling=LatinHypercubeSampling(iterations=100,
                                                 criterion="maxmin"),
                 variant="DE/rand/1/bin",
                 CR=0.5,
                 F=0.3,
                 dither="vector",
                 jitter=False,
                 **kwargs):
        """

        Parameters
        ----------

        pop_size : {pop_size}

        sampling : {sampling}

        variant : {{DE/(rand|best)/1/(bin/exp)}}
         The different variants of DE to be used. DE/x/y/z where x how to select individuals to be pertubed,
         y the number of difference vector to be used and z the crossover type. One of the most common variant
         is DE/rand/1/bin.

        F : float
         The weight to be used during the crossover.

        CR : float
         The probability the individual exchanges variable values from the donor vector.

        dither : {{'no', 'scalar', 'vector'}}
         One strategy to introduce adaptive weights (F) during one run. The option allows
         the same dither to be used in one iteration ('scalar') or a different one for
         each individual ('vector).

        jitter : bool
         Another strategy for adaptive weights (F). Here, only a very small value is added or
         subtracted to the weight used for the crossover for each individual.


        """

        _, self.var_selection, self.var_n, self.var_mutation, = variant.split(
            "/")

        if self.var_mutation == "exp":
            mutation = ExponentialCrossover(CR)
        elif self.var_mutation == "bin":
            mutation = UniformCrossover(CR)

        super().__init__(pop_size=pop_size,
                         sampling=sampling,
                         selection=RandomSelection(),
                         crossover=DifferentialEvolutionCrossover(
                             weight=F, dither=dither, jitter=jitter),
                         mutation=mutation,
                         survival=None,
                         **kwargs)

        self.func_display_attrs = disp_single_objective
コード例 #8
0
ファイル: rvea.py プロジェクト: water4you4ever/pymoo
    def __init__(self,
                 ref_dirs,
                 alpha=2.0,
                 adapt_freq=0.1,
                 pop_size=None,
                 sampling=FloatRandomSampling(),
                 selection=RandomSelection(),
                 crossover=SimulatedBinaryCrossover(eta=30, prob=1.0),
                 mutation=PolynomialMutation(eta=20, prob=None),
                 eliminate_duplicates=True,
                 n_offsprings=None,
                 display=MultiObjectiveDisplay(),
                 **kwargs):
        """

        Parameters
        ----------

        ref_dirs : {ref_dirs}
        adapt_freq : float
            Defines the ratio of generation when the reference directions are updated.
        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 positive number.
        sampling : {sampling}
        selection : {selection}
        crossover : {crossover}
        mutation : {mutation}
        eliminate_duplicates : {eliminate_duplicates}
        n_offsprings : {n_offsprings}

        """

        # set reference directions and pop_size
        self.ref_dirs = ref_dirs
        if self.ref_dirs is not None:
            if pop_size is None:
                pop_size = len(self.ref_dirs)

        # the fraction of n_max_gen when the the reference directions are adapted
        self.adapt_freq = adapt_freq

        # you can override the survival if necessary
        survival = kwargs.pop("survival", None)
        if survival is None:
            survival = APDSurvival(ref_dirs, alpha=alpha)

        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)
コード例 #9
0
class DifferentialEvolution(GeneticAlgorithm):
    def __init__(self, variant="DE/rand/1/exp", CR=0.1, F=0.75, **kwargs):
        set_default_if_none("real", kwargs)
        super().__init__(**kwargs)
        self.selection = RandomSelection()

        self.crossover = DifferentialEvolutionCrossover(weight=F)

        _, self.var_selection, self.var_n, self.var_mutation, = variant.split(
            "/")

        self.mutation = DifferentialEvolutionMutation(self.var_mutation, CR)
        self.func_display_attrs = disp_single_objective

    def _next(self, pop):

        # create offsprings and add it to the data of the algorithm
        if self.var_selection == "rand":
            P = self.selection.do(pop, self.pop_size, self.crossover.n_parents)
        elif self.var_selection == "best":
            P = self.selection.do(pop, self.pop_size,
                                  self.crossover.n_parents - 1)
            best = np.argmin(pop.get("F")[:, 0])
            P = np.hstack([np.full(len(pop), best)[:, None], P])
        else:
            raise Exception("Unknown selection: %s" % self.var_selection)

        self.off = self.crossover.do(self.problem, pop, P)

        # do the mutation by using the offsprings
        self.off = self.mutation.do(self.problem, pop, algorithm=self)

        # evaluate the results
        self.evaluator.eval(self.problem, self.off, algorithm=self)

        # replace whenever offspring is better than population member
        for i in range(len(pop)):
            if self.off[i].F < pop[i].F:
                pop[i] = self.off[i]

        return pop
コード例 #10
0
ファイル: so_DE.py プロジェクト: hihiworld/pymoo
    def _next(self, pop):

        # all neighbors shuffled (excluding the individual itself)
        P = RandomSelection().do(pop, self.pop_size, self.crossover.n_parents - 1)
        P = np.concatenate([np.arange(self.pop_size)[:, None], P], axis=1)

        # do recombination and create an offspring
        X = self.crossover.do(self.problem, pop.X[P, :])
        F, _ = self.evaluator.eval(self.problem, X)

        # replace whenever offspring is better than population member
        off_is_better = np.where(F < pop.F)[0]
        pop.F[off_is_better, :] = F[off_is_better, :]
        pop.X[off_is_better, :] = X[off_is_better, :]
コード例 #11
0
def set_default_if_none(var_type, kwargs):
    set_if_none(kwargs, 'pop_size', 100)
    set_if_none(kwargs, 'verbose', False)
    set_if_none(kwargs, 'selection', RandomSelection())

    # values for mating
    if var_type == "real":
        set_if_none(kwargs, 'sampling', RealRandomSampling())
        set_if_none(kwargs, 'crossover', SimulatedBinaryCrossover())
        set_if_none(kwargs, 'mutation', PolynomialMutation())
    elif var_type == "binary":
        set_if_none(kwargs, 'sampling', BinaryRandomSampling())
        set_if_none(kwargs, 'crossover', BinaryUniformCrossover())
        set_if_none(kwargs, 'mutation', BinaryBitflipMutation())
        set_if_none(kwargs, 'eliminate_duplicates', True)
コード例 #12
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)
コード例 #13
0
    def __init__(self,
                 variant="DE/rand+best/1/bin",
                 CR=0.5,
                 F=0.75,
                 n_replace=None,
                 **kwargs):

        _, self.var_selection, self.var_n, self.var_mutation, = variant.split("/")

        set_if_none(kwargs, 'pop_size', 200)
        set_if_none(kwargs, 'sampling', LatinHypercubeSampling(criterion="maxmin", iterations=100))
        set_if_none(kwargs, 'crossover', DifferentialEvolutionCrossover(weight=F))
        set_if_none(kwargs, 'selection', RandomSelection())
        set_if_none(kwargs, 'mutation', DifferentialEvolutionMutation(self.var_mutation, CR))
        set_if_none(kwargs, 'survival', None)
        super().__init__(**kwargs)

        self.n_replace = n_replace
        self.func_display_attrs = disp_single_objective
コード例 #14
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()
コード例 #15
0
ファイル: rnsga2.py プロジェクト: yidan3166/pymoo
def rnsga2(ref_points,
           epsilon=0.001,
           normalization="front",
           weights=None,
           extreme_points_as_reference_points=False,
           **kwargs):
    """


    Parameters
    ----------

    ref_points : {ref_points}

    epsilon : float

    weights : np.array

    normalization : {{'no', 'front', 'ever'}}

    extreme_points_as_reference_points : bool



    Returns
    -------
    rnsga2 : :class:`~pymoo.model.algorithm.Algorithm`
        Returns an RNSGA2 algorithm object.


    """

    rnsga2 = nsga2(**kwargs)

    rnsga2.epsilon = epsilon
    rnsga2.weights = weights
    rnsga2.normalization = normalization
    rnsga2.selection = RandomSelection()
    rnsga2.survival = RankAndModifiedCrowdingSurvival(
        ref_points, epsilon, weights, normalization,
        extreme_points_as_reference_points)

    return rnsga2
コード例 #16
0
ファイル: so_de.py プロジェクト: yidan3166/pymoo
    def __init__(self,
                 variant,
                 CR,
                 F,
                 dither,
                 jitter,
                 **kwargs):

        _, self.var_selection, self.var_n, self.var_mutation, = variant.split("/")

        set_if_none(kwargs, 'pop_size', 200)
        set_if_none(kwargs, 'sampling', LatinHypercubeSampling(criterion="maxmin", iterations=100))
        set_if_none(kwargs, 'crossover', DifferentialEvolutionCrossover(weight=F, dither=dither, jitter=jitter))
        set_if_none(kwargs, 'selection', RandomSelection())

        if self.var_mutation == "exp":
            set_if_none(kwargs, 'mutation', ExponentialCrossover(CR))
        elif self.var_mutation == "bin":
            set_if_none(kwargs, 'mutation', UniformCrossover(CR))

        set_if_none(kwargs, 'survival', None)
        super().__init__(**kwargs)

        self.func_display_attrs = disp_single_objective
コード例 #17
0
        self.crossovers = crossovers
        self.mutations = mutations
        self.repairs = repairs if len(repairs) > 0 else [NoRepair()]

    def do(self, problem, pop, n_offsprings, **kwargs):
        # randomly choose a combination to be tried
        self.selection = random.choice(self.selections)
        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,