Skip to content

Commit

Permalink
Corrected design
Browse files Browse the repository at this point in the history
  • Loading branch information
LebedevIlyaG committed Apr 24, 2024
1 parent f5bfd5e commit b2cfb96
Show file tree
Hide file tree
Showing 21 changed files with 51 additions and 81 deletions.
1 change: 0 additions & 1 deletion examples/GKLS_async_example.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from iOpt.output_system.listeners.console_outputers import ConsoleOutputListener
from iOpt.output_system.listeners.static_painters import StaticPainterNDListener
from iOpt.solver import Solver
from iOpt.solver_parametrs import SolverParameters
from problems.GKLS import GKLS
Expand Down
1 change: 0 additions & 1 deletion examples/GKLS_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,3 @@

# Решение задачи
solver.solve()

1 change: 0 additions & 1 deletion examples/Genetic_algorithm/TSP/_2D/Problems/ga_tsp_2d.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import numpy as np
from iOpt.trial import Point
from iOpt.trial import FunctionValue
from iOpt.trial import Trial
from iOpt.problem import Problem
from sko.GA import GA_TSP
from typing import Dict
Expand Down
2 changes: 1 addition & 1 deletion examples/MCO_Grishagin_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

# output of the Pareto set (coordinates - function values)
var = [trial.point.float_variables for trial in sol.best_trials]
val = [[trial.function_values[i].value for i in range(2)]for trial in sol.best_trials ]
val = [[trial.function_values[i].value for i in range(2)] for trial in sol.best_trials]
print("size pareto set: ", len(var))
for fvar, fval in zip(var, val):
print(fvar, fval)
Expand Down
12 changes: 5 additions & 7 deletions examples/MCO_Test1_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,23 +29,21 @@

# вывод множества Парето (координаты - значения функций)
var = [trial.point.float_variables for trial in sol.best_trials]
val = [[trial.function_values[i].value for i in range(2)]for trial in sol.best_trials ]
val = [[trial.function_values[i].value for i in range(2)] for trial in sol.best_trials]
print("size pareto set: ", len(var))
for fvar, fval in zip(var, val):
print(fvar, fval)

# Точки для постороения графика множества Парето x[0]-x[1]
#x1 = [trial.point.float_variables[0] for trial in sol.best_trials]
#x2 = [trial.point.float_variables[1] for trial in sol.best_trials]
# x1 = [trial.point.float_variables[0] for trial in sol.best_trials]
# x2 = [trial.point.float_variables[1] for trial in sol.best_trials]

#plt.plot(x1, x2, 'ro')
#plt.show()
# plt.plot(x1, x2, 'ro')
# plt.show()

# Точки для постороения графика множества Парето y[0]-y[1]
fv1 = [trial.function_values[0].value for trial in sol.best_trials]
fv2 = [trial.function_values[1].value for trial in sol.best_trials]

plt.plot(fv1, fv2, 'ro')
plt.show()


3 changes: 1 addition & 2 deletions examples/grid_search_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
cfol = ConsoleOutputListener(mode='full')
solver2.add_listener(cfol)


solver2.load_progress(log)

solver2.release_all_listener()
solver2.release_all_listener()
1 change: 0 additions & 1 deletion iOpt/method/async_parallel_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from iOpt.evolvent.evolvent import Evolvent
from iOpt.method.async_calculator import AsyncCalculator
from iOpt.method.index_method_evaluate import IndexMethodEvaluate
from iOpt.method.listener import Listener
from iOpt.method.method import Method
from iOpt.method.optim_task import OptimizationTask
Expand Down
8 changes: 2 additions & 6 deletions iOpt/method/calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,8 @@ def __init__(self,
self.parameters = parameters
Calculator.worker_init(self.evaluate_method)
self.pool = ProcessPool(parameters.number_of_parallel_points,
initializer=Calculator.worker_init,
initargs=(self.evaluate_method,))


initializer=Calculator.worker_init,
initargs=(self.evaluate_method,))

