Пример #1
0
def decentralizeCosts(individual, locator, gV):
    """
    :param individual: list of all parameters corresponding to an individual configuration
    :param locator: locator set to the scenario
    :param gV: global variables
    :type individual: list
    :type locator: string
    :type gV: class
    :return: costsDisc
    :rtype: float
    """
    indCombi = sFn.individual_to_barcode(individual, gV)
    buildList = sFn.extract_building_names_from_csv(locator.pathRaw +
                                                    "/Total.csv")
    costsDisc = 0

    for i in range(len(indCombi)):
        if indCombi[i] == "0":  # Decentralized building
            building_name = buildList[i]
            df = pd.read_csv(
                locator.get_optimization_disconnected_result_file(
                    building_name))
            dfBest = df[df["Best configuration"] == 1]
            costsDisc += dfBest["Annualized Investment Costs [CHF]"].iloc[0]

    print costsDisc, "costsDisc"
    return costsDisc
Пример #2
0
def GHPCheck(individual, locator, Qnom, gv):
    """
    This function computes the geothermal availability and modifies the individual to
    comply with it

    :param individual: list with variables included in each individual.
    :param locator: path to the demand folder
    :param Qnom: Nominal installed capacity in the district heating plant
    :param gv: Global Variables
    :type individual: list
    :type locator: string
    :type Qnom: float
    :type gv: class

    :return: None
    :rtype: NoneType
    """
    areaArray = np.array(
        pd.read_csv(locator.get_geothermal_potential(), usecols=["Area_geo"]))
    buildArray = np.array(
        pd.read_csv(locator.get_geothermal_potential(), usecols=["Name"]))

    buildList = sFn.extract_building_names_from_csv(locator.get_total_demand())
    barcode = sFn.individual_to_barcode(individual)

    Qallowed = 0

    for index, buildName in zip(barcode, buildList):
        if index == "1":
            areaAvail = areaArray[np.where(buildArray == buildName)[0][0]][0]
            Qallowed += np.ceil(
                areaAvail / gv.GHP_A) * gv.GHP_HmaxSize  #[W_th]

    print Qallowed, "Qallowed"
    if Qallowed < individual[11] * Qnom:
        print "GHP share modified !"

        if Qallowed < 1E-3:
            oldValue = individual[11]
            shareLoss = individual[11]
            individual[10] = 0
            individual[11] = 0

        else:
            oldValue = individual[11]
            shareLoss = oldValue - Qallowed / Qnom
            individual[11] = Qallowed / Qnom

        # Adapt the other shares
        nPlant = 0
        for i in range(gv.nHeat - 1):
            if individual[2 * i] > 0:
                nPlant += 1
                individual[2 * i +
                           1] += individual[2 * i + 1] * shareLoss / (1 -
                                                                      oldValue)

        if nPlant == 0:  # there was only the GHP --> replaced by only NG Boiler
            individual[2] = 1
            individual[3] = 1 - individual[11]
Пример #3
0
def checkNtw(individual, DHN_network_list, DCN_network_list, locator, gv,
             config, building_names):
    """
    This function calls the distribution routine if necessary
    
    :param individual: network configuration considered
    :param ntwList: list of DHN configurations previously encounterd in the master
    :param locator: path to the folder
    :type individual: list
    :type ntwList: list
    :type locator: string
    :return: None
    :rtype: Nonetype
    """
    DHN_barcode, DCN_barcode, DHN_configuration, DCN_configuration = supportFn.individual_to_barcode(
        individual, building_names)

    if not (DHN_barcode in DHN_network_list) and DHN_barcode.count("1") > 0:
        DHN_network_list.append(DHN_barcode)

        total_demand = supportFn.createTotalNtwCsv(DHN_barcode, locator)
        building_names = total_demand.Name.values

        # Run the substation and distribution routines
        substation.substation_main(locator,
                                   total_demand,
                                   building_names,
                                   DHN_configuration,
                                   DCN_configuration,
                                   Flag=True)

        summarize_network.network_main(locator, total_demand, building_names,
                                       config, gv, DHN_barcode)

    if not (DCN_barcode in DCN_network_list) and DCN_barcode.count("1") > 0:
        DCN_network_list.append(DCN_barcode)

        total_demand = supportFn.createTotalNtwCsv(DCN_barcode, locator)
        building_names = total_demand.Name.values

        # Run the substation and distribution routines
        substation.substation_main(locator,
                                   total_demand,
                                   building_names,
                                   DHN_configuration,
                                   DCN_configuration,
                                   Flag=True)

        summarize_network.network_main(locator, total_demand, building_names,
                                       config, gv, DCN_barcode)
Пример #4
0
def checkNtw(individual, ntwList, locator, gv):
    """
    This function calls the distribution routine if necessary
    
    :param individual: network configuration considered
    :param ntwList: list of DHN configurations previously encounterd in the master
    :param locator: path to the folder
    :type individual: list
    :type ntwList: list
    :type locator: string
    :return: None
    :rtype: Nonetype
    """
    indCombi = sFn.individual_to_barcode(individual, gv)
    print indCombi, 2

    if not (indCombi in ntwList) and indCombi.count("1") > 0:
        ntwList.append(indCombi)

        if indCombi.count("1") == 1:
            total_demand = pd.read_csv(
                os.path.join(locator.get_optimization_network_results_folder(),
                             "Total_%(indCombi)s.csv" % locals()))
            building_names = total_demand.Name.values
            print "Direct launch of distribution summary routine for", indCombi
            nM.network_main(locator, total_demand, building_names, gv,
                            indCombi)

        else:
            total_demand = sFn.createTotalNtwCsv(indCombi, locator)
            building_names = total_demand.Name.values

            # Run the substation and distribution routines
            print "Re-run the substation routine for new distribution configuration", indCombi
            sMain.substation_main(locator, total_demand, building_names, gv,
                                  indCombi)

            print "Launch distribution summary routine"
            nM.network_main(locator, total_demand, building_names, gv,
                            indCombi)
Пример #5
0
def calc_master_to_slave_variables(individual, Q_heating_max_W,
                                   Q_cooling_max_W, building_names, ind_num,
                                   gen):
    """
    This function reads the list encoding a configuration and implements the corresponding
    for the slave routine's to use
    :param individual: list with inidividual
    :param Q_heating_max_W:  peak heating demand
    :param locator: locator class
    :param gv: global variables class
    :type individual: list
    :type Q_heating_max_W: float
    :type locator: string
    :type gv: class
    :return: master_to_slave_vars : class MasterSlaveVariables
    :rtype: class
    """
    # initialise class storing dynamic variables transfered from master to slave optimization
    master_to_slave_vars = slave_data.SlaveData()
    configkey = "".join(str(e)[0:4] for e in individual)

    DHN_barcode, DCN_barcode, DHN_configuration, DCN_configuration = supportFn.individual_to_barcode(
        individual, building_names)
    configkey = configkey[:-2 * len(DHN_barcode)] + hex(
        int(str(DHN_barcode), 2)) + hex(int(str(DCN_barcode), 2))
    master_to_slave_vars.configKey = configkey
    master_to_slave_vars.number_of_buildings_connected_heating = DHN_barcode.count(
        "1")  # counting the number of buildings connected in DHN
    master_to_slave_vars.number_of_buildings_connected_cooling = DCN_barcode.count(
        "1")  # counting the number of buildings connectedin DCN
    master_to_slave_vars.individual_number = ind_num
    master_to_slave_vars.generation_number = gen

    Q_heating_nom_W = Q_heating_max_W * (1 + Q_MARGIN_FOR_NETWORK)
    Q_cooling_nom_W = Q_cooling_max_W * (1 + Q_MARGIN_FOR_NETWORK)

    # Heating systems

    #CHP units with NG & furnace with biomass wet
    if individual[0] == 1 or individual[0] == 3:
        if FURNACE_ALLOWED == True:
            master_to_slave_vars.Furnace_on = 1
            master_to_slave_vars.Furnace_Q_max_W = max(
                individual[1] * Q_heating_nom_W, Q_MIN_SHARE * Q_heating_nom_W)
            master_to_slave_vars.Furn_Moist_type = "wet"
        elif CC_ALLOWED == True:
            master_to_slave_vars.CC_on = 1
            master_to_slave_vars.CC_GT_SIZE_W = max(
                individual[1] * Q_heating_nom_W * 1.3,
                Q_MIN_SHARE * Q_heating_nom_W * 1.3)
            #1.3 is the conversion factor between the GT_Elec_size NG and Q_DHN
            master_to_slave_vars.gt_fuel = "NG"

    #CHP units with BG& furnace with biomass dry
    if individual[0] == 2 or individual[0] == 4:
        if FURNACE_ALLOWED == True:
            master_to_slave_vars.Furnace_on = 1
            master_to_slave_vars.Furnace_Q_max_W = max(
                individual[1] * Q_heating_nom_W, Q_MIN_SHARE * Q_heating_nom_W)
            master_to_slave_vars.Furn_Moist_type = "dry"
        elif CC_ALLOWED == True:
            master_to_slave_vars.CC_on = 1
            master_to_slave_vars.CC_GT_SIZE_W = max(
                individual[1] * Q_heating_nom_W * 1.5,
                Q_MIN_SHARE * Q_heating_nom_W * 1.5)
            #1.5 is the conversion factor between the GT_Elec_size BG and Q_DHN
            master_to_slave_vars.gt_fuel = "BG"

    # Base boiler NG
    if individual[2] == 1:
        master_to_slave_vars.Boiler_on = 1
        master_to_slave_vars.Boiler_Q_max_W = max(
            individual[3] * Q_heating_nom_W, Q_MIN_SHARE * Q_heating_nom_W)
        master_to_slave_vars.BoilerType = "NG"

    # Base boiler BG
    if individual[2] == 2:
        master_to_slave_vars.Boiler_on = 1
        master_to_slave_vars.Boiler_Q_max_W = max(
            individual[3] * Q_heating_nom_W, Q_MIN_SHARE * Q_heating_nom_W)
        master_to_slave_vars.BoilerType = "BG"

    # peak boiler NG
    if individual[4] == 1:
        master_to_slave_vars.BoilerPeak_on = 1
        master_to_slave_vars.BoilerPeak_Q_max_W = max(
            individual[5] * Q_heating_nom_W, Q_MIN_SHARE * Q_heating_nom_W)
        master_to_slave_vars.BoilerPeakType = "NG"

    # peak boiler BG
    if individual[4] == 2:
        master_to_slave_vars.BoilerPeak_on = 1
        master_to_slave_vars.BoilerPeak_Q_max_W = max(
            individual[5] * Q_heating_nom_W, Q_MIN_SHARE * Q_heating_nom_W)
        master_to_slave_vars.BoilerPeakType = "BG"

    # lake - heat pump
    if individual[6] == 1 and HP_LAKE_ALLOWED == True:
        master_to_slave_vars.HP_Lake_on = 1
        master_to_slave_vars.HPLake_maxSize_W = max(
            individual[7] * Q_heating_nom_W, Q_MIN_SHARE * Q_heating_nom_W)

    # sewage - heatpump
    if individual[8] == 1 and HP_SEW_ALLOWED == True:
        master_to_slave_vars.HP_Sew_on = 1
        master_to_slave_vars.HPSew_maxSize_W = max(
            individual[9] * Q_heating_nom_W, Q_MIN_SHARE * Q_heating_nom_W)

    # Gwound source- heatpump
    if individual[10] == 1 and GHP_ALLOWED == True:
        master_to_slave_vars.GHP_on = 1
        GHP_Qmax = max(individual[11] * Q_heating_nom_W,
                       Q_MIN_SHARE * Q_heating_nom_W)
        master_to_slave_vars.GHP_number = GHP_Qmax / GHP_HMAX_SIZE

    # heat recovery servers and compresor
    irank = N_HEAT * 2
    master_to_slave_vars.WasteServersHeatRecovery = individual[irank]
    master_to_slave_vars.WasteCompressorHeatRecovery = 0

    # Solar systems
    shareAvail = 1  # all buildings in the neighborhood are connected to the solar potential

    irank = N_HEAT * 2 + N_HR

    heating_block = N_HEAT * 2 + N_HR + N_SOLAR * 2 + INDICES_CORRESPONDING_TO_DHN
    master_to_slave_vars.DHN_supplyunits = DHN_configuration
    # cooling systems

    # Lake Cooling
    if individual[heating_block] == 1 and LAKE_COOLING_ALLOWED is True:
        master_to_slave_vars.Lake_cooling_on = 1
        master_to_slave_vars.Lake_cooling_size_W = max(
            individual[heating_block + 1] * Q_cooling_nom_W,
            Q_MIN_SHARE * Q_cooling_nom_W)

    # VCC Cooling
    if individual[heating_block + 2] == 1 and VCC_ALLOWED is True:
        master_to_slave_vars.VCC_on = 1
        master_to_slave_vars.VCC_cooling_size_W = max(
            individual[heating_block + 3] * Q_cooling_nom_W,
            Q_MIN_SHARE * Q_cooling_nom_W)

    # Absorption Chiller Cooling
    if individual[heating_block +
                  4] == 1 and ABSORPTION_CHILLER_ALLOWED is True:
        master_to_slave_vars.Absorption_Chiller_on = 1
        master_to_slave_vars.Absorption_chiller_size_W = max(
            individual[heating_block + 5] * Q_cooling_nom_W,
            Q_MIN_SHARE * Q_cooling_nom_W)

    # Storage Cooling
    if individual[heating_block + 6] == 1 and STORAGE_COOLING_ALLOWED is True:
        if (individual[heating_block + 2] == 1 and VCC_ALLOWED is True) or (
                individual[heating_block + 4] == 1
                and ABSORPTION_CHILLER_ALLOWED is True):
            master_to_slave_vars.storage_cooling_on = 1
            master_to_slave_vars.Storage_cooling_size_W = max(
                individual[heating_block + 7] * Q_cooling_nom_W,
                Q_MIN_SHARE * Q_cooling_nom_W)
            if master_to_slave_vars.Storage_cooling_size_W > STORAGE_COOLING_SHARE_RESTRICTION * Q_cooling_nom_W:
                master_to_slave_vars.Storage_cooling_size_W = STORAGE_COOLING_SHARE_RESTRICTION * Q_cooling_nom_W

    master_to_slave_vars.DCN_supplyunits = DCN_configuration
    master_to_slave_vars.SOLAR_PART_PV = max(
        individual[irank] * individual[irank + 1] * shareAvail, 0)
    master_to_slave_vars.SOLAR_PART_PVT = max(
        individual[irank + 2] * individual[irank + 3] * shareAvail, 0)
    master_to_slave_vars.SOLAR_PART_SC_ET = max(
        individual[irank + 4] * individual[irank + 5] * shareAvail, 0)
    master_to_slave_vars.SOLAR_PART_SC_FP = max(
        individual[irank + 6] * individual[irank + 7] * shareAvail, 0)

    return master_to_slave_vars
