Skip to content

Commit

Permalink
add changes from autopep8 for E501
Browse files Browse the repository at this point in the history
  • Loading branch information
Flaminietta committed Jan 23, 2024
1 parent 11a34a0 commit b9aa3bf
Show file tree
Hide file tree
Showing 8 changed files with 344 additions and 175 deletions.
31 changes: 19 additions & 12 deletions mcda/configuration/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,19 @@ class Config(object):
'monte_carlo_sampling',
'output_path']

_list_values: list[str] = ['marginal_distribution_for_each_indicator', 'polarity_for_each_indicator']
_list_values: list[str] = [
'marginal_distribution_for_each_indicator', 'polarity_for_each_indicator']

_str_values = ['input_matrix_path', 'output_path', 'sensitivity_on', 'normalization', 'aggregation',
'robustness_on', 'on_single_weights', 'on_all_weights','given_weights', 'on_indicators']
'robustness_on', 'on_single_weights', 'on_all_weights', 'given_weights', 'on_indicators']

_int_values = ['monte_carlo_runs', 'num_cores']

_dict_values = ['sensitivity', 'robustness', 'monte_carlo_sampling']

_keys_of_dict_values = {'sensitivity': ['sensitivity_on', 'normalization', 'aggregation'],
'robustness': ['robustness_on', 'on_single_weights', 'on_all_weights',
'given_weights', 'on_indicators'],
'given_weights', 'on_indicators'],
'monte_carlo_sampling': ['monte_carlo_runs', 'num_cores',
'marginal_distribution_for_each_indicator']}

Expand All @@ -50,9 +51,10 @@ def __init__(self, input_config: dict):
int_values = self._int_values
list_values = self._list_values
dict_values = self._dict_values
#keys_of_dict_values = self._keys_of_dict_values
# keys_of_dict_values = self._keys_of_dict_values

self._validate(input_config, valid_keys, str_values, int_values, list_values, dict_values)
self._validate(input_config, valid_keys, str_values,
int_values, list_values, dict_values)
self._config = copy.deepcopy(input_config)

