コード例 #1
0
def calibrate_variables(args, pool) -> HyperParameters:
  sampling = MixedVariableSampling(mask, {
    # Real numbers are sampled via Latin Hypercube Sampling
    'real': get_sampling('real_lhs'),

    # Integer numbers are sampled via Uniform Random Sampling
    'int': get_sampling('int_random')
  })

  crossover = MixedVariableCrossover(mask, {
    'real': get_crossover('real_sbx', prob=0.9, eta=3.0),
    'int': get_crossover('real_sbx', prob=0.9, eta=3.0)
  })

  mutation = MixedVariableMutation(mask, {
    # Real numbers are mutated via polynomial mutation
    'real': get_mutation('real_pm', eta=3.0),

    # Integer numbers are mutated via polynomial mutation
    'int': get_mutation('int_pm', eta=3.0)
  })

  problem = MetaProblem(args, parallelization=('starmap', pool.starmap))
  algorithm = NSGA2(
    pop_size=EXECUTIONS_FOR_ITERATION,
    sampling=sampling,
    crossover=crossover,
    mutation=mutation,
    eliminate_duplicates=True,
  )
  termination = utils.get_termination_for_variables(max_iterations=MAX_ITERATIONS)

  res, \
    best_solution, \
    min_average, \
    min_stddev = utils.get_minimizer(problem, algorithm, termination)

  best_solution = res.X[0]
  min_average = res.F[0][0]
  min_stddev = res.F[0][1]

  mutation_probability = get_var(best_solution, 'mutation_probability')
  crossover_rate = get_var(best_solution, 'crossover_rate')
  mu = get_var(best_solution, 'mu')
  lambda_ = get_var(best_solution, 'lambda')
  k = get_var(best_solution, 'k')

  hyperparameters = HyperParameters(
    mutation_probability=mutation_probability,
    crossover_rate=crossover_rate,
    mu=mu,
    lambda_=lambda_,
    k=k
  )
  
  save_csv(args, best_solution, min_average, min_stddev)

  return hyperparameters
コード例 #2
0
    def test_pymoo_nsgaii(self):
        moo_algorithm = NSGA2(pop_size=40,
                              n_offsprings=10,
                              sampling=get_sampling("real_random"),
                              crossover=get_crossover("real_sbx",
                                                      prob=0.9,
                                                      eta=15),
                              mutation=get_mutation("real_pm", eta=20),
                              eliminate_duplicates=True)

        problem = ProblemConstraint()

        algorithm = Pymoo(problem)
        algorithm.options['verbose_level'] = 0
        algorithm.options['n_iterations'] = 40
        algorithm.options['algorithm'] = moo_algorithm
        algorithm.run()

        f_1 = []
        f_2 = []
        for individual in problem.last_population():
            f_1.append(individual.costs[0])
            f_2.append(individual.costs[1])

        # print(len(problem.individuals))
        # for individual in problem.individuals:
        #    print(individual)

        self.assertLess(min(f_1), 1.5)
        self.assertGreater(max(f_1), 74)
        self.assertLess(max(f_2), 1.5)
        self.assertGreater(max(f_2), 0.75)
コード例 #3
0
ファイル: rand_keydata.py プロジェクト: rtosholdings/riptable
def gen_index_MOO(lo,
                  hi,
                  size,
                  s_metric,
                  c_metric,
                  d_metric,
                  dist=None,
                  sort=0.0,
                  clustered=0.0,
                  dispersed=0.0):
    max_error = 0.25
    prob = SCDArrayGen(lo, hi, size, s_metric, c_metric, d_metric, sort,
                       clustered, dispersed)
    alg = NSGA2(
        pop_size=100,
        sampling=get_sampling("int_random"),
        crossover=get_crossover("int_two_point"),
        mutation=get_mutation("int_pm"),
    )
    res = minimize(prob, alg, seed=3)

    #optionally screen out solutions that still deviated from the desired values by too much
    # mask = res.F < max_error
    # masksum = np.sum(mask, axis=1) == 3
    return res.X
