예제 #1
0
def calibrate(run_counts):
    """调用优化计算模型进行参数优选
    Parameters
    ----------
    run_counts: int   运行次数

    Returns
    ---------
    optimal_params: list
          非劣解集
    """
    algorithm = NSGAII(XajCalibrate(), population_size=500, variator=GAOperator(SBX(0.95, 20.0), PM(2, 25.0)))
    algorithm.run(run_counts)
    # algorithm.run(run_counts)

    # We could also get only the non-dominated solutions,这里只展示非劣解集
    nondominated_solutions = nondominated(algorithm.result)

    # plot the results using matplotlib
    # 如果目标超过三个,可视化方面需要进行降维操作,这里先以两个目标为例进行分析
    plt.scatter([s.objectives[0] for s in nondominated_solutions],
                [s.objectives[1] for s in nondominated_solutions])
    plt.xlim([0, 1])
    plt.ylim([0, 1])
    plt.xlabel("$mare$")
    plt.ylabel("$nse$")
    plt.show()

    # 返回最优参数
    optimal_params = []
    for nondominated_solution in nondominated_solutions:
        optimal_params.append(nondominated_solution.variables)
    return optimal_params
예제 #2
0
    def __init__(self,
                 problem,
                 epsilons,
                 population_size=100,
                 generator=RandomGenerator(),
                 selector=TournamentSelector(2),
                 recency_list_size=50,
                 max_mutation_index=10,
                 **kwargs):
        super(BorgMOEA, self).__init__(
            EpsMOEA(problem, epsilons, population_size, generator, selector,
                    **kwargs))
        self.recency_list = deque()
        self.recency_list_size = recency_list_size
        self.restarted_last_check = False
        self.base_mutation_index = 0
        self.max_mutation_index = max_mutation_index

        # overload the variator and iterate method
        self.algorithm.variator = Multimethod(self, [
            GAOperator(SBX(), PM()),
            DifferentialEvolution(),
            UM(),
            PCX(),
            UNDX(),
            SPX()
        ])

        self.algorithm.iterate = self.iterate
예제 #3
0
    def __init__(self,
                 problem,
                 epsilons,
                 population_size=100,
                 generator=RandomGenerator(),
                 selector=TournamentSelector(2),
                 variator=None,
                 **kwargs):
        self.problem = problem

        # Parameterization taken from
        # Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed
        variators = [
            GAOperator(
                SBX(probability=self.sbx_prop,
                    distribution_index=self.sbx_dist),
                PM(probability=self.pm_p, distribution_index=self.pm_dist)),
            GAOperator(
                PCX(nparents=self.pcx_nparents,
                    noffspring=self.pcx_noffspring,
                    eta=self.pcx_eta,
                    zeta=self.pcx_zeta),
                PM(probability=self.pm_p, distribution_index=self.pm_dist)),
            GAOperator(
                DifferentialEvolution(crossover_rate=self.de_rate,
                                      step_size=self.de_stepsize),
                PM(probability=self.pm_p, distribution_index=self.pm_dist)),
            GAOperator(
                UNDX(nparents=self.undx_nparents,
                     noffspring=self.undx_noffspring,
                     zeta=self.undx_zeta,
                     eta=self.undx_eta),
                PM(probability=self.pm_p, distribution_index=self.pm_dist)),
            GAOperator(
                SPX(nparents=self.spx_nparents,
                    noffspring=self.spx_noffspring,
                    expansion=self.spx_expansion),
                PM(probability=self.pm_p, distribution_index=self.pm_dist)),
            UM(probability=self.um_p)
        ]

        variator = Multimethod(self, variators)

        super(GenerationalBorg, self).__init__(
            NSGAII(problem, population_size, generator, selector, variator,
                   EpsilonBoxArchive(epsilons), **kwargs))
