Пример #1
0
 def create_view(self, parent):
     view = Solution(self.problem)
     self.variables = parent.variables[self.indices][:]
     self.objectives = parent.objectives[:]
     self.constraints = parent.constraints[:]
     self.evaluated = parent.evaluated
     return view
Пример #2
0
def buildHypervolumeFrame(model, convergence, archive, nondominated, run,
                          method, outcomes):
    dfs = []

    solutions = []
    problem = to_problem(model, 'levers')
    if outcomes == None:
        outcomes = getOutcomeNames(model)
    hyplist = []
    for index, row in nondominated[outcomes].iterrows():
        solution = Solution(problem)
        solution.objectives[:] = list(row)
        solutions.append(solution)

    hyp = getHypervolumeObj(method=method)

    for name, grp in convergence.groupby(['run_index']):
        hyplist.append(list(grp.hypervolume)[-1])
    finalhyp = hyp.calculate(solutions)
    hyplist.append(finalhyp)

    sizes = []
    for name, grp in archive.groupby(['run_index']):
        sizes.append(grp.shape[0])
    nondsize = nondominated.shape[0]
    sizes.append(nondsize)

    df = pd.DataFrame({'hypervolume': hyplist})
    df['run'] = df.index
    df['model'] = model.name
    df['baseModel'] = model.name
    df['type'] = 'individual'
    df['size'] = sizes
    dfs.append(df)

    df = pd.DataFrame({'hypervolume': [finalhyp]})
    df['run'] = run
    df['model'] = '_' + model.name
    df['baseModel'] = model.name
    df['type'] = 'final'
    df['size'] = nondsize
    dfs.append(df)

    return pd.concat(dfs)
Пример #3
0

from platypus import *

# create the problem
problem = DTLZ2(3)

# solve it using NSGA-II
algorithm = NSGAII(problem)
algorithm.run(10000)

# generate the reference set for 3D DTLZ2
reference_set = EpsilonBoxArchive([0.02, 0.02, 0.02])

for _ in range(1000):
    solution = Solution(problem)
    solution.variables = [random.uniform(0,1) if i < problem.nobjs-1 else 0.5 for i in range(problem.nvars)]
    solution.evaluate()
    reference_set.add(solution)

# compute the indicators
gd = GenerationalDistance(reference_set)
print("Generational Distance:", gd.calculate(algorithm.result))

igd = InvertedGenerationalDistance(reference_set)
print("Inverted Generational Distance:", igd.calculate(algorithm.result))

hyp = Hypervolume(reference_set)
print("Hypervolume:", hyp.calculate(algorithm.result))