コード例 #4
0
def solve(seed):
    print(f"Starting seed {seed}")

    folder = os.path.join(
        os.path.dirname(
            os.path.dirname(os.path.dirname(os.path.realpath(__file__)))),
        "results")

    start = time.time()
    method = get_algorithm("ga",
                           pop_size=20,
                           sampling=get_sampling("int_random"),
                           crossover=get_crossover("int_sbx",
                                                   prob=1.0,
                                                   eta=3.0),
                           mutation=get_mutation("int_pm", eta=3.0),
                           eliminate_duplicates=True,
                           callback=MyCallback(folder))

    res = minimize(ISCSO2019(),
                   method,
                   termination=('n_eval', 10000),
                   seed=seed,
                   verbose=True)
    end = time.time()
    elapsed = end - start

    np.savetxt(os.path.join(folder, f"ga_{seed}.x"),
               res.pop.get("X").astype(np.int))
    np.savetxt(os.path.join(folder, f"ga_{seed}.f"), res.pop.get("F"))
    np.savetxt(os.path.join(folder, f"ga_{seed}.g"), res.pop.get("G"))

    print(f"Finished seed {seed} - runtime: {elapsed}")
コード例 #5
0
def optimizer():
    return NSGA2(pop_size=5,
                 n_offsprings=7,
                 sampling=get_sampling("real_random"),
                 crossover=get_crossover("real_sbx", prob=0.9, eta=15),
                 mutation=get_mutation("real_pm", eta=20),
                 eliminate_duplicates=True)
コード例 #6
0
async def optimize(evaluate, configs):
    # config
    # D = 8  decision space dimension
    # N0 = 100  initial population
    # Ng = 100  total generation
    # seed = None  random seed
    D, Ng, N0, seed = itemgetter('D', 'Ng', 'N0', 'seed')(configs)

    problem = Evaluator(evaluate, D)
    algorithm = NSGA2(pop_size=N0,
                      n_offsprings=N0,
                      sampling=get_sampling('real_random'),
                      crossover=get_crossover('real_sbx', prob=0.9, eta=15),
                      mutation=get_mutation('real_pm', eta=20),
                      eliminate_duplicates=True)
    termination = get_termination('n_gen', Ng)
    await asyncio.sleep(0)
    res = minimize(problem,
                   algorithm,
                   termination,
                   seed=seed,
                   save_history=True,
                   verbose=False)
    gbest = (res.X, res.F)

    return gbest
コード例 #7
0
def calibrate_final_tuning(args, pool, hyperparameters: HyperParameters):
  sampling = MixedVariableSampling(mask, {
    # Integer numbers are sampled via Uniform Random Sampling
    'int': get_sampling('int_random')
  })

  crossover = MixedVariableCrossover(mask, {
    'int': get_crossover('real_sbx', prob=0.9, eta=3.0)
  })

  mutation = MixedVariableMutation(mask, {
    # Integer numbers are mutated via polynomial mutation
    'int': get_mutation('int_pm', eta=3.0)
  })
  
  problem = MetaProblem(args, hyperparameters=hyperparameters, parallelization=None)
  algorithm = NSGA2(
    pop_size=EXECUTIONS_FOR_ITERATION,
    sampling=sampling,
    crossover=crossover,
    mutation=mutation,
    eliminate_duplicates=True,
  )
  termination = utils.get_termination_for_final_tuning(time=ITERATIONS_TIME)

  res, \
    best_solution, \
    min_average, \
    min_stddev = utils.get_minimizer(problem, algorithm, termination)
  
  save_csv(args, best_solution, min_average, min_stddev)
