<commit_before>"""
Multi criteria decision analysis
"""
from __future__ import division
from __future__ import print_function

import json
import os

import pandas as pd
import numpy as np
import cea.config
import cea.inputlocator
from cea.optimization.lca_calculations import LcaCalculations
from cea.technologies.heat_exchangers import calc_Cinv_HEX
import cea.optimization.distribution.network_optimization_features as network_opt
from cea.analysis.multicriteria.optimization_post_processing.locating_individuals_in_generation_script import \
    locating_individuals_in_generation_script, create_data_address_file
from math import ceil, log

__author__ = "<NAME>"
__copyright__ = "Copyright 2018, Architecture and Building Systems - ETH Zurich"
__credits__ = ["<NAME>", "<NAME>", "<NAME>"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"


def multi_criteria_main(locator, config):
    # local variables
    generation = config.multi_criteria.generation

    # This calculates the exact path of the individual
    # It might be that this individual was repeated already some generations back
    # so we make sure that a pointer to the right address exists first
    if not os.path.exists(locator.get_address_of_individuals_of_a_generation(generation)):
        data_address = locating_individuals_in_generation_script(generation, locator)
    else:
        data_address = pd.read_csv(locator.get_address_of_individuals_of_a_generation(generation))

    # import data storing information about the generation
    data_processed = preprocessing_generations_data(locator, generation)
    district_heating_network = data_processed['district_heating_network']
    district_cooling_network = data_processed['district_cooling_network']

    # compile cost data
    if district_cooling_network:
        compiled_data_df = pd.DataFrame()
        individual_list = data_processed['individual_list']
        for i, individual in enumerate(individual_list):
            df_current_individual = pd.DataFrame(data_processed['data_generation'].loc[i])
            compiled_data_df = compiled_data_df.append(preprocessing_cost_data_DC(individual,
                                                                                  df_current_individual,
                                                                                  locator,
                                                                                  data_processed,
                                                                                  data_address,
                                                                                  config), ignore_index=True)
        compiled_data_df = compiled_data_df.assign(individual=individual_list)

    if district_heating_network:
        # compile the data
        compiled_data_df = pd.DataFrame()
        individual_list = data_processed['individual_list']
        for i, individual in enumerate(individual_list):
            compiled_data_df = compiled_data_df.append(preprocessing_cost_data_DH(individual,
                                                                                  locator,
                                                                                  data_processed,
                                                                                  data_address,
                                                                                  config), ignore_index=True)
        compiled_data_df['individual'] = individual_list

    # normalize data
    compiled_data_df = normalize_compiled_data(compiled_data_df)
    # rank data
    compiled_data_df['TAC_rank'] = compiled_data_df['normalized_TAC'].rank(ascending=True)
    compiled_data_df['emissions_rank'] = compiled_data_df['normalized_emissions'].rank(ascending=True)
    compiled_data_df['prim_rank'] = compiled_data_df['normalized_prim'].rank(ascending=True)

    ## user defined mcda
    compiled_data_df['user_MCDA'] = compiled_data_df['normalized_Capex_total'] * \
                                    config.multi_criteria.capextotal * \
                                    config.multi_criteria.economicsustainability + \
                                    compiled_data_df[ 'normalized_Opex'] * \
                                    config.multi_criteria.opex * config.multi_criteria.economicsustainability + \
                                    compiled_data_df['normalized_TAC'] * \
                                    config.multi_criteria.annualizedcosts * config.multi_criteria.economicsustainability + \
                                    compiled_data_df['normalized_emissions'] *\
                                    config.multi_criteria.emissions * config.multi_criteria.environmentalsustainability + \
                                    compiled_data_df['normalized_prim'] *\
                                    config.multi_criteria.primaryenergy * config.multi_criteria.environmentalsustainability + \
                                    compiled_data_df['normalized_renewable_share'] *\
                                    config.multi_criteria.renewableshare * config.multi_criteria.socialsustainability

    compiled_data_df['user_MCDA_rank'] = compiled_data_df['user_MCDA'].rank(ascending=True)

    compiled_data_df.to_csv(locator.get_multi_criteria_analysis(generation))
    return


def normalize_compiled_data(compiled_data_df):
    # TAC
    if (max(compiled_data_df['TAC_Mio']) - min(compiled_data_df['TAC_Mio'])) > 1E-8:
        normalized_TAC = (compiled_data_df['TAC_Mio'] - min(compiled_data_df['TAC_Mio'])) / (
                max(compiled_data_df['TAC_Mio']) - min(compiled_data_df['TAC_Mio']))
    else:
        normalized_TAC = [1] * len(compiled_data_df['TAC_Mio'])
    # emission
    if (max(compiled_data_df['total_emissions_kiloton']) - min(compiled_data_df['total_emissions_kiloton'])) > 1E-8:
        normalized_emissions = (compiled_data_df['total_emissions_kiloton'] - min(
            compiled_data_df['total_emissions_kiloton'])) / (
                                       max(compiled_data_df['total_emissions_kiloton']) - min(
                                   compiled_data_df['total_emissions_kiloton']))
    else:
        normalized_emissions = [1] * len(compiled_data_df['total_emissions_kiloton'])
    # primary energy
    if (max(compiled_data_df['total_prim_energy_TJ']) - min(compiled_data_df['total_prim_energy_TJ'])) > 1E-8:
        normalized_prim = (compiled_data_df['total_prim_energy_TJ'] - min(compiled_data_df['total_prim_energy_TJ'])) / (
                max(compiled_data_df['total_prim_energy_TJ']) - min(compiled_data_df['total_prim_energy_TJ']))
    else:
        normalized_prim = [1] * len(compiled_data_df['total_prim_energy_TJ'])
    # capex
    if (max(compiled_data_df['Capex_total_Mio']) - min(compiled_data_df['Capex_total_Mio'])) > 1E-8:
        normalized_Capex_total = (compiled_data_df['Capex_total_Mio'] - min(compiled_data_df['Capex_total_Mio'])) / (
                max(compiled_data_df['Capex_total_Mio']) - min(compiled_data_df['Capex_total_Mio']))
    else:
        normalized_Capex_total = [1] * len(compiled_data_df['Capex_total_Mio'])<commit_msg>refactor multicriteria ranking<commit_after>"""
Multi criteria decision analysis
"""
from __future__ import division
from __future__ import print_function

import json
import os

import pandas as pd
import numpy as np
import cea.config
import cea.inputlocator
from cea.optimization.lca_calculations import LcaCalculations
from cea.technologies.heat_exchangers import calc_Cinv_HEX
import cea.optimization.distribution.network_optimization_features as network_opt
from cea.analysis.multicriteria.optimization_post_processing.locating_individuals_in_generation_script import \
    locating_individuals_in_generation_script, create_data_address_file
from math import ceil, log

__author__ = "<NAME>"
__copyright__ = "Copyright 2018, Architecture and Building Systems - ETH Zurich"
__credits__ = ["<NAME>", "<NAME>", "<NAME>"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"


def multi_criteria_main(locator, config):
    # local variables
    generation = config.multi_criteria.generation

    # This calculates the exact path of the individual
    # It might be that this individual was repeated already some generations back
    # so we make sure that a pointer to the right address exists first
    if not os.path.exists(locator.get_address_of_individuals_of_a_generation(generation)):
        data_address = locating_individuals_in_generation_script(generation, locator)
    else:
        data_address = pd.read_csv(locator.get_address_of_individuals_of_a_generation(generation))

    # import data storing information about the generation
    data_processed = preprocessing_generations_data(locator, generation)
    district_heating_network = data_processed['district_heating_network']
    district_cooling_network = data_processed['district_cooling_network']

    # compile cost data
    if district_cooling_network:
        compiled_data_df = pd.DataFrame()
        individual_list = data_processed['individual_list']
        for i, individual in enumerate(individual_list):
            df_current_individual = pd.DataFrame(data_processed['data_generation'].loc[i])
            compiled_data_df = compiled_data_df.append(preprocessing_cost_data_DC(individual,
                                                                                  df_current_individual,
                                                                                  locator,
                                                                                  data_processed,
                                                                                  data_address,
                                                                                  config), ignore_index=True)
        compiled_data_df = compiled_data_df.assign(individual=individual_list)

    if district_heating_network:
        # compile the data
        compiled_data_df = pd.DataFrame()
        individual_list = data_processed['individual_list']
        for i, individual in enumerate(individual_list):
            compiled_data_df = compiled_data_df.append(preprocessing_cost_data_DH(individual,
                                                                                  locator,
                                                                                  data_processed,
                                                                                  data_address,
                                                                                  config), ignore_index=True)
        compiled_data_df['individual'] = individual_list

    # normalize data
    compiled_data_df = normalize_compiled_data(compiled_data_df)
    # rank data
    compiled_data_df = rakn_normalized_data(compiled_data_df, config)

    compiled_data_df.to_csv(locator.get_multi_criteria_analysis(generation))
    return

def rakn_normalized_data(compiled_data_df, config):
    compiled_data_df['TAC_rank'] = compiled_data_df['normalized_TAC'].rank(ascending=True)
    compiled_data_df['emissions_rank'] = compiled_data_df['normalized_emissions'].rank(ascending=True)
    compiled_data_df['prim_rank'] = compiled_data_df['normalized_prim'].rank(ascending=True)
    ## user defined mcda
    compiled_data_df['user_MCDA'] = compiled_data_df['normalized_Capex_total'] * \
                                    config.multi_criteria.capextotal * \
                                    config.multi_criteria.economicsustainability + \
                                    compiled_data_df['normalized_Opex'] * \
                                    config.multi_criteria.opex * config.multi_criteria.economicsustainability + \
                                    compiled_data_df['normalized_TAC'] * \
                                    config.multi_criteria.annualizedcosts * config.multi_criteria.economicsustainability + \
                                    compiled_data_df['normalized_emissions'] * \
                                    config.multi_criteria.emissions * config.multi_criteria.environmentalsustainability + \
                                    compiled_data_df['normalized_prim'] * \
                                    config.multi_criteria.primaryenergy * config.multi_criteria.environmentalsustainability + \
                                    compiled_data_df['normalized_renewable_share'] * \
                                    config.multi_criteria.renewableshare * config.multi_criteria.socialsustainability
    compiled_data_df['user_MCDA_rank'] = compiled_data_df['user_MCDA'].rank(ascending=True)
    return compiled_data_df


def normalize_compiled_data(compiled_data_df):
    # TAC
    if (max(compiled_data_df['TAC_Mio']) - min(compiled_data_df['TAC_Mio'])) > 1E-8:
        normalized_TAC = (compiled_data_df['TAC_Mio'] - min(compiled_data_df['TAC_Mio'])) / (
                max(compiled_data_df['TAC_Mio']) - min(compiled_data_df['TAC_Mio']))
    else:
        normalized_TAC = [1] * len(compiled_data_df['TAC_Mio'])
    # emission
    if (max(compiled_data_df['total_emissions_kiloton']) - min(compiled_data_df['total_emissions_kiloton'])) > 1E-8:
        normalized_emissions = (compiled_data_df['total_emissions_kiloton'] - min(
            compiled_data_df['total_emissions_kiloton'])) / (
                                       max(compiled_data_df['total_emissions_kiloton']) - min(
                                   compiled_data_df['total_emissions_kiloton']))
    else:
        normalized_emissions = [1] * len(compiled_data_df['total_emissions_kiloton'])
    # primary energy
    if (max(compiled_data_df['total_prim_energy_TJ']) - min(compiled_data_df['total_prim_energy_TJ'])) > 1E-8:
        normalized_prim = (compiled_data_df['total_prim_energy_TJ'] - min(compiled_data_df['total_prim_energy_TJ'])) / (
                max(compiled_data_df['total_prim_energy_TJ']) - min(compiled_data_df['total_prim_energy_TJ']))
    else:
        normalized_prim = [1] * len(compiled_data_df['total_prim_energy_TJ'])
    # capex
    if (max(compiled_data_df['Capex_total_Mio']) - min(compiled_data_df['Capex_total_Mio'])) > 1E-8:
        normalized_Capex_total = (compiled_data_df['Capex_total_Mio'] - min(compiled_data_df['Capex_total_Mio'])) / (
                max(compiled_data_df['Capex_total_Mio']) - min(compiled_data_df['Capex_total_Mio']))
    else:
        normalized_Capex_total = [1] * len(compiled_data_df['Capex_total_Mio'])
{'fraction_non_alphanumeric': 0.08051485690811995, 'fraction_numerical': 0.0024647405175955085, 'mean_word_length': 2.386737769533967, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 82, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '650046', 'n_tokens_mistral': 4130, 'n_tokens_neox': 3891, 'n_words': 584}