ei = EpsilonIndicator(reference_set)
Пример #4
0
    def optimize(self):
        os.system("rm -f pf* ps* opt.log")
        f = open('opt.log', 'w')
        self.best_y = np.min(self.dby)
        for iter in range(self.max_iter):
            self.model = GP_MCMC(self.dbx,
                                 self.dby,
                                 self.B,
                                 self.num_init,
                                 warp=self.warp,
                                 mcmc=self.mcmc)
            print("GP built")
            print(self.model.m, flush=True)

            guess_x = self.gen_guess()
            num_guess = guess_x.shape[0]

            def obj(x):
                lcb, ei, pi = self.model.MACE_acq(np.array([x]))
                log_ei = np.log(1e-40 + ei)
                log_pi = np.log(1e-40 + pi)
                return [lcb[0], -1 * log_ei[0], -1 * log_pi[0]]

            problem = Problem(self.dim, 3)
            for i in range(self.dim):
                problem.types[i] = Real(self.lb[i], self.ub[i])

            init_s = [Solution(problem) for i in range(num_guess)]
            for i in range(num_guess):
                init_s[i].variables = [x for x in guess_x[i, :]]

            problem.function = obj
            gen = InjectedPopulation(init_s)
            arch = Archive()
            algorithm = NSGAII(problem,
                               population=100,
                               generator=gen,
                               archive=arch)

            def cb(a):
                print(a.nfe, len(a.archive), flush=True)

            algorithm.run(self.mo_eval, callback=cb)

            if len(algorithm.result) > self.B:
                optimized = algorithm.result
            else:
                optimized = algorithm.population

            idxs = np.arange(len(optimized))
            idxs = np.random.permutation(idxs)
            idxs = idxs[0:self.B]
            for i in idxs:
                x = np.array(optimized[i].variables)
                y = self.f(x)
                if y < self.best_y:
                    self.best_y = y
                    self.best_x = x
                self.dbx = np.concatenate((self.dbx, x.reshape(1, x.size)),
                                          axis=0)
                self.dby = np.concatenate((self.dby, y.reshape(1, 1)), axis=0)
            pf = np.array([s.objectives for s in optimized])
            ps = np.array([s.variables for s in optimized])
            self.pf = pf
            self.ps = ps
            pf[:, 1] = np.exp(-1 * pf[:, 1])  # from -1*log_ei to ei
            pf[:, 2] = np.exp(-1 * pf[:, 2])  # from -1*log_pi to pi
            np.savetxt('pf%d' % iter, pf)
            np.savetxt('ps%d' % iter, ps)
            np.savetxt('dbx', self.dbx)
            np.savetxt('dby', self.dby)

            if self.debug:
                f.write("After iter %d, evaluated: %d, best is %g\n" %
                        (iter, self.dby.size, np.min(self.dby)))
                best_lcb, best_ei, best_pi = self.model.MACE_acq(self.best_x)
                f.write('Best x,  LCB: %g, EI: %g, PI: %g\n' %
                        (best_lcb[0], best_ei[0], best_pi[0]))
                f.write(
                    'Tau = %g, eps = %g, kappa = %g, ystd = %g, ymean = %g\n' %
                    (self.model.tau, self.model.eps, self.model.kappa,
                     self.model.std, self.model.mean))
                f.write('Hypers:\n' + str(self.model.s) + '\n')
                evaled_x = self.dbx[-1 * self.B:, :]
                evaled_y = self.dby[-1 * self.B:]
                evaled_pf = self.pf[idxs]

                for i in range(self.B):
                    predy, preds = self.model.predict(evaled_x[i, :])
                    predy = predy.reshape(predy.size)
                    preds = preds.reshape(preds.size)
                    pred = [(predy[ii], preds[ii]) for ii in range(predy.size)]
                    f.write('X:    ')
                    for d in range(self.dim):
                        f.write(' ' + str(evaled_x[i, d]) + ' ')
                    f.write('\n')
                    f.write('Y:    ' + str(evaled_y[i, 0]) + '\n')
                    f.write('ACQ:  ' + str(evaled_pf[i, :]) + '\n')
                    f.write('Pred:\n' + str(np.array(pred)) + '\n')
                    f.write('---------------\n')
                f.flush()
        f.close()
Пример #5
0
 def generate(self, problem):
     solution = Solution(problem)
     k = np.random.randint(self.min_k, self.max_k + 1)
     solution.variables[0] = self.scale * np.random.rand(self.n, k)
     solution.variables[1] = self.scale * np.random.rand(self.m, k, k)
     return solution
Пример #6
0
 def generate(self, problem, k):
     solution = Solution(problem)
     solution.variables[0] = self.scale * np.random.rand(self.n, k)
     solution.variables[1] = self.scale * np.random.rand(self.m, k, k)
     return solution
Пример #7
0
 def generate(self, problem):
     solution = Solution(problem)
     i = np.random.randint(self.max_k) + 1
     solution.variables[0] = self.scale * np.random.rand(self.n, i)
     solution.variables[1] = self.scale * np.random.rand(self.m, i, i)
     return solution
Пример #8
0
 def random(self):
     solution = Solution(self)
     self._generate_random_rules(solution)
     self._generate_random_fuzzysets(solution)
     return solution
Пример #9
0
 def evaluate(self, solution: Solution):
     score, cost = self.nrp_instance.get_score_cost(solution.variables[0])
     # Changed
     solution.objectives[:] = [score, cost]
     solution.constraints[:] = [cost, score]