コード例 #8
0
    def test_multiObjOptimization(self):
        algorithm = NSGA2(pop_size=10,
                          n_offsprings=10,
                          sampling=get_sampling("real_random"),
                          crossover=get_crossover("real_sbx", prob=0.9,
                                                  eta=15),
                          mutation=get_mutation("real_pm", eta=20),
                          eliminate_duplicates=True)
        termination = get_termination("n_gen", 5)
        bayer = self.datasetUtils.readCFAImages()
        twoComplement = self.datasetUtils.twoComplementMatrix(bayer)
        twoComplement = twoComplement.astype("float32")
        problem = MyProblem(twoComplement)
        res = minimize(problem,
                       algorithm,
                       termination,
                       save_history=True,
                       verbose=True)

        # Objective Space
        res.F = 1 / res.F
        plot = Scatter(title="Objective Space")
        plot.add(res.F)
        plot.show()
        print("Best filter{}".format(np.reshape(res.opt[-1].X, [2, 2])))
コード例 #9
0
ファイル: ga_experiment.py プロジェクト: yamizi/Covid19
def run(countryname, capacity):
    problem = ScheduleProblem(country_name=countryname, critical_capacity=capacity, record_all=True)


    algorithm = NSGA2(
        pop_size=100,
        n_offsprings=100,
        sampling=get_sampling("int_random"),
        crossover=get_crossover("int_sbx", prob=0.9, eta=15),
        mutation=get_mutation("int_pm", eta=20),
        eliminate_duplicates=True
    )

    termination = get_termination("n_gen", 100)
    res = minimize(problem,
                algorithm,
                termination,
                seed=1,
                pf=problem.pareto_front(use_cache=False),
                save_history=True,
                verbose=True)

    # create the performance indicator object with reference point (4,4)
    metric = Hypervolume(ref_point=np.array([1.0, 1.0]))

    # collect the population in each generation
    pop_each_gen = [a.pop for a in res.history]

    with open("./experiments/ga_{}_lastpop.json".format(countryname), 'w') as f:
        json.dump( {"df":[e.to_dict() for e in problem.last[0]],"x":problem.last[1].tolist()}, f)

    with open("./experiments/ga_{}_lastobj.json".format(countryname), 'w') as f:
        json.dump( {"deaths": problem.last_objectives[0].tolist(), "activity":problem.last_objectives[1].tolist()} , f)

    # Objective Space
    fig = plt.figure()
    plot = Scatter(title = "Objective Space")
    plot.add(res.F)
    plt.savefig("./experiments/ga_{}_objective.png".format(countryname))

    # receive the population in each generation
    obj_and_feasible_each_gen = [pop[pop.get("feasible")[:,0]].get("F") for pop in pop_each_gen]

    # calculate for each generation the HV metric
    hv = [metric.calc(f) for f in obj_and_feasible_each_gen]

    # function evaluations at each snapshot
    n_evals = np.array([a.evaluator.n_eval for a in res.history])

    # visualize the convergence curve
    fig = plt.figure()
    plt.plot(n_evals, hv, '-o')
    plt.title("Convergence")
    plt.xlabel("Function Evaluations")
    plt.ylabel("Hypervolume")
    plt.savefig("./experiments/ga_{}_hypervolume.png".format(countryname))
    plt.show()
コード例 #10
0
 def test_nsga2(self):
     moo_algorithm = NSGA2(pop_size=10,
                           n_offsprings=10,
                           sampling=get_sampling("real_random"),
                           crossover=get_crossover("real_sbx",
                                                   prob=0.9,
                                                   eta=15),
                           mutation=get_mutation("real_pm", eta=20),
                           eliminate_duplicates=True)
     self.moo(moo_algorithm)
コード例 #11
0
 def set_algorithm(self):
     self.algorithm = NSGA2(pop_size=self.pop_size,
                            n_offsprings=self.n_offsprings,
                            sampling=get_sampling("real_lhs"),
                            crossover=get_crossover("real_sbx",
                                                    prob=0.9,
                                                    eta=15),
                            mutation=get_mutation("real_pm", eta=20),
                            eliminate_duplicates=True)
     self.termination = get_termination("n_gen", self.n_gen)