def _validate(self, input_config, valid_keys, str_values, int_values, list_values, dict_values):
Expand All @@ -65,21 +67,25 @@ def _validate(self, input_config, valid_keys, str_values, int_values, list_value

if key in str_values:
if not isinstance(input_config[key], str):
raise TypeError("value of {} in the input config is not a string".format(key))
raise TypeError(
"value of {} in the input config is not a string".format(key))

if key in int_values:
if not isinstance(input_config[key], int):
raise TypeError("value of {} in the input config is not an integer".format(key))
raise TypeError(
"value of {} in the input config is not an integer".format(key))

if key in list_values:
if not isinstance(input_config[key], list):
raise TypeError("value of {} in the input config is not a list".format(key))
raise TypeError(
"value of {} in the input config is not a list".format(key))

if key in dict_values:
if not isinstance(input_config[key], dict):
raise TypeError("value of {} in the input config is not a dictionary".format(key))
Config.check_dict_keys(input_config[key], Config._keys_of_dict_values[key])

raise TypeError(
"value of {} in the input config is not a dictionary".format(key))
Config.check_dict_keys(
input_config[key], Config._keys_of_dict_values[key])

def get_property(self, property_name: str):
return self._config[property_name]
Expand Down Expand Up @@ -118,4 +124,5 @@ def check_dict_keys(dic: Dict[str, Any], keys: List[str]):
def check_key(dic: dict, key: str):
"""Check if a key is in a dict"""
if key not in dic.keys():
raise KeyError("The key = {} is not present in dictionary: {}".format(key, dic))
raise KeyError(
"The key = {} is not present in dictionary: {}".format(key, dic))
345 changes: 230 additions & 115 deletions mcda/mcda_run.py

Large diffs are not rendered by default.

23 changes: 15 additions & 8 deletions mcda/mcda_with_robustness.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ def convert_list(data_list):
"""
alternatives, num_runs = data_list[0].shape

transposed_list = [pd.DataFrame(index=range(alternatives)) for _ in range(num_runs)]
transposed_list = [pd.DataFrame(index=range(
alternatives)) for _ in range(num_runs)]

for i, df in enumerate(data_list):
for n in range(num_runs):
Expand Down Expand Up @@ -105,17 +106,23 @@ def create_n_randomly_sampled_matrices(self) -> List[pd.DataFrame]:
distribution_type = marginal_pdf[i]

if distribution_type == 'exact':
samples = self.repeat_series_to_create_df(parameter1, num_runs).T
samples = self.repeat_series_to_create_df(
parameter1, num_runs).T
elif distribution_type == 'normal':
samples = np.random.normal(loc=parameter1, scale=parameter2, size=(num_runs, len(parameter1)))
samples = np.random.normal(
loc=parameter1, scale=parameter2, size=(num_runs, len(parameter1)))
elif distribution_type == 'uniform':
samples = np.random.uniform(low=parameter1, high=parameter2, size=(num_runs, len(parameter1)))
samples = np.random.uniform(
low=parameter1, high=parameter2, size=(num_runs, len(parameter1)))
elif distribution_type == 'lnorm':
samples = np.random.lognormal(mean=parameter1, sigma=parameter2, size=(num_runs, len(parameter1)))
samples = np.random.lognormal(
mean=parameter1, sigma=parameter2, size=(num_runs, len(parameter1)))
elif distribution_type == 'poisson':
samples = np.random.poisson(lam=parameter1, size=(num_runs, len(parameter1)))
samples = np.random.poisson(
lam=parameter1, size=(num_runs, len(parameter1)))
else:
raise ValueError(f"Invalid marginal distribution type: {distribution_type}")
raise ValueError(
f"Invalid marginal distribution type: {distribution_type}")

# check if any sample is negative and rescale btw 0 and 1
if (samples < 0).any().any():
Expand All @@ -127,4 +134,4 @@ def create_n_randomly_sampled_matrices(self) -> List[pd.DataFrame]:

list_random_matrix = self.convert_list(sampled_matrices)

return list_random_matrix
return list_random_matrix
21 changes: 14 additions & 7 deletions mcda/mcda_without_robustness.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,15 @@ def normalize_indicators(self, method=None) -> dict:
:return: a dictionary that contains the normalized values of each indicator per normalization method.
Normalization functions implemented: minmax; target; standardized; rank
"""
norm = Normalization(self._input_matrix, self._config.polarity_for_each_indicator)
norm = Normalization(self._input_matrix,
self._config.polarity_for_each_indicator)

normalized_indicators = {}

if method is None or method == 'minmax':
indicators_scaled_minmax_01 = norm.minmax(feature_range=(0, 1))
indicators_scaled_minmax_no0 = norm.minmax(feature_range=(0.1, 1)) # for aggregation "geometric" and "harmonic" that accept no 0
# for aggregation "geometric" and "harmonic" that accept no 0
indicators_scaled_minmax_no0 = norm.minmax(feature_range=(0.1, 1))
normalized_indicators["minmax_no0"] = indicators_scaled_minmax_no0
normalized_indicators["minmax_01"] = indicators_scaled_minmax_01
if method is None or method == 'target':
Expand All @@ -54,16 +56,19 @@ def normalize_indicators(self, method=None) -> dict:
normalized_indicators["target_no0"] = indicators_scaled_target_no0
normalized_indicators["target_01"] = indicators_scaled_target_01
if method is None or method == 'standardized':
indicators_scaled_standardized_any = norm.standardized(feature_range=('-inf', '+inf'))
indicators_scaled_standardized_no0 = norm.standardized(feature_range=(0.1, '+inf'))
indicators_scaled_standardized_any = norm.standardized(
feature_range=('-inf', '+inf'))
indicators_scaled_standardized_no0 = norm.standardized(
feature_range=(0.1, '+inf'))
normalized_indicators["standardized_any"] = indicators_scaled_standardized_any
normalized_indicators["standardized_no0"] = indicators_scaled_standardized_no0
if method is None or method == 'rank':
indicators_scaled_rank = norm.rank()
normalized_indicators["rank"] = indicators_scaled_rank
if method != None and method not in ['minmax', 'target', 'standardized', 'rank']:
logger.error('Error Message', stack_info=True)
raise ValueError('The selected normalization method is not supported')
raise ValueError(
'The selected normalization method is not supported')

return normalized_indicators

Expand Down Expand Up @@ -110,10 +115,12 @@ def aggregate_indicators(self, normalized_indicators: dict, weights: list, metho
col_names_method.append("harm-" + key)
if method is None or method == 'minimum':
if key == "standardized_any":
scores_minimum[key] = pd.Series(agg.minimum(self.normalized_indicators["standardized_any"]))
scores_minimum[key] = pd.Series(agg.minimum(
self.normalized_indicators["standardized_any"]))
col_names_method.append("min-" + key)

dict_list = [scores_weighted_sum, scores_geometric, scores_harmonic, scores_minimum]
dict_list = [scores_weighted_sum, scores_geometric,
scores_harmonic, scores_minimum]

for d in dict_list:
if d:
Expand Down
9 changes: 6 additions & 3 deletions mcda/utility_functions/aggregation.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,11 @@ def geometric(self, norm_indicators: pd.DataFrame()) -> np.ndarray:

if (norm_indicators <= 0).any().any():
logger.error('Error Message', stack_info=True)
raise ValueError('Weighted geometric mean cannot work with non-positive values in normalized indicators')
raise ValueError(
'Weighted geometric mean cannot work with non-positive values in normalized indicators')
else:
scores = stats.mstats.gmean(norm_indicators.astype(float), axis=1, weights=self.weights)
scores = stats.mstats.gmean(norm_indicators.astype(
float), axis=1, weights=self.weights)

return scores

Expand All @@ -78,7 +80,8 @@ def harmonic(self, norm_indicators: pd.DataFrame()) -> np.ndarray:

if (norm_indicators == 0).any().any():
logger.error('Error Message', stack_info=True)
raise ValueError('With 0 values normalized indicators, the weighted harmonic mean will output 0s')
raise ValueError(
'With 0 values normalized indicators, the weighted harmonic mean will output 0s')
else:
scores = stats.hmean(norm_indicators, axis=1, weights=self.weights)

Expand Down
30 changes: 20 additions & 10 deletions mcda/utility_functions/normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ def reversed_minmax_scaler(data, feature_range: tuple):
if (feature_range == (0, 1)):
scaled_data = (max_val - data) / (max_val - min_val)
else:
scaled_data = (max_val - data) / (max_val - min_val) * (1 - 0.1) + 0.1
scaled_data = (max_val - data) / \
(max_val - min_val) * (1 - 0.1) + 0.1

return scaled_data

Expand All @@ -83,7 +84,8 @@ def minmax(self, feature_range: tuple) -> pd.DataFrame():

# for + polarity
x = indicators_plus.to_numpy() # returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler(feature_range=feature_range, copy=False)
min_max_scaler = preprocessing.MinMaxScaler(
feature_range=feature_range, copy=False)
x_scaled = min_max_scaler.fit_transform(x)
indicators_scaled_minmax_plus = pd.DataFrame(x_scaled)

Expand All @@ -93,7 +95,8 @@ def minmax(self, feature_range: tuple) -> pd.DataFrame():
indicators_scaled_minmax_minus = pd.DataFrame(y_scaled)

# merge back scaled values for positive and negative polarities
indicators_scaled_minmax = pd.DataFrame(index=range(original_shape[0]), columns=range(original_shape[1]))
indicators_scaled_minmax = pd.DataFrame(index=range(
original_shape[0]), columns=range(original_shape[1]))
for i, index_p in enumerate(ind_plus): indicators_scaled_minmax.iloc[:,
index_p] = indicators_scaled_minmax_plus.iloc[:, i]
for j, index_n in enumerate(ind_minus): indicators_scaled_minmax.iloc[:,
Expand All @@ -116,16 +119,19 @@ def target(self, feature_range: tuple) -> pd.DataFrame():
indicators_minus = pol[3]

if (feature_range == (0, 1)):
indicators_scaled_target_plus = indicators_plus / indicators_plus.max(axis=0) # for + polarity
indicators_scaled_target_minus = 1 - indicators_minus / indicators_minus.max(axis=0) # for - polarity
indicators_scaled_target_plus = indicators_plus / \
indicators_plus.max(axis=0) # for + polarity
indicators_scaled_target_minus = 1 - indicators_minus / \
indicators_minus.max(axis=0) # for - polarity
else:
indicators_scaled_target_plus = indicators_plus / indicators_plus.max(axis=0) * (
1 - 0.1) + 0.1 # for + polarity
indicators_scaled_target_minus = (1 - indicators_minus / indicators_minus.max(axis=0)) * (
1 - 0.1) + 0.1 # for - polarity

# merge back scaled values for positive and negative polarities
indicators_scaled_target = pd.DataFrame(index=range(original_shape[0]), columns=range(original_shape[1]))
indicators_scaled_target = pd.DataFrame(index=range(
original_shape[0]), columns=range(original_shape[1]))
for i, index_p in enumerate(ind_plus): indicators_scaled_target.iloc[:,
index_p] = indicators_scaled_target_plus.iloc[:, i]
for j, index_n in enumerate(ind_minus): indicators_scaled_target.iloc[:,
Expand Down Expand Up @@ -153,7 +159,8 @@ def standardized(self, feature_range: tuple) -> pd.DataFrame():
axis=0) # for - polarity

# merge back scaled values for positive and negative polarities
indicators_scaled_standardized = pd.DataFrame(index=range(original_shape[0]), columns=range(original_shape[1]))
indicators_scaled_standardized = pd.DataFrame(index=range(
original_shape[0]), columns=range(original_shape[1]))
for i, index_p in enumerate(ind_plus): indicators_scaled_standardized.iloc[:,
index_p] = indicators_scaled_stand_plus.iloc[:, i]
for j, index_n in enumerate(ind_minus): indicators_scaled_standardized.iloc[:,
Expand All @@ -180,11 +187,14 @@ def rank(self) -> pd.DataFrame():
indicators_plus = pol[2]
indicators_minus = pol[3]

indicators_scaled_rank_plus = indicators_plus.rank(axis=0) # for + polarity
indicators_scaled_rank_minus = (-1 * indicators_minus).rank(axis=0) # for - polarity
indicators_scaled_rank_plus = indicators_plus.rank(
axis=0) # for + polarity
# for - polarity
indicators_scaled_rank_minus = (-1 * indicators_minus).rank(axis=0)

# merge back scaled values for positive and negative polarities
indicators_scaled_rank = pd.DataFrame(index=range(original_shape[0]), columns=range(original_shape[1]))
indicators_scaled_rank = pd.DataFrame(index=range(
original_shape[0]), columns=range(original_shape[1]))
for i, index_p in enumerate(ind_plus): indicators_scaled_rank.iloc[:,
index_p] = indicators_scaled_rank_plus.iloc[:, i]
for j, index_n in enumerate(ind_minus): indicators_scaled_rank.iloc[:,
Expand Down
Loading

0 comments on commit b9aa3bf

Please sign in to comment.