Added ways to get uniformly distributed points #4
64 errors
Black found 64 errors
Annotations
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/validators.py#L1-L61
import pandas as pd
import numpy as np
class ValidationError(Exception):
- """Raised when an error related to the validation is encountered.
- """
+ """Raised when an error related to the validation is encountered."""
-def validate_ref_point_with_ideal_and_nadir(
- dimensions_data: pd.DataFrame, reference_point: pd.DataFrame
-):
+def validate_ref_point_with_ideal_and_nadir(dimensions_data: pd.DataFrame, reference_point: pd.DataFrame):
validate_ref_point_dimensions(dimensions_data, reference_point)
validate_ref_point_data_type(reference_point)
validate_ref_point_with_ideal(dimensions_data, reference_point)
validate_with_ref_point_nadir(dimensions_data, reference_point)
-def validate_ref_point_with_ideal(
- dimensions_data: pd.DataFrame, reference_point: pd.DataFrame
-):
+def validate_ref_point_with_ideal(dimensions_data: pd.DataFrame, reference_point: pd.DataFrame):
validate_ref_point_dimensions(dimensions_data, reference_point)
ideal_fitness = dimensions_data.loc["ideal"] * dimensions_data.loc["minimize"]
ref_point_fitness = reference_point * dimensions_data.loc["minimize"]
if not (ideal_fitness <= ref_point_fitness).all(axis=None):
- problematic_columns = ideal_fitness.index[
- (ideal_fitness > ref_point_fitness).values.tolist()[0]
- ].values
+ problematic_columns = ideal_fitness.index[(ideal_fitness > ref_point_fitness).values.tolist()[0]].values
msg = (
f"Reference point should be worse than or equal to the ideal point\n"
f"The following columns have problematic values: {problematic_columns}"
)
raise ValidationError(msg)
-def validate_with_ref_point_nadir(
- dimensions_data: pd.DataFrame, reference_point: pd.DataFrame
-):
+def validate_with_ref_point_nadir(dimensions_data: pd.DataFrame, reference_point: pd.DataFrame):
validate_ref_point_dimensions(dimensions_data, reference_point)
nadir_fitness = dimensions_data.loc["nadir"] * dimensions_data.loc["minimize"]
ref_point_fitness = reference_point * dimensions_data.loc["minimize"]
if not (ref_point_fitness <= nadir_fitness).all(axis=None):
- problematic_columns = nadir_fitness.index[
- (nadir_fitness < ref_point_fitness).values.tolist()[0]
- ].values
+ problematic_columns = nadir_fitness.index[(nadir_fitness < ref_point_fitness).values.tolist()[0]].values
msg = (
f"Reference point should be better than or equal to the nadir point\n"
f"The following columns have problematic values: {problematic_columns}"
)
raise ValidationError(msg)
-def validate_ref_point_dimensions(
- dimensions_data: pd.DataFrame, reference_point: pd.DataFrame
-):
+def validate_ref_point_dimensions(dimensions_data: pd.DataFrame, reference_point: pd.DataFrame):
if not dimensions_data.shape[1] == reference_point.shape[1]:
msg = (
f"There is a mismatch in the number of columns of the dataframes.\n"
f"Columns in dimensions data: {dimensions_data.columns}\n"
f"Columns in the reference point provided: {reference_point.columns}"
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/validators.py#L70-L84
def validate_ref_point_data_type(reference_point: pd.DataFrame):
for dtype in reference_point.dtypes:
if not pd.api.types.is_numeric_dtype(dtype):
- msg = (
- f"Type of data in reference point dataframe should be numeric.\n"
- f"Provided datatype: {dtype}"
- )
+ msg = f"Type of data in reference point dataframe should be numeric.\n" f"Provided datatype: {dtype}"
raise ValidationError(msg)
def validate_specified_solutions(indices: np.ndarray, n_solutions: int) -> None:
"""Validate the Decision maker's choice of preferred/non-preferred solutions.
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/validators.py#L94-L117
if indices.shape[0] < 1:
raise ValidationError("Please specify at least one (non-)preferred solution.")
if not isinstance(indices, (np.ndarray, list)):
raise ValidationError(
- "Please specify index/indices of (non-)preferred solutions in a list, even if there is only "
- "one."
+ "Please specify index/indices of (non-)preferred solutions in a list, even if there is only " "one."
)
if not all(0 <= i <= (n_solutions - 1) for i in indices):
msg = "indices of (non-)preferred solutions should be between 0 and {}. Current indices are {}.".format(
n_solutions - 1, indices
)
raise ValidationError(msg)
-def validate_bounds(
- dimensions_data: pd.DataFrame, bounds: np.ndarray, n_objectives: int
-) -> None:
+def validate_bounds(dimensions_data: pd.DataFrame, bounds: np.ndarray, n_objectives: int) -> None:
"""Validate the Decision maker's desired lower and upper bounds for objective values.
Args:
dimensions_data (pd.DataFrame): DataFrame including information whether an objective is minimized or
maximized, for each objective. In addition, includes ideal and nadir vectors.
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/validators.py#L122-L140
Raises:
ValidationError: In case desired bounds are invalid.
"""
if not isinstance(bounds, np.ndarray):
- msg = "Please specify bounds as a numpy array. Current type: {}.".format(
- type(bounds)
- )
+ msg = "Please specify bounds as a numpy array. Current type: {}.".format(type(bounds))
raise ValidationError(msg)
if len(bounds) != n_objectives:
- msg = "Length of 'bounds' ({}) must be the same as number of objectives ({}).".format(
- len(bounds), n_objectives
- )
+ msg = "Length of 'bounds' ({}) must be the same as number of objectives ({}).".format(len(bounds), n_objectives)
raise ValidationError(msg)
if not all(isinstance(b, (np.ndarray, list)) for b in bounds):
print(type(bounds[0]))
msg = "Please give bounds for each objective in a list."
raise ValidationError(msg)
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/validators.py#L144-L157
msg = "Lower bound cannot be greater than upper bound. Please specify lower bound first, then upper bound."
raise ValidationError(msg)
# check that bounds are within ideal and nadir points for each objective
for i, b in enumerate(bounds):
- if (
- dimensions_data.loc["minimize"].values.tolist()[i] == 1
- ): # minimized objectives
+ if dimensions_data.loc["minimize"].values.tolist()[i] == 1: # minimized objectives
if dimensions_data.loc["ideal"].values.tolist()[i] is not None:
if b[0] < dimensions_data.loc["ideal"].values.tolist()[i]:
msg = "Lower bound cannot be lower than ideal value for objective. Ideal vector: {}.".format(
dimensions_data.loc["ideal"].values.tolist()
)
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L11-L23
from typing import Type, List, Union, Dict
class PreferenceIncorporatedSpaceError(Exception):
- """Raised when an error related to the preference incorporated space is encountered.
- """
+ """Raised when an error related to the preference incorporated space is encountered."""
class PreferenceIncorporatedSpace:
def __init__(
self,
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L45-L75
if utopian is not None:
self.utopian = utopian
if nadir is not None:
self.nadir = nadir
- self.initialized_scalarizers = [
- scalarizer(utopian=utopian, nadir=nadir, rho=rho)
- for scalarizer in scalarizers
- ]
+ self.initialized_scalarizers = [scalarizer(utopian=utopian, nadir=nadir, rho=rho) for scalarizer in scalarizers]
self.has_additional_constraints = False
self.constrained_scalarizers = []
for scalarizer in self.initialized_scalarizers:
# self.required_keys = scalarizer.required_keys.keys()
self.constrained_scalarizers.append(scalarizer.has_additional_constraints)
- self.has_additional_constraints = (
- self.has_additional_constraints or scalarizer.has_additional_constraints
- )
+ self.has_additional_constraints = self.has_additional_constraints or scalarizer.has_additional_constraints
def __call__(self, objective_vector: np.ndarray):
- mapped_vectors = np.zeros(
- (len(objective_vector), len(self.initialized_scalarizers))
- )
+ mapped_vectors = np.zeros((len(objective_vector), len(self.initialized_scalarizers)))
for i, scalarizer in enumerate(self.initialized_scalarizers):
mapped_vectors[:, i] = scalarizer(objective_vector, self.preferences[i])
return mapped_vectors
def evaluate_constraints(self, objective_vector: np.ndarray):
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L81-L94
if not has_constraints:
continue
constraints = np.hstack(
(
constraints,
- scalarizer.evaluate_constraints(
- objective_vector, self.preferences[i]
- ),
+ scalarizer.evaluate_constraints(objective_vector, self.preferences[i]),
)
)
class classificationPIS:
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L132-L182
self.nadir = nadir
self.nimbus = NIMBUS_GLIDE(utopian=utopian, nadir=nadir)
self.nimbus_copycat = reference_point_method_GLIDE(utopian=utopian, nadir=nadir)
- self.initialized_scalarizers = [
- scalarizer(utopian=utopian, nadir=nadir, rho=rho)
- for scalarizer in scalarizers
- ]
+ self.initialized_scalarizers = [scalarizer(utopian=utopian, nadir=nadir, rho=rho) for scalarizer in scalarizers]
self.has_additional_constraints = False
def update_preference(self, preference: dict):
-
self.preference = preference
if "classifications" in preference.keys():
self.classification_preference = preference
- self.RP_preference = classification_to_reference_point(
- preference, ideal=self.utopian, nadir=self.nadir
- )
+ self.RP_preference = classification_to_reference_point(preference, ideal=self.utopian, nadir=self.nadir)
else:
- raise PreferenceIncorporatedSpaceError(
- "Classification preference expected."
- )
+ raise PreferenceIncorporatedSpaceError("Classification preference expected.")
def __call__(self, objective_vector: np.ndarray):
-
# IOPIS/NIMBUS logic
- nimbus_obj = self.nimbus(
- objective_vector=objective_vector, preference=self.classification_preference
- )
- nimbus_constraint = self.nimbus.evaluate_constraints(
- objective_vector, self.classification_preference
- )
+ nimbus_obj = self.nimbus(objective_vector=objective_vector, preference=self.classification_preference)
+ nimbus_constraint = self.nimbus.evaluate_constraints(objective_vector, self.classification_preference)
feasible = np.all(nimbus_constraint > 0, axis=1)
if not feasible.any():
nimbus_optimal = objective_vector[nimbus_constraint.max(axis=1).argmax()]
else:
nimbus_obj[~feasible] = np.inf
nimbus_optimal = objective_vector[nimbus_obj.argmin()]
# IOPIS mapping
- mapped_vectors = np.zeros(
- (len(objective_vector), len(self.initialized_scalarizers) + 1)
- )
+ mapped_vectors = np.zeros((len(objective_vector), len(self.initialized_scalarizers) + 1))
mapped_vectors[:, 0] = self.nimbus_copycat(
objective_vector=objective_vector,
preference={"reference point": nimbus_optimal},
)
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L192-L205
num_DM: int = 2,
scalarizer: Type[GLIDEBase] = AUG_STOM_GLIDE,
nadir: np.ndarray = None,
rho: float = 1e-6,
):
- super().__init__(
- scalarizers=[scalarizer] * num_DM, utopian=utopian, nadir=nadir, rho=rho
- )
+ super().__init__(scalarizers=[scalarizer] * num_DM, utopian=utopian, nadir=nadir, rho=rho)
def update_preference(self, preference: List[Dict]):
self.preferences = preference
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/request.py#L215-L243
f"Mismatch in column names of data and dimensions_data.\n"
f"Column names in data: {data.columns}"
f"Column names in dimensions_data: {dimensions_data.columns}"
)
raise RequestError(msg)
- rouge_indices = [
- index
- for index in dimensions_data.index
- if index not in acceptable_dimensions_data_indices
- ]
+ rouge_indices = [index for index in dimensions_data.index if index not in acceptable_dimensions_data_indices]
if rouge_indices:
msg = (
f"dimensions_data should only contain the following indices:\n"
f"{acceptable_dimensions_data_indices}\n"
f"The dataframe provided contains the following unsupported indices:\n"
f"{rouge_indices}"
)
raise RequestError(msg)
if not isinstance(chart_title, (str, type(None))):
- msg = (
- f"Chart title should be a string. Provided chart type is:"
- f"{type(chart_title)}"
- )
+ msg = f"Chart title should be a string. Provided chart type is:" f"{type(chart_title)}"
raise RequestError(msg)
if not isinstance(message, str):
if not isinstance(message, list):
msg = (
f"Message/s to be printed should be string or list of strings"
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/request.py#L324-L339
msg = (
f"Dimensional data should be in a pandas dataframe.\n"
f"Provided data is of type: {type(dimensions_data)}"
)
raise RequestError(msg)
- rouge_indices = [
- index
- for index in dimensions_data.index
- if index not in acceptable_dimensions_data_indices
- ]
+ rouge_indices = [index for index in dimensions_data.index if index not in acceptable_dimensions_data_indices]
if rouge_indices:
msg = (
f"dimensions_data should only contain the following indices:\n"
f"{acceptable_dimensions_data_indices}\n"
f"The dataframe provided contains the following unsupported indices:\n"
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/request.py#L375-L388
RequestError: If reference point is not provided in a pandas DataFrame.
"""
if not isinstance(value, pd.DataFrame):
msg = "Reference should be provided in a pandas dataframe format"
raise RequestError(msg)
- self.content["validator"](
- reference_point=value, dimensions_data=self.content["dimensions_data"]
- )
+ self.content["validator"](reference_point=value, dimensions_data=self.content["dimensions_data"])
self._response = value
class PreferredSolutionPreference(BaseRequest):
"""Methods can use this class to ask the Decision maker to provide their preferences
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/EpsilonConstraintMethod.py#L4-L16
from desdeo_tools.solver.ScalarSolver import ScalarMinimizer
from typing import Optional, Callable, Union
class ECMError(Exception):
- """Raised when an error related to the Epsilon Constraint Method is encountered.
- """
+ """Raised when an error related to the Epsilon Constraint Method is encountered."""
class EpsilonConstraintMethod:
"""A class to represent a class for scalarizing MOO problems using the epsilon
constraint method.
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/EpsilonConstraintMethod.py#L61-L86
if ival != self._to_be_minimized
]
)
if len(epsilon_left_side) != len(self.epsilons):
- msg = (
- "The lenght of the epsilons array ({}) must match the total number of objectives - 1 ({})."
- ).format(len(self.epsilons), len(self.objectives(xs)) - 1)
+ msg = ("The lenght of the epsilons array ({}) must match the total number of objectives - 1 ({}).").format(
+ len(self.epsilons), len(self.objectives(xs)) - 1
+ )
raise ECMError(msg)
# evaluate values of epsilon constraint functions
- e: np.ndarray = np.array(
- [-(f - v) for f, v in zip(epsilon_left_side, self.epsilons)]
- )
+ e: np.ndarray = np.array([-(f - v) for f, v in zip(epsilon_left_side, self.epsilons)])
if self.constraints(xs) is not None:
c = self.constraints(xs)
- return np.concatenate(
- [c, e], axis=None
- ) # does it work with multiple constraints?
+ return np.concatenate([c, e], axis=None) # does it work with multiple constraints?
else:
return e
def __call__(self, objective_vector: np.ndarray) -> Union[float, np.ndarray]:
"""
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/EpsilonConstraintMethod.py#L90-L119
Returns:
Value of objective function to be minimized.
"""
if np.shape(objective_vector)[0] > 1: # more rows than one
- return np.array(
- [
- objective_vector[i][self._to_be_minimized]
- for i, _ in enumerate(objective_vector)
- ]
- )
+ return np.array([objective_vector[i][self._to_be_minimized] for i, _ in enumerate(objective_vector)])
else:
return objective_vector[0][self._to_be_minimized]
# Testing the method
if __name__ == "__main__":
# 1. Define objective functions, bounds and constraints
def volume(r, h):
- return np.pi * r ** 2 * h
+ return np.pi * r**2 * h
def area(r, h):
- return 2 * np.pi ** 2 + np.pi * r * h
+ return 2 * np.pi**2 + np.pi * r * h
# add third objective
def weight(v):
return 0.01 * v
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/EpsilonConstraintMethod.py#L146-L159
# index of which objective function to minimize
obj_min = 2
# set upper bound(s) for the other objectives, in the same order than which corresponding objective functions
# are defined
- epsil = np.array(
- [2000, -100]
- ) # multiply the epsilons with -1, if the constraint is of form f_i(x) >= e_i
+ epsil = np.array([2000, -100]) # multiply the epsilons with -1, if the constraint is of form f_i(x) >= e_i
# create an instance of EpsilonConstraintMethod-class for given problem
eps = EpsilonConstraintMethod(objective, obj_min, epsil, constraints=con_golden)
# constraint evaluator, used by the solver
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/EpsilonConstraintMethod.py#L164-L185
# 3. Solve
# starting point
x0 = np.array([2, 11])
- minimizer = ScalarMinimizer(
- scalarized_objective, bounds, constraint_evaluator=cons_evaluate, method=None
- )
+ minimizer = ScalarMinimizer(scalarized_objective, bounds, constraint_evaluator=cons_evaluate, method=None)
# minimize
res = minimizer.minimize(x0)
final_r, final_h = res["x"][0], res["x"][1]
final_obj = objective(res["x"]).squeeze()
final_V, final_A, final_W = final_obj[0], final_obj[1], final_obj[2]
print(f"Final cake specs: radius: {final_r}cm, height: {final_h}cm.")
- print(
- f"Final cake dimensions: volume: {final_V}, area: {-final_A}, weight: {final_W}."
- )
+ print(f"Final cake dimensions: volume: {final_V}, area: {-final_A}, weight: {final_W}.")
print(final_r / final_h)
print(res)
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/ASF.py#L14-L27
Instances of the implementations of this class should function as
function.
"""
@abstractmethod
- def __call__(
- self, objective_vector: np.ndarray, reference_point: np.ndarray
- ) -> Union[float, np.ndarray]:
+ def __call__(self, objective_vector: np.ndarray, reference_point: np.ndarray) -> Union[float, np.ndarray]:
"""Evaluate the ASF.
Args:
objective_vectors (np.ndarray): The objective vectors to calculate
the values.
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/ASF.py#L53-L66
"""
def __init__(self, weights: np.ndarray):
self.weights = weights
- def __call__(
- self, objective_vector: np.ndarray, reference_point: np.ndarray
- ) -> Union[float, np.ndarray]:
+ def __call__(self, objective_vector: np.ndarray, reference_point: np.ndarray) -> Union[float, np.ndarray]:
"""Evaluate the simple order-representing ASF.
Args:
objective_vector (np.ndarray): A vector representing a solution in
the solution space.
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/ASF.py#L118-L131
self.preferential_factors = preferential_factors
self.nadir = nadir
self.utopian_point = utopian_point
self.rho = rho
- def __call__(
- self, objective_vector: np.ndarray, reference_point: np.ndarray
- ) -> Union[float, np.ndarray]:
+ def __call__(self, objective_vector: np.ndarray, reference_point: np.ndarray) -> Union[float, np.ndarray]:
mu = self.preferential_factors
f = objective_vector
q = reference_point
rho = self.rho
z_nad = self.nadir
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/ASF.py#L181-L194
self.lt_inds = lt_inds
self.lte_inds = lte_inds
self.rho = rho
self.rho_sum = rho_sum
- def __call__(
- self, objective_vector: np.ndarray, reference_point: np.ndarray
- ) -> Union[float, np.ndarray]:
+ def __call__(self, objective_vector: np.ndarray, reference_point: np.ndarray) -> Union[float, np.ndarray]:
# assure this function works with single objective vectors
if objective_vector.ndim == 1:
f = objective_vector.reshape((1, -1))
else:
f = objective_vector
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/ASF.py#L231-L244
def __init__(self, ideal: np.ndarray, rho: float = 1e-6, rho_sum: float = 1e-6):
self.ideal = ideal
self.rho = rho
self.rho_sum = rho_sum
- def __call__(
- self, objective_vectors: np.ndarray, reference_point: np.ndarray
- ) -> Union[float, np.ndarray]:
+ def __call__(self, objective_vectors: np.ndarray, reference_point: np.ndarray) -> Union[float, np.ndarray]:
# assure this function works with single objective vectors
if objective_vectors.ndim == 1:
f = objective_vectors.reshape((1, -1))
else:
f = objective_vectors
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/ASF.py#L346-L366
nad = self.nadir
uto = self.ideal - self.rho
ex_mask = np.full((f.shape[1]), True, dtype=bool)
ex_mask[self.index_to_exclude] = False
- max_term = np.max(
- (f[:, ex_mask] - nad[ex_mask]) / (nad[ex_mask] - z[ex_mask]), axis=1
- )
- sum_term_1 = self.rho_sum * np.sum(
- (f[:, ex_mask]) / (nad[ex_mask] - z[ex_mask]), axis=1
- )
+ max_term = np.max((f[:, ex_mask] - nad[ex_mask]) / (nad[ex_mask] - z[ex_mask]), axis=1)
+ sum_term_1 = self.rho_sum * np.sum((f[:, ex_mask]) / (nad[ex_mask] - z[ex_mask]), axis=1)
# avoid division by zeros
- sum_term_2 = self.rho_sum * np.sum(
- (f[:, ~ex_mask]) / (nad[~ex_mask] - uto[~ex_mask]), axis=1
- )
+ sum_term_2 = self.rho_sum * np.sum((f[:, ~ex_mask]) / (nad[~ex_mask] - uto[~ex_mask]), axis=1)
return max_term + sum_term_1 + sum_term_2
class GuessASF(ASFBase):
github-actions / Black
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/MOEADSF.py#L4-L16
from abc import abstractmethod
from typing import Union
class MOEADSFError(Exception):
- """Raised when an error related to the MOEADSF classes is encountered.
- """
+ """Raised when an error related to the MOEADSF classes is encountered."""
class MOEADSFBase(abc.ABC):
"""A base class for representing scalarizing functions for the MOEA/D algorithm.
Instances of the implementations of this class should work as function.