コード例 #12
0
 def do(self, problem, n_samples, **kwargs):
     cpy = copy.deepcopy(problem)
     _range = (problem.xu - problem.xl)
     cpy.xl = np.maximum(
         np.ceil(self.X - _range * self.perc / 2).astype(np.int),
         problem.xl)
     cpy.xu = np.minimum(
         np.ceil(self.X + _range * self.perc / 2).astype(np.int),
         problem.xu)
     return get_sampling("int_random").do(cpy, n_samples - 1).merge(
         Population().new("X", np.atleast_2d(self.X)))
コード例 #13
0
ファイル: Pymoo.py プロジェクト: randersonLemos/SIDRAT
    def _de(self) -> object:
        sampling = get_sampling("int_random")

        algorithm = DE(pop_size=self._tamanho_populacao,
                       sampling=sampling,
                       variant="DE/rand/1/bin",
                       CR=0.5,
                       F=0.3,
                       dither="vector",
                       jitter=False)
        return algorithm
コード例 #14
0
    def test_single_crossover(self):
        problem = get_problem('zdt1')
        sampling = get_sampling('real_random')
        pop = sampling.do(problem, n_samples=3)

        crossover = get_crossover('real_sbx', eta=20)
        crossover.do(problem, pop[0], pop[1])
        crossover.do(problem, pop, np.array([[0, 1]]))

        crossover = get_crossover('real_de')
        crossover.do(problem, pop[0], pop[1], pop[2])
        crossover.do(problem, pop, np.array([[0, 1, 2]]))
コード例 #15
0
def test_surrogate_optimize_with_all_selection_and_infill_methods(
        infill, surrogate_select_method):
    # Define original problem
    try:
        problem = benchmarks.zdt3()

        # Sample
        randomSample = sampling.rand(problem, 15)

        # Define surrogate ensemble

        # Define Optimizer
        optimizer = NSGA2(pop_size=20,
                          n_offsprings=10,
                          sampling=get_sampling("real_random"),
                          crossover=get_crossover("real_sbx", prob=0.9,
                                                  eta=15),
                          mutation=get_mutation("real_pm", eta=20),
                          eliminate_duplicates=True)

        # Define termination criteria

        termination = get_termination("n_gen", 10)

        # Define infill criteria

        infill_method = infill

        # Define surrogate selection

        surrogate_selection_function = surrogate_select_method
        # Optimize

        samples = copy.deepcopy(randomSample)
        surrogate_ensemble = [
            LinearRegression(),
            KNeighborsRegressor(),
            DecisionTreeRegressor(),
        ]
        res = surrogate_optimization.optimize(problem,
                                              optimizer,
                                              termination,
                                              surrogate_ensemble,
                                              samples,
                                              infill_method,
                                              surrogate_selection_function,
                                              n_infill=2,
                                              max_samples=20)
    except Exception as e:
        raise pytest.fail(
            "infill: {0} /n and surrogate_selection: {1}/n raise a error: {2}".
            format(infill, surrogate_select_method, e))
コード例 #16
0
ファイル: Pymoo.py プロジェクト: randersonLemos/SIDRAT
    def _ga(self) -> object:
        sampling = get_sampling("int_random")
        crossover = get_crossover("int_sbx")
        mutation = get_mutation("int_pm")

        algorithm = get_algorithm("ga",
                                  pop_size=self._tamanho_populacao,
                                  sampling=sampling,
                                  crossover=crossover,
                                  mutation=mutation,
                                  eliminate_duplicates=True)

        return algorithm