@staticmethod
def worker_init(evaluate_method: ICriterionEvaluateMethod):
Expand All @@ -45,7 +43,6 @@ def worker_init(evaluate_method: ICriterionEvaluateMethod):
"""
Calculator.evaluate_method = evaluate_method


@staticmethod
def worker(point: SearchDataItem) -> SearchDataItem:
r"""
Expand All @@ -60,7 +57,6 @@ def worker(point: SearchDataItem) -> SearchDataItem:
point.set_index(-10)
return point


def calculate_functionals_for_items(self, points: list[SearchDataItem]) -> list[SearchDataItem]:
r"""
Сalculation method for multiple points
Expand Down
4 changes: 1 addition & 3 deletions iOpt/method/default_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import sys


class DefaultCalculator:
def __init__(self,
evaluate_method: ICriterionEvaluateMethod,
Expand All @@ -20,8 +21,6 @@ def __init__(self,
self.evaluate_method = evaluate_method
self.parameters = parameters



def calculate_functionals_for_items(self, points: list[SearchDataItem]) -> list[SearchDataItem]:
r"""
Метод проведения испытаний для множества точек
Expand All @@ -36,4 +35,3 @@ def calculate_functionals_for_items(self, points: list[SearchDataItem]) -> list[
point.set_index(-10)

return points

8 changes: 0 additions & 8 deletions iOpt/method/grid_search_method.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
from __future__ import annotations

import copy
import math
import sys
from typing import Tuple
import numpy as np

from iOpt.evolvent.evolvent import Evolvent
Expand All @@ -12,10 +8,6 @@
from iOpt.method.search_data import SearchDataItem
from iOpt.solver_parametrs import SolverParameters
from iOpt.method.method import Method
from iOpt.trial import FunctionValue, FunctionType
from iOpt.method.calculator import Calculator

from iOpt.trial import Point, FunctionValue


class GridSearchMethod(Method):
Expand Down
2 changes: 0 additions & 2 deletions iOpt/method/index_method.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import math
import sys

import numpy as np

Expand All @@ -12,7 +11,6 @@
from iOpt.method.search_data import SearchDataItem
from iOpt.solver_parametrs import SolverParameters
from iOpt.method.method import Method
from iOpt.trial import FunctionValue, FunctionType


class IndexMethod(Method):
Expand Down
3 changes: 2 additions & 1 deletion iOpt/method/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from iOpt.method.method import Method
import numpy as np


class Listener:
"""
Event listener base class
Expand All @@ -11,7 +12,7 @@ class Listener:
def before_method_start(self, method: Method):
pass

def on_end_iteration(self, curr_points : np.ndarray(shape=(1), dtype=SearchDataItem), solution: Solution):
def on_end_iteration(self, curr_points: np.ndarray(shape=(1), dtype=SearchDataItem), solution: Solution):
pass

def on_method_stop(self, search_data: SearchData, solution: Solution, status: bool):
Expand Down
41 changes: 16 additions & 25 deletions iOpt/method/mco_method.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from typing import Tuple

import sys

import numpy as np

from enum import Enum
Expand All @@ -14,11 +12,13 @@
from iOpt.trial import FunctionValue, FunctionType, Trial
from iOpt.method.optim_task import TypeOfCalculation


class TypeOfParetoRelation(Enum):
DOMINANT = 1
NONCOMPARABLE = 0
NONDOMINATED = -1


class MCOMethod(MixedIntegerMethod):
"""
The MCOMethod class contains an implementation of the Global Search Algorithm for multi-criteria problems
Expand All @@ -34,7 +34,6 @@ def __init__(self,
self.is_recalc_all_convolution = True
self.max_iter_for_convolution = 0


def set_max_iter_for_convolution(self, max_iter_for_convolution) -> None:
self.max_iter_for_convolution = max_iter_for_convolution

Expand All @@ -52,7 +51,7 @@ def recalc_all_convolution(self) -> None:
if self.best:
self.task.calculate(self.best, -1, TypeOfCalculation.CONVOLUTION)
for item in self.search_data:
if(item.get_z()<self.best.get_z() and item.get_z()>0 and item.get_index()>=self.best.get_index()):
if self.best.get_z() > item.get_z() > 0 and item.get_index() >= self.best.get_index():
self.best = item

self.is_recalc_all_convolution = False
Expand All @@ -69,29 +68,27 @@ def calculate_iteration_point(self) -> Tuple[SearchDataItem, SearchDataItem]: #

return super(MCOMethod, self).calculate_iteration_point()


def update_optimum(self, point: SearchDataItem) -> None:
r"""
Updates the estimate of the optimum.
:param point: new trial point.
"""
if self.best is None or self.best.get_index() < point.get_index() or (
self.best.get_index() == point.get_index() and point.get_z() < self.best.get_z()):
self.best.get_index() == point.get_index() and point.get_z() < self.best.get_z()):
self.best = point
self.recalcR = True
self.Z[point.get_index()] = point.get_z()

if not (self.search_data.solution.best_trials[0].point):
if not self.search_data.solution.best_trials[0].point:
self.search_data.solution.best_trials[0] = self.best


if (point.get_index() == self.task.problem.number_of_constraints):
if point.get_index() == self.task.problem.number_of_constraints:
self.update_min_max_value(point)
self.pareto_set_update(point)

def pareto_set_update(self, point: SearchDataItem) -> None:
if (self.search_data.get_count() == 0):
if self.search_data.get_count() == 0:
return

pareto_set: np.ndarray(shape=(1), dtype=Trial) = []
Expand All @@ -101,42 +98,42 @@ def pareto_set_update(self, point: SearchDataItem) -> None:
for trial in self.search_data.solution.best_trials:
old_point = trial.function_values
relation = self.type_of_pareto_relation(new_point, old_point)
if (relation == TypeOfParetoRelation.NONCOMPARABLE):
if relation == TypeOfParetoRelation.NONCOMPARABLE:
add_point = True
pareto_set = np.append(pareto_set, trial)
elif (relation == TypeOfParetoRelation.DOMINANT):
elif relation == TypeOfParetoRelation.DOMINANT:
add_point = True
elif (relation == TypeOfParetoRelation.NONDOMINATED):
elif relation == TypeOfParetoRelation.NONDOMINATED:
add_point = False
break
if add_point:
pareto_set = np.append(pareto_set, Trial(point.point, point.function_values))
self.search_data.solution.best_trials = pareto_set
# if we don't add a point, then the pareto set doesn't change.


def type_of_pareto_relation(self, p1: np.ndarray(shape=(1), dtype=FunctionValue),
p2: np.ndarray(shape=(1), dtype=FunctionValue)) -> TypeOfParetoRelation:
count_dom = 0
count_equal = 0
number_of_objectives = self.task.problem.number_of_objectives
for i in range(number_of_objectives):
if (p1[i].value<p2[i].value):
if p1[i].value < p2[i].value:
count_dom += 1
elif (p1[i].value == p2[i].value):
elif p1[i].value == p2[i].value:
count_equal += 1
if count_dom == 0:
return TypeOfParetoRelation.NONDOMINATED
elif (count_dom + count_equal) == number_of_objectives:
return TypeOfParetoRelation.DOMINANT
else:
return TypeOfParetoRelation.NONCOMPARABLE

def update_min_max_value(self,
data_item: SearchDataItem):
data_item: SearchDataItem):
# If the minimum and maximum values have not yet been changed after initialization
if (self.task.min_value[0]==self.task.max_value[0] and self.task.min_value[0]==0):
if self.task.min_value[0] == self.task.max_value[0] and self.task.min_value[0] == 0:
# if the search information has been uploaded
if (self.search_data.get_count()>0):
if self.search_data.get_count() > 0:
self.task.min_value = [fv.value for fv in self.search_data.get_last_item().function_values]
self.task.max_value = [fv.value for fv in self.search_data.get_last_item().function_values]
for trial in self.search_data:
Expand Down Expand Up @@ -224,9 +221,3 @@ def calculate_m(self, curr_point: SearchDataItem, left_point: SearchDataItem) ->
if m > self.M[index] or (self.M[index] == 1.0 and m > 1e-12):
self.M[index] = m
self.recalcR = True






