def test_should_dominance_comparator_return_zero_if_the_two_solutions_have_one_objective_with_the_same_value(self): solution = FloatSolution(3, 1, 0, [], []) solution2 = FloatSolution(3, 1, 0, [], []) solution.objectives = [1.0] solution2.objectives = [1.0] self.assertEqual(0, self.comparator.compare(solution, solution2))
def test_should_dominance_comparator_return_minus_one_if_the_two_solutions_have_one_objective_and_the_first_one_is_lower(self): solution = FloatSolution(3, 1, 0, [], []) solution2 = FloatSolution(3, 1, 0, [], []) solution.objectives = [1.0] solution2.objectives = [2.0] self.assertEqual(-1, self.comparator.compare(solution, solution2))
def test_should_dominance_comparator_work_properly_case_3(self): """ Case d: solution1 has objectives [-1.0, 5.0, 9.0] and solution2 has [-2.0, 5.0, 10.0] """ solution = FloatSolution(3, 3, 0, [], []) solution2 = FloatSolution(3, 3, 0, [], []) solution.objectives = [-1.0, 5.0, 9.0] solution2.objectives = [-2.0, 5.0, 10.0] self.assertEqual(0, self.comparator.compare(solution, solution2))
def test_should_dominance_comparator_work_properly_case_a(self): ''' Case A: solution1 has objectives [-1.0, 5.0, 9.0] and solution2 has [2.0, 6.0, 15.0] ''' solution = FloatSolution(3, 3, 0, [], []) solution2 = FloatSolution(3, 3, 0, [], []) solution.objectives = [-1.0, 5.0, 9.0] solution2.objectives = [2.0, 6.0, 15.0] self.assertEqual(-1, self.comparator.compare(solution, solution2))
def test_should_dominance_comparator_work_properly_with_constrains_case_2(self): """ Case 2: solution1 has a lower degree of constraint violation than solution 2 """ solution1 = FloatSolution(3, 3, 0, [], []) solution2 = FloatSolution(3, 3, 0, [], []) solution1.attributes["overall_constraint_violation"] = -0.3 solution2.attributes["overall_constraint_violation"] = -0.1 solution1.objectives = [-1.0, 5.0, 9.0] solution2.objectives = [-2.0, 5.0, 10.0] self.assertEqual(1, self.comparator.compare(solution1, solution2))
def evaluate(self, solution: FloatSolution) -> FloatSolution: k = self.number_of_variables - self.number_of_objectives + 1 g = sum([ pow(x, 0.1) for x in solution.variables[self.number_of_variables - k:] ]) t = pi / (4.0 * (1.0 + g)) theta = [0.0] * (self.number_of_objectives - 1) theta[0] = solution.variables[0] * pi / 2.0 theta[1:] = [ t * (1.0 + 2.0 * g * solution.variables[i]) for i in range(1, self.number_of_objectives - 1) ] f = [1.0 + g for _ in range(self.number_of_objectives)] for i in range(self.number_of_objectives): for j in range(self.number_of_objectives - (i + 1)): f[i] *= cos(theta[j]) if i != 0: aux = self.number_of_objectives - (i + 1) f[i] *= sin(theta[aux]) solution.objectives = [f[x] for x in range(self.number_of_objectives)] return solution
def evaluate(self, solution: FloatSolution) -> FloatSolution: Vars = solution.variables result = create_run_scenario_turnright(Vars, self.config) solution.objectives = result return solution
def evaluate(self, solution: FloatSolution) -> FloatSolution: input_vars = np.array(solution.variables).reshape(1, -1) input_vars = self.std_in.transform(input_vars) objct_vals = self.reg_model.predict(input_vars)[0] objct_vals[0] = -1 * objct_vals[0] objct_vals[1] = np.abs(3.5 - objct_vals[1]) solution.objectives = list(objct_vals) return solution
def evaluate(self, solution: FloatSolution) -> FloatSolution: Vars = solution.variables # print("Variables:", Vars) result = create_run_scenario_overtake(Vars, self.config) solution.objectives = result return solution
def evaluate(self, solution: FloatSolution) -> FloatSolution: # print(solution.__str__) Vars = solution.variables # L = np.array(solution.variables) # print(L.shape) # bestlog = gl.get_value('BestPop') # print("\033[1;32m round: \033[0m",bestlog.round) result = create_run_scenario_overtake(Vars, self.bestpop, self.config) solution.objectives = result # lock = Lock() # with lock: # time.sleep(1) # lock.acquire() # self.bestpop.add_results(result) # print(self.bestpop.pop) # lock.release() # Lock = threading.Lock() # Lock.acquire() # print("\033[1;32m round: \033[0m", self.bestpop.round) # print("\033[1;32m before: bestlog.pop \033[0m", self.bestpop.pop) # self.bestpop.update_bestpop(result) # print("\033[1;32m after: bestlog.pop \033[0m", self.bestpop.pop) # Lock.release() # global BestPopulation # Lock = threading.Lock() # Lock.acquire() # BestPopulation = gl.get_value('BestPop') # print("\033[1;32m round: \033[0m",BestPopulation.round) # print("\033[1;32m before: bestlog.pop \033[0m", BestPopulation.pop) # BestPopulation.update_bestpop(result) # gl.set_value('BestPop', BestPopulation) # print("\033[1;32m after: bestlog.pop \033[0m", BestPopulation.pop) # Lock.release() # with bestpop.get_lock(): # 直接调用get_lock()函数获取锁 # # # bestlog = globalvar.get_value('BestPop') # bestpop.update_bestpop(result) # # # globalvar.set_value('BestPop', bestlog) # print("\033[1;32m bestlog.pop \033[0m", bestpop.pop) return solution
def read_front_from_file_as_solutions(file_path: str): """ Reads a front from a file and returns a list of solution objects. :return: List of solution objects. """ front = [] with open(file_path) as file: for line in file: vector = [float(x) for x in line.split()] solution = FloatSolution(2, 2, 0, [], []) solution.objectives = vector front.append(solution) return front
def evaluate(self, solution: FloatSolution) -> FloatSolution: k = self.number_of_variables - self.number_of_objectives + 1 g = sum([(x - 0.5) * (x - 0.5) for x in solution.variables[self.number_of_variables - k:]]) solution.objectives = [1.0 + g] * self.number_of_objectives for i in range(self.number_of_objectives): for j in range(self.number_of_objectives - (i + 1)): solution.objectives[i] *= cos(solution.variables[j] * 0.5 * pi) if i != 0: solution.objectives[i] *= sin(0.5 * pi * solution.variables[self.number_of_objectives - (i + 1)]) return solution
def read_front_from_file_as_solutions(file_path: str) -> List[S]: """ Reads a front from a file and returns a list of solution objects. :return: List of solution objects. """ front = [] if Path(file_path).is_file(): with open(file_path) as file: for line in file: vector = [float(x) for x in line.split()] solution = FloatSolution(2, 2, 0, [], []) solution.objectives = vector front.append(solution) else: raise Exception('Reference front file was not found at {}'.format(file_path)) return front
def test_should_copy_work_properly(self) -> None: solution = FloatSolution(2, 3, [0.0, 0.5], [1.0, 2.0]) solution.variables = [1.24, 2.66] solution.objectives = [0.16, -2.34, 9.25] solution.attributes["attr"] = "value" new_solution = copy.copy(solution) self.assertEqual(solution.number_of_variables, new_solution.number_of_variables) self.assertEqual(solution.number_of_objectives, new_solution.number_of_objectives) self.assertEqual(solution.variables, new_solution.variables) self.assertEqual(solution.objectives, new_solution.objectives) self.assertEqual(solution.lower_bound, new_solution.lower_bound) self.assertEqual(solution.upper_bound, new_solution.upper_bound) self.assertIs(solution.lower_bound, solution.lower_bound) self.assertIs(solution.upper_bound, solution.upper_bound) self.assertEqual(solution.attributes, new_solution.attributes)
def read_front_from_file_as_solutions(file_path: str) -> List[S]: """ Reads a front from a file and returns a list of solution objects. :return: List of solution objects. """ front = [] if Path(file_path).is_file(): with open(file_path) as file: for line in file: vector = [float(x) for x in line.split()] solution = FloatSolution(2, 2, 0, [], []) solution.objectives = vector front.append(solution) else: raise Exception( 'Reference front file was not found at {}'.format(file_path)) return front
def evaluate(self, solution: FloatSolution) -> FloatSolution: k = self.number_of_variables - self.number_of_objectives + 1 g = sum([(x - 0.5) * (x - 0.5) for x in solution.variables[self.number_of_variables - k:]]) solution.objectives = [1.0 + g] * self.number_of_objectives for i in range(self.number_of_objectives): for j in range(self.number_of_objectives - (i + 1)): solution.objectives[i] *= cos(solution.variables[j] * 0.5 * pi) if i != 0: solution.objectives[i] *= sin( 0.5 * pi * solution.variables[self.number_of_objectives - (i + 1)]) return solution
def evaluate(self, solution: FloatSolution) -> FloatSolution: k = self.number_of_variables - self.number_of_objectives + 1 g = sum([(x - 0.5) * (x - 0.5) - cos(20.0 * pi * (x - 0.5)) for x in solution.variables[self.number_of_variables - k:]]) g = 100 * (k + g) solution.objectives = [(1.0 + g) * 0.5] * self.number_of_objectives for index_var in range(self.number_of_objectives): for j in range(self.number_of_objectives - (index_var + 1)): solution.objectives[index_var] *= solution.variables[j] if index_var != 0: solution.objectives[index_var] *= 1 - solution.variables[ self.number_of_objectives - (index_var + 1)] return solution
def evaluate(self, solution: FloatSolution) -> FloatSolution: Vars = solution.variables result = create_run_scenario_turnright(Vars, self.config) solution.objectives = result ## check if find such pattern # goal_flag = np.zeros((7), dtype=int) # for j in range(7): # if result[j] < self.target_value_threshold[j]: # goal_flag[j] = 1 # else: # goal_flag[j] = 0 # if (goal_flag == self.config.goal_selection_flag).all(): # self.problem_solved = 1 return solution
def test_should_copy_work_properly(self) -> None: solution = FloatSolution(2, 3, 2, [0.0, 0.5], [1.0, 2.0]) solution.variables = [1.24, 2.66] solution.objectives = [0.16, -2.34, 9.25] solution.attributes["attr"] = "value" new_solution = copy.copy(solution) self.assertEqual(solution.number_of_variables, new_solution.number_of_variables) self.assertEqual(solution.number_of_objectives, new_solution.number_of_objectives) self.assertEqual(solution.number_of_constraints, new_solution.number_of_constraints) self.assertEqual(solution.variables, new_solution.variables) self.assertEqual(solution.objectives, new_solution.objectives) self.assertEqual(solution.lower_bound, new_solution.lower_bound) self.assertEqual(solution.upper_bound, new_solution.upper_bound) self.assertIs(solution.lower_bound, solution.lower_bound) self.assertIs(solution.upper_bound, solution.upper_bound) self.assertEqual({}, new_solution.attributes)
def evaluate(self, solution: FloatSolution) -> FloatSolution: k = self.number_of_variables - self.number_of_objectives + 1 g = sum([(x - 0.5) * (x - 0.5) - cos(20.0 * pi * (x - 0.5)) for x in solution.variables[self.number_of_variables - k:]]) g = 100 * (k + g) solution.objectives = [(1.0 + g) * 0.5] * self.number_of_objectives for i in range(self.number_of_objectives): for j in range(self.number_of_objectives - (i + 1)): solution.objectives[i] *= solution.variables[j] if i != 0: solution.objectives[i] *= 1 - solution.variables[self.number_of_objectives - (i + 1)] return solution
def evaluate(self, solution: FloatSolution) -> FloatSolution: alpha = 100.0 k = self.number_of_variables - self.number_of_objectives + 1 g = sum([(x - 0.5)**2 for x in solution.variables[self.number_of_variables - k:]]) f = [1.0 + g for _ in range(self.number_of_objectives)] for i in range(self.number_of_objectives): for j in range(self.number_of_objectives - (i + 1)): f[i] *= cos(pow(solution.variables[j], alpha) * pi / 2.0) if i != 0: aux = self.number_of_objectives - (i + 1) f[i] *= sin(pow(solution.variables[aux], alpha) * pi / 2.0) solution.objectives = [f[x] for x in range(self.number_of_objectives)] return solution
def generate_existing_solution( self, variables: List[float], is_objectives: bool = False) -> FloatSolution: new_solution = FloatSolution(self.lower_bound, self.upper_bound, self.number_of_objectives, self.number_of_constraints) if not is_objectives: new_solution.variables = [ variables[index_var] for index_var in range(self.number_of_variables) ] self.evaluate(new_solution) else: new_solution.objectives = [ variables[index_var] for index_var in range(self.number_of_objectives) ] return new_solution
def evaluate(self, solution: FloatSolution) -> FloatSolution: k = self.number_of_variables - self.number_of_objectives + 1 g = sum([(x - 0.5)**2 - cos(20.0 * pi * (x - 0.5)) for x in solution.variables[self.number_of_variables - k:]]) g = 100.0 * (k + g) f = [1.0 + g for _ in range(self.number_of_objectives)] for i in range(self.number_of_objectives): for j in range(self.number_of_objectives - (i + 1)): f[i] *= cos(solution.variables[j] * 0.5 * pi) if i != 0: aux = self.number_of_objectives - (i + 1) f[i] *= sin(solution.variables[aux] * 0.5 * pi) solution.objectives = [f[x] for x in range(self.number_of_objectives)] return solution
def read_solutions(filename: str) -> List[FloatSolution]: """Reads a reference front from a file. :param filename: File path where the front is located. """ front = [] if Path(filename).is_file(): with open(filename) as file: for line in file: vector = [float(x) for x in line.split()] solution = FloatSolution([], [], len(vector)) solution.objectives = vector front.append(solution) else: logger.warning( "Reference front file was not found at {}".format(filename)) return front
def configure_experiment(problems: dict, n_run: int): jobs = [] num_processes = config.num_cpu population = 10 generations = 10 max_evaluations = population * generations for run in range(n_run): for problem_tag, problem in problems.items(): reference_point = FloatSolution([0, 0], [1, 1], problem.number_of_objectives, ) reference_point.objectives = np.repeat(1, problem.number_of_objectives).tolist() jobs.append( Job( algorithm=NSGAIII( problem=problem, population_size=population, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), population_evaluator=MultiprocessEvaluator(processes=num_processes), termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations), reference_directions=UniformReferenceDirectionFactory(4, n_points=100), ), algorithm_tag='NSGAIII', problem_tag=problem_tag, run=run, ) ) jobs.append( Job( algorithm=GDE3( problem=problem, population_size=population, population_evaluator=MultiprocessEvaluator(processes=num_processes), termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations), cr=0.5, f=0.5, ), algorithm_tag='GDE3', problem_tag=problem_tag, run=run, ) ) jobs.append( Job( algorithm=SPEA2( problem=problem, population_size=population, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), population_evaluator=MultiprocessEvaluator(processes=num_processes), termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations), offspring_population_size=population, ), algorithm_tag='SPEA2', problem_tag=problem_tag, run=run, ) ) return jobs
from jmetal.operator import SBXCrossover, PolynomialMutation from jmetal.problem import ZDT1 from jmetal.util.solution import read_solutions, print_function_values_to_file, print_variables_to_file from jmetal.util.termination_criterion import StoppingByEvaluations if __name__ == '__main__': problem = ZDT1() problem.reference_front = read_solutions( filename='resources/reference_front/ZDT1.pf') reference_point = FloatSolution( [0], [1], problem.number_of_objectives, ) reference_point.objectives = [1., 1.] # Mandatory for HYPE algorithm = HYPE(problem=problem, reference_point=reference_point, population_size=100, 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(25000)) algorithm.run() front = algorithm.get_result()
def to_jmetal_solution(tuple_solution) -> FloatSolution: vector = [round(float(x), 2) for x in tuple_solution] solution = FloatSolution([], [], len(vector)) solution.objectives = vector return solution
def evaluate(self, solution: FloatSolution) -> FloatSolution: ##################################### ''' Script parameters that should change ''' year = '2017' # model year trial_name = "2017_debug" #output file name ID fail_time = 400 # maximum model run time (seconds) # WSC delineation, use wsc_viewer.py to verify delineation regions = { 'Default': np.r_[1:10], 'Thomas': np.r_[10:28], 'South': np.r_[46:51], 'North': np.r_[28:46, 51:63] } debug = 'off' # see below for description ##################################### thread = multiprocessing.Process() process_id = str(thread.name) process_id = process_id.replace("-", "_") process_id = process_id.replace(":", "_") os_fold = self.os_sep() init = os.getcwd() + os_fold + 'models' + os_fold + year + os_fold + 'init' model_folder = os.getcwd() + os_fold + 'models' + os_fold + year + os_fold + str(process_id) data_path = os.getcwd() + os_fold + 'data' + os_fold + year dec_vars = solution.variables[0:5] wsc_vals = dec_vars[2:5] files = os.listdir(init) if os.path.exists(model_folder): shutil.rmtree(model_folder) if os.path.exists(model_folder) == False: os.mkdir(model_folder) for file in files: shutil.copy(init + os_fold + file, model_folder) self.write_control(dec_vars[0], "EXH2O", model_folder, 0) self.write_control(dec_vars[1], "ESTR", model_folder, 0) self.write_wsc(wsc_vals, regions, model_folder) print([process_id, dec_vars]) # debug on will raise error when model fails if debug == 'on': self.run_cequal(model_folder, fail_time) error_bn = self.Error_BN(model_folder, data_path, year) error_ci = self.Error_CI(model_folder, data_path, year) solution.objectives = ([error_bn['TempRMSE'], error_bn['CondRMSE'], error_ci['TempRMSE'], error_ci['CondRMSE']]) all_objs = ([error_bn['TempRMSE'], error_bn['CondRMSE'], error_ci['TempRMSE'], error_ci['CondRMSE']]) if debug == 'off': try: self.run_cequal(model_folder, fail_time) error_bn = self.Error_BN(model_folder, data_path, year) error_ci = self.Error_CI(model_folder, data_path, year) solution.objectives = ([error_bn['TempRMSE'], error_bn['CondRMSE'], error_ci['TempRMSE'], error_ci['CondRMSE']]) all_objs = ([error_bn['TempRMSE'], error_bn['CondRMSE'], error_ci['TempRMSE'], error_ci['CondRMSE']]) except: print("bad model") solution.objectives = [1e9] * self.number_of_objectives all_objs = [1e9] * 4 self.write_full_outputs(solution.variables, all_objs, trial_name, year) print(solution.objectives) shutil.rmtree(model_folder) return solution