예제 #4
0
    def __init__(self,
                 problem,
                 epsilons,
                 population_size=100,
                 generator=RandomGenerator(),
                 selector=TournamentSelector(2),
                 variator=None,
                 **kwargs):

        L = len(problem.parameters)

        # -------------------------------------------------------------------
        #                           DefaultValue            BorgValue
        # PM   probability          1.0                     1.0 / L
        #      distribution index   20                      < 100 (20)
        #      source     Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed
        #
        # SBX  probability          1.0                     > 0.8 (1.0)
        #      distribution index   15                      < 100 (15)
        #      source     Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed;
        #                 Simulated Binary Crossover for Continuous Search
        #                 Space - Deb, Agrawal
        #
        # PCX  nparents             10                      3 (10)
        #      noffspring           2                       2-15 (2)
        #      eta                  0.1                     (0.1)
        #      zeta                 0.1                     (0.1)
        #      source     A Computationally Efficient Evolutionary Algorithm
        #                 for Real-Parameter Optimization - Deb et al 2002
        #
        # DE   crossover rate       0.1                     0.6 (0.1)
        #      step size            0.5                     0.6 (0.5)
        #      source     Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed
        #
        # UNDX nparents             10                      3 (10)
        #      noffspring           2                       2 (2)
        #      zeta                 0.5                     0.5
        #      eta                  0.35                    0.35/sqrt(L) (0.35)
        #      source     Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed;
        #                 A Computationally Efficient Evolutionary Algorithm
        #                 for Real-Parameter Optimization - Deb et al 2002
        #
        # SPX  nparents             10                      L + 1 (10)
        #      noffspring           2                       L + 1 (2)
        #      expansion            None                    sqrt((L+1)+1) (3.0)
        #      source     Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed;
        #                 Multi-parent Recombination with Simplex Crossover
        #                 in Real Coded Genetic Algorithms - Tsutsui
        #
        # UM   probability          1                       1.0 / L
        #      source     Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed
        # -------------------------------------------------------------------

        variators = [
            GAOperator(SBX(probability=1.0, distribution_index=15.0),
                       PM(probability=1.0 / L, distribution_index=20.0)),
            GAOperator(PCX(nparents=3, noffspring=2, eta=0.1, zeta=0.1),
                       PM(probability=1.0 / L, distribution_index=20.0)),
            GAOperator(
                DifferentialEvolution(crossover_rate=0.6, step_size=0.6),
                PM(probability=1.0 / L, distribution_index=20.0)),
            GAOperator(
                UNDX(nparents=3, noffspring=2, zeta=0.5, eta=0.35 / sqrt(L)),
                PM(probability=1.0 / L, distribution_index=20.0)),
            GAOperator(
                SPX(nparents=L + 1, noffspring=L + 1, expansion=sqrt(L + 2)),
                PM(probability=1.0 / L, distribution_index=20.0)),
            UM(probability=1 / L)
        ]

        variator = Multimethod(self, variators)

        super(NSGAIIHybrid, self).__init__(
            NSGAII(problem, population_size, generator, selector, variator,
                   EpsilonBoxArchive(epsilons), **kwargs))