コード例 #17
0
def run_multiJ(dict_t):
    # def run_multiJ():
    mask = [
        "real", "int", "real", "real", "int", "int", "int", "int", "int",
        "int", "int"
    ]
    sampling = MixedVariableSampling(mask, {
        "real": get_sampling("real_random"),
        "int": get_sampling("int_random")
    })
    crossover = MixedVariableCrossover(
        mask, {
            "real": get_crossover("real_sbx", prob=1.0, eta=3.0),
            "int": get_crossover("int_sbx", prob=1.0, eta=3.0)
        })
    mutation = MixedVariableMutation(
        mask, {
            "real": get_mutation("real_pm", eta=3.0),
            "int": get_mutation("int_pm", eta=3.0)
        })
    #[V_gBurn,ng,Tdig,debt_level,V_cng_p,e_priceS,farm1,farm2,farm3,farm4,farm5,farm6,farm7]
    problem = BiogasMultiJ(dict_t)
    # problem = BiogasMultiJ()
    algorithm = NSGA2(
        pop_size=dict_t['NSGA_pop'],
        sampling=sampling,
        crossover=crossover,
        n_offsprings=dict_t['NSGA_off'],
        mutation=mutation,
        eliminate_duplicates=True,
    )
    res = minimize(problem,
                   algorithm, ("n_gen", dict_t['NSGA_gen']),
                   verbose=True,
                   seed=1,
                   save_history=True)
    return res
コード例 #18
0
def set_algorithm(name, no_obj, setup):
    """
    Text.

    Args:
        name (str): Name of the optimization algorithm.
        n_obj (int): Number of objectives.
        setup (dict): Optimization setup parameters.

    Returns:
        algorithm (): Optization algorithm object.
    """
    if name == "default":
        if no_obj == 1:
            name = "ga"
        elif no_obj > 1:
            name = "nsga3"

    # Get settings
    setup_gen = load_json(
        os.path.join(settings["root"], "app", "config", "opticonf", "general"))
    setup_alg = load_json(
        os.path.join(settings["root"], "app", "config", "opticonf", name))
    algorithm_args = {}

    # Get optimization settings objects
    algorithm_args["sampling"] = get_sampling(setup_gen["sampling"])

    if "operators" in setup:
        for operator in setup["operators"]:
            algorithm_args[operator] = get_operator(operator, setup)

    # Get reference directions
    if name == "nsga3":
        algorithm_args["ref_dirs"] = get_reference_directions(
            "energy", no_obj, setup_alg["ref_dirs_coef"] * no_obj)

    # Modify population
    if "n_offsprings" in setup:
        algorithm_args["n_offsprings"] = setup["n_offsprings"]
    if "pop_size" in setup:
        algorithm_args["pop_size"] = setup["pop_size"]

    algorithm = get_algorithm(name,
                              eliminate_duplicates=True,
                              **algorithm_args)

    return algorithm
コード例 #19
0
def runGA():

    start = time.time()

    pop_size = 10
    n_mascons = 1

    algorithm = get_algorithm("ga",
                              pop_size=pop_size,
                              sampling=get_sampling("int_random"),
                              crossover=get_crossover("int_sbx",
                                                      prob=0.9,
                                                      eta=3.0),
                              mutation=get_mutation("int_pm", eta=3.0),
                              eliminate_duplicates=True)

    problem = MasconModel(n_mascons)  #n  #n_p

    res = minimize(problem, algorithm, seed=1, save_history=True, verbose=True)

    end = time.time()
    elapsedTime = (end - start)

    resultWithCoord = getCoordinatesByIndex(res.X)
    repeated_values = getRepeatedValues(res.X.tolist())

    print("Elapsed (after compilation) = %s" % elapsedTime)
    print("Best solution found: %s" % res.X)
    print("Function value: %s" % res.F)

    #Save GA info to database
    gaDict = {
        "properties": {
            "fopt": res.F.tolist(),
            "degree": 165,
            "order": 165,
            "gen": res.algorithm.n_gen,
            "population": pop_size,
            "time": elapsedTime,
            "n_mascons": n_mascons,
            "solution": res.X.tolist(),
            "solution_repeated_values": repeated_values,
        },
        "data": resultWithCoord
    }

    saveJson(gaDict, 'n_' + str(n_mascons))  #save information in a json file