Пример #6
0
def evaluation_main(individual, building_names, locator, solar_features,
                    network_features, gv, config, prices, lca, ind_num, gen):
    """
    This function evaluates an individual

    :param individual: list with values of the individual
    :param building_names: list with names of buildings
    :param locator: locator class
    :param solar_features: solar features call to class
    :param network_features: network features call to class
    :param gv: global variables class
    :param optimization_constants: class containing constants used in optimization
    :param config: configuration file
    :param prices: class of prices used in optimization
    :type individual: list
    :type building_names: list
    :type locator: string
    :type solar_features: class
    :type network_features: class
    :type gv: class
    :type optimization_constants: class
    :type config: class
    :type prices: class
    :return: Resulting values of the objective function. costs, CO2, prim
    :rtype: tuple

    """
    # Check the consistency of the individual or create a new one
    individual = check_invalid(individual, len(building_names), config)

    # Initialize objective functions costs, CO2 and primary energy
    costs_USD = 0
    GHG_tonCO2 = 0
    PEN_MJoil = 0
    Q_heating_uncovered_design_W = 0
    Q_heating_uncovered_annual_W = 0

    # Create the string representation of the individual
    DHN_barcode, DCN_barcode, DHN_configuration, DCN_configuration = supportFn.individual_to_barcode(
        individual, building_names)

    if DHN_barcode.count("1") == gv.num_tot_buildings:
        network_file_name_heating = "Network_summary_result_all.csv"
        Q_DHNf_W = pd.read_csv(
            locator.get_optimization_network_all_results_summary('all'),
            usecols=["Q_DHNf_W"]).values
        Q_heating_max_W = Q_DHNf_W.max()
    elif DHN_barcode.count("1") == 0:
        network_file_name_heating = "Network_summary_result_all.csv"
        Q_heating_max_W = 0
    else:
        network_file_name_heating = "Network_summary_result_" + hex(
            int(str(DHN_barcode), 2)) + ".csv"
        if not os.path.exists(
                locator.get_optimization_network_results_summary(DHN_barcode)):
            total_demand = supportFn.createTotalNtwCsv(DHN_barcode, locator)
            building_names = total_demand.Name.values
            # Run the substation and distribution routines
            substation.substation_main(locator,
                                       total_demand,
                                       building_names,
                                       DHN_configuration,
                                       DCN_configuration,
                                       Flag=True)
            summarize_network.network_main(locator, total_demand,
                                           building_names, config, gv,
                                           DHN_barcode)

        Q_DHNf_W = pd.read_csv(
            locator.get_optimization_network_results_summary(DHN_barcode),
            usecols=["Q_DHNf_W"]).values
        Q_heating_max_W = Q_DHNf_W.max()

    if DCN_barcode.count("1") == gv.num_tot_buildings:
        network_file_name_cooling = "Network_summary_result_all.csv"
        if individual[
                N_HEAT *
                2] == 1:  # if heat recovery is ON, then only need to satisfy cooling load of space cooling and refrigeration
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_all_results_summary('all'),
                usecols=["Q_DCNf_space_cooling_and_refrigeration_W"]).values
        else:
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_all_results_summary('all'),
                usecols=[
                    "Q_DCNf_space_cooling_data_center_and_refrigeration_W"
                ]).values
        Q_cooling_max_W = Q_DCNf_W.max()
    elif DCN_barcode.count("1") == 0:
        network_file_name_cooling = "Network_summary_result_all.csv"
        Q_cooling_max_W = 0
    else:
        network_file_name_cooling = "Network_summary_result_" + hex(
            int(str(DCN_barcode), 2)) + ".csv"

        if not os.path.exists(
                locator.get_optimization_network_results_summary(DCN_barcode)):
            total_demand = supportFn.createTotalNtwCsv(DCN_barcode, locator)
            building_names = total_demand.Name.values

            # Run the substation and distribution routines
            substation.substation_main(locator,
                                       total_demand,
                                       building_names,
                                       DHN_configuration,
                                       DCN_configuration,
                                       Flag=True)
            summarize_network.network_main(locator, total_demand,
                                           building_names, config, gv,
                                           DCN_barcode)

        if individual[
                N_HEAT *
                2] == 1:  # if heat recovery is ON, then only need to satisfy cooling load of space cooling and refrigeration
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_results_summary(DCN_barcode),
                usecols=["Q_DCNf_space_cooling_and_refrigeration_W"]).values
        else:
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_results_summary(DCN_barcode),
                usecols=[
                    "Q_DCNf_space_cooling_data_center_and_refrigeration_W"
                ]).values
        Q_cooling_max_W = Q_DCNf_W.max()

    Q_heating_nom_W = Q_heating_max_W * (1 + Q_MARGIN_FOR_NETWORK)
    Q_cooling_nom_W = Q_cooling_max_W * (1 + Q_MARGIN_FOR_NETWORK)

    # Modify the individual with the extra GHP constraint
    try:
        check.GHPCheck(individual, locator, Q_heating_nom_W, gv)
    except:
        print "No GHP constraint check possible \n"

    # Export to context
    master_to_slave_vars = calc_master_to_slave_variables(
        individual, Q_heating_max_W, Q_cooling_max_W, building_names, ind_num,
        gen)
    master_to_slave_vars.network_data_file_heating = network_file_name_heating
    master_to_slave_vars.network_data_file_cooling = network_file_name_cooling
    master_to_slave_vars.total_buildings = len(building_names)
    master_to_slave_vars.DHN_barcode = DHN_barcode
    master_to_slave_vars.DCN_barcode = DCN_barcode

    if master_to_slave_vars.number_of_buildings_connected_heating > 1:
        if DHN_barcode.count("0") == 0:
            master_to_slave_vars.fNameTotalCSV = locator.get_total_demand()
        else:
            master_to_slave_vars.fNameTotalCSV = os.path.join(
                locator.get_optimization_network_totals_folder(),
                "Total_%(DHN_barcode)s.csv" % locals())
    else:
        master_to_slave_vars.fNameTotalCSV = locator.get_optimization_substations_total_file(
            DHN_barcode)

    if master_to_slave_vars.number_of_buildings_connected_cooling > 1:
        if DCN_barcode.count("0") == 0:
            master_to_slave_vars.fNameTotalCSV = locator.get_total_demand()
        else:
            master_to_slave_vars.fNameTotalCSV = os.path.join(
                locator.get_optimization_network_totals_folder(),
                "Total_%(DCN_barcode)s.csv" % locals())
    else:
        master_to_slave_vars.fNameTotalCSV = locator.get_optimization_substations_total_file(
            DCN_barcode)

    # Thermal Storage Calculations; Run storage optimization
    costs_storage_USD, GHG_storage_tonCO2, PEN_storage_MJoil = storage_main.storage_optimization(
        locator, master_to_slave_vars, lca, prices, config)

    costs_USD += costs_storage_USD
    GHG_tonCO2 += GHG_storage_tonCO2
    PEN_MJoil += PEN_storage_MJoil

    # District Heating Calculations
    if config.district_heating_network:

        if DHN_barcode.count("1") > 0:

            (PEN_heating_MJoil, GHG_heating_tonCO2, costs_heating_USD,
             Q_heating_uncovered_design_W, Q_heating_uncovered_annual_W
             ) = heating_main.heating_calculations_of_DH_buildings(
                 locator, master_to_slave_vars, gv, config, prices, lca)
        else:

            GHG_heating_tonCO2 = 0
            costs_heating_USD = 0
            PEN_heating_MJoil = 0
    else:
        GHG_heating_tonCO2 = 0
        costs_heating_USD = 0
        PEN_heating_MJoil = 0

    costs_USD += costs_heating_USD
    GHG_tonCO2 += GHG_heating_tonCO2
    PEN_MJoil += PEN_heating_MJoil

    # District Cooling Calculations
    if gv.ZernezFlag == 1:
        costs_cooling_USD, GHG_cooling_tonCO2, PEN_cooling_MJoil = 0, 0, 0
    elif config.district_cooling_network:
        reduced_timesteps_flag = False
        (costs_cooling_USD, GHG_cooling_tonCO2, PEN_cooling_MJoil
         ) = cooling_main.cooling_calculations_of_DC_buildings(
             locator, master_to_slave_vars, network_features, gv, prices, lca,
             config, reduced_timesteps_flag)
    else:
        costs_cooling_USD, GHG_cooling_tonCO2, PEN_cooling_MJoil = 0, 0, 0

    costs_USD += costs_cooling_USD
    GHG_tonCO2 += GHG_cooling_tonCO2
    PEN_MJoil += PEN_cooling_MJoil

    # District Electricity Calculations
    (costs_electricity_USD, GHG_electricity_tonCO2, PEN_electricity_MJoil
     ) = electricity_main.electricity_calculations_of_all_buildings(
         DHN_barcode, DCN_barcode, locator, master_to_slave_vars,
         network_features, gv, prices, lca, config)

    costs_USD += costs_electricity_USD
    GHG_tonCO2 += GHG_electricity_tonCO2
    PEN_MJoil += PEN_electricity_MJoil

    # Natural Gas Import Calculations. Prices, GHG and PEN are already included in the various sections.
    # This is to save the files for further processing and plots
    natural_gas_main.natural_gas_imports(master_to_slave_vars, locator, config)

    # Capex Calculations
    print "Add extra costs"
    (costs_additional_USD,
     GHG_additional_tonCO2, PEN_additional_MJoil) = cost_model.addCosts(
         building_names, locator, master_to_slave_vars,
         Q_heating_uncovered_design_W, Q_heating_uncovered_annual_W,
         solar_features, network_features, gv, config, prices, lca)

    costs_USD += costs_additional_USD
    GHG_tonCO2 += GHG_additional_tonCO2
    PEN_MJoil += PEN_additional_MJoil

    summarize_individual.summarize_individual_main(master_to_slave_vars,
                                                   building_names, individual,
                                                   solar_features, locator,
                                                   config)

    # Converting costs into float64 to avoid longer values
    costs_USD = np.float64(costs_USD)
    GHG_tonCO2 = np.float64(GHG_tonCO2)
    PEN_MJoil = np.float64(PEN_MJoil)

    print('Total costs = ' + str(costs_USD))
    print('Total CO2 = ' + str(GHG_tonCO2))
    print('Total prim = ' + str(PEN_MJoil))

    # Saving capacity details of the individual

    return costs_USD, GHG_tonCO2, PEN_MJoil, master_to_slave_vars, individual