Пример #10
0
import random
from platypus import (NSGAII, DTLZ2, Solution, EpsilonBoxArchive, GenerationalDistance, InvertedGenerationalDistance,
                      Hypervolume, EpsilonIndicator, Spacing)

# create the problem
problem = DTLZ2(3)

# solve it using NSGA-II
algorithm = NSGAII(problem)
algorithm.run(10000)

# generate the reference set for 3D DTLZ2
reference_set = EpsilonBoxArchive([0.02, 0.02, 0.02])

for _ in range(1000):
    solution = Solution(problem)
    solution.variables = [random.uniform(0,1) if i < problem.nobjs-1 else 0.5 for i in range(problem.nvars)]
    solution.evaluate()
    reference_set.add(solution)

# compute the indicators
gd = GenerationalDistance(reference_set)
print("Generational Distance:", gd.calculate(algorithm.result))

igd = InvertedGenerationalDistance(reference_set)
print("Inverted Generational Distance:", igd.calculate(algorithm.result))

hyp = Hypervolume(reference_set)
print("Hypervolume:", hyp.calculate(algorithm.result))

ei = EpsilonIndicator(reference_set)
Пример #11
0
 def generate(self, problem):
     solution = Solution(problem)
     solution.variables[0] = random_walk()
     return solution