コード例 #20
0
    def test_problems(self):

        PROBLEMS = get_problem_options()
        PROBLEMS.extend(get_global_optimization_problem_options())

        for _tuple in PROBLEMS:
            name = _tuple[0]
            print(name, "OK")

            if name in exclude:
                continue

            problem = get_problem(name)

            X = get_sampling("real_random").do(problem, Population(), 100).get("X")

            out = problem.evaluate(X)
コード例 #21
0
ファイル: operators.py プロジェクト: codeaudit/clip-glass
def get_operators(config):
    if config.config == "DeepMindBigGAN":
        mask = ["real"]*config.dim_z + ["bool"]*config.num_classes
        
        real_sampling = None
        if config.config == "DeepMindBigGAN":
            real_sampling = TruncatedNormalRandomSampling()

        sampling = MixedVariableSampling(mask, {
            "real": real_sampling,
            "bool": BinaryRandomSampling(prob=5/1000)
        })

        crossover = MixedVariableCrossover(mask, {
            "real": get_crossover("real_sbx", prob=1.0, eta=3.0),
            "bool": get_crossover("bin_hux", prob=0.2)
        })

        mutation = MixedVariableMutation(mask, {
            "real": get_mutation("real_pm", prob=0.5, eta=3.0),
            "bool": get_mutation("bin_bitflip", prob=10/1000)
        })

        return dict(
            sampling=sampling,
            crossover=crossover,
            mutation=mutation
        )
    
    elif config.config.split("_")[0] == "StyleGAN2":
        return dict(
            sampling=NormalRandomSampling(),
            crossover=get_crossover("real_sbx", prob=1.0, eta=3.0),
            mutation=get_mutation("real_pm", prob=0.5, eta=3.0)
        )
    
    elif config.config == "GPT2":
        return dict(
            sampling=get_sampling("int_random"),
            crossover=get_crossover("int_sbx", prob=1.0, eta=3.0),
            mutation=get_mutation("int_pm", prob=0.5, eta=3.0)
        )

    else:
        raise Exception("Unknown config")
コード例 #22
0
def optimize(
    evaluator: FitnessEvaluator,
    free_parameters_range: "OrderedDict[str, Tuple[int, int]]",
    metrics: List[Metric],
    execution_time: Optional[str],
    power_of_2: Optional[List[str]],
) -> float:
    problem = MyProblem(evaluator, free_parameters_range, metrics)

    algorithm = NSGA2(
        repair=MyRepair(power_of_2) if power_of_2 else None,
        pop_size=10 * len(free_parameters_range.keys()),
        n_offsprings=10 * len(free_parameters_range.keys()),
        sampling=get_sampling("int_random"),
        crossover=get_crossover("int_sbx", prob=0.9, eta=15),
        mutation=get_mutation("int_pm", eta=20),
        eliminate_duplicates=True,
    )

    if execution_time:
        termination = get_termination("time", execution_time)
        res = minimize(
            problem,
            algorithm,
            termination,
            seed=1,
            save_history=True,
            verbose=True,
        )
    else:
        res = minimize(
            problem,
            algorithm,
            seed=1,
            save_history=True,
            verbose=True,
        )
    # TODO take this out and write file
    design_space_path = "dovado_work/design_space.csv"
    objective_space_path = "dovado_work/objective_space.csv"
    Path(design_space_path).open("w")
    Path(objective_space_path).open("w")
    np.savetxt(design_space_path, res.X, delimiter=",")
    np.savetxt(objective_space_path, res.F, delimiter=",")
    return res.exec_time
