コード例 #1
0
    def make_platypus_objective_function_counting(self,
                                                  sources,
                                                  times_more_detectors=1):
        """
        This balances the number of detectors with the quality of the outcome
        """
        total_ret_func = make_total_lookup_function(
            sources, masked=True)  # the function to be optimized
        counting_func = make_counting_objective()

        def multiobjective_func(x):  # this is the double objective function
            return [total_ret_func(x), counting_func(x)]

        # there is an x, y, and a mask for each source so there must be three
        # times more input variables
        # the upper bound on the number of detectors n times the number of
        # sources
        num_inputs = len(sources) * 3 * times_more_detectors
        NUM_OUPUTS = 2  # the default for now
        # define the demensionality of input and output spaces
        problem = Problem(num_inputs, NUM_OUPUTS)
        x, y, time = sources[0]  # expand the first source
        min_x = min(x)
        min_y = min(y)
        max_x = max(x)
        max_y = max(y)
        print("min x : {}, max x : {}, min y : {}, max y : {}".format(
            min_x, max_x, min_y, max_y))
        problem.types[0::3] = Real(min_x, max_x)  # This is the feasible region
        problem.types[1::3] = Real(min_y, max_y)
        # This appears to be inclusive, so this is really just (0, 1)
        problem.types[2::3] = Binary(1)
        problem.function = multiobjective_func
        return problem
コード例 #2
0
 def generate_problem(self):
     # 1 decision variables, 1 objectives, 2 constraints
     problem = Problem(1, 1, 2)
     problem.types[:] = Binary(len(self.requirements))
     problem.directions[:] = Problem.MAXIMIZE
     problem.constraints[0] = "!=0"
     problem.constraints[1] = "<=0"
     problem.function = self.get_problem_function
     return problem
コード例 #3
0
ファイル: core.py プロジェクト: cherusk/tw_projector
    def __init__(self, tasks, atomic_slot_size):
        super(LushHighPrio, self).__init__(1, 1, 1)

        self.tasks = tasks
        self.items_count = len(tasks)

        self.types[0] = Binary(self.items_count)
        self.directions[0] = Problem.MAXIMIZE
        self.constraints[0] = Constraint("<=", atomic_slot_size)
        self.function = self.fitness
コード例 #4
0
def so_run(population_size):
    so_problem = Problem(1, 1, 1)
    so_problem.types[:] = Binary(len(requirements))
    so_problem.directions[:] = Problem.MAXIMIZE
    so_problem.constraints[:] = "<={}".format(budget)
    so_problem.function = single_objective_nrp
    so_algorithm = GeneticAlgorithm(so_problem, population_size)
    so_algorithm.run(runs)
    x_so = [solution.objectives[0] for solution in so_algorithm.result]
    y_so = [solution.constraints[0] * (-1) for solution in so_algorithm.result]
    return x_so, y_so, so_algorithm
コード例 #5
0
 def __init__(self, nrp_instance: NRPInstance):
     # 1 decision variable, 2 objectives, 2 constraint
     super(NRP_Problem_MO, self).__init__(1, 2, 2)
     self.nrp_instance = nrp_instance
     self.types[:] = Binary(len(nrp_instance.requirements))
     # Maximize score
     self.directions[0] = Problem.MAXIMIZE
     # Minimize cost
     self.directions[1] = Problem.MINIMIZE
     self.constraints[0] = "<={}".format(nrp_instance.budget)
     self.constraints[1] = ">0"
コード例 #6
0
 def __init__(self, nrp_instance: NRPInstance):
     # 1 decision variable, 1 objective, 2 constraint
     super(NRP_Problem_SO, self).__init__(1, 1, 2)
     self.nrp_instance = nrp_instance
     # Binary solution with size of number of requirements
     self.types[:] = Binary(len(nrp_instance.requirements))
     # Maximize score
     self.directions[:] = Problem.MAXIMIZE
     #  Cost <= budget and score > 0
     self.constraints[0] = "<={}".format(nrp_instance.budget)
     self.constraints[1] = ">0"
コード例 #7
0
 def __init__(self, name):
     # Estrutura do cromossomo:
     # tamanho da imagem (2 bits),
     # filtros convolutivos na primeira camada (2 bits),
     # filtros convolutivos na segunda camada (2 bits),
     # learnin_rate(2 bits),
     # momentum (2 bits)
     # TOTAL: 10 bits
     encoding = [Binary(2), Binary(2), Binary(2), Binary(2), Binary(2)]
     variables = len(encoding)
     # dois objetivos: acuracia e tempo
     objectives = 2
     super(MProblem, self).__init__(variables, objectives)
     # indica pasta da base de dados, uma pasta com imagens para cada classe
     self.types[:] = encoding
     self.class_name = name
     self.id = 0
     self.cnfg = configuracao.config()
     self.base_x = None
     self.base_y = None