8 changes: 4 additions & 4 deletions iOpt/method/mco_method_evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ def calculate_functionals(self, point: SearchDataItem) -> SearchDataItem:
return point

for i in range(self.task.problem.number_of_objectives):
point.function_values[number_of_constraints+i] = FunctionValue(FunctionType.OBJECTIV, i)
point = self.task.calculate(point, number_of_constraints+i)
point.function_values[number_of_constraints + i] = FunctionValue(FunctionType.OBJECTIV, i)
point = self.task.calculate(point, number_of_constraints + i)

point = self.task.calculate(point, -1, TypeOfCalculation.CONVOLUTION)
point.set_index(number_of_constraints)
Expand All @@ -57,9 +57,9 @@ def copy_functionals(self, dist_point: SearchDataItem, src_point: SearchDataItem
dist_point = self.task.calculate(dist_point, -1, TypeOfCalculation.CONVOLUTION)

def update_min_max_value(self,
data_item: SearchDataItem):
data_item: SearchDataItem):
# If the minimum and maximum values have not yet been changed after initialization
if (self.task.min_value[0] == self.task.max_value[0] and self.task.min_value[0] == 0):
if self.task.min_value[0] == self.task.max_value[0] and self.task.min_value[0] == 0:
self.task.min_value = [fv.value for fv in data_item.function_values]
self.task.max_value = [fv.value for fv in data_item.function_values]
else:
Expand Down
9 changes: 5 additions & 4 deletions iOpt/method/mco_method_many_lambdas.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ def __init__(self,
calculator: Calculator
):
super().__init__(parameters, task, evolvent, search_data, calculator)
self.current_lambdas = None
self.is_recalc_all_convolution = True
self.max_iter_for_convolution = 0
self.number_of_lambdas = parameters.number_of_lambdas
Expand Down Expand Up @@ -58,7 +59,7 @@ def change_lambdas(self) -> None:
def init_lambdas(self) -> None:
if self.task.problem.number_of_objectives == 2:
if self.number_of_lambdas > 1:
h = 1.0/(self.number_of_lambdas-1)
h = 1.0 / (self.number_of_lambdas - 1)
else:
h = 1
if not self.start_lambdas:
Expand All @@ -75,13 +76,13 @@ def init_lambdas(self) -> None:
elif len(self.start_lambdas) == 1:
self.lambdas_list.append(self.start_lambdas[0])
for i in range(1, self.number_of_lambdas):
lambda_0 = self.start_lambdas[0][0] + i*h
lambda_0 = self.start_lambdas[0][0] + i * h
if lambda_0 > 1:
lambda_0 = lambda_0 - 1
lambda_1 = 1 - lambda_0
lambdas = [lambda_0, lambda_1]
self.lambdas_list.append(lambdas)
else: # многомерный случай
else: # многомерный случай
if len(self.start_lambdas) == self.number_of_lambdas:
for i in range(self.number_of_lambdas):
self.lambdas_list.append(self.start_lambdas[i])
Expand All @@ -107,4 +108,4 @@ def init_lambdas(self) -> None:

self.current_lambdas = self.lambdas_list[0]
self.max_iter_for_convolution = \
int(self.parameters.global_method_iteration_count / self.number_of_lambdas)
int(self.parameters.global_method_iteration_count / self.number_of_lambdas)
2 changes: 1 addition & 1 deletion iOpt/method/mco_optim_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ def __init__(self,
self.is_scaling = is_scaling
super().__init__(problem, lambda_param)


def calculate_convolution(self,
data_item: SearchDataItem,
min_value: np.ndarray(shape=(1), dtype=np.double) = [],
Expand All @@ -66,6 +65,7 @@ def calculate_convolution(self,
data_item.set_z(value)
return data_item


class MCOOptimizationTask(OptimizationTask):
def __init__(self,
problem: Problem,
Expand Down
Loading

0 comments on commit b2cfb96

Please sign in to comment.