Пример #7
0
def mcda_indicators(individual, locator, plot = 0):
    """
    Computes the specific operational costs and the share of local resources
    
    """
    configKey = "".join(str(e)[0:4] for e in individual)
    print configKey
    buildList = sFn.extract_building_names_from_csv(locator.pathRaw + "/Total.csv")
    gv = cea.globalvar.GlobalVariables()
    
    # Recover data from the PP activation file
    resourcesFile = os.path.join(locator.get_optimization_slave_results_folder(), "%(configKey)sPPActivationPattern.csv" % locals())
    resourcesdf = pd.read_csv(resourcesFile, usecols=["ESolarProducedPVandPVT", "Q_AddBoiler", "Q_BoilerBase", "Q_BoilerPeak", "Q_CC", "Q_GHP", \
                                                        "Q_HPLake", "Q_HPSew", "Q_primaryAddBackupSum", "Q_uncontrollable"])
                                                        
    Electricity_Solar = resourcesdf.ESolarProducedPVandPVT.sum()
    Q_AddBoiler = resourcesdf.Q_AddBoiler.sum()
    Q_BoilerBase = resourcesdf.Q_BoilerBase.sum()
    Q_BoilerPeak = resourcesdf.Q_BoilerPeak.sum()
    Q_CC = resourcesdf.Q_CC.sum()
    Q_GHP = resourcesdf.Q_GHP.sum()
    Q_HPLake = resourcesdf.Q_HPLake.sum()
    Q_HPSew = resourcesdf.Q_HPSew.sum()
    Q_storage_missmatch = resourcesdf.Q_primaryAddBackupSum.sum()
    Q_uncontrollable = resourcesdf.Q_uncontrollable.sum()

    # Recover data from the Storage Operation file
    resourcesFile = os.path.join(locator.get_optimization_slave_results_folder(),
                                 "%(configKey)sStorageOperationData.csv" % locals())
    resourcesdf = pd.read_csv(resourcesFile, usecols=["Q_SCandPVT_coldstream"])
    Q_fromSolar = resourcesdf.Q_SCandPVT_coldstream.sum()


    # Recover heating needs for decentralized buildings
    indCombi = sFn.individual_to_barcode(individual, gv)
    QfromNG = 0
    QfromBG = 0
    QfromGHP = 0
    
    for i in range(len(indCombi)):
        if indCombi[i] == "0": # Decentralized building
            building_name = buildList[i]
            df = pd.read_csv(locator.get_optimization_disconnected_result_file(building_name))
            dfBest = df[ df["Best configuration"] == 1 ]
               
            QfromNG += dfBest["QfromNG"].iloc[0]
            QfromBG += dfBest["QfromBG"].iloc[0]
            QfromGHP += dfBest["QfromGHP"].iloc[0]

    # Recover electricity and cooling needs
    totalFile = locator.pathRaw + "/Total.csv"
    df = pd.read_csv(totalFile, usecols=["Ealf", "Eauxf", "Ecaf", "Edataf", "Epf"])
    arrayTotal = np.array(df)
    totalElec = np.sum(arrayTotal) * 1E6 # [Wh]

    df = pd.read_csv(totalFile, usecols=["Qcdataf", "Qcicef", "Qcpf", "Qcsf"])
    arrayTotal = np.array(df)
    if individual[12] == 0:
        totalCool = ( np.sum((arrayTotal)[:,:-1]) + np.sum((arrayTotal)[:,-1:]) * (1+gv.DCNetworkLoss) ) * 1E6 # [Wh]
    else:
        totalCool = ( np.sum((arrayTotal)[:,1:-1]) + np.sum((arrayTotal)[:,-1:]) * (1+gv.DCNetworkLoss) ) * 1E6 # [Wh]
    
    
    # Computes the specific operational costs
    totalEnergy = Q_AddBoiler + Q_BoilerBase + Q_BoilerPeak + Q_CC + Q_GHP + Q_HPLake + \
                  Q_HPSew  + Q_uncontrollable + totalElec + totalCool + \
                  QfromNG + QfromBG + QfromGHP# + Q_storage_missmatch
                  
    shareCC_NG = individual[0] % 2 * Q_CC / totalEnergy
    shareCC_BG = ( individual[0] + 1 ) % 2 * Q_CC / totalEnergy
    shareBB_NG = individual[2] % 2 * Q_BoilerBase / totalEnergy
    shareBB_BG = ( individual[2] + 1 ) % 2 * Q_BoilerBase / totalEnergy
    shareBP_NG = individual[4] % 2 * Q_BoilerPeak / totalEnergy
    shareBP_BG = ( individual[4] + 1 ) % 2 * Q_BoilerPeak / totalEnergy
    shareHPLake = Q_HPLake / totalEnergy
    shareHPSew = Q_HPSew / totalEnergy
    shareGHP = Q_GHP / totalEnergy
    shareExtraNG = (Q_AddBoiler + Q_storage_missmatch) / totalEnergy
    shareHR = (Q_uncontrollable - Q_fromSolar) / totalEnergy
    shareHeatSolar = Q_fromSolar / totalEnergy
    shareDecentralizedNG = QfromNG / totalEnergy
    shareDecentralizedBG = QfromBG / totalEnergy
    shareDecentralizedGHP = QfromGHP / totalEnergy
    shareElecGrid = (totalElec - Electricity_Solar) / totalEnergy
    shareElecSolar = Electricity_Solar / totalEnergy
    shareCoolLake = totalCool / totalEnergy
    
    printout = 1
    if printout:
        print 'CC_NG', individual[0] % 2 * Q_CC
        print 'CC_BG', ( individual[0] + 1 ) % 2 * Q_CC
        print 'BB_NG', individual[2] % 2 * Q_BoilerBase
        print 'BB_BG', ( individual[2] + 1 ) % 2 * Q_BoilerBase
        print 'BP_NG', individual[4] % 2 * Q_BoilerPeak
        print 'BP_BG', ( individual[4] + 1 ) % 2 * Q_BoilerPeak
        print 'HPLake', Q_HPLake
        print 'HPSew', Q_HPSew
        print 'GHP', Q_GHP
        print 'ExtraNG', (Q_AddBoiler + Q_storage_missmatch)
        print 'HR', (Q_uncontrollable - Q_fromSolar)
        print 'HeatSolar', Q_fromSolar
        print 'DecentralizedNG', QfromNG
        print 'DecentralizedBG', QfromBG
        print 'DecentralizedGHP', QfromGHP
        print 'ElecGrid', (totalElec - Electricity_Solar)
        print 'ElecSolar', Electricity_Solar
        print 'CoolLake', totalCool

        print 'shareCC_NG', shareCC_NG*100 
        print 'shareCC_BG', shareCC_BG*100
        print 'shareBB_NG', shareBB_NG*100
        print 'shareBB_BG',  shareBB_BG*100
        print 'shareBP_NG', shareBP_NG*100
        print 'shareBP_BG', shareBP_BG*100 
        print 'shareHPLake', shareHPLake*100 
        print 'shareHPSew', shareHPSew*100 
        print 'shareGHP', shareGHP*100 
        print 'shareExtraNG', shareExtraNG*100 
        print 'shareHR', shareHR*100
        print 'shareHeatSolar', shareHeatSolar*100
        print 'shareDecentralizedNG', shareDecentralizedNG*100
        print 'shareDecentralizedBG', shareDecentralizedBG*100 
        print 'shareDecentralizedGHP', shareDecentralizedGHP*100
        print 'shareElecGrid' ,shareElecGrid*100 
        print 'shareElecSolar', shareElecSolar*100 
        print 'shareCoolLake', shareCoolLake*100

    specificCosts = gv.ELEC_PRICE * shareElecGrid + \
                    gv.NG_PRICE * (shareCC_NG + shareBB_NG + shareBP_NG + shareExtraNG + shareDecentralizedNG) + \
                    gv.BG_PRICE * (shareCC_BG + shareBB_BG + shareBP_BG + shareDecentralizedBG)
    
    # Computes the share of local resources
    shareLocal = shareHPLake + shareHPSew + shareGHP + shareHR + shareHeatSolar + shareDecentralizedGHP + shareElecSolar + shareCoolLake
    
    # Plots the pie chart for energy resources use
    if plot == 1:
        fig = plt.figure()
        subplot = fig.add_subplot(111, adjustable = 'box', aspect = 1, title = 'Energy mix')
        
        labels = ['Lake', 'Solar', 'HR', 'Ground', 'Gas', 'Grid']
        shareLake = shareHPLake + shareCoolLake
        shareSolar = shareHeatSolar + shareElecSolar
        shareHRAll = shareHPSew + shareHR
        shareGround = shareGHP + shareDecentralizedGHP
        shareGas = 1 - shareLake - shareSolar - shareHRAll - shareGround - shareElecGrid
        
        fracs = [ shareLake, shareSolar, shareHRAll, shareGround, shareGas, shareElecGrid ]
        colors = ['RoyalBlue', 'Gold', 'LightGreen', 'SandyBrown', 'OrangeRed', 'Gray']
        
        zipper = [ (l,f,c) for (l,f,c) in zip(labels,fracs,colors) if f > 0.001 ]
        labelsPlot, fracsPlot, colorsPlot = map( list, zip(*zipper) )
        subplot.pie(fracsPlot, labels = labelsPlot, colors = colorsPlot, startangle = 90, autopct='%1.1f%%', pctdistance = 0.65)
        
        plt.show()
    
    return specificCosts, shareLocal