コード例 #8
0
def mo_run(population_size):
    mo_problem = Problem(2, 2, 2)
    mo_problem.types[:] = Binary(len(requirements))
    mo_problem.directions[0] = Problem.MAXIMIZE
    mo_problem.directions[1] = Problem.MINIMIZE
    mo_problem.constraints[:] = "<={}".format(budget)
    mo_problem.function = multi_objective_nrp
    mo_nsga = NSGAII(mo_problem, population_size)
    mo_nsga.run(runs)
    x_mo = [solution.objectives[0] for solution in mo_nsga.result]
    y_mo = [solution.objectives[1] * (-1) for solution in mo_nsga.result]
    return x_mo, y_mo, mo_nsga
コード例 #9
0
    def __init__(self, Amin, M, J, splits, objectives, TFmax=7):
        """
        @param Amin: minimum number of antecedents per rule
        @param M: maximum number of rules per individual
        @param J: matrix representing the initial rulebase
        @param splits: fuzzy partitions for input features
        @param objectives: array of objectives (2 or more). The first one is typically expresses the performance
                        for predictions. Indeed, the solutions will be sorted according to this objective (best-to-worst)
        @param TFmax: maximum number of fuzzy sets per feature (i.e. maximum granularity)
        """
        self.Amin = Amin
        self.M = M
        self.Mmax = J.shape[0]
        self.Mmin = len(set(J[:, -1]))
        self.M = np.clip(self.M, self.Mmin, self.Mmax)
        self.F = J.shape[1] - 1
        self.TFmax = TFmax

        self.J = J
        self.initialBfs = splits
        self.G = np.array([len(split) for split in splits])

        self.objectives = objectives
        self.crb_l = 2 * self.M
        self.gran_l = self.F
        self.cdb_l = self.gran_l * self.TFmax

        # Creation of the problem and assignment of the types
        #      CRB: rule part
        #      Granularities: number of fuzzy sets
        #      CDB: database part
        super(RCSProblem, self).__init__(self.crb_l + self.gran_l + self.cdb_l,
                                         len(objectives))
        self.types[0:self.crb_l:2] = [Real(0, self.M) for _ in range(self.M)]
        self.types[1:self.crb_l:2] = [Binary(self.F) for _ in range(self.M)]
        self.types[self.crb_l:self.crb_l +
                   self.gran_l] = [Real(2, self.TFmax) for _ in range(self.F)]
        self.types[self.crb_l +
                   self.gran_l:] = [Real(0, 1) for _ in range(self.cdb_l)]

        # Maximize objectives by minimizing opposite
        self.directions[:] = [Problem.MINIMIZE for _ in range(len(objectives))]

        self.train_x = None
        self.train_y = None
コード例 #10
0
def make_multiobjective_function_counting(sources,
                                          bounds,
                                          times_more_detectors=1,
                                          interpolation_method="nearest"):
    """
    This balances the number of detectors with the quality of the outcome
    bounds : list[(x_min, x_max), (y_min, y_max), ...]
        The bounds on the feasible region
    """
    objective_function = make_single_objective_function(
        sources, interpolation_method=interpolation_method,
        masked=True)  # the function to be optimized
    counting_function = make_counting_objective()

    def multiobjective_func(x):  # this is the double objective function
        return [objective_function(x), counting_function(x)]

    # there is an x, y, and a mask for each source so there must be three
    # times more input variables
    # the upper bound on the number of detectors n times the number of
    # sources
    parameterized_locations = sources[0].parameterized_locations
    dimensionality = parameterized_locations.shape[1]

    # We add a boolean flag to each location variable
    num_inputs = len(sources) * (dimensionality + 1) * times_more_detectors
    NUM_OUPUTS = 2  # the default for now
    # define the demensionality of input and output spaces
    problem = Problem(num_inputs, NUM_OUPUTS)

    logging.warning(
        f"Creating a multiobjective counting function with dimensionality {dimensionality}"
    )
    logging.warning(f"bounds are {bounds}")

    for i in range(dimensionality):
        # splat "*" notation is expanding the pair which is low, high
        problem.types[i::(dimensionality + 1)] = Real(
            *bounds[i])  # This is the feasible region

    # indicator on whether the source is on
    problem.types[dimensionality::(dimensionality + 1)] = Binary(1)
    problem.function = multiobjective_func
    return problem