コード例 #23
0
def run_nsga(s):
    # Define range for decision variables
    algorithm = NSGA2(pop_size=100,
                      sampling=get_sampling("bin_random"),
                      crossover=get_crossover("real_sbx",
                                              prob=0.9,
                                              prob_per_variable=1.0),
                      mutation=get_mutation("real_pm", prob=0.8),
                      eliminate_duplicates=True)
    termination = get_termination("n_gen", 100)
    problem = FunctionalProblem(1, my_objs, xl=np.array([0]), xu=np.array([1]))
    result = minimize(problem,
                      algorithm,
                      termination,
                      seed=int(s),
                      save_history=True,
                      verbose=True)
    print("function:" + str(result.F))
    print("x:" + str(result.X))
コード例 #24
0
def run(cross=0.7, ag=None, mut=0.01):
    algorithm = GA(
        pop_size=100,
        sampling=get_sampling("real_random"),
        crossover=get_crossover("real_one_point", prob=cross),
        mutation=get_mutation("real_pm", eta=20, prob=mut),  #bin_bitflip
        n_offsprings=ag,  #ag=1 -> steady-state, ag=None -> geracional
        eliminate_duplicates=True)

    X, F = problem.evaluate(np.random.rand(100, 1),
                            return_values_of=["X", "F"])

    termination = get_termination("n_eval", 25000)

    res = minimize(
        problem,
        algorithm,
        ('n_gen', 200),
        termination,
        seed=10,  # elitismo
        verbose=False)
    return X, F, res
コード例 #25
0
    def __init__(self):
        super(SequencePrototypeExperiment, self).__init__()
        self.evaluation_period = 24
        self.pumps = 2

        self.problem = WaterDemandProblem(
            evaluation_period=self.evaluation_period,
            problem_arguments=dict(n_var=self.evaluation_period * self.pumps,
                                   n_obj=3,
                                   n_constr=1,
                                   xl=0,
                                   xu=1,
                                   type_var=np.bool),
        )

        self.algorithm_arguments = dict(nsga2=dict(
            sampling=get_sampling("bin_random"),
            crossover=get_crossover("bin_hux"),
            mutation=get_mutation("bin_bitflip"),
        ))

        self.init_runner()
        self.init_fitness()
コード例 #26
0
ファイル: Pymoo.py プロジェクト: randersonLemos/SIDRAT
    def _nsga3(self) -> object:
        sampling = get_sampling("int_random")
        crossover = get_crossover("int_sbx")
        mutation = get_mutation("int_pm")
        # create the reference directions to be used for the optimization
        if self._nome_of_mono is None:
            ref_dirs = get_reference_directions("das-dennis",
                                                len(self._nomes_direcoes_of),
                                                n_partitions=len(
                                                    self._variaveis))
        else:
            ref_dirs = get_reference_directions("das-dennis",
                                                1,
                                                n_partitions=len(
                                                    self._variaveis))

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

        return algorithm