Пример #8
0
def supply_calculation(individual, building_names, total_demand, locator,
                       extra_costs, extra_CO2, extra_primary_energy,
                       solar_features, network_features, gv, config, prices,
                       lca):
    """
    This function evaluates one supply system configuration of the case study.
    :param individual: a list that indicates the supply system configuration
    :type individual: list
    :param building_names: names of all building in the district
    :type building_names: ndarray
    :param locator:
    :param extra_costs: cost of decentralized supply systems
    :param extra_CO2: CO2 emission of decentralized supply systems
    :param extra_primary_energy: Primary energy of decentralized supply systems
    :param solar_features: Energy production potentials of solar technologies, including area of installed panels and annual production
    :type solar_features: dict
    :param network_features: hourly network operating conditions (thermal/pressure losses) and capital costs
    :type network_features: dict
    :param gv:
    :param config:
    :param prices:
    :return:
    """
    individual = evaluation.check_invalid(individual, len(building_names),
                                          config)

    # Initialize objective functions costs, CO2 and primary energy
    costs_USD = 0.0
    GHG_tonCO2 = extra_CO2
    PEN_MJoil = extra_primary_energy
    Q_uncovered_design_W = 0.0
    Q_uncovered_annual_W = 0.0

    # Create the string representation of the individual
    DHN_barcode, DCN_barcode, DHN_configuration, DCN_configuration = supportFn.individual_to_barcode(
        individual, building_names)

    # read the total loads from buildings connected to thermal networks
    if DHN_barcode.count("1") == gv.num_tot_buildings:
        network_file_name_heating = "Network_summary_result_all.csv"
        Q_DHNf_W = pd.read_csv(
            locator.get_optimization_network_all_results_summary('all'),
            usecols=["Q_DHNf_W"]).values
        Q_heating_max_W = Q_DHNf_W.max()
    elif DHN_barcode.count("1") == 0:
        network_file_name_heating = "Network_summary_result_all.csv"
        Q_heating_max_W = 0.0
    else:
        # Run the substation and distribution routines
        substation.substation_main(locator,
                                   total_demand,
                                   building_names,
                                   DHN_configuration,
                                   DCN_configuration,
                                   Flag=True)

        summarize_network.network_main(locator, total_demand, building_names,
                                       config, gv, DHN_barcode)

        network_file_name_heating = "Network_summary_result_" + hex(
            int(str(DHN_barcode), 2)) + ".csv"
        Q_DHNf_W = pd.read_csv(
            locator.get_optimization_network_results_summary(DHN_barcode),
            usecols=["Q_DHNf_W"]).values
        Q_heating_max_W = Q_DHNf_W.max()

    if DCN_barcode.count("1") == gv.num_tot_buildings:
        network_file_name_cooling = "Network_summary_result_all.csv"
        if individual[
                N_HEAT *
                2] == 1:  # if heat recovery is ON, then only need to satisfy cooling load of space cooling and refrigeration
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_all_results_summary('all'),
                usecols=["Q_DCNf_space_cooling_and_refrigeration_W"]).values
        else:
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_all_results_summary('all'),
                usecols=[
                    "Q_DCNf_space_cooling_data_center_and_refrigeration_W"
                ]).values
        Q_cooling_max_W = Q_DCNf_W.max()
    elif DCN_barcode.count("1") == 0:
        network_file_name_cooling = "Network_summary_result_none.csv"
        Q_cooling_max_W = 0
    else:
        # Run the substation and distribution routines
        substation.substation_main(locator,
                                   total_demand,
                                   building_names,
                                   DHN_configuration,
                                   DCN_configuration,
                                   Flag=True)

        summarize_network.network_main(locator, total_demand, building_names,
                                       config, gv, DCN_barcode)

        network_file_name_cooling = "Network_summary_result_" + hex(
            int(str(DCN_barcode), 2)) + ".csv"

        if individual[
                N_HEAT *
                2] == 1:  # if heat recovery is ON, then only need to satisfy cooling load of space cooling and refrigeration
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_results_summary(DCN_barcode),
                usecols=["Q_DCNf_space_cooling_and_refrigeration_W"]).values
        else:
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_results_summary(DCN_barcode),
                usecols=[
                    "Q_DCNf_space_cooling_data_center_and_refrigeration_W"
                ]).values
        Q_cooling_max_W = Q_DCNf_W.max()

    Q_heating_nom_W = Q_heating_max_W * (1 + Q_MARGIN_FOR_NETWORK)
    Q_cooling_nom_W = Q_cooling_max_W * (1 + Q_MARGIN_FOR_NETWORK)

    # Modify the individual with the extra GHP constraint
    try:
        check.GHPCheck(individual, locator, Q_heating_nom_W, gv)
    except:
        print "No GHP constraint check possible \n"

    # Export to context
    individual_number = calc_individual_number(locator)
    master_to_slave_vars = evaluation.calc_master_to_slave_variables(
        individual, Q_heating_max_W, Q_cooling_max_W, building_names,
        individual_number, GENERATION_NUMBER)
    master_to_slave_vars.network_data_file_heating = network_file_name_heating
    master_to_slave_vars.network_data_file_cooling = network_file_name_cooling
    master_to_slave_vars.total_buildings = len(building_names)

    if master_to_slave_vars.number_of_buildings_connected_heating > 1:
        if DHN_barcode.count("0") == 0:
            master_to_slave_vars.fNameTotalCSV = locator.get_total_demand()
        else:
            master_to_slave_vars.fNameTotalCSV = os.path.join(
                locator.get_optimization_network_totals_folder(),
                "Total_%(DHN_barcode)s.csv" % locals())
    else:
        master_to_slave_vars.fNameTotalCSV = locator.get_optimization_substations_total_file(
            DHN_barcode)

    if master_to_slave_vars.number_of_buildings_connected_cooling > 1:
        if DCN_barcode.count("0") == 0:
            master_to_slave_vars.fNameTotalCSV = locator.get_total_demand()
        else:
            master_to_slave_vars.fNameTotalCSV = os.path.join(
                locator.get_optimization_network_totals_folder(),
                "Total_%(DCN_barcode)s.csv" % locals())
    else:
        master_to_slave_vars.fNameTotalCSV = locator.get_optimization_substations_total_file(
            DCN_barcode)

    costs_storage_USD, GHG_storage_tonCO2, PEN_storage_MJoil = storage_main.storage_optimization(
        locator, master_to_slave_vars, lca, prices, config)

    costs_USD += costs_storage_USD
    GHG_tonCO2 += GHG_storage_tonCO2
    PEN_MJoil += PEN_storage_MJoil

    # slave optimization of heating networks
    if config.district_heating_network:
        if DHN_barcode.count("1") > 0:
            (PEN_heating_MJoil, GHG_heating_tonCO2, costs_heating_USD,
             Q_uncovered_design_W, Q_uncovered_annual_W
             ) = heating_main.heating_calculations_of_DH_buildings(
                 locator, master_to_slave_vars, gv, config, prices, lca)
        else:
            GHG_heating_tonCO2 = 0.0
            costs_heating_USD = 0.0
            PEN_heating_MJoil = 0.0
    else:
        GHG_heating_tonCO2 = 0.0
        costs_heating_USD = 0.0
        PEN_heating_MJoil = 0.0

    costs_USD += costs_heating_USD
    GHG_tonCO2 += GHG_heating_tonCO2
    PEN_MJoil += PEN_heating_MJoil

    # slave optimization of cooling networks
    if gv.ZernezFlag == 1:
        costs_cooling_USD, GHG_cooling_tonCO2, PEN_cooling_MJoil = 0.0, 0.0, 0.0
    elif config.district_cooling_network and DCN_barcode.count("1") > 0:
        reduced_timesteps_flag = config.supply_system_simulation.reduced_timesteps
        (costs_cooling_USD, GHG_cooling_tonCO2, PEN_cooling_MJoil
         ) = cooling_main.cooling_calculations_of_DC_buildings(
             locator, master_to_slave_vars, network_features, gv, prices, lca,
             config, reduced_timesteps_flag)
        # if reduced_timesteps_flag:
        #     # reduced timesteps simulation for a month (May)
        #     coolCosts = coolCosts * (8760/(3624/2880))
        #     coolCO2 = coolCO2 * (8760/(3624/2880))
        #     coolPrim = coolPrim * (8760/(3624/2880))
        #     # FIXME: check results
    else:
        costs_cooling_USD, GHG_cooling_tonCO2, PEN_cooling_MJoil = 0.0, 0.0, 0.0

    # District Electricity Calculations
    costs_electricity_USD, GHG_electricity_tonCO2, PEN_electricity_MJoil = electricity_main.electricity_calculations_of_all_buildings(
        DHN_barcode, DCN_barcode, locator, master_to_slave_vars,
        network_features, gv, prices, lca, config)

    costs_USD += costs_electricity_USD
    GHG_tonCO2 += GHG_electricity_tonCO2
    PEN_MJoil += PEN_electricity_MJoil

    natural_gas_main.natural_gas_imports(master_to_slave_vars, locator, config)

    # print "Add extra costs"
    # add costs of disconnected buildings (best configuration)
    (costs_additional_USD,
     GHG_additional_tonCO2, PEN_additional_MJoil) = cost_model.addCosts(
         building_names, locator, master_to_slave_vars, Q_uncovered_design_W,
         Q_uncovered_annual_W, solar_features, network_features, gv, config,
         prices, lca)

    costs_USD += costs_additional_USD
    GHG_tonCO2 += GHG_additional_tonCO2
    PEN_MJoil += PEN_additional_MJoil

    costs_USD = (np.float64(costs_USD) / 1e6).round(2)  # $ to Mio$
    GHG_tonCO2 = (np.float64(GHG_tonCO2) / 1e6).round(2)  # kg to kilo-ton
    PEN_MJoil = (np.float64(PEN_MJoil) / 1e6).round(2)  # MJ to TJ

    # add electricity costs corresponding to

    # print ('Additional costs = ' + str(addCosts))
    # print ('Additional CO2 = ' + str(addCO2))
    # print ('Additional prim = ' + str(addPrim))

    print('Total annualized costs [USD$(2015) Mio/yr] = ' + str(costs_USD))
    print('Green house gas emission [kton-CO2/yr] = ' + str(GHG_tonCO2))
    print('Primary energy [TJ-oil-eq/yr] = ' + str(PEN_MJoil))

    results = {
        'TAC_Mio_per_yr': [costs_USD.round(2)],
        'CO2_kton_per_yr': [GHG_tonCO2.round(2)],
        'Primary_Energy_TJ_per_yr': [PEN_MJoil.round(2)]
    }
    results_df = pd.DataFrame(results)
    results_path = os.path.join(
        locator.get_optimization_slave_results_folder(GENERATION_NUMBER),
        'ind_' + str(individual_number) + '_results.csv')
    results_df.to_csv(results_path)

    with open(locator.get_optimization_checkpoint_initial(), "wb") as fp:
        pop = []
        g = GENERATION_NUMBER
        epsInd = []
        invalid_ind = []
        fitnesses = []
        capacities = []
        disconnected_capacities = []
        halloffame = []
        halloffame_fitness = []
        euclidean_distance = []
        spread = []
        cp = dict(population=pop,
                  generation=g,
                  epsIndicator=epsInd,
                  testedPop=invalid_ind,
                  population_fitness=fitnesses,
                  capacities=capacities,
                  disconnected_capacities=disconnected_capacities,
                  halloffame=halloffame,
                  halloffame_fitness=halloffame_fitness,
                  euclidean_distance=euclidean_distance,
                  spread=spread)
        json.dump(cp, fp)

    return costs_USD, GHG_tonCO2, PEN_MJoil, master_to_slave_vars, individual