コード例 #11
0
def moea(name, solsize, popsize, wscalar_, moea_type, max_gen=float('inf'), timeLimit=float('inf')):
    from platypus import HUX, BitFlip, TournamentSelector
    from platypus import Problem, Binary
    from platypus import NSGAII, NSGAIII, SPEA2
    
    from platyplus.operators import varOr
    from platyplus.algorithms import SMSEMOA
    
    time_start = time.perf_counter()
    logger.info('Running '+moea_type+' in '+name)
    
    prMutation = 0.1
    prVariation = 1-prMutation
    
    vartor = varOr(HUX(), BitFlip(1), prVariation, prMutation)
    
    def evalKnapsack(x):
        return wscalar_.fobj([xi[0] for xi in x])
    
    problem = Problem(wscalar_.N, wscalar_.M)
    problem.types[:] = [Binary(1) for i in range(wscalar_.N)]
    problem.function = evalKnapsack
    
    
    if moea_type in ['NSGAII', 'NSGAII-2', 'NSGAII-4']:
        alg = NSGAII(problem, population_size=popsize,
                     selector=TournamentSelector(1),
                     variator=vartor)
    elif moea_type in ['NSGAIII', 'NSGAIII-2', 'NSGAIII-4']:
        alg = NSGAIII(problem, divisions_outer=3,
                      population_size=popsize,
                      selector=TournamentSelector(1),
                      variator=vartor)
    elif moea_type in ['SPEA2', 'SPEA2-2', 'SPEA2-4']:
        alg = SPEA2(problem, population_size=popsize,
                     selector=TournamentSelector(1),
                     variator=vartor)
    elif moea_type in ['SMSdom']:
        alg = SMSEMOA(problem, population_size=popsize,
                     selector=TournamentSelector(1),
                     variator=vartor,
                     selection_method = 'nbr_dom')
    elif moea_type in ['SMShv']:
        alg = SMSEMOA(problem, population_size=popsize,
                     selector=TournamentSelector(1),
                     variator=vartor,
                     selection_method = 'hv_contr')
        
    gen = 1
    while gen<max_gen and time.perf_counter()-time_start<timeLimit:
        alg.step()
        gen+=1
    
    alg.population_size = solsize
    alg.step()

    moeaSols = [evalKnapsack(s.variables) for s in alg.result]

    moea_time = time.perf_counter() - time_start

    logger.info(moea_type+' in '+name+' finnished.')
    
    return moeaSols, moea_time
コード例 #12
0
 def __init__(self):
     super(SVM, self).__init__(1, 1)
     self.X, self.Y = read_data('radiomics.csv')
     self.types[:] = Binary(self.X.shape[1])
     self.model = get_model()
     self.directions[:] = Problem.MAXIMIZE
コード例 #13
0
 def __init__(self):
     super(Schaffer, self).__init__(1, 2)
     global col
     self.types[:] = Binary(col)
コード例 #14
0
ファイル: knapsack.py プロジェクト: comsip/RL-NSGAII
from platypus import GeneticAlgorithm, Problem, Constraint, Binary, nondominated, unique

# This simple example has an optimal value of 15 when picking items 1 and 4.
items = 7
capacity = 9
weights = [2, 3, 6, 7, 5, 9, 4]
profits = [6, 5, 8, 9, 6, 7, 3]


def knapsack(x):
    selection = x[0]
    total_weight = sum(
        [weights[i] if selection[i] else 0 for i in range(items)])
    total_profit = sum(
        [profits[i] if selection[i] else 0 for i in range(items)])

    return total_profit, total_weight


problem = Problem(1, 1, 1)
problem.types[0] = Binary(items)
problem.directions[0] = Problem.MAXIMIZE
problem.constraints[0] = Constraint("<=", capacity)
problem.function = knapsack

algorithm = GeneticAlgorithm(problem)
algorithm.run(10000)

for solution in unique(nondominated(algorithm.result)):
    print(solution.variables, solution.objectives)
コード例 #15
0
def multi_obj(vars):
    # x = vars[0]
    # y = vars[1]
    w1, w2, w3, w4 = 1, 1, 1, 1
    g_int = list(map(int, vars[0]))
    set_g(g_int)
    o1 = w1 * (1 - sum(g_int) / N)
    o2 = w2 * sum(gamma_lam(g_int)) / K
    o3 = w3 * np.sum(np.dot(g_int, eta_s(g_int))) / N
    o4 = w4 * emin(g_int) / max(er)
    # draw_active(g_int)
    return [o1 + o2 + o3 + o4]  #, [-x + y - 1, x + y - 7]


problem = Problem(1, 1)  #  decision variables,  objectives, and  constraints,
problem.types[:] = Binary(N)
problem.directions[:] = Problem.MAXIMIZE
# problem.constraints[:] = "<=0"
problem.function = multi_obj

algorithm = NSGAII(problem)
algorithm.run(100)

print(algorithm.result)

# for solution in algorithm.result:
#     # print(solution)
#     print(solution.objectives)

from circle_plot import Plotter
print(g)