예제 #5
0
    def __init__(self,
                 problem,
                 epsilons,
                 population_size=100,
                 generator=RandomGenerator(),
                 selector=TournamentSelector(2),
                 variator=None,
                 **kwargs):

        L = len(problem.nvars)
        p = 1 / L

        # Parameterization taken from
        # Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed
        variators = [
            GAOperator(SBX(probability=1.0, distribution_index=15.0),
                       PM(probability=p, distribution_index=20.0)),
            GAOperator(PCX(nparents=3, noffspring=2, eta=0.1, zeta=0.1),
                       PM(probability=p, distribution_index=20.0)),
            GAOperator(
                DifferentialEvolution(crossover_rate=0.6, step_size=0.6),
                PM(probability=p, distribution_index=20.0)),
            GAOperator(
                UNDX(nparents=3,
                     noffspring=2,
                     zeta=0.5,
                     eta=0.35 / math.sqrt(L)),
                PM(probability=p, distribution_index=20.0)),
            GAOperator(
                SPX(nparents=L + 1,
                    noffspring=L + 1,
                    expansion=math.sqrt(L + 2)),
                PM(probability=p, distribution_index=20.0)),
            UM(probability=1 / L)
        ]

        variator = Multimethod(self, variators)

        super(GenerationalBorg, self).__init__(
            NSGAII(problem, population_size, generator, selector, variator,
                   EpsilonBoxArchive(epsilons), **kwargs))

        # class GeneAsGenerationalBorg(EpsilonProgressContinuation):
        #     '''A generational implementation of the BORG Framework, combined with
        #     the GeneAs appraoch for heterogenously typed decision variables
        #
        #     This algorithm adopts Epsilon Progress Continuation, and Auto Adaptive
        #     Operator Selection, but embeds them within the NSGAII generational
        #     algorithm, rather than the steady state implementation used by the BORG
        #     algorithm.
        #
        #     Note:: limited to RealParameters only.
        #
        #     '''
        #
        #     # TODO::
        #     # Addressing the limitation to RealParameters is non-trivial. The best
        #     # option seems to be to extent MultiMethod. Have a set of GAoperators
        #     # for each datatype.
        #     # next Iterate over datatypes and apply the appropriate operator.
        #     # Implementing this in platypus is non-trivial. We probably need to do some
        #     # dirty hacking to create 'views' on the relevant part of the
        #     # solution that is to be modified by the operator
        #     #
        #     # A possible solution is to create a wrapper class for the operators
        #     # This class would create the 'view' on the solution. This view should
        #     # also have a fake problem description because the number of
        #     # decision variables is sometimes used by operators. After applying the
        #     # operator to the view, we can than take the results and set these on the
        #     # actual solution
        #     #
        #     # Also: How many operators are there for Integers and Subsets?
        #
        #     def __init__(self, problem, epsilons, population_size=100,
        #                  generator=RandomGenerator(), selector=TournamentSelector(2),
        #                  variator=None, **kwargs):
        #
        #         L = len(problem.parameters)
        #         p = 1/L
        #
        #         # Parameterization taken from
        #         # Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed
        #         real_variators = [GAOperator(SBX(probability=1.0, distribution_index=15.0),
        #                                PM(probability=p, distribution_index=20.0)),
        #                     GAOperator(PCX(nparents=3, noffspring=2, eta=0.1, zeta=0.1),
        #                                PM(probability =p, distribution_index=20.0)),
        #                     GAOperator(DifferentialEvolution(crossover_rate=0.6,
        #                                                      step_size=0.6),
        #                                PM(probability=p, distribution_index=20.0)),
        #                     GAOperator(UNDX(nparents= 3, noffspring=2, zeta=0.5,
        #                                     eta=0.35/math.sqrt(L)),
        #                                PM(probability= p, distribution_index=20.0)),
        #                     GAOperator(SPX(nparents=L+1, noffspring=L+1,
        #                                    expansion=math.sqrt(L+2)),
        #                                PM(probability=p, distribution_index=20.0)),
        #                     UM(probability = 1/L)]
        #
        #         # TODO
        #         integer_variators = []
        #         subset_variators = []
        #
        #         variators = [VariatorWrapper(variator) for variator in real_variators]
        #         variator = Multimethod(self, variators)
        #
        #         super(GenerationalBorg, self).__init__(
        #                 NSGAII(problem,
        #                        population_size,
        #                        generator,
        #                        selector,
        #                        variator,
        #                        EpsilonBoxArchive(epsilons),
        #                        **kwargs))
        #
        #
        # class VariatorWrapper(object):
        #     def __init__(self, actual_variator, indices, problem):
        #         '''
        #
        #         Parameters
        #         ----------
        #         actual_variator : underlying GAOperator
        #         indices : np.array
        #                   indices to which the variator should be applied
        #         probem :  a representation of the problem considering only the
        #                   same kind of Parameters
        #
        #         '''
        #         self.variator = actual_variator
        #         self.indices = indices
        #
        #     def evolve(self, parents):

        fake_parents = [self.create_view[p] for p in parents]
        fake_children = self.variator.evolve(fake_parents)

        # tricky, no 1 to 1 mapping between parents and children
        # some methods have 3 parents, one child
        children = [map_back]

        pass
예제 #6
0
파일: ga.py 프로젝트: clbcabral/PonyGE2
    return ''.join(sb)


def evaluate(variables):
    genome = variables[0]
    phenotype = genome_to_grammar(genome)
    phenotype = phenotype.replace(' ', '')
    accuracy, f1score = 0, 0  #get_metrics(phenotype)
    # print(phenotype, accuracy, f1score)
    return accuracy, f1score


problem = Problem(1, 2)
problem.types[0] = Genome(100, 255)
problem.directions[0] = Problem.MAXIMIZE
problem.directions[1] = Problem.MAXIMIZE
problem.function = evaluate

operator = GAOperator(GenomeSinglePointCrossover(probability=0.75),
                      GenomeUniformMutation(probability=0.25))