Пример #9
0
def supply_calculation(individual, building_names, total_demand, locator,
                       extra_costs, extra_CO2, extra_primary_energy,
                       solar_features, network_features, gv, config, prices,
                       lca):
    """
    This function evaluates one supply system configuration of the case study.
    :param individual: a list that indicates the supply system configuration
    :type individual: list
    :param building_names: names of all building in the district
    :type building_names: ndarray
    :param locator:
    :param extra_costs: cost of decentralized supply systems
    :param extra_CO2: CO2 emission of decentralized supply systems
    :param extra_primary_energy: Primary energy of decentralized supply systems
    :param solar_features: Energy production potentials of solar technologies, including area of installed panels and annual production
    :type solar_features: dict
    :param network_features: hourly network operating conditions (thermal/pressure losses) and capital costs
    :type network_features: dict
    :param gv:
    :param config:
    :param prices:
    :return:
    """
    individual = evaluation.check_invalid(individual, len(building_names),
                                          config)

    # Initialize objective functions costs, CO2 and primary energy
    costs = 0
    CO2 = extra_CO2
    prim = extra_primary_energy
    QUncoveredDesign = 0
    QUncoveredAnnual = 0

    # Create the string representation of the individual
    DHN_barcode, DCN_barcode, DHN_configuration, DCN_configuration = sFn.individual_to_barcode(
        individual, building_names)

    # read the total loads from buildings connected to thermal networks
    if DHN_barcode.count("1") == gv.num_tot_buildings:
        network_file_name_heating = "Network_summary_result_all.csv"
        Q_DHNf_W = pd.read_csv(
            locator.get_optimization_network_all_results_summary('all'),
            usecols=["Q_DHNf_W"]).values
        Q_heating_max_W = Q_DHNf_W.max()
    elif DHN_barcode.count("1") == 0:
        network_file_name_heating = "Network_summary_result_all.csv"
        Q_heating_max_W = 0
    else:
        # Run the substation and distribution routines
        sMain.substation_main(locator,
                              total_demand,
                              building_names,
                              DHN_configuration,
                              DCN_configuration,
                              Flag=True)

        nM.network_main(locator, total_demand, building_names, config, gv,
                        DHN_barcode)

        network_file_name_heating = "Network_summary_result_" + hex(
            int(str(DHN_barcode), 2)) + ".csv"
        Q_DHNf_W = pd.read_csv(
            locator.get_optimization_network_results_summary(DHN_barcode),
            usecols=["Q_DHNf_W"]).values
        Q_heating_max_W = Q_DHNf_W.max()

    if DCN_barcode.count("1") == gv.num_tot_buildings:
        network_file_name_cooling = "Network_summary_result_all.csv"
        if individual[
                N_HEAT *
                2] == 1:  # if heat recovery is ON, then only need to satisfy cooling load of space cooling and refrigeration
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_all_results_summary('all'),
                usecols=["Q_DCNf_space_cooling_and_refrigeration_W"]).values
        else:
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_all_results_summary('all'),
                usecols=[
                    "Q_DCNf_space_cooling_data_center_and_refrigeration_W"
                ]).values
        Q_cooling_max_W = Q_DCNf_W.max()
    elif DCN_barcode.count("1") == 0:
        network_file_name_cooling = "Network_summary_result_none.csv"
        Q_cooling_max_W = 0
    else:
        # Run the substation and distribution routines
        sMain.substation_main(locator,
                              total_demand,
                              building_names,
                              DHN_configuration,
                              DCN_configuration,
                              Flag=True)

        nM.network_main(locator, total_demand, building_names, config, gv,
                        DCN_barcode)

        network_file_name_cooling = "Network_summary_result_" + hex(
            int(str(DCN_barcode), 2)) + ".csv"

        if individual[
                N_HEAT *
                2] == 1:  # if heat recovery is ON, then only need to satisfy cooling load of space cooling and refrigeration
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_results_summary(DCN_barcode),
                usecols=["Q_DCNf_space_cooling_and_refrigeration_W"]).values
        else:
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_results_summary(DCN_barcode),
                usecols=[
                    "Q_DCNf_space_cooling_data_center_and_refrigeration_W"
                ]).values
        Q_cooling_max_W = Q_DCNf_W.max()

    Q_heating_nom_W = Q_heating_max_W * (1 + Q_MARGIN_FOR_NETWORK)
    Q_cooling_nom_W = Q_cooling_max_W * (1 + Q_MARGIN_FOR_NETWORK)

    # Modify the individual with the extra GHP constraint
    try:
        cCheck.GHPCheck(individual, locator, Q_heating_nom_W, gv)
    except:
        print "No GHP constraint check possible \n"

    # Export to context
    individual_number = calc_individual_number(locator)
    master_to_slave_vars = evaluation.calc_master_to_slave_variables(
        individual, Q_heating_max_W, Q_cooling_max_W, building_names,
        individual_number, GENERATION_NUMBER)
    master_to_slave_vars.network_data_file_heating = network_file_name_heating
    master_to_slave_vars.network_data_file_cooling = network_file_name_cooling
    master_to_slave_vars.total_buildings = len(building_names)

    if master_to_slave_vars.number_of_buildings_connected_heating > 1:
        if DHN_barcode.count("0") == 0:
            master_to_slave_vars.fNameTotalCSV = locator.get_total_demand()
        else:
            master_to_slave_vars.fNameTotalCSV = os.path.join(
                locator.get_optimization_network_totals_folder(),
                "Total_%(DHN_barcode)s.csv" % locals())
    else:
        master_to_slave_vars.fNameTotalCSV = locator.get_optimization_substations_total_file(
            DHN_barcode)

    if master_to_slave_vars.number_of_buildings_connected_cooling > 1:
        if DCN_barcode.count("0") == 0:
            master_to_slave_vars.fNameTotalCSV = locator.get_total_demand()
        else:
            master_to_slave_vars.fNameTotalCSV = os.path.join(
                locator.get_optimization_network_totals_folder(),
                "Total_%(DCN_barcode)s.csv" % locals())
    else:
        master_to_slave_vars.fNameTotalCSV = locator.get_optimization_substations_total_file(
            DCN_barcode)

    # slave optimization of heating networks
    if config.optimization.isheating:
        if DHN_barcode.count("1") > 0:
            (slavePrim, slaveCO2, slaveCosts, QUncoveredDesign,
             QUncoveredAnnual) = sM.slave_main(locator, master_to_slave_vars,
                                               solar_features, gv, config,
                                               prices)
        else:
            slaveCO2 = 0
            slaveCosts = 0
            slavePrim = 0
    else:
        slaveCO2 = 0
        slaveCosts = 0
        slavePrim = 0

    costs += slaveCosts
    CO2 += slaveCO2
    prim += slavePrim

    # slave optimization of cooling networks
    if gv.ZernezFlag == 1:
        coolCosts, coolCO2, coolPrim = 0, 0, 0
    elif config.optimization.iscooling and DCN_barcode.count("1") > 0:
        reduced_timesteps_flag = config.supply_system_simulation.reduced_timesteps
        (coolCosts, coolCO2,
         coolPrim) = coolMain.coolingMain(locator, master_to_slave_vars,
                                          network_features, gv, prices, lca,
                                          config, reduced_timesteps_flag)
        # if reduced_timesteps_flag:
        #     # reduced timesteps simulation for a month (May)
        #     coolCosts = coolCosts * (8760/(3624/2880))
        #     coolCO2 = coolCO2 * (8760/(3624/2880))
        #     coolPrim = coolPrim * (8760/(3624/2880))
        #     # FIXME: check results
    else:
        coolCosts, coolCO2, coolPrim = 0, 0, 0

    # print "Add extra costs"
    # add costs of disconnected buildings (best configuration)
    (addCosts, addCO2,
     addPrim) = eM.addCosts(DHN_barcode, DCN_barcode, building_names, locator,
                            master_to_slave_vars, QUncoveredDesign,
                            QUncoveredAnnual, solar_features, network_features,
                            gv, config, prices, lca)

    # recalculate the addCosts by substracting the decentralized costs and add back to corresponding supply system
    Cost_diff, CO2_diff, Prim_diff = calc_decentralized_building_costs(
        config, locator, master_to_slave_vars, DHN_barcode, DCN_barcode,
        building_names)
    addCosts = addCosts + Cost_diff
    addCO2 = addCO2 + CO2_diff
    addPrim = addPrim + Prim_diff

    # add Capex and Opex of PV
    data_electricity = pd.read_csv(
        os.path.join(
            locator.
            get_optimization_slave_electricity_activation_pattern_cooling(
                individual_number, GENERATION_NUMBER)))

    total_area_for_pv = data_electricity['Area_PV_m2'].max()
    # remove the area installed with solar collectors
    sc_installed_area = 0
    if config.supply_system_simulation.decentralized_systems == 'Single-effect Absorption Chiller':
        for (index, building_name) in zip(DCN_barcode, building_names):
            if index == "0":
                sc_installed_area = sc_installed_area + pd.read_csv(
                    locator.PV_results(building_name))['Area_PV_m2'].max()
    pv_installed_area = total_area_for_pv - sc_installed_area
    Capex_a_PV, Opex_fixed_PV = calc_Cinv_pv(pv_installed_area, locator,
                                             config)
    pv_annual_production_kWh = (data_electricity['E_PV_W'].sum()) / 1000

    # electricity calculations
    data_network_electricity = pd.read_csv(
        os.path.join(
            locator.
            get_optimization_slave_electricity_activation_pattern_cooling(
                individual_number, GENERATION_NUMBER)))

    data_cooling = pd.read_csv(
        os.path.join(
            locator.get_optimization_slave_cooling_activation_pattern(
                individual_number, GENERATION_NUMBER)))

    total_demand = pd.read_csv(locator.get_total_demand())
    building_names = total_demand.Name.values
    total_electricity_demand_W = data_network_electricity['E_total_req_W']
    E_decentralized_appliances_W = np.zeros(8760)

    for i, name in zip(
            DCN_barcode, building_names
    ):  # adding the electricity demand from the decentralized buildings
        if i is '0':
            building_demand = pd.read_csv(locator.get_demand_results_folder() +
                                          '//' + name + ".csv",
                                          usecols=['E_sys_kWh'])
            E_decentralized_appliances_W += building_demand['E_sys_kWh'] * 1000

    total_electricity_demand_W = total_electricity_demand_W.add(
        E_decentralized_appliances_W)
    E_for_hot_water_demand_W = np.zeros(8760)

    for i, name in zip(
            DCN_barcode, building_names
    ):  # adding the electricity demand for hot water from all buildings
        building_demand = pd.read_csv(locator.get_demand_results_folder() +
                                      '//' + name + ".csv",
                                      usecols=['E_ww_kWh'])
        E_for_hot_water_demand_W += building_demand['E_ww_kWh'] * 1000

    total_electricity_demand_W = total_electricity_demand_W.add(
        E_for_hot_water_demand_W)
    # Electricity of Energy Systems
    lca = lca_calculations(locator, config)
    E_VCC_W = data_cooling['Opex_var_VCC'] / lca.ELEC_PRICE
    E_VCC_backup_W = data_cooling['Opex_var_VCC_backup'] / lca.ELEC_PRICE
    E_ACH_W = data_cooling['Opex_var_ACH'] / lca.ELEC_PRICE
    E_CT_W = abs(data_cooling['Opex_var_CT']) / lca.ELEC_PRICE
    total_electricity_demand_W = total_electricity_demand_W.add(E_VCC_W)
    total_electricity_demand_W = total_electricity_demand_W.add(E_VCC_backup_W)
    total_electricity_demand_W = total_electricity_demand_W.add(E_ACH_W)
    total_electricity_demand_W = total_electricity_demand_W.add(E_CT_W)
    E_from_CHP_W = data_network_electricity[
        'E_CHP_to_directload_W'] + data_network_electricity['E_CHP_to_grid_W']
    E_from_PV_W = data_network_electricity[
        'E_PV_to_directload_W'] + data_network_electricity['E_PV_to_grid_W']

    E_CHP_to_directload_W = np.zeros(8760)
    E_CHP_to_grid_W = np.zeros(8760)
    E_PV_to_directload_W = np.zeros(8760)
    E_PV_to_grid_W = np.zeros(8760)
    E_from_grid_W = np.zeros(8760)

    # modify simulation timesteps
    if reduced_timesteps_flag == False:
        start_t = 0
        stop_t = 8760
    else:
        # timesteps in May
        start_t = 2880
        stop_t = 3624
    timesteps = range(start_t, stop_t)

    for hour in timesteps:
        E_hour_W = total_electricity_demand_W[hour]
        if E_hour_W > 0:
            if E_from_PV_W[hour] > E_hour_W:
                E_PV_to_directload_W[hour] = E_hour_W
                E_PV_to_grid_W[hour] = E_from_PV_W[
                    hour] - total_electricity_demand_W[hour]
                E_hour_W = 0
            else:
                E_hour_W = E_hour_W - E_from_PV_W[hour]
                E_PV_to_directload_W[hour] = E_from_PV_W[hour]

            if E_from_CHP_W[hour] > E_hour_W:
                E_CHP_to_directload_W[hour] = E_hour_W
                E_CHP_to_grid_W[hour] = E_from_CHP_W[hour] - E_hour_W
                E_hour_W = 0
            else:
                E_hour_W = E_hour_W - E_from_CHP_W[hour]
                E_CHP_to_directload_W[hour] = E_from_CHP_W[hour]

            E_from_grid_W[hour] = E_hour_W

    date = data_network_electricity.DATE.values

    results = pd.DataFrame(
        {
            "DATE": date,
            "E_total_req_W": total_electricity_demand_W,
            "E_from_grid_W": E_from_grid_W,
            "E_VCC_W": E_VCC_W,
            "E_VCC_backup_W": E_VCC_backup_W,
            "E_ACH_W": E_ACH_W,
            "E_CT_W": E_CT_W,
            "E_PV_to_directload_W": E_PV_to_directload_W,
            "E_CHP_to_directload_W": E_CHP_to_directload_W,
            "E_CHP_to_grid_W": E_CHP_to_grid_W,
            "E_PV_to_grid_W": E_PV_to_grid_W,
            "E_for_hot_water_demand_W": E_for_hot_water_demand_W,
            "E_decentralized_appliances_W": E_decentralized_appliances_W,
            "E_total_to_grid_W_negative": -E_PV_to_grid_W - E_CHP_to_grid_W
        }
    )  # let's keep this negative so it is something exported, we can use it in the graphs of likelihood

    if reduced_timesteps_flag:
        reduced_el_costs = ((results['E_from_grid_W'].sum() +
                             results['E_total_to_grid_W_negative'].sum()) *
                            lca.ELEC_PRICE)
        electricity_costs = reduced_el_costs * (8760 / (stop_t - start_t))
    else:
        electricity_costs = ((results['E_from_grid_W'].sum() +
                              results['E_total_to_grid_W_negative'].sum()) *
                             lca.ELEC_PRICE)

    # emission from data
    data_emissions = pd.read_csv(
        os.path.join(
            locator.get_optimization_slave_investment_cost_detailed(
                individual_number, GENERATION_NUMBER)))
    update_PV_emission = abs(
        2 * data_emissions['CO2_PV_disconnected']).values[0]  # kg-CO2
    update_PV_primary = abs(
        2 * data_emissions['Eprim_PV_disconnected']).values[0]  # MJ oil-eq

    costs += addCosts + coolCosts + electricity_costs + Capex_a_PV + Opex_fixed_PV
    CO2 = CO2 + addCO2 + coolCO2 - update_PV_emission
    prim = prim + addPrim + coolPrim - update_PV_primary
    # Converting costs into float64 to avoid longer values
    costs = (np.float64(costs) / 1e6).round(2)  # $ to Mio$
    CO2 = (np.float64(CO2) / 1e6).round(2)  # kg to kilo-ton
    prim = (np.float64(prim) / 1e6).round(2)  # MJ to TJ

    # add electricity costs corresponding to

    # print ('Additional costs = ' + str(addCosts))
    # print ('Additional CO2 = ' + str(addCO2))
    # print ('Additional prim = ' + str(addPrim))

    print('Total annualized costs [USD$(2015) Mio/yr] = ' + str(costs))
    print('Green house gas emission [kton-CO2/yr] = ' + str(CO2))
    print('Primary energy [TJ-oil-eq/yr] = ' + str(prim))

    results = {
        'TAC_Mio_per_yr': [costs.round(2)],
        'CO2_kton_per_yr': [CO2.round(2)],
        'Primary_Energy_TJ_per_yr': [prim.round(2)]
    }
    results_df = pd.DataFrame(results)
    results_path = os.path.join(
        locator.get_optimization_slave_results_folder(GENERATION_NUMBER),
        'ind_' + str(individual_number) + '_results.csv')
    results_df.to_csv(results_path)

    with open(locator.get_optimization_checkpoint_initial(), "wb") as fp:
        pop = []
        g = GENERATION_NUMBER
        epsInd = []
        invalid_ind = []
        fitnesses = []
        capacities = []
        disconnected_capacities = []
        halloffame = []
        halloffame_fitness = []
        euclidean_distance = []
        spread = []
        cp = dict(population=pop,
                  generation=g,
                  epsIndicator=epsInd,
                  testedPop=invalid_ind,
                  population_fitness=fitnesses,
                  capacities=capacities,
                  disconnected_capacities=disconnected_capacities,
                  halloffame=halloffame,
                  halloffame_fitness=halloffame_fitness,
                  euclidean_distance=euclidean_distance,
                  spread=spread)
        json.dump(cp, fp)

    return costs, CO2, prim, master_to_slave_vars, individual
