def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[S]]: ranking = StrengthRanking(self.dominance_comparator) density_estimator = KNearestNeighborDensityEstimator() r = RankingAndDensityEstimatorReplacement(ranking, density_estimator, RemovalPolicyType.SEQUENTIAL) solutions = r.replace(population, offspring_population) front = get_non_dominated_solutions(solutions) objective1 = -1 / self.Uobjecive1 * np.array( [solution.objectives[0] for solution in front]) objective2 = -1 / self.Uobjecive2 * np.array( [solution.objectives[1] for solution in front]) HV = calculateHypervolume(list(zip(objective1, objective2))) print('Hypervolume;', HV) self.hypervolumeByGeneration.append(HV) # DO IGD calculation here IGD = InvertedGenerationalDistance(self.reference_front) igd = IGD.compute( list( zip(-np.array([solution.objectives[0] for solution in front]), -np.array([solution.objectives[1] for solution in front])))) print('IGD1:', igd) # obj1front=1/self.Uobjecive1*self.reference_front[:, 0] # obj2front=1/self.Uobjecive2*self.reference_front[:,1] # igd2 = calculateIGD(list(zip(objective1,objective2)), list(zip(obj1front,obj2front))) # print('IGD2:',igd2) self.IGDbyGeneration.append(igd) return solutions
def hypervolume_convergenve(algorithm, n_simulations=30): runs = [] for n in tqdm(range(n_simulations)): algo = get_algorithm_instance(algorithm) algo.run() front = get_raw_front(get_non_dominated_solutions(algo.get_result()), var_dict) hv = HV.compute(front, reference_point) runs.append(hv) return runs
def spread_convergenve(algorithm, n_simulations=30): runs = [] for n in tqdm(range(n_simulations)): algo = get_algorithm_instance(algorithm) algo.run() front = get_raw_front(get_non_dominated_solutions(algo.get_result()), var_dict) spread = Spread.compute(front) runs.append(spread) return runs
def transform(): for i in range(2): print(i) algorithm1.run() front = get_non_dominated_solutions(algorithm1.get_result()) for solution in front: solutions.append(solution) # save to files front_sol1 = [] resultat = [] for solution in front: res = 0 res = solution.objectives[0] * 0.1 + solution.objectives[ 1] * 0.5 + solution.objectives[2] * 0.2 + solution.objectives[ 3] * 0.2 resultat.append(res) front_sol1.append(solution.objectives) best_sol = resultat.index(min(resultat)) all3.append(front[best_sol]) all2[i] = front[best_sol].objectives # print_function_values_to_file(front,r"C:\Users\User\Desktop\MOOC\NSGAIII\function_values.txt") # print_variables_to_file(front, r"C:\Users\User\Desktop\MOOC\NSGAIII\VARMOOC.txt") print_function_values_to_screen(front) #print_variables_to_screen(front) # plot_front = Plot(title='Pareto front approximation', axis_labels=['nb_nodes','max_containers/node','cohesion','coupling','changes']) # plot_front.plot(front, label='NSGAIII-MOOC', filename=r"C:\Users\User\Desktop\MOOC\NSGAIII\MOOC", format='png') state = all3[0].variables print(state) containers, initial_state, machines = create() print(machines) keep_trace1(containers, state, machines, r'C:\Users\User\Desktop\docker\docker-compose1.yml')
def oneRun(problemType, numberOfitems: int, population_size: int, maxEvaluations: int): filename = 'knapsack_instances/%s/%d.txt' % (problemType, numberOfitems) problem = MOKnapsack(from_file=True, filename=filename) filename = 'PF/%s/%d.txt' % (problemType, numberOfitems) with open(filename) as file: lines = file.readlines() data = [line.split() for line in lines if len(line.split()) >= 1] calibratedFront = np.asfarray(data[0:], dtype=np.int32) max_evaluations = maxEvaluations utopianPoint = (np.amax(calibratedFront[:, 0]), np.amax(calibratedFront[:, 1])) algorithm = MyAlgorithm(problem=problem, population_size=population_size, mutation=BitFlipMutation(probability=1.0 / problem.number_of_bits), crossover=SPXCrossover(probability=0.9), termination=StoppingByEvaluations(max_evaluations), utopian=utopianPoint, referenceFront=calibratedFront) algorithm.run() solutions = algorithm.get_result() HVbyGen = algorithm.getHyperVolumeByGeneration() IGDbyGen = algorithm.getIGDByGeneration() front = get_non_dominated_solutions(solutions) # for solution in front: # print(solution.variables) # print(-solution.objectives[0],-solution.objectives[1]) objective1 = -1 / utopianPoint[0] * np.array( [solution.objectives[0] for solution in front]) objective2 = -1 / utopianPoint[1] * np.array( [solution.objectives[1] for solution in front]) # print(calculateHypervolume(list(zip(objective1,objective2)))) # plt.scatter(objective1, objective2) # plt.title('%s_%d'%(problemType,numberOfitems)) # plt.xlabel("Objective 1") # plt.ylabel("Objective 2") # plt.savefig('%s_%d'%(problemType,numberOfitems)) return HVbyGen, IGDbyGen
def nsgaii_train(particoes, regras, instancias, classes): problem = MixedIntegerFloatProblem(particoes, regras, instancias, classes) max_evaluations = 10 algorithm = NSGAII( problem=problem, population_size=10, offspring_population_size=10, mutation=CompositeMutation([IntegerPolynomialMutation(0.05, 20), IntegerPolynomialMutation(0.05, 20), PolynomialMutation(0.05, 20.0)]), crossover=CompositeCrossover([IntegerSBXCrossover(probability=0.95, distribution_index=20), IntegerSBXCrossover(probability=0.95, distribution_index=20), SBXCrossover(probability=0.95, distribution_index=20)]), termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations) ) algorithm.run() front = get_non_dominated_solutions(algorithm.get_result()) # Save results to file print_function_values_to_file(front, 'FUN.' + algorithm.label) print_variables_to_file(front, 'VAR.' + algorithm.label) print('Algorithm (continuous problem): ' + algorithm.get_name()) print('Problem: ' + problem.get_name()) print('Computing time: ' + str(algorithm.total_computing_time)) minAcuracia = 0 index = -1 for i, f in enumerate(front): if minAcuracia > f.objectives[0]: minAcuracia = f.objectives[0] index = i #for variable in front[index].variables: #print(variable.variables) particoes = problem.alterar_centroids(front[index].variables[2].variables) new_regras = problem.cromossomo_para_regras(front[index].variables[0].variables, front[index].variables[1].variables, problem.semente.qtdAntecedenteRegra, particoes) return particoes, new_regras
def run_DynamicNSGAII(problems): for problem in problems: time_counter = TimeCounter(delay=1) time_counter.observable.register(problem[1]) time_counter.start() max_evaluations = 25000 algorithm = DynamicNSGAII( problem=problem[1], population_size=100, offspring_population_size=100, mutation=PolynomialMutation(probability=1.0 / problem[1].number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations), ) algorithm.observable.register(observer=ProgressBarObserver(max=max_evaluations)) algorithm.observable.register(observer=VisualizerObserver()) algorithm.observable.register(observer=PlotFrontToFileObserver(problem[0] + "_dynamic_front_vis")) algorithm.observable.register(observer=WriteFrontToFileObserver(problem[0] + "_dynamic_front")) #algorithm.observable.register(observer=BasicObserver()) algorithm.run() front = algorithm.get_result() non_dominated_solutions = get_non_dominated_solutions(front) # save to files print_function_values_to_file(front, 'FUN.DYNAMICNSGAII.' + problem[0]) print_variables_to_file(front, 'VAR.DYNAMICNSGAII.' + problem[0]) # Plot plot_front = Plot(title='Pareto front approximation', axis_labels=['x', 'y']) plot_front.plot(front, label='DynamicNSGAII-FDA2', filename='DYNAMICNSGAII-'+problem[0], format='png')
if __name__ == "__main__": problem = MixedIntegerFloatProblem(10, 10, 100, -100, -1000, 1000) max_evaluations = 25000 algorithm = NSGAII( problem=problem, population_size=100, offspring_population_size=100, mutation=CompositeMutation([ IntegerPolynomialMutation(0.01, 20), PolynomialMutation(0.01, 20.0) ]), crossover=CompositeCrossover([ IntegerSBXCrossover(probability=1.0, distribution_index=20), SBXCrossover(probability=1.0, distribution_index=20), ]), termination_criterion=StoppingByEvaluations( max_evaluations=max_evaluations), ) algorithm.run() front = get_non_dominated_solutions(algorithm.get_result()) # Save results to file print_function_values_to_file(front, "FUN." + algorithm.label) print_variables_to_file(front, "VAR." + algorithm.label) print(f"Algorithm: {algorithm.get_name()}") print(f"Problem: {problem.get_name()}") print(f"Computing time: {algorithm.total_computing_time}")
offspring_population_size=100, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), termination_criterion=StoppingByEvaluations( max_evaluations=max_evaluations)) algorithm.run() solutions = algorithm.get_result() from jmetal.lab.visualization.plotting import Plot from jmetal.util.solution import get_non_dominated_solutions front = get_non_dominated_solutions(solutions) plot_front = Plot(title='Pareto front approximation', axis_labels=['x', 'y']) plot_front.plot(front, label='OMOPSO-ZDT1') # Save results save = { 0: 'Maximal profits', 1: 'Maximal green hydrogen', 2: 'Maximal electrolyser efficiency' } res_dict = { save[problem.objective]: [front[i].objectives[0] for i in range(front.__len__())], 'IRR': [front[i].objectives[1] for i in range(front.__len__())],
with open(fileName + '.txt') as f: lines = f.readlines() solution_list = [] count = 0 for line in lines: print('loading file, percentage: \t' + str(round(float(count/len(lines) * 100), 2))) solution = Solution(number_of_variables=7, number_of_objectives=2) result = eval(line) solution.objectives[0] = result[0] solution.objectives[1] = result[1] solution_list.append(solution) count += 1 print('Obtaining the pareto front') pareto_front = get_non_dominated_solutions(solution_list) with open('Paretofront.pf', 'w') as f: for pareto in pareto_front: f.write(str(pareto.objectives)) f.write('\n') plot_front = Plot(title='Pareto front approximation', axis_labels=['Interfaces', 'TIRF']) plot_front.plot(pareto_front, label='NSGAII-OTN') # ------------------------Saving multithread implementation ---------------- # from jmetal.core.solution import Solution # from jmetal.lab.visualization import Plot # from jmetal.util.solution import get_non_dominated_solutions # # from Models.Network import Network
crossover=IntegerSBXCrossover(probability=0.3, distribution_index=20), termination_criterion=StoppingByEvaluationsCustom( max_evaluations=max_evaluations, reference_point=[5000, 2.1], AlgorithmName='Reference') # termination_criterion=stopCriterion ) progress_bar = ProgressBarObserver(max=max_evaluations) algorithm.observable.register(progress_bar) algorithm.run() solutions = algorithm.get_result() for solution in solutions: if not solution.objectives[1] >= 1.3: solutionsResult.append(solution) if executions == (timesToRun - 1): frontResult = get_non_dominated_solutions(solutionsResult) for sol in frontResult: log_front.log( str(sol.objectives[0]) + " " + str(sol.objectives[1])) log_front.save() plot_front = Plot(title='Pareto front approximation', axis_labels=['Interfaces', 'TIRF']) plot_front.plot(frontResult, label='NSGAII-OTN') stopTime = timeit.default_timer() print('Execution Time:', stopTime - startTime)
def get_raw_front(solutions, var_dict): l = get_non_dominated_solutions(solutions) return np.array(list(map(lambda p: p.objectives, l)))
def get_current_front(self): return copy(get_non_dominated_solutions(self.get_result()))
offspring_population_size=100, mutation=PolynomialMutation(probability=mutation_probability, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), termination_criterion=StoppingByEvaluations(max_evaluations)) ibea_enhanced.run() print('Total computing time for IBEA: {:.4f} s'.format( ibea_enhanced.total_computing_time)) """#### Front Analysis of Algorithms <a id='enha_front'> </a> [Back to top](#top) """ smpso_enhanced_front = get_non_dominated_solutions(smpso_enhanced.get_result()) ompso_enhanced_front = get_non_dominated_solutions(ompso_enhanced.get_result()) nsgaii_enhanced_front = get_non_dominated_solutions( nsgaii_enhanced.get_result()) speaii_enhanced_front = get_non_dominated_solutions( speaii_enhanced.get_result()) moead_enhanced_front = get_non_dominated_solutions(moead_enhanced.get_result()) ibea_enhanced_front = get_non_dominated_solutions(ibea_enhanced.get_result()) enhanced_fronts = [ smpso_enhanced_front, ompso_enhanced_front, nsgaii_enhanced_front, speaii_enhanced_front, moead_enhanced_front, ibea_enhanced_front ] labels = [ 'SMPSO-DipoloSimplesMO2', 'OMPSO-DipoloSimplesMO2',