algorithm = NSGAII(problem, population_size=50, variator=operator)
# algorithm = SPEA2(problem, population_size=50, variator=operator)

for i in range(30):
    print('Geração:', i + 1)
    algorithm.step()
    for solution in unique(nondominated(algorithm.result)):
        genome = solution.variables[0]
        phenotype = genome_to_grammar(genome)
        print(phenotype, solution.objectives)
예제 #7
0
 #using the PCA and k-medoid algorithm?
 if editable_data['Perfrom scenario reduction'] == 'yes':
     print('Perfrom scenarios reduction using k-medoid algorithm')
     clustring_kmediod_PCA.kmedoid_clusters()
 #Do we need to perfrom the two stage stochastic programming using NSGA-II?
 if editable_data['Perform two stage optimization'] == 'yes':
     print('Perfrom two-stage stochastic optimization')
     problem = NSGA2_design_parallel_discrete.TwoStageOpt()
     with ProcessPoolEvaluator(
             int(editable_data['num_processors'])
     ) as evaluator:  #max number of accepted processors is 61 by program/ I have 8 processor on my PC
         algorithm = NSGAII(problem,
                            population_size=int(
                                editable_data['population_size']),
                            evaluator=evaluator,
                            variator=GAOperator(HUX(), BitFlip()))
         algorithm.run(int(editable_data['num_iterations']))
     NSGA2_design_parallel_discrete.results_extraction(problem, algorithm)
 #Do we need to generate Pareto-front and parallel coordinates plots for the results?
 if editable_data['Visualizing the final results'] == 'yes':
     from Two_Stage_SP.plot_results_design import parallel_plots, ParetoFront_EFs
     file_name = city_DES + '_Discrete_EF_' + str(
         float(editable_data['renewable percentage'])) + '_design_' + str(
             editable_data['num_iterations']) + '_' + str(
                 editable_data['population_size']) + '_' + str(
                     editable_data['num_processors']) + '_processors'
     results_path = os.path.join(sys.path[0], file_name)
     if not os.path.exists(results_path):
         print(
             'The results folder is not available. Please, generate the results first'
         )
예제 #8
0
    def run_algorithm(self):
        file_path = self.lineFilePath.text()
        if file_path == "":
            self.show_simple_error("Please choose file!")
            return
        print(file_path)
        # Reading file to NRP instance
        reader: AbstractFileReader = None
        if self.radioClassicFormat.isChecked():
            reader = ClassicFileReader()
        else:
            reader = CommonFileReader()
        try:
            self.nrp_instance: NRPInstance = reader.read_nrp_instance(
                filename=file_path)
        except RuntimeError as ex:
            # If cycle
            self.show_file_error(ex, str(ex))
            return
        except Exception as ex:
            self.show_file_error(ex)
            return
        # Multi or Single
        nrp_problem: Problem = None
        self.is_last_single = not self.radioMulti.isChecked()
        if self.radioMulti.isChecked():
            nrp_problem = NRP_Problem_MO(self.nrp_instance)
        else:
            nrp_problem = NRP_Problem_SO(self.nrp_instance)

        algorithm: AbstractGeneticAlgorithm = None
        # TODO Move somewhere and add config
        # Crossover probability is 0.8 and mutation probability = 1 / (size of binary vector)
        variator = None
        # TODO try single-point crossover
        variator = GAOperator(HUX(probability=0.8), BitFlip(probability=1))
        selector = TournamentSelector(5)
        #  Dep or without dep
        if self.radioDependYes.isChecked():
            algorithm = NSGAII_Repair(nrp_problem,
                                      repairer=Repairer(
                                          self.nrp_instance.requirements),
                                      variator=variator,
                                      selector=selector)
        else:
            algorithm = NSGAII(nrp_problem,
                               variator=variator,
                               selector=selector)
        #  Take n runs
        try:
            nruns = int(self.lineNumOfRuns.text())
            if nruns < 1 or nruns > 10000000:
                self.show_simple_error(
                    "Number of runs must be between 1 and 10000000!")
                return
        except ValueError:
            self.show_simple_error("Number of runs must be integer!")
            return

        self.wait_start()
        worker = Worker(self.run_and_back, algorithm, nruns)
        self.threadpool.start(worker)