Пример #10
0
def evaluation_main(individual, building_names, locator, extraCosts, extraCO2,
                    extraPrim, solar_features, network_features, gv, config,
                    prices, lca, ind_num, gen):
    """
    This function evaluates an individual

    :param individual: list with values of the individual
    :param building_names: list with names of buildings
    :param locator: locator class
    :param extraCosts: costs calculated before optimization of specific energy services
     (process heat and electricity)
    :param extraCO2: green house gas emissions calculated before optimization of specific energy services
     (process heat and electricity)
    :param extraPrim: primary energy calculated before optimization ofr specific energy services
     (process heat and electricity)
    :param solar_features: solar features call to class
    :param network_features: network features call to class
    :param gv: global variables class
    :param optimization_constants: class containing constants used in optimization
    :param config: configuration file
    :param prices: class of prices used in optimization
    :type individual: list
    :type building_names: list
    :type locator: string
    :type extraCosts: float
    :type extraCO2: float
    :type extraPrim: float
    :type solar_features: class
    :type network_features: class
    :type gv: class
    :type optimization_constants: class
    :type config: class
    :type prices: class
    :return: Resulting values of the objective function. costs, CO2, prim
    :rtype: tuple

    """
    # Check the consistency of the individual or create a new one
    individual = check_invalid(individual, len(building_names), config)

    # Initialize objective functions costs, CO2 and primary energy
    costs = extraCosts
    CO2 = extraCO2
    prim = extraPrim
    QUncoveredDesign = 0
    QUncoveredAnnual = 0

    # Create the string representation of the individual
    DHN_barcode, DCN_barcode, DHN_configuration, DCN_configuration = sFn.individual_to_barcode(
        individual, building_names)

    if DHN_barcode.count("1") == gv.num_tot_buildings:
        network_file_name_heating = "Network_summary_result_all.csv"
        Q_DHNf_W = pd.read_csv(
            locator.get_optimization_network_all_results_summary('all'),
            usecols=["Q_DHNf_W"]).values
        Q_heating_max_W = Q_DHNf_W.max()
    elif DHN_barcode.count("1") == 0:
        network_file_name_heating = "Network_summary_result_all.csv"
        Q_heating_max_W = 0
    else:
        network_file_name_heating = "Network_summary_result_" + hex(
            int(str(DHN_barcode), 2)) + ".csv"
        if not os.path.exists(
                locator.get_optimization_network_results_summary(DHN_barcode)):
            total_demand = sFn.createTotalNtwCsv(DHN_barcode, locator)
            building_names = total_demand.Name.values
            # Run the substation and distribution routines
            sMain.substation_main(locator,
                                  total_demand,
                                  building_names,
                                  DHN_configuration,
                                  DCN_configuration,
                                  Flag=True)
            nM.network_main(locator, total_demand, building_names, config, gv,
                            DHN_barcode)

        Q_DHNf_W = pd.read_csv(
            locator.get_optimization_network_results_summary(DHN_barcode),
            usecols=["Q_DHNf_W"]).values
        Q_heating_max_W = Q_DHNf_W.max()

    if DCN_barcode.count("1") == gv.num_tot_buildings:
        network_file_name_cooling = "Network_summary_result_all.csv"
        if individual[
                N_HEAT *
                2] == 1:  # if heat recovery is ON, then only need to satisfy cooling load of space cooling and refrigeration
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_all_results_summary('all'),
                usecols=["Q_DCNf_space_cooling_and_refrigeration_W"]).values
        else:
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_all_results_summary('all'),
                usecols=[
                    "Q_DCNf_space_cooling_data_center_and_refrigeration_W"
                ]).values
        Q_cooling_max_W = Q_DCNf_W.max()
    elif DCN_barcode.count("1") == 0:
        network_file_name_cooling = "Network_summary_result_all.csv"
        Q_cooling_max_W = 0
    else:
        network_file_name_cooling = "Network_summary_result_" + hex(
            int(str(DCN_barcode), 2)) + ".csv"

        if not os.path.exists(
                locator.get_optimization_network_results_summary(DCN_barcode)):
            total_demand = sFn.createTotalNtwCsv(DCN_barcode, locator)
            building_names = total_demand.Name.values

            # Run the substation and distribution routines
            sMain.substation_main(locator,
                                  total_demand,
                                  building_names,
                                  DHN_configuration,
                                  DCN_configuration,
                                  Flag=True)
            nM.network_main(locator, total_demand, building_names, config, gv,
                            DCN_barcode)

        if individual[
                N_HEAT *
                2] == 1:  # if heat recovery is ON, then only need to satisfy cooling load of space cooling and refrigeration
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_results_summary(DCN_barcode),
                usecols=["Q_DCNf_space_cooling_and_refrigeration_W"]).values
        else:
            Q_DCNf_W = pd.read_csv(
                locator.get_optimization_network_results_summary(DCN_barcode),
                usecols=[
                    "Q_DCNf_space_cooling_data_center_and_refrigeration_W"
                ]).values
        Q_cooling_max_W = Q_DCNf_W.max()

    Q_heating_nom_W = Q_heating_max_W * (1 + Q_MARGIN_FOR_NETWORK)
    Q_cooling_nom_W = Q_cooling_max_W * (1 + Q_MARGIN_FOR_NETWORK)

    # Modify the individual with the extra GHP constraint
    try:
        cCheck.GHPCheck(individual, locator, Q_heating_nom_W, gv)
    except:
        print "No GHP constraint check possible \n"

    # Export to context
    master_to_slave_vars = calc_master_to_slave_variables(
        individual, Q_heating_max_W, Q_cooling_max_W, building_names, ind_num,
        gen)
    master_to_slave_vars.network_data_file_heating = network_file_name_heating
    master_to_slave_vars.network_data_file_cooling = network_file_name_cooling
    master_to_slave_vars.total_buildings = len(building_names)

    if master_to_slave_vars.number_of_buildings_connected_heating > 1:
        if DHN_barcode.count("0") == 0:
            master_to_slave_vars.fNameTotalCSV = locator.get_total_demand()
        else:
            master_to_slave_vars.fNameTotalCSV = os.path.join(
                locator.get_optimization_network_totals_folder(),
                "Total_%(DHN_barcode)s.csv" % locals())
    else:
        master_to_slave_vars.fNameTotalCSV = locator.get_optimization_substations_total_file(
            DHN_barcode)

    if master_to_slave_vars.number_of_buildings_connected_cooling > 1:
        if DCN_barcode.count("0") == 0:
            master_to_slave_vars.fNameTotalCSV = locator.get_total_demand()
        else:
            master_to_slave_vars.fNameTotalCSV = os.path.join(
                locator.get_optimization_network_totals_folder(),
                "Total_%(DCN_barcode)s.csv" % locals())
    else:
        master_to_slave_vars.fNameTotalCSV = locator.get_optimization_substations_total_file(
            DCN_barcode)

    if config.optimization.isheating:

        if DHN_barcode.count("1") > 0:

            (slavePrim, slaveCO2, slaveCosts, QUncoveredDesign,
             QUncoveredAnnual) = sM.slave_main(locator, master_to_slave_vars,
                                               solar_features, gv, config,
                                               prices, lca)
        else:

            slaveCO2 = 0
            slaveCosts = 0
            slavePrim = 0
    else:
        slaveCO2 = 0
        slaveCosts = 0
        slavePrim = 0

    costs += slaveCosts
    CO2 += slaveCO2
    prim += slavePrim

    if gv.ZernezFlag == 1:
        coolCosts, coolCO2, coolPrim = 0, 0, 0
    elif config.optimization.iscooling:
        reduced_timesteps_flag = False
        (coolCosts, coolCO2,
         coolPrim) = coolMain.coolingMain(locator, master_to_slave_vars,
                                          network_features, gv, prices, lca,
                                          config, reduced_timesteps_flag)
    else:
        coolCosts, coolCO2, coolPrim = 0, 0, 0

    print "Add extra costs"
    (addCosts, addCO2,
     addPrim) = eM.addCosts(DHN_barcode, DCN_barcode, building_names, locator,
                            master_to_slave_vars, QUncoveredDesign,
                            QUncoveredAnnual, solar_features, network_features,
                            gv, config, prices, lca)

    costs += addCosts + coolCosts
    CO2 += addCO2 + coolCO2
    prim += addPrim + coolPrim
    # Converting costs into float64 to avoid longer values
    costs = np.float64(costs)
    CO2 = np.float64(CO2)
    prim = np.float64(prim)

    print('Total costs = ' + str(costs))
    print('Total CO2 = ' + str(CO2))
    print('Total prim = ' + str(prim))

    return costs, CO2, prim, master_to_slave_vars, individual
