Merge branch 'pr/Sepuliini/49' #1
Annotations
110 errors and 2 warnings
desdeo_tools/interaction/request.py#L388
Line too long (122 > 120 characters) (E501)
|
desdeo_tools/interaction/validators.py#L98
Line too long (123 > 120 characters) (E501)
|
desdeo_tools/interaction/validators.py#L99
Continuation line under-indented for visual indent (E128)
|
desdeo_tools/maps/preference_incorporated_space_RP.py#L217
Blank line at end of file (W391)
|
desdeo_tools/scalarization/MOEADSF.py#L118
Line too long (127 > 120 characters) (E501)
|
desdeo_tools/solver/ScalarSolver.py#L1
Trailing whitespace (W291)
|
desdeo_tools/solver/ScalarSolver.py#L14
Block comment should start with '# ' (E265)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/validators.py#L1
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}"
|
desdeo_tools/solver/ScalarSolver.py#L17
Block comment should start with '# ' (E265)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/validators.py#L70
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.
|
desdeo_tools/solver/ScalarSolver.py#L79
Blank line contains whitespace (W293)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/validators.py#L93
"""
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.")
+ raise ValidationError(
+ "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)
+ 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:
"""Validate the Decision maker's desired lower and upper bounds for objective values.
|
desdeo_tools/solver/ScalarSolver.py#L81
Trailing whitespace (W291)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/validators.py#L135
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['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())
+ 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()
+ )
raise ValidationError(msg)
- if dimensions_data.loc['nadir'].values.tolist()[i] is not None:
- if b[1] > dimensions_data.loc['nadir'].values.tolist()[i]:
- msg = "Upper bound cannot be higher than nadir value for objective. Nadir vector: {}." \
- .format(dimensions_data.loc['nadir'].values.tolist())
+ if dimensions_data.loc["nadir"].values.tolist()[i] is not None:
+ if b[1] > dimensions_data.loc["nadir"].values.tolist()[i]:
+ msg = "Upper bound cannot be higher than nadir value for objective. Nadir vector: {}.".format(
+ dimensions_data.loc["nadir"].values.tolist()
+ )
raise ValidationError(msg)
else: # maximized objectives:
- if dimensions_data.loc['ideal'].values.tolist()[i] is not None:
- if b[1] > dimensions_data.loc['ideal'].values.tolist()[i]:
- msg = "Upper bound cannot be higher than ideal value for objective. Ideal vector: {}." \
- .format(dimensions_data.loc['ideal'].values.tolist())
+ if dimensions_data.loc["ideal"].values.tolist()[i] is not None:
+ if b[1] > dimensions_data.loc["ideal"].values.tolist()[i]:
+ msg = "Upper bound cannot be higher than ideal value for objective. Ideal vector: {}.".format(
+ dimensions_data.loc["ideal"].values.tolist()
+ )
raise ValidationError(msg)
- if dimensions_data.loc['nadir'].values.tolist()[i] is not None:
- if b[0] < dimensions_data.loc['nadir'].values.tolist()[i]:
- msg = "Lower bound cannot be lower than nadir value for objective. Nadir vector: {}." \
- .format(dimensions_data.loc['nadir'].values.tolist())
+ if dimensions_data.loc["nadir"].values.tolist()[i] is not None:
+ if b[0] < dimensions_data.loc["nadir"].values.tolist()[i]:
+ msg = "Lower bound cannot be lower than nadir value for objective. Nadir vector: {}.".format(
+ dimensions_data.loc["nadir"].values.tolist()
+ )
raise ValidationError(msg)
|
desdeo_tools/solver/ScalarSolver.py#L88
Blank line contains whitespace (W293)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/request.py#L10
)
from desdeo_tools.utilities.frozen import FrozenClass
class RequestError(Exception):
- """Raised when an error related to the Request class is encountered.
- """
+ """Raised when an error related to the Request class is encountered."""
class BaseRequest(FrozenClass):
"""The base class for all Request classes. Request classes are to be used
to handle interaction between the user and the methods, as well as within
|
desdeo_tools/solver/ScalarSolver.py#L94
Line too long (141 > 120 characters) (E501)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/request.py#L216
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"
|
desdeo_tools/solver/ScalarSolver.py#L95
Blank line contains whitespace (W293)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/request.py#L325
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"
|
desdeo_tools/solver/ScalarSolver.py#L100
Line too long (132 > 120 characters) (E501)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/interaction/request.py#L376
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 in form of preferred solution(s).
- """
+ """Methods can use this class to ask the Decision maker to provide their preferences in form of preferred solution(s)."""
def __init__(
self,
n_solutions: int,
message: str = None,
|
desdeo_tools/solver/ScalarSolver.py#L111
Blank line contains whitespace (W293)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L11
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,
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L45
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):
|
desdeo_tools/solver/ScalarSolver.py#L112
Too many blank lines (2) (E303)
|
desdeo_tools/solver/ScalarSolver.py#L114
Block comment should start with '# ' (E265)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L81
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:
|
desdeo_tools/solver/ScalarSolver.py#L116
Trailing whitespace (W291)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L132
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},
)
|
desdeo_tools/solver/ScalarSolver.py#L117
Trailing whitespace (W291)
|
desdeo_tools/solver/ScalarSolver.py#L119
Trailing whitespace (W291)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L192
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
|
desdeo_tools/solver/ScalarSolver.py#L122
Blank line contains whitespace (W293)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/maps/preference_incorporated_space_RP.py#L212
):
super().__init__(utopian=utopian, nadir=nadir, scalarizers=scalarizers, rho=rho)
def update_preference(self, preference: dict):
self.preferences = [preference] * self.num_scalarizers
-
|
desdeo_tools/solver/ScalarSolver.py#L127
Blank line contains whitespace (W293)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/EpsilonConstraintMethod.py#L4
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.
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/EpsilonConstraintMethod.py#L26
Remember to multiply the epsilon value with -1!
constraints (Optional[Callable]): Function that returns definitions of other constraints, if existing.
"""
def __init__(
- self, objectives: Callable, to_be_minimized: int, epsilons: np.ndarray,
- constraints: Optional[Callable]
+ self, objectives: Callable, to_be_minimized: int, epsilons: np.ndarray, constraints: Optional[Callable]
):
self.objectives = objectives
self._to_be_minimized = to_be_minimized
self.epsilons = epsilons
self.constraints = constraints
|
desdeo_tools/solver/ScalarSolver.py#L131
Unexpected spaces around keyword / parameter equals (E251)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/EpsilonConstraintMethod.py#L49
"""
xs = np.atleast_2d(xs)
# evaluate epsilon constraint function "left-side" values with given decision variables
epsilon_left_side = np.array(
- [val for nrow, row in enumerate(self.objectives(xs))
- for ival, val in enumerate(row) if ival != self._to_be_minimized
- ])
+ [
+ val
+ for nrow, row in enumerate(self.objectives(xs))
+ for ival, val in enumerate(row)
+ 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)])
|
desdeo_tools/solver/ScalarSolver.py#L132
Unexpected spaces around keyword / parameter equals (E251)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/EpsilonConstraintMethod.py#L88
# 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
|
desdeo_tools/solver/ScalarSolver.py#L132
Unexpected spaces around keyword / parameter equals (E251)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/MOEADSF.py#L4
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.
|
desdeo_tools/solver/ScalarSolver.py#L133
Unexpected spaces around keyword / parameter equals (E251)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/MOEADSF.py#L38
"""
pass
class Tchebycheff(MOEADSFBase):
- """Implements the Tchebycheff scalarizing function.
- """
+ """Implements the Tchebycheff scalarizing function."""
def __call__(
self,
objective_vector: np.ndarray,
reference_vector: np.ndarray,
|
desdeo_tools/solver/ScalarSolver.py#L133
Unexpected spaces around keyword / parameter equals (E251)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/MOEADSF.py#L62
Note:
The shaped of objective_vector and reference_vector must match.
"""
if not objective_vector.shape == reference_vector.shape:
- msg = (
- "The dimensions of the objective vector {} and "
- "reference_vector {} do not match."
- ).format(objective_vector.shape, reference_vector.shape)
+ msg = ("The dimensions of the objective vector {} and " "reference_vector {} do not match.").format(
+ objective_vector.shape, reference_vector.shape
+ )
raise MOEADSFError(msg)
feval = np.abs(objective_vector - ideal_vector) * reference_vector
max_fun = np.max(feval)
return max_fun
class WeightedSum(MOEADSFBase):
- """Implements the Weighted sum scalarization function
- """
+ """Implements the Weighted sum scalarization function"""
- def __call__(
- self, objective_vector: np.ndarray, reference_vector: np.ndarray
- ) -> Union[float, np.ndarray]:
+ def __call__(self, objective_vector: np.ndarray, reference_vector: np.ndarray) -> Union[float, np.ndarray]:
"""Evaluate the WeightedSum scalarizing function.
Args:
objective_vector (np.ndarray): A vector representing a solution in
the objective space.
|
desdeo_tools/solver/ScalarSolver.py#L134
Unexpected spaces around keyword / parameter equals (E251)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/MOEADSF.py#L94
Note:
The shaped of objective_vector and reference_vector must match. A reference point is not needed.
"""
if not objective_vector.shape == reference_vector.shape:
- msg = (
- "The dimensions of the objective vector {} and "
- "reference_vector {} do not match."
- ).format(objective_vector.shape, reference_vector.shape)
+ msg = ("The dimensions of the objective vector {} and " "reference_vector {} do not match.").format(
+ objective_vector.shape, reference_vector.shape
+ )
raise MOEADSFError(msg)
feval = np.sum(objective_vector * reference_vector)
return feval
|
desdeo_tools/solver/ScalarSolver.py#L134
Unexpected spaces around keyword / parameter equals (E251)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/MOEADSF.py#L140
Note:
The shaped of objective_vector and reference_vector must match. The reference point is not needed.
"""
if not objective_vector.shape == reference_vector.shape:
- msg = (
- "The dimensions of the objective vector {} and "
- "reference_vector {} do not match."
- ).format(objective_vector.shape, reference_vector.shape)
+ msg = ("The dimensions of the objective vector {} and " "reference_vector {} do not match.").format(
+ objective_vector.shape, reference_vector.shape
+ )
raise MOEADSFError(msg)
norm_weights = np.linalg.norm(reference_vector)
weights = np.true_divide(reference_vector, norm_weights)
fx_a = objective_vector - ideal_vector
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/Scalarizer.py#L50
res_scal = self._scalarizer(res_eval)
return res_scal
def __call__(self, xs: np.ndarray) -> np.ndarray:
- """Wrapper to the evaluate method.
- """
+ """Wrapper to the evaluate method."""
return self.evaluate(xs)
class DiscreteScalarizer:
- """Implements a class to scalarize discrete vectors given a scalarizing function.
- """
+ """Implements a class to scalarize discrete vectors given a scalarizing function."""
def __init__(self, scalarizer: Callable, scalarizer_args: Dict = None):
self._scalarizer = scalarizer
self._scalarizer_args = scalarizer_args
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/solver/ScalarSolver.py#L1
-# THIS CELL CAN BE REMOVED WHEN TOOLS AND PROBLEM REPOSITORYS
+# THIS CELL CAN BE REMOVED WHEN TOOLS AND PROBLEM REPOSITORYS
# HAVE BEEN UPDATED
"""Implements methods for solving scalar valued functions.
"""
import numpy as np
|
desdeo_tools/solver/ScalarSolver.py#L135
Unexpected spaces around keyword / parameter equals (E251)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/solver/ScalarSolver.py#L9
from typing import Callable, Dict, Optional, Union
from desdeo_tools.scalarization.Scalarizer import DiscreteScalarizer, Scalarizer
from scipy.optimize import NonlinearConstraint, differential_evolution, minimize
from desdeo_tools.scalarization.ASF import PointMethodASF
-#from desdeo_problem import variable_builder, ScalarObjective, MOProblem
-
-
-#import rbfopt
+
+# from desdeo_problem import variable_builder, ScalarObjective, MOProblem
+
+
+# import rbfopt
class ScalarSolverException(Exception):
pass
class ScalarMethod:
- """A class the define and implement methods for minimizing scalar valued functions.
- """
+ """A class the define and implement methods for minimizing scalar valued functions."""
def __init__(self, method: Callable, method_args=None, use_scipy: Optional[bool] = False):
"""
Args:
method (Callable): A callable minimizer function which expects a
|
desdeo_tools/solver/ScalarSolver.py#L135
Unexpected spaces around keyword / parameter equals (E251)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/solver/ScalarSolver.py#L74
class MixedIntegerMinimizer:
"""Implements methods for solving scalar valued functions.
-
+
Args:
- scalarized_objective (Callable): The objective function that has been scalarized
+ scalarized_objective (Callable): The objective function that has been scalarized
and ready for minimization.
problem (MOProblem): A MOProblem instance required to get variable types.
minlp_solver_path (str): The path to the bonmin solver.
"""
def __init__(self, scalarized_objective: Callable, problem, minlp_solver_path: str):
-
# Try importing rbfopt
try:
global rbfopt
import rbfopt
except ImportError:
- raise ScalarSolverException("The library 'rbfopt' is required for using MixedIntegerMinimizer. Please install it and try again.")
-
+ raise ScalarSolverException(
+ "The library 'rbfopt' is required for using MixedIntegerMinimizer. Please install it and try again."
+ )
+
self.scalarized_objective = scalarized_objective
self.problem = problem
self.lower_bounds = [var.get_bounds()[0] for var in self.problem.variables]
self.upper_bounds = [var.get_bounds()[1] for var in self.problem.variables]
- var_types = np.array(["I" if var.type.lower() in ["i", "integervariable", "integer"] else "R" for var in problem.variables])
+ var_types = np.array(
+ ["I" if var.type.lower() in ["i", "integervariable", "integer"] else "R" for var in problem.variables]
+ )
self.var_types = var_types
self.minlp_solver_path = minlp_solver_path
print("Scalarized objectives: ", self.scalarized_objective)
print(f"Problem: {self.problem}")
print(f"Lower bounds: {self.lower_bounds}")
print(f"Upper bounds: {self.upper_bounds}")
print(f"Var_types: {self.var_types}")
print(f"minlp_solver_path: {self.minlp_solver_path}")
-
def create_settings(self, max_evaluations=25, nlp_solver_path="ipopt"):
settings = rbfopt.RbfoptSettings(
#'/Users/seanjana/Desktop/Työt/project_codes/COIN_Bundle/coin.macos64.20211124/bonmin'
max_evaluations=max_evaluations,
- global_search_method="solver",
- nlp_solver_path=nlp_solver_path,
+ global_search_method="solver",
+ nlp_solver_path=nlp_solver_path,
minlp_solver_path=self.minlp_solver_path,
- print_solver_output=False
+ print_solver_output=False,
)
return settings
-
+
def evaluate_objective(self, x):
result = self.scalarized_objective(x)
print(f"Evaluating at {x}, result: {result}")
return result
-
+
def minimize(self, x0, **kwargs):
print(self.var_types)
bb = rbfopt.RbfoptUserBlackBox(
- dimension =len(self.lower_bounds),
- var_lower = self.lower_bounds,
- var_upper = self.upper_bounds,
- var_type = self.var_types,
- obj_funct = lambda x, **kwargs: scalarized_objectives(x, **kwargs)[0]
+ dimension=len(self.lower_bounds),
+ var_lower=self.lower_bounds,
+ var_upper=self.upper_bounds,
+ var_type=self.var_types,
+ obj_funct=lambda x, **kwargs: scalarized_objectives(x, **kwargs)[0],
)
-
- null_stream = open(os.devnull, 'w')
+
+ null_stream = open(os.devnull, "w")
alg = rbfopt.RbfoptAlgorithm(self.create_settings(), bb)
alg.set_output_stream(null_stream)
val, x, itercount, evalcount, fast_evalcount = alg.optimize()
null_stream.close()
-
- return {'x': x, 'fun': val, 'success': itercount > 0, 'itercount': itercount, 'evalcount': evalcount, 'fast_evalcount': fast_evalcount}
+
+ return {
+ "x": x,
+ "fun": val,
+ "success": itercount > 0,
+ "itercount": itercount,
+ "evalcount": evalcount,
+ "fast_evalcount": fast_evalcount,
+ }
class ScalarMinimizer:
"""Implements a class for minimizing scalar valued functions with bounds set for the
variables, and constraints.
|
desdeo_tools/solver/ScalarSolver.py#L135
Undefined name 'scalarized_objectives' (F821)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/solver/ScalarSolver.py#L154
self,
scalarizer: Scalarizer,
bounds: np.ndarray,
constraint_evaluator: Callable = None,
method: Optional[Union[ScalarMethod, str]] = None,
- problem = None,
- **kwargs
+ problem=None,
+ **kwargs,
):
"""
Args:
scalarizer (Scalarizer): A Scalarizer to be minimized.
bounds (np.ndarray): The bounds of the independent variables the
|
desdeo_tools/solver/ScalarSolver.py#L137
Blank line contains whitespace (W293)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/solver/ScalarSolver.py#L180
self.presets = ["scipy_minimize", "scipy_de", "MixedIntegerMinimizer"]
self._scalarizer = scalarizer
self._bounds = bounds
self.problem = problem
self._constraint_evaluator = constraint_evaluator
-
+
if method is None or method == "MixedIntegerMinimizer":
# Check if problem contains integer variables
integer_vars = any([var.type.lower() in ["i", "integervariable", "integer"] for var in problem.variables])
if integer_vars:
# Use MixedIntegerMinimizer if integer variables are found
- minlp_solver_path = kwargs.get('minlp_solver_path', None)
+ minlp_solver_path = kwargs.get("minlp_solver_path", None)
if minlp_solver_path is None:
- raise ValueError("Please provide a path to the MinLP solver via 'minlp_solver_path' keyword argument.")
+ raise ValueError(
+ "Please provide a path to the MinLP solver via 'minlp_solver_path' keyword argument."
+ )
self._use_scipy = False
- self._mixed_integer_minimizer = MixedIntegerMinimizer(self._scalarizer, problem, minlp_solver_path=minlp_solver_path)
+ self._mixed_integer_minimizer = MixedIntegerMinimizer(
+ self._scalarizer, problem, minlp_solver_path=minlp_solver_path
+ )
self._method = ScalarMethod(lambda x, _, **y: self._mixed_integer_minimizer.minimize(x, **y))
-
elif (method is None) or (method == "scipy_minimize"):
# scipy minimize
self._use_scipy = True
# Assuming the gradient reqruies evaluation of the
|
desdeo_tools/solver/ScalarSolver.py#L144
Blank line contains whitespace (W293)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/solver/ScalarSolver.py#L215
self._bounds[:, 1] -= 1e-6
scipy_de_method = ScalarMethod(
lambda x, _, **y: differential_evolution(x, **y), method_args={"polish": True}
)
self._method = scipy_de_method
-
+
else:
self._use_scipy = method._use_scipy
self._method = method
if self._use_scipy:
|
desdeo_tools/solver/ScalarSolver.py#L145
Line too long (143 > 120 characters) (E501)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/solver/ScalarSolver.py#L228
# only relevant if the 'polish' option is set in scipy's DE
self._bounds[:, 0] += 1e-6
self._bounds[:, 1] -= 1e-6
def get_presets(self):
- """Return the list of preset minimizers available.
-
- """
+ """Return the list of preset minimizers available."""
return self.get_presets
def minimize(self, x0: np.ndarray) -> Dict:
"""Minimizes the scalarizer given an initial guess x0.
|
desdeo_tools/solver/ScalarSolver.py#L159
Unexpected spaces around keyword / parameter equals (E251)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/solver/ScalarSolver.py#L263
return res
class DiscreteMinimizer:
- """Implements a class for finding the minimum value of a discrete of scalarized vectors.
- """
+ """Implements a class for finding the minimum value of a discrete of scalarized vectors."""
def __init__(
self,
discrete_scalarizer: DiscreteScalarizer,
constraint_evaluator: Optional[Callable[[np.ndarray], np.ndarray]] = None,
|
desdeo_tools/solver/ScalarSolver.py#L159
Unexpected spaces around keyword / parameter equals (E251)
|
desdeo_tools/solver/ScalarSolver.py#L185
Blank line contains whitespace (W293)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/solver/ScalarSolver.py#L318
res = self._scalarizer(tmp)
min_value = np.nanmin(res)
min_index = np.nanargmin(res)
return {"x": min_index, "fun": min_value, "success": True}
+
if __name__ == "__main__":
from desdeo_tools.scalarization.ASF import PointMethodASF
ideal = np.array([0, 0, 0, 0])
nadir = np.array([1, 1, 1, 1])
|
desdeo_tools/solver/ScalarSolver.py#L193
Line too long (123 > 120 characters) (E501)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L3
from abc import abstractmethod
from typing import Union
class GLIDEError(Exception):
- """Raised when an error related to the ASF classes is encountered.
- """
+ """Raised when an error related to the ASF classes is encountered."""
class GLIDEBase:
"""
Implements the non-differentiable variant of GLIDE-II as proposed in
|
desdeo_tools/solver/ScalarSolver.py#L195
Line too long (133 > 120 characters) (E501)
|
desdeo_tools/solver/ScalarSolver.py#L199
Too many blank lines (2) (E303)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L29
nadir (np.ndarray, optional): The nadir point. Defaults to None.
rho (float, optional): The augmentation term for the scalarization function.
Defaults to 1e-6.
"""
- def __init__(
- self,
- utopian: np.ndarray = None,
- nadir: np.ndarray = None,
- rho: float = 1e-6,
- **kwargs
- ):
-
+ def __init__(self, utopian: np.ndarray = None, nadir: np.ndarray = None, rho: float = 1e-6, **kwargs):
self.has_additional_constraints = False
self.utopian = utopian
self.nadir = nadir
self.rho = rho
self.required_keys: dict = {}
|
desdeo_tools/solver/ScalarSolver.py#L220
Blank line contains whitespace (W293)
|
desdeo_tools/solver/ScalarSolver.py#L323
Expected 2 blank lines after class or function definition, found 1 (E305)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L68
max_term = np.max(mu[:, I_alpha] * f_minus_q[:, I_alpha], axis=1)
sum_term = self.rho * np.sum(self.w * f_minus_q, axis=1)
return max_term + sum_term
- def evaluate_constraints(
- self, objective_vector: np.ndarray, preference: dict
- ) -> Union[None, np.ndarray]:
+ def evaluate_constraints(self, objective_vector: np.ndarray, preference: dict) -> Union[None, np.ndarray]:
# TODO: Description for Args & Returns are yet to be filled.
"""Evaluate the additional contraints generated by the GLIDE-II formulation.
Note:
Additional contraints produced by the GLIDE-II formulation are implemented
|
desdeo_tools/solver/ScalarSolver.py#L324
Redefinition of unused 'PointMethodASF' from line 13 (F811)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L159
nadir (np.ndarray, optional): The nadir point. Defaults to None.
rho (float, optional): The augmentation term for the scalarization function.
Defaults to 1e-6.
"""
- def __init__(
- self,
- utopian: np.ndarray = None,
- nadir: np.ndarray = None,
- rho: float = 1e-6,
- **kwargs
- ):
+ def __init__(self, utopian: np.ndarray = None, nadir: np.ndarray = None, rho: float = 1e-6, **kwargs):
super().__init__(utopian=utopian, nadir=nadir, rho=rho, **kwargs)
self.has_additional_constraints = False
- self.__I_alpha = np.full_like(
- utopian, dtype=np.bool_, fill_value=True
- ).flatten()
- self.__I_epsilon = np.full_like(
- utopian, dtype=np.bool_, fill_value=False
- ).flatten()
+ self.__I_alpha = np.full_like(utopian, dtype=np.bool_, fill_value=True).flatten()
+ self.__I_epsilon = np.full_like(utopian, dtype=np.bool_, fill_value=False).flatten()
self.__w = 1
self.__mu = 1 / (nadir - utopian)
self.required_keys = {
"reference point": (
"Used to calculate the direction of improvement: "
|
desdeo_tools/utilities/polytopes.py#L58
Missing whitespace after ',' (E231)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L237
nadir (np.ndarray, optional): The nadir point. Defaults to None.
rho (float, optional): The augmentation term for the scalarization function.
Defaults to 1e-6.
"""
- def __init__(
- self,
- utopian: np.ndarray = None,
- nadir: np.ndarray = None,
- rho: float = 1e-6,
- **kwargs
- ):
+ def __init__(self, utopian: np.ndarray = None, nadir: np.ndarray = None, rho: float = 1e-6, **kwargs):
super().__init__(utopian=utopian, nadir=nadir, rho=rho, **kwargs)
self.has_additional_constraints = False
- self.__I_alpha = np.full_like(
- utopian, dtype=np.bool_, fill_value=True
- ).flatten()
- self.__I_epsilon = np.full_like(
- utopian, dtype=np.bool_, fill_value=False
- ).flatten()
+ self.__I_alpha = np.full_like(utopian, dtype=np.bool_, fill_value=True).flatten()
+ self.__I_epsilon = np.full_like(utopian, dtype=np.bool_, fill_value=False).flatten()
self.__w = 0
self.required_keys = {
"reference point": (
"Used to calculate the direction of improvement: "
"a line going from the nadir point to the reference point. "
|
desdeo_tools/utilities/polytopes.py#L59
Missing whitespace after ',' (E231)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L313
nadir (np.ndarray, optional): The nadir point. Defaults to None.
rho (float, optional): The augmentation term for the scalarization function.
Defaults to 1e-6.
"""
- def __init__(
- self,
- utopian: np.ndarray = None,
- nadir: np.ndarray = None,
- rho: float = 1e-6,
- **kwargs
- ):
+ def __init__(self, utopian: np.ndarray = None, nadir: np.ndarray = None, rho: float = 1e-6, **kwargs):
super().__init__(utopian=utopian, nadir=nadir, rho=rho, **kwargs)
self.__w = 1
class NIMBUS_GLIDE(GLIDEBase):
|
desdeo_tools/utilities/polytopes.py#L59
Missing whitespace after ',' (E231)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L340
nadir (np.ndarray, optional): The nadir point. Defaults to None.
rho (float, optional): The augmentation term for the scalarization function.
Defaults to 1e-6.
"""
- def __init__(
- self,
- utopian: np.ndarray = None,
- nadir: np.ndarray = None,
- rho: float = 1e-6,
- **kwargs
- ):
+ def __init__(self, utopian: np.ndarray = None, nadir: np.ndarray = None, rho: float = 1e-6, **kwargs):
super().__init__(utopian=utopian, nadir=nadir, rho=rho, **kwargs)
self.__mu = self.__w = 1 / (self.nadir - self.utopian)
self.has_additional_constraints = True
self.required_keys = {
- "current solution": (
- "A solution preferred by the DM currently. " "(type: numpy.ndarray)"
- ),
+ "current solution": ("A solution preferred by the DM currently. " "(type: numpy.ndarray)"),
"classifications": (
"A list of same length as the number of objectives. Elements can only "
"include some or all of ['<', '<=', '=', '>=', '0']. These classify "
"the different objectives as defined in the NIMBUS or GLIDE-II paper. "
"(type: list)"
|
desdeo_tools/utilities/polytopes.py#L60
Missing whitespace after ',' (E231)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L410
def I_alpha(self):
return self.improve_unconstrained + self.improve_constrained
@Property
def I_epsilon(self):
- return (
- self.improve_unconstrained
- + self.improve_constrained
- + self.satisfactory
- + self.relax_constrained
- )
+ return self.improve_unconstrained + self.improve_constrained + self.satisfactory + self.relax_constrained
@Property
def w(self):
# This was in the paper
return self.__w
|
desdeo_tools/utilities/polytopes.py#L60
Missing whitespace after ',' (E231)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L434
@Property
def q(self):
q = np.full_like(self.utopian, fill_value=0, dtype=float)
q[self.improve_unconstrained] = self.utopian[self.improve_unconstrained]
- q[self.improve_constrained] = self.preference["levels"][
- self.improve_constrained
- ]
+ q[self.improve_constrained] = self.preference["levels"][self.improve_constrained]
return q
@Property
def epsilon(self):
e = np.full_like(self.utopian, fill_value=np.nan, dtype=float)
- case1 = (
- self.improve_constrained + self.improve_unconstrained + self.satisfactory
- )
+ case1 = self.improve_constrained + self.improve_unconstrained + self.satisfactory
case2 = self.relax_constrained
e[case1] = self.preference["current solution"][case1]
e[case2] = self.preference["levels"][case2]
return e
|
desdeo_tools/utilities/polytopes.py#L61
Missing whitespace after ',' (E231)
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L477
nadir (np.ndarray, optional): The nadir point. Defaults to None.
rho (float, optional): The augmentation term for the scalarization function.
Defaults to 1e-6.
"""
- def __init__(
- self,
- utopian: np.ndarray = None,
- nadir: np.ndarray = None,
- rho: float = 1e-6,
- **kwargs
- ):
+ def __init__(self, utopian: np.ndarray = None, nadir: np.ndarray = None, rho: float = 1e-6, **kwargs):
super().__init__(utopian=utopian, nadir=nadir, rho=rho, **kwargs)
- self.__mu = (self.nadir - self.utopian) / np.max(
- np.abs(np.vstack((utopian, nadir))), axis=0
- )
+ self.__mu = (self.nadir - self.utopian) / np.max(np.abs(np.vstack((utopian, nadir))), axis=0)
self.__w = 0
self.I_epsilon = np.full_like(self.utopian, dtype=np.bool_, fill_value=True)
self.has_additional_constraints = True
self.required_keys = {
- "current solution": (
- "A solution preferred by the DM currently. " "(type: numpy.ndarray)"
- ),
+ "current solution": ("A solution preferred by the DM currently. " "(type: numpy.ndarray)"),
"classifications": (
"A list of same length as the number of objectives. Elements can only "
"include some or all of [<=', '=', '>=']. These classify "
"the different objectives as defined in the GLIDE-II paper. "
"(type: list)"
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L586
nadir (np.ndarray, optional): The nadir point. Has no effect on STOM calculation. Defaults to None.
rho (float, optional): The augmentation term for the scalarization function.
Defaults to 1e-6.
"""
- def __init__(
- self,
- utopian: np.ndarray = None,
- nadir: np.ndarray = None,
- rho: float = 1e-6,
- **kwargs
- ):
+ def __init__(self, utopian: np.ndarray = None, nadir: np.ndarray = None, rho: float = 1e-6, **kwargs):
super().__init__(utopian=utopian, nadir=None, rho=rho, **kwargs)
self.has_additional_constraints = False
- self.__I_alpha = np.full_like(
- utopian, dtype=np.bool_, fill_value=True
- ).flatten()
- self.__I_epsilon = np.full_like(
- utopian, dtype=np.bool_, fill_value=False
- ).flatten()
+ self.__I_alpha = np.full_like(utopian, dtype=np.bool_, fill_value=True).flatten()
+ self.__I_epsilon = np.full_like(utopian, dtype=np.bool_, fill_value=False).flatten()
self.__w = 0
self.required_keys = {
"reference point": (
"Used to calculate the direction of improvement: "
"a line going from the reference point to the utopian point. "
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L662
nadir (np.ndarray, optional): The nadir point. Has no effect on STOM calculation. Defaults to None.
rho (float, optional): The augmentation term for the scalarization function.
Defaults to 1e-6.
"""
- def __init__(
- self,
- utopian: np.ndarray = None,
- nadir: np.ndarray = None,
- rho: float = 1e-6,
- **kwargs
- ):
+ def __init__(self, utopian: np.ndarray = None, nadir: np.ndarray = None, rho: float = 1e-6, **kwargs):
super().__init__(utopian=utopian, nadir=None, rho=rho, **kwargs)
self.has_additional_constraints = False
self.__w = 1
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L690
nadir (np.ndarray, optional): The nadir point. Defaults to None.
rho (float, optional): The augmentation term for the scalarization function.
Defaults to 1e-6.
"""
- def __init__(
- self,
- utopian: np.ndarray = None,
- nadir: np.ndarray = None,
- rho: float = 1e-6,
- **kwargs
- ):
+ def __init__(self, utopian: np.ndarray = None, nadir: np.ndarray = None, rho: float = 1e-6, **kwargs):
super().__init__(utopian=utopian, nadir=None, rho=rho, **kwargs)
self.has_additional_constraints = False
- self.__I_alpha = np.full_like(
- utopian, dtype=np.bool_, fill_value=True
- ).flatten()
- self.__I_epsilon = np.full_like(
- utopian, dtype=np.bool_, fill_value=False
- ).flatten()
+ self.__I_alpha = np.full_like(utopian, dtype=np.bool_, fill_value=True).flatten()
+ self.__I_epsilon = np.full_like(utopian, dtype=np.bool_, fill_value=False).flatten()
self.__w = 1
self.required_keys = {
- "mu": (
- "Vector defining the direction of improvement of the scalarizer. "
- "(type: numpy.ndarray)"
- )
+ "mu": ("Vector defining the direction of improvement of the scalarizer. " "(type: numpy.ndarray)")
}
@Property
def I_epsilon(self):
return self.__I_epsilon
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/scalarization/GLIDE_II.py#L765
nadir (np.ndarray, optional): The nadir point. Defaults to None.
rho (float, optional): The augmentation term for the scalarization function.
Defaults to 1e-6.
"""
- def __init__(
- self, current_objective_vector: np.ndarray, rho: float = 1e-6, **kwargs
- ):
+ def __init__(self, current_objective_vector: np.ndarray, rho: float = 1e-6, **kwargs):
super().__init__(utopian=None, nadir=None, rho=rho, **kwargs)
self.current_objective_vector = current_objective_vector
self.has_additional_constraints = False
- self.__I_alpha = np.full_like(
- current_objective_vector, dtype=np.bool_, fill_value=True
- ).flatten()
- self.__I_epsilon = np.full_like(
- current_objective_vector, dtype=np.bool_, fill_value=False
- ).flatten()
+ self.__I_alpha = np.full_like(current_objective_vector, dtype=np.bool_, fill_value=True).flatten()
+ self.__I_epsilon = np.full_like(current_objective_vector, dtype=np.bool_, fill_value=False).flatten()
self.__w = 0
@Property
def I_epsilon(self):
return self.__I_epsilon
|
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/utilities/preference_converters.py#L1
"""Provides implementations that convert one type of preference information to another."""
import numpy as np
-def classification_to_reference_point(
- classification_preference: dict, ideal: np.ndarray, nadir: np.ndarray
-) -> dict:
+def classification_to_reference_point(classification_preference: dict, ideal: np.ndarray, nadir: np.ndarray) -> dict:
"""Convert classification type of preference (e.g. NIMBUS) to reference point
preference.
Args:
classification_preference (dict): A dict containing keys 'current solution',
|
/home/runner/work/desdeo-tools/desdeo-tools/desdeo_tools/utilities/preference_converters.py#L19
dict: The preference in the form of a reference point. Contains one key:
"reference point", which maps to the preference in a numpy array structure.
"""
z_bar = np.zeros_like(nadir, dtype=float)
- improve_inds = np.where(
- np.array(classification_preference["classifications"]) == "<"
- )[0]
- acceptable_inds = np.where(
- np.array(classification_preference["classifications"]) == "="
- )[0]
- free_inds = np.where(np.array(classification_preference["classifications"]) == "0")[
- 0
- ]
- improve_until_inds = np.where(
- np.array(classification_preference["classifications"]) == "<="
- )[0]
- impaire_until_inds = np.where(
- np.array(classification_preference["classifications"]) == ">="
- )[0]
+ improve_inds = np.where(np.array(classification_preference["classifications"]) == "<")[0]
+ acceptable_inds = np.where(np.array(classification_preference["classifications"]) == "=")[0]
+ free_inds = np.where(np.array(classification_preference["classifications"]) == "0")[0]
+ improve_until_inds = np.where(np.array(classification_preference["classifications"]) == "<=")[0]
+ impaire_until_inds = np.where(np.array(classification_preference["classifications"]) == ">=")[0]
z_bar[improve_inds] = ideal[improve_inds]
z_bar[improve_until_inds] = classification_preference["levels"][improve_until_inds]
- z_bar[acceptable_inds] = classification_preference["current solution"][
- acceptable_inds
- ]
+ z_bar[acceptable_inds] = classification_preference["current solution"][acceptable_inds]
z_bar[impaire_until_inds] = classification_preference["levels"][impaire_until_inds]
z_bar[free_inds] = nadir[free_inds]
return {"reference point": z_bar}
|
Ruff (E501):
desdeo_tools/interaction/request.py#L388
desdeo_tools/interaction/request.py:388:121: E501 Line too long (122 > 120 characters)
|
Ruff (E501):
desdeo_tools/interaction/validators.py#L98
desdeo_tools/interaction/validators.py:98:121: E501 Line too long (123 > 120 characters)
|
Ruff (E501):
desdeo_tools/scalarization/MOEADSF.py#L118
desdeo_tools/scalarization/MOEADSF.py:118:121: E501 Line too long (127 > 120 characters)
|
Ruff (E501):
desdeo_tools/solver/ScalarSolver.py#L94
desdeo_tools/solver/ScalarSolver.py:94:121: E501 Line too long (141 > 120 characters)
|
Ruff (E501):
desdeo_tools/solver/ScalarSolver.py#L100
desdeo_tools/solver/ScalarSolver.py:100:121: E501 Line too long (132 > 120 characters)
|
Ruff (F821):
desdeo_tools/solver/ScalarSolver.py#L135
desdeo_tools/solver/ScalarSolver.py:135:45: F821 Undefined name `scalarized_objectives`
|
Ruff (E501):
desdeo_tools/solver/ScalarSolver.py#L145
desdeo_tools/solver/ScalarSolver.py:145:121: E501 Line too long (143 > 120 characters)
|
Ruff (E501):
desdeo_tools/solver/ScalarSolver.py#L193
desdeo_tools/solver/ScalarSolver.py:193:121: E501 Line too long (123 > 120 characters)
|
Ruff (E501):
desdeo_tools/solver/ScalarSolver.py#L195
desdeo_tools/solver/ScalarSolver.py:195:121: E501 Line too long (133 > 120 characters)
|
Ruff (F811):
desdeo_tools/solver/ScalarSolver.py#L324
desdeo_tools/solver/ScalarSolver.py:324:48: F811 Redefinition of unused `PointMethodASF` from line 13
|
Run linters
The following actions uses node12 which is deprecated and will be forced to run on node16: actions/checkout@v2, actions/setup-python@v1, wearerequired/lint-action@v1. For more info: https://github.blog/changelog/2023-06-13-github-actions-all-actions-will-run-on-node16-instead-of-node12-by-default/
|
Run linters
Unexpected input(s) 'isort', 'isort_args', valid inputs are ['github_token', 'continue_on_error', 'auto_fix', 'git_no_verify', 'git_name', 'git_email', 'commit_message', 'check_name', 'neutral_check_on_warning', 'stylelint', 'stylelint_args', 'stylelint_dir', 'stylelint_extensions', 'stylelint_command_prefix', 'gofmt', 'gofmt_args', 'gofmt_dir', 'gofmt_extensions', 'gofmt_command_prefix', 'golint', 'golint_args', 'golint_dir', 'golint_extensions', 'golint_command_prefix', 'eslint', 'eslint_args', 'eslint_dir', 'eslint_extensions', 'eslint_command_prefix', 'prettier', 'prettier_args', 'prettier_dir', 'prettier_extensions', 'prettier_command_prefix', 'xo', 'xo_args', 'xo_dir', 'xo_extensions', 'xo_command_prefix', 'php_codesniffer', 'php_codesniffer_args', 'php_codesniffer_dir', 'php_codesniffer_extensions', 'php_codesniffer_command_prefix', 'black', 'black_args', 'black_dir', 'black_extensions', 'black_command_prefix', 'flake8', 'flake8_args', 'flake8_dir', 'flake8_extensions', 'flake8_command_prefix', 'mypy', 'mypy_args', 'mypy_dir', 'mypy_extensions', 'mypy_command_prefix', 'oitnb', 'oitnb_args', 'oitnb_dir', 'oitnb_extensions', 'oitnb_command_prefix', 'rubocop', 'rubocop_args', 'rubocop_dir', 'rubocop_extensions', 'rubocop_command_prefix', 'erblint', 'erblint_args', 'erblint_dir', 'erblint_extensions', 'erblint_command_prefix', 'swiftformat', 'swiftformat_args', 'swiftformat_dir', 'swiftformat_extensions', 'swiftformat_command_prefix', 'swift_format_lockwood', 'swift_format_lockwood_args', 'swift_format_lockwood_dir', 'swift_format_lockwood_extensions', 'swift_format_lockwood_command_prefix', 'swift_format_official', 'swift_format_official_args', 'swift_format_official_dir', 'swift_format_official_extensions', 'swift_format_official_command_prefix', 'swiftlint', 'swiftlint_args', 'swiftlint_dir', 'swiftlint_extensions', 'swiftlint_command_prefix', 'dotnet_format', 'dotnet_format_args', 'dotnet_format_dir', 'dotnet_format_extensions', 'dotnet_format_command_prefix']
|