Пример #12
0
 def generate(self, problem):
     solution = Solution(problem)
     solution.variables[0] = degree_random(random.randint(k // 3, (k * 2) // 3))
     return solution
Пример #13
0
 def generate(self, problem):
     solution = Solution(problem)
     solution.variables[0] = list(nx.dfs_preorder_nodes(G, source=random.choice(list(G))))[::self.step_size]
     return solution
Пример #14
0
def ga(variables, outpu):  #genetic algorithm function
    if gv.vector == 0:
        gv.algo = int(input("Enter the no: of iterations\nuser input: "))
        print(" \n*****  Optimization  procedures have started. *****\n")
    if gv.constraint == "n":
        problem = Problem(variables, outpu)
    if gv.constraint == "y":
        problem = Problem(variables, outpu, len(
            gv.bigconst))  # specify the no of objectives and inputs
    for i in range(0, len(gv.bigres)):
        problem.types[i:i + 1] = [Real(gv.bigres[i][3], gv.bigres[i][2])
                                  ]  # loop to intialise the limkits
    for i in range(0, len(gv.bigconst)):
        for j in range(len(gv.bigconst[i])):
            if gv.bigconst[i][j] == 1:
                problem.constraints[i:i + 1] = "<=0"  #constraint assigning
            elif gv.bigconst[i][j] == 2:
                problem.constraints[i:i + 1] = ">=0"
    problem.function = evaluator  # call the simulator
    v_population_size = 10
    init_pop = [Solution(problem) for i in range(v_population_size)]
    pop_indiv = [[x.rand() for x in problem.types]
                 for i in range(v_population_size)]

    for i in range(v_population_size):
        init_pop[i].variables = pop_indiv[i]

    if gv.algoindex == 1:
        algorithm = NSGAII(problem,
                           population_size=v_population_size,
                           generator=InjectedPopulation(init_pop))
    elif gv.algoindex == 2:
        algorithm = NSGAIII(problem,
                            12,
                            population_size=v_population_size,
                            generator=InjectedPopulation(init_pop))
    elif gv.algoindex == 3:
        algorithm = CMAES(problem,
                          epsilons=0.05,
                          population_size=v_population_size,
                          generator=InjectedPopulation(init_pop))
    elif gv.algoindex == 4:
        algorithm = GDE3(problem,
                         population_size=v_population_size,
                         generator=InjectedPopulation(init_pop))
    elif gv.algoindex == 5:
        algorithm = IBEA(problem,
                         population_size=v_population_size,
                         generator=InjectedPopulation(init_pop))
    elif gv.algoindex == 6:
        algorithm = MOEAD(problem,
                          divisions_outer=12,
                          population_size=v_population_size,
                          generator=InjectedPopulation(init_pop))
    elif gv.algoindex == 7:
        algorithm = OMOPSO(problem,
                           epsilons=0.05,
                           population_size=v_population_size,
                           generator=InjectedPopulation(init_pop))
    elif gv.algoindex == 8:
        algorithm = SMPSO(problem,
                          population_size=v_population_size,
                          generator=InjectedPopulation(init_pop))
    elif gv.algoindex == 9:
        algorithm = SPEA2(problem,
                          population_size=v_population_size,
                          generator=InjectedPopulation(init_pop))
    elif gv.algoindex == 10:
        algorithm = EpsMOEA(problem,
                            epsilons=0.05,
                            population_size=v_population_size,
                            generator=InjectedPopulation(init_pop))
    algorithm.run(gv.algo)
    feasible_solutions = [s for s in algorithm.result if s.feasible]
    nondominanted_solutions = nondominated(algorithm.result)
    f = open("feasible.txt", "a")
    f.write("\nThis is a set of feasible_solutions values\n")
    f.close()
    for ki in range(len(feasible_solutions)):
        f = open("feasible.txt", "a")
        f.write("\n This is solution  " + str(ki + 1) + "\n")
        f.close()
        for i in range(len(feasible_solutions[ki].variables)):
            f = open("feasible.txt", "a")
            f.write(" The value of  element " + str(i + 1) + " is " +
                    str(feasible_solutions[ki].variables[i]) + "\n")
            f.close()
        for i in range(len(feasible_solutions[ki].objectives)):
            f = open("feasible.txt", "a")
            #f.write( "The  error  of target " +str(i+1) + " is  " + str(feasible_solutions[ki].objectives[i]) + "\n")
            if gv.bigout[i][3] >= 0:
                tru = gv.bigout[i][3] - feasible_solutions[ki].objectives[
                    i]**0.5
                f.write(" The value of  target " + str(i + 1) + " is " +
                        str(tru) + " and the corresponding error value is " +
                        str(feasible_solutions[ki].objectives[i]) + "\n")
            else:
                tru = gv.bigout[i][3] + feasible_solutions[ki].objectives[
                    i]**0.5
                f.write(" The value of  target " + str(i + 1) + " is " +
                        str(tru) + " and the corresponding error value is " +
                        str(feasible_solutions[ki].objectives[i]) + "\n")
            f.close()
    f = open("nondominanted_solutions.txt", "a")
    f.write("\nThis is a set of nondominanted_solutions values\n")
    f.close()
    for ki in range(len(nondominanted_solutions)):
        f = open("nondominanted_solutions.txt", "a")
        f.write("\n This is solution  " + str(ki + 1) + "\n")
        f.close()
        for i in range(len(nondominanted_solutions[ki].variables)):
            f = open("nondominanted_solutions.txt", "a")
            f.write(" The value of  element " + str(i + 1) + " is " +
                    str(nondominanted_solutions[ki].variables[i]) + "\n")
            f.close()
        for i in range(len(nondominanted_solutions[ki].objectives)):
            f = open("nondominanted_solutions.txt", "a")
            #f.write(str(i+1) + " th  objective error " + " value is " + str(nondominanted_solutions[ki].objectives[i]) + "\n")
            if gv.bigout[i][3] >= 0:
                tru = gv.bigout[i][3] - nondominanted_solutions[ki].objectives[
                    i]**0.5
                f.write(" The value of  target " + str(i + 1) + " is " +
                        str(tru) + " and the corresponding error value is " +
                        str(nondominanted_solutions[ki].objectives[i]) + "\n")
            else:
                tru = gv.bigout[i][3] + nondominanted_solutions[ki].objectives[
                    i]**0.5
                f.write(" The value of  target " + str(i + 1) + " is " +
                        str(tru) + " and the corresponding error value is " +
                        str(nondominanted_solutions[ki].objectives[i]) + "\n")

            f.close()

    return