Пример #11
0
def evaluation_main(individual, building_names, locator, extraCosts, extraCO2,
                    extraPrim, solar_features, network_features, gv):
    """
    This function evaluates an individual

    :param individual: list with values of the individual
    :param building_names: list with names of buildings
    :param locator: locator class
    :param extraCosts: costs calculated before optimization of specific energy services
     (process heat and electricity)
    :param extraCO2: green house gas emissions calculated before optimization of specific energy services
     (process heat and electricity)
    :param extraPrim: primary energy calculated before optimization ofr specific energy services
     (process heat and electricity)
    :param solar_features: solar features call to class
    :param network_features: network features call to class
    :param gv: global variables class
    :type individual: list
    :type building_names: list
    :type locator: string
    :type extraCosts: float
    :type extraCO2: float
    :type extraPrim: float
    :type solar_features: class
    :type network_features: class
    :type gv: class
    :return: Resulting values of the objective function. costs, CO2, prim
    :rtype: tuple

    """
    # Check the consistency of the individual or create a new one
    individual = check_invalid(individual, len(building_names), gv)

    # Initialize objective functions costs, CO2 and primary energy
    costs = extraCosts
    CO2 = extraCO2
    prim = extraPrim

    QUncoveredDesign = 0
    QUncoveredAnnual = 0

    # Create the string representation of the individual
    individual_barcode = sFn.individual_to_barcode(individual, gv)

    if individual_barcode.count("0") == 0:
        network_file_name = "Network_summary_result_all.csv"
    else:
        network_file_name = "Network_summary_result_" + individual_barcode + ".csv"

    if individual_barcode.count("1") > 0:
        Qheatmax = sFn.calcQmax(
            network_file_name,
            locator.get_optimization_network_results_folder(), gv)
    else:
        Qheatmax = 0

    print Qheatmax, "Qheatmax in distribution"
    Qnom = Qheatmax * (1 + gv.Qmargin_ntw)

    # Modify the individual with the extra GHP constraint
    try:
        cCheck.GHPCheck(individual, locator, Qnom, gv)
        print "GHP constraint checked \n"
    except:
        print "No GHP constraint check possible \n"

    # Export to context
    master_to_slave_vars = calc_master_to_slave_variables(
        individual, Qheatmax, locator, gv)
    master_to_slave_vars.NETWORK_DATA_FILE = network_file_name

    if master_to_slave_vars.nBuildingsConnected > 1:
        if individual_barcode.count("0") == 0:
            master_to_slave_vars.fNameTotalCSV = locator.get_total_demand()
        else:
            master_to_slave_vars.fNameTotalCSV = os.path.join(
                locator.get_optimization_network_totals_folder(),
                "Total_%(individual_barcode)s.csv" % locals())
    else:
        master_to_slave_vars.fNameTotalCSV = locator.get_optimization_substations_total_file(
            individual_barcode)

    if individual_barcode.count("1") > 0:

        print "Slave routine on", master_to_slave_vars.configKey
        (slavePrim, slaveCO2, slaveCosts, QUncoveredDesign,
         QUncoveredAnnual) = sM.slave_main(locator, master_to_slave_vars,
                                           solar_features, gv)
        costs += slaveCosts
        CO2 += slaveCO2
        prim += slavePrim

    else:
        print "No buildings connected to distribution \n"

    print "Add extra costs"
    (addCosts, addCO2,
     addPrim) = eM.addCosts(individual_barcode, building_names, locator,
                            master_to_slave_vars, QUncoveredDesign,
                            QUncoveredAnnual, solar_features, network_features,
                            gv)
    print addCosts, addCO2, addPrim, "addCosts, addCO2, addPrim \n"

    if gv.ZernezFlag == 1:
        coolCosts, coolCO2, coolPrim = 0, 0, 0
    else:
        (coolCosts, coolCO2, coolPrim) = coolMain.coolingMain(
            locator, master_to_slave_vars.configKey, network_features,
            master_to_slave_vars.WasteServersHeatRecovery, gv)

    print coolCosts, coolCO2, coolPrim, "coolCosts, coolCO2, coolPrim \n"

    costs += addCosts + coolCosts
    CO2 += addCO2 + coolCO2
    prim += addPrim + coolPrim

    print "Evaluation of", master_to_slave_vars.configKey, "done"
    print costs, CO2, prim, " = costs, CO2, prim \n"

    return costs, CO2, prim