コード例 #27
0
        # DO NOT raise any Exception if the alg_name does not require
        # any input reference direction function
        pass
    except Exception as e:
        print(e)
        sys.exit()

    if alg_name == "NSGA2":
        sampling_func = MOO_CONFIG["sampling_func"]
        pop_size = alg_specific_args["pop_size"]
        #################
        # set algorithm #
        #################
        algorithm = NSGA2(
            pop_size=pop_size,
            sampling=get_sampling(sampling_func),
            crossover=get_crossover(crossover_func, **crossover_func_args),
            mutation=get_mutation(mutation_func, **mutation_func_args),
            eliminate_duplicates=True
        )
        #####################
        # algorithm logging #
        #####################
        MOO_log(
            msg="algorithm = {}(\n"
            "pop_size={},\n"
            "sampling=get_sampling({}),\n"
            "crossover=get_crossover({},{}),\n"
            "mutation=get_mutation({},{}),\n"
            "eliminate_duplicates=True\n"
            ")".format(
コード例 #28
0
        #f2 = 0.1341 * pow(x[:0], -0.000011) * pow(x[:,2], -0.5745) * pow(x[:,1], 3.4097)*-1
        #f1 = 0.047 * pow( x[:,0], 0.8121) * pow(x[:,1],0.1233) * pow(x[:,2], -0.1585)
        #f2 = 9.795 * pow( x[:,0], 0.8014) * pow(x[:,1],0.8437) * pow(x[:,2], -0.6462) * -1
        Nu1= m.exp(6.1949) * pow(x[:,0], -0.2858) * pow(x[:,2], -0.0356) * pow(x[:,1], -0.0819)
        ff = m.exp(2.3258) * pow(x[:,0], -0.3119) * pow(x[:,2], -1.0354) * pow(x[:,1], 0.7006)
        Nu = [-1*x for x in Nu1]
        out["F"] = anp.column_stack([Nu,ff])
        #out["G"] = anp.column_stack([0,0])    


problem=MyProb()

algorithm = NSGA2(
        pop_size = 100,
        n_offsprings = 10,
        sampling = get_sampling("real_random"),
        crossover = get_crossover("real_sbx", prob = 0.9, eta = 15),
        mutation = get_mutation("real_pm", eta=20),
        eliminate_duplicates = True
        )


res = minimize(MyProb(), 
               algorithm, 
               ("n_gen", 500), 
               seed =1, 
               pf = problem.pareto_front(use_cache=False),
               save_history=True,
               verbose= True)

コード例 #29
0
ファイル: evolution_skyline.py プロジェクト: BigDaMa/DFS
            f2_all.append(results[1] * -1)  #fairness
            f3_all.append(results[2] * -1)  #robustness
            f4_all.append(results[3] * -1)  # simplicity

            #g1_all.append(c1)

        out["F"] = anp.column_stack([f1_all, f2_all])


problem = MyProblem()

population_size = 100
cross_over_rate = 0.9
algorithm = NSGA2(
    pop_size=population_size,
    sampling=get_sampling("bin_random"),
    crossover=get_crossover(
        'bin_one_point'
    ),  #get_crossover("bin_hux"),#get_crossover("bin_two_point"),
    mutation=BinaryBitflipMutation(1.0 / X_train.shape[1]),
    elimate_duplicates=True,
    #n_offsprings= cross_over_rate * population_size
)
'''
algorithm = NSGA2(pop_size=population_size,
				  sampling=get_sampling("bin_random"),
				  crossover=get_crossover("bin_hux"),#get_crossover("bin_two_point"),
				  mutation=get_mutation("bin_bitflip"),
				  elimate_duplicates=True)
'''
コード例 #30
0
ファイル: benchmark_nsga2.py プロジェクト: mbeza/pymoo-1
     'problem': get_problem("zdt3", n_var=30),
     'crossover': SimulatedBinaryCrossover(15),
     'mutation': PolynomialMutation(20)
 },
 'zdt4': {
     'pop_size': 100,
     'termination': ('n_gen', 200),
     'problem': get_problem("zdt4", n_var=10),
     'crossover': SimulatedBinaryCrossover(15),
     'mutation': PolynomialMutation(20)
 },
 'zdt5': {
     'pop_size': 100,
     'termination': ('n_gen', 400),
     'problem': get_problem("zdt5", normalize=False),
     'sampling': get_sampling("bin_random"),
     'crossover': get_crossover("bin_two_point"),
     'mutation': get_mutation("bin_bitflip")
 },
 'zdt6': {
     'pop_size': 100,
     'termination': ('n_gen', 400),
     'problem': get_problem("zdt6", n_var=10),
     'crossover': SimulatedBinaryCrossover(15),
     'mutation': PolynomialMutation(20)
 },
 'kursawe': {
     'pop_size': 100,
     'termination': ('n_gen', 100),
     'problem': get_problem("kursawe"),
     'crossover': SimulatedBinaryCrossover(10),