Пример #12
0
def calc_master_to_slave_variables(individual, Qmax, locator, gv):
    """
    This function reads the list encoding a configuration and implements the corresponding
    for the slave routine's to use

    :param individual: list with inidividual
    :param Qmax:  peak heating demand
    :param locator: locator class
    :param gv: global variables class
    :type individual: list
    :type Qmax: float
    :type locator: string
    :type gv: class
    :return: master_to_slave_vars : class MasterSlaveVariables
    :rtype: class
    """
    # initialise class storing dynamic variables transfered from master to slave optimization
    master_to_slave_vars = slave_data.SlaveData()
    master_to_slave_vars.configKey = "".join(str(e)[0:4] for e in individual)

    individual_barcode = sFn.individual_to_barcode(individual, gv)
    master_to_slave_vars.nBuildingsConnected = individual_barcode.count(
        "1")  # counting the number of buildings connected

    Qnom = Qmax * (1 + gv.Qmargin_ntw)

    # Heating systems

    #CHP units with NG & furnace with biomass wet
    if individual[0] == 1 or individual[0] == 3:
        if gv.Furnace_allowed == 1:
            master_to_slave_vars.Furnace_on = 1
            master_to_slave_vars.Furnace_Q_max = max(individual[1] * Qnom,
                                                     gv.QminShare * Qnom)
            print master_to_slave_vars.Furnace_Q_max, "Furnace wet"
            master_to_slave_vars.Furn_Moist_type = "wet"
        elif gv.CC_allowed == 1:
            master_to_slave_vars.CC_on = 1
            master_to_slave_vars.CC_GT_SIZE = max(individual[1] * Qnom * 1.3,
                                                  gv.QminShare * Qnom * 1.3)
            #1.3 is the conversion factor between the GT_Elec_size NG and Q_DHN
            print master_to_slave_vars.CC_GT_SIZE, "CC NG"
            master_to_slave_vars.gt_fuel = "NG"

    #CHP units with BG& furnace with biomass dry
    if individual[0] == 2 or individual[0] == 4:
        if gv.Furnace_allowed == 1:
            master_to_slave_vars.Furnace_on = 1
            master_to_slave_vars.Furnace_Q_max = max(individual[1] * Qnom,
                                                     gv.QminShare * Qnom)
            print master_to_slave_vars.Furnace_Q_max, "Furnace dry"
            master_to_slave_vars.Furn_Moist_type = "dry"
        elif gv.CC_allowed == 1:
            master_to_slave_vars.CC_on = 1
            master_to_slave_vars.CC_GT_SIZE = max(individual[1] * Qnom * 1.5,
                                                  gv.QminShare * Qnom * 1.5)
            #1.5 is the conversion factor between the GT_Elec_size BG and Q_DHN
            print master_to_slave_vars.CC_GT_SIZE, "CC BG"
            master_to_slave_vars.gt_fuel = "BG"

    # Base boiler NG
    if individual[2] == 1:
        master_to_slave_vars.Boiler_on = 1
        master_to_slave_vars.Boiler_Q_max = max(individual[3] * Qnom,
                                                gv.QminShare * Qnom)
        print master_to_slave_vars.Boiler_Q_max, "Boiler base NG"
        master_to_slave_vars.BoilerType = "NG"

    # Base boiler BG
    if individual[2] == 2:
        master_to_slave_vars.Boiler_on = 1
        master_to_slave_vars.Boiler_Q_max = max(individual[3] * Qnom,
                                                gv.QminShare * Qnom)
        print master_to_slave_vars.Boiler_Q_max, "Boiler base BG"
        master_to_slave_vars.BoilerType = "BG"

    # peak boiler NG
    if individual[4] == 1:
        master_to_slave_vars.BoilerPeak_on = 1
        master_to_slave_vars.BoilerPeak_Q_max = max(individual[5] * Qnom,
                                                    gv.QminShare * Qnom)
        print master_to_slave_vars.BoilerPeak_Q_max, "Boiler peak NG"
        master_to_slave_vars.BoilerPeakType = "NG"

    # peak boiler BG
    if individual[4] == 2:
        master_to_slave_vars.BoilerPeak_on = 1
        master_to_slave_vars.BoilerPeak_Q_max = max(individual[5] * Qnom,
                                                    gv.QminShare * Qnom)
        print master_to_slave_vars.BoilerPeak_Q_max, "Boiler peak BG"
        master_to_slave_vars.BoilerPeakType = "BG"

    # lake - heat pump
    if individual[6] == 1 and gv.HPLake_allowed == 1:
        master_to_slave_vars.HP_Lake_on = 1
        master_to_slave_vars.HPLake_maxSize = max(individual[7] * Qnom,
                                                  gv.QminShare * Qnom)
        print master_to_slave_vars.HPLake_maxSize, "Lake"

    # sewage - heatpump
    if individual[8] == 1 and gv.HPSew_allowed == 1:
        master_to_slave_vars.HP_Sew_on = 1
        master_to_slave_vars.HPSew_maxSize = max(individual[9] * Qnom,
                                                 gv.QminShare * Qnom)
        print master_to_slave_vars.HPSew_maxSize, "Sewage"

    # Gwound source- heatpump
    if individual[10] == 1 and gv.GHP_allowed == 1:
        master_to_slave_vars.GHP_on = 1
        GHP_Qmax = max(individual[11] * Qnom, gv.QminShare * Qnom)
        master_to_slave_vars.GHP_number = GHP_Qmax / gv.GHP_HmaxSize
        print GHP_Qmax, "GHP"

    # heat recovery servers and compresor
    irank = gv.nHeat * 2
    master_to_slave_vars.WasteServersHeatRecovery = individual[irank]
    master_to_slave_vars.WasteCompressorHeatRecovery = individual[irank + 1]

    # Solar systems
    roof_area = np.array(
        pd.read_csv(locator.get_total_demand(), usecols=["Aroof_m2"]))

    areaAvail = 0
    totalArea = 0
    for i in range(len(individual_barcode)):
        index = individual_barcode[i]
        if index == "1":
            areaAvail += roof_area[i][0]
        totalArea += roof_area[i][0]

    shareAvail = areaAvail / totalArea

    irank = gv.nHeat * 2 + gv.nHR
    master_to_slave_vars.SOLAR_PART_PV = max(
        individual[irank] * individual[irank + 1] * individual[irank + 6] *
        shareAvail, 0)
    print master_to_slave_vars.SOLAR_PART_PV, "PV"
    master_to_slave_vars.SOLAR_PART_PVT = max(
        individual[irank + 2] * individual[irank + 3] * individual[irank + 6] *
        shareAvail, 0)
    print master_to_slave_vars.SOLAR_PART_PVT, "PVT"
    master_to_slave_vars.SOLAR_PART_SC = max(
        individual[irank + 4] * individual[irank + 5] * individual[irank + 6] *
        shareAvail, 0)
    print master_to_slave_vars.SOLAR_PART_SC, "SC"

    return master_to_slave_vars