示例#1
0
def calc_pareto_Qhp(locator, total_demand, gv):
    """
    This function calculates the contribution to the pareto optimal results of process heating,

    :param locator: locator class
    :param total_demand: dataframe with building demand
    :param gv: global variables
    :type locator: class
    :type total_demand: class
    :type gv: class
    :return: hpCosts, hpCO2, hpPrim
    :rtype: tuple
    """
    hpCosts = 0
    hpCO2 = 0
    hpPrim = 0

    if total_demand["Qhprof_MWhyr"].sum() > 0:
        df = total_demand[total_demand.Qhprof_kWh != 0]

        for name in df.Name:
            # Extract process heat needs
            Qhprof = pd.read_csv(locator.get_demand_results_file(name),
                                 usecols=["Qhprof_kWh"]).Qhprof_kWh.values

            Qnom = 0
            Qannual = 0
            # Operation costs / CO2 / Prim
            for i in range(8760):
                Qgas = Qhprof[
                    i] * 1E3 / gv.Boiler_eta_hp  # [Wh] Assumed 0.9 efficiency

                if Qgas < Qnom:
                    Qnom = Qgas * (1 + gv.Qmargin_Disc)

                Qannual += Qgas
                hpCosts += Qgas * gv.NG_PRICE  # [CHF]
                hpCO2 += Qgas * 3600E-6 * gv.NG_BACKUPBOILER_TO_CO2_STD  # [kg CO2]
                hpPrim += Qgas * 3600E-6 * gv.NG_BACKUPBOILER_TO_OIL_STD  # [MJ-oil-eq]

            # Investment costs
            hpCosts += boilers.calc_Cinv_boiler(Qnom, Qannual, gv)
    else:
        hpCosts = hpCO2 = hpPrim = 0
    return hpCosts, hpCO2, hpPrim
示例#2
0
def addCosts(indCombi, buildList, locator, dicoSupply, Q_uncovered_design_W,
             Q_uncovered_annual_W, solarFeat, ntwFeat, gv):
    """
    Computes additional costs / GHG emisions / primary energy needs
    for the individual
    addCosts = additional costs
    addCO2 = GHG emissions
    addPrm = primary energy needs

    :param indCombi: parameter indicating if the building is connected or not
    :param buildList: list of buildings in the district
    :param locator: input locator set to scenario
    :param dicoSupply: class containing the features of a specific individual
    :param Q_uncovered_design_W: hourly max of the heating uncovered demand
    :param Q_uncovered_annual_W: total heating uncovered
    :param solarFeat: solar features
    :param ntwFeat: network features
    :param gv: global variables
    :type indCombi: string
    :type buildList: list
    :type locator: string
    :type dicoSupply: class
    :type Q_uncovered_design_W: float
    :type Q_uncovered_annual_W: float
    :type solarFeat: class
    :type ntwFeat: class
    :type gv: class

    :return: returns the objectives addCosts, addCO2, addPrim
    :rtype: tuple
    """
    addCosts = 0
    addCO2 = 0
    addPrim = 0
    nBuildinNtw = 0

    # Add the features from the disconnected buildings
    print "\n COSTS FROM DISCONNECTED BUILDINGS"
    os.chdir(locator.get_optimization_disconnected_folder())
    CostDiscBuild = 0
    CO2DiscBuild = 0
    PrimDiscBuild = 0
    FurnaceInvCost = 0
    CCInvCost = 0
    BoilerBInvCost = 0
    BoilerPInvCost = 0
    HPLakeInvC = 0
    HPSewInvC = 0
    GHPInvC = 0
    PVInvC = 0
    SCInvC = 0
    PVTInvC = 0
    BoilerAddInvC = 0
    StorageHEXCost = 0
    StorageHPCost = 0
    StorageInvC = 0
    NetworkCost = 0
    SubstHEXCost = 0
    PVTHEXCost = 0
    SCHEXCost = 0
    pumpCosts = 0
    GasConnectionInvCost = 0

    for (index, building_name) in zip(indCombi, buildList):
        if index == "0":
            discFileName = "DiscOp_" + building_name + "_result.csv"
            df = pd.read_csv(discFileName)
            dfBest = df[df["Best configuration"] == 1]
            CostDiscBuild += dfBest["Total Costs [CHF]"].iloc[0]  # [CHF]
            CO2DiscBuild += dfBest["CO2 Emissions [kgCO2-eq]"].iloc[
                0]  # [kg CO2]
            PrimDiscBuild += dfBest["Primary Energy Needs [MJoil-eq]"].iloc[
                0]  # [MJ-oil-eq]

            print dfBest["Total Costs [CHF]"].iloc[
                0], building_name, "disconnected"

        else:
            nBuildinNtw += 1

    addCosts += CostDiscBuild
    addCO2 += CO2DiscBuild
    addPrim += PrimDiscBuild

    # Add the features for the distribution

    if indCombi.count("1") > 0:
        os.chdir(locator.get_optimization_slave_results_folder())

        print " \n MACHINERY COSTS"
        # Add the investment costs of the energy systems
        # Furnace
        if dicoSupply.Furnace_on == 1:
            P_design_W = dicoSupply.Furnace_Q_max

            fNameSlavePP = locator.get_optimization_slave_pp_activation_pattern(
                dicoSupply.configKey)
            dfFurnace = pd.read_csv(fNameSlavePP, usecols=["Q_Furnace_W"])
            arrayFurnace_W = np.array(dfFurnace)

            Q_annual_W = 0
            for i in range(int(np.shape(arrayFurnace_W)[0])):
                Q_annual_W += arrayFurnace_W[i][0]

            FurnaceInvCost = furnace.calc_Cinv_furnace(P_design_W, Q_annual_W,
                                                       gv)
            addCosts += FurnaceInvCost

            print furnace.calc_Cinv_furnace(P_design_W, Q_annual_W,
                                            gv), " Furnace"

        # CC
        if dicoSupply.CC_on == 1:
            CC_size_W = dicoSupply.CC_GT_SIZE
            CCInvCost = chp.calc_Cinv_CCT(CC_size_W, gv)
            addCosts += CCInvCost
            print chp.calc_Cinv_CCT(CC_size_W, gv), " CC"

        # Boiler Base
        if dicoSupply.Boiler_on == 1:
            Q_design_W = dicoSupply.Boiler_Q_max

            fNameSlavePP = locator.get_optimization_slave_pp_activation_pattern(
                dicoSupply.configKey)
            dfBoilerBase = pd.read_csv(fNameSlavePP,
                                       usecols=["Q_BoilerBase_W"])
            arrayBoilerBase_W = np.array(dfBoilerBase)

            Q_annual_W = 0
            for i in range(int(np.shape(arrayBoilerBase_W)[0])):
                Q_annual_W += arrayBoilerBase_W[i][0]

            BoilerBInvCost = boiler.calc_Cinv_boiler(Q_design_W, Q_annual_W,
                                                     gv)
            addCosts += BoilerBInvCost
            print boiler.calc_Cinv_boiler(Q_design_W, Q_annual_W,
                                          gv), " Boiler Base "

        # Boiler Peak
        if dicoSupply.BoilerPeak_on == 1:
            Q_design_W = dicoSupply.BoilerPeak_Q_max

            fNameSlavePP = locator.get_optimization_slave_pp_activation_pattern(
                dicoSupply.configKey)
            dfBoilerPeak = pd.read_csv(fNameSlavePP,
                                       usecols=["Q_BoilerPeak_W"])
            arrayBoilerPeak_W = np.array(dfBoilerPeak)

            Q_annual_W = 0
            for i in range(int(np.shape(arrayBoilerPeak_W)[0])):
                Q_annual_W += arrayBoilerPeak_W[i][0]
            BoilerPInvCost = boiler.calc_Cinv_boiler(Q_design_W, Q_annual_W,
                                                     gv)
            addCosts += BoilerPInvCost
            print boiler.calc_Cinv_boiler(Q_design_W, Q_annual_W,
                                          gv), " Boiler Peak"

        # HP Lake
        if dicoSupply.HP_Lake_on == 1:
            HP_Size_W = dicoSupply.HPLake_maxSize
            HPLakeInvC = hp.calc_Cinv_HP(HP_Size_W, gv)
            addCosts += HPLakeInvC
            print hp.calc_Cinv_HP(HP_Size_W, gv), " HP Lake"

        # HP Sewage
        if dicoSupply.HP_Sew_on == 1:
            HP_Size_W = dicoSupply.HPSew_maxSize
            HPSewInvC = hp.calc_Cinv_HP(HP_Size_W, gv)
            addCosts += HPSewInvC
            print hp.calc_Cinv_HP(HP_Size_W, gv), "HP Sewage"

        # GHP
        if dicoSupply.GHP_on == 1:
            fNameSlavePP = locator.get_optimization_slave_pp_activation_pattern(
                dicoSupply.configKey)
            dfGHP = pd.read_csv(fNameSlavePP, usecols=["E_GHP_req_W"])
            arrayGHP_W = np.array(dfGHP)

            GHP_Enom_W = np.amax(arrayGHP_W)
            GHPInvC = hp.calc_Cinv_GHP(GHP_Enom_W, gv) * gv.EURO_TO_CHF
            addCosts += GHPInvC
            print hp.calc_Cinv_GHP(GHP_Enom_W, gv) * gv.EURO_TO_CHF, " GHP"

        # Solar technologies

        PV_peak_kW = dicoSupply.SOLAR_PART_PV * solarFeat.A_PV_m2 * gv.nPV  #kW
        PVInvC = pv.calc_Cinv_pv(PV_peak_kW)
        addCosts += PVInvC
        print pv.calc_Cinv_pv(PV_peak_kW), "PV peak"

        SC_area_m2 = dicoSupply.SOLAR_PART_SC * solarFeat.A_SC_m2
        SCInvC = stc.calc_Cinv_SC(SC_area_m2, gv)
        addCosts += SCInvC
        print stc.calc_Cinv_SC(SC_area_m2, gv), "SC area"

        PVT_peak_kW = dicoSupply.SOLAR_PART_PVT * solarFeat.A_PVT_m2 * gv.nPVT  #kW
        PVTInvC = pvt.calc_Cinv_PVT(PVT_peak_kW, gv)
        addCosts += PVTInvC
        print pvt.calc_Cinv_PVT(PVT_peak_kW, gv), "PVT peak"

        # Back-up boiler
        BoilerAddInvC = boiler.calc_Cinv_boiler(Q_uncovered_design_W,
                                                Q_uncovered_annual_W, gv)
        addCosts += BoilerAddInvC
        print boiler.calc_Cinv_boiler(Q_uncovered_design_W,
                                      Q_uncovered_annual_W,
                                      gv), "backup boiler"

        # Hex and HP for Heat recovery
        print "\n STORAGE PART COSTS"
        if dicoSupply.WasteServersHeatRecovery == 1:
            df = pd.read_csv(os.path.join(
                locator.get_optimization_network_results_folder(),
                dicoSupply.NETWORK_DATA_FILE),
                             usecols=["Qcdata_netw_total_kWh"])
            array = np.array(df)
            Q_HEX_max_kWh = np.amax(array)
            StorageHEXCost += hex.calc_Cinv_HEX(Q_HEX_max_kWh, gv)

            print hex.calc_Cinv_HEX(Q_HEX_max_kWh, gv), "Hex for data center"

            df = pd.read_csv(
                locator.get_optimization_slave_storage_operation_data(
                    dicoSupply.configKey),
                usecols=["HPServerHeatDesignArray_kWh"])
            array = np.array(df)
            Q_HP_max_kWh = np.amax(array)
            StorageHEXCost += hp.calc_Cinv_HP(Q_HP_max_kWh, gv)
            print hp.calc_Cinv_HP(Q_HP_max_kWh, gv), "HP for data center"

        if dicoSupply.WasteCompressorHeatRecovery == 1:
            df = pd.read_csv(os.path.join(
                locator.get_optimization_network_results_folder(),
                dicoSupply.NETWORK_DATA_FILE),
                             usecols=["Ecaf_netw_total_kWh"])
            array = np.array(df)
            Q_HEX_max_kWh = np.amax(array)

            StorageHEXCost += hex.calc_Cinv_HEX(Q_HEX_max_kWh, gv)
            print hex.calc_Cinv_HEX(Q_HEX_max_kWh,
                                    gv), "Hex for compressed air"

            df = pd.read_csv(
                locator.get_optimization_slave_storage_operation_data(
                    dicoSupply.configKey),
                usecols=["HPCompAirDesignArray_kWh"])
            array = np.array(df)
            Q_HP_max_kWh = np.amax(array)

            StorageHEXCost += hp.calc_Cinv_HP(Q_HP_max_kWh, gv)
            print hp.calc_Cinv_HP(Q_HP_max_kWh, gv), "HP for compressed air"
        addCosts += StorageHEXCost

        # Heat pump solar to storage
        df = pd.read_csv(
            locator.get_optimization_slave_storage_operation_data(
                dicoSupply.configKey),
            usecols=["HPScDesignArray_Wh", "HPpvt_designArray_Wh"])
        array = np.array(df)
        Q_HP_max_PVT_Wh = np.amax(array[:, 1])
        QhpMax_SC_Wh = np.amax(array[:, 0])

        StorageHPCost += hp.calc_Cinv_HP(Q_HP_max_PVT_Wh, gv)
        print hp.calc_Cinv_HP(Q_HP_max_PVT_Wh, gv), "HP for PVT"

        StorageHPCost += hp.calc_Cinv_HP(QhpMax_SC_Wh, gv)
        print hp.calc_Cinv_HP(QhpMax_SC_Wh, gv), "HP for SC"

        # HP for storage operation
        df = pd.read_csv(locator.get_optimization_slave_storage_operation_data(
            dicoSupply.configKey),
                         usecols=[
                             "E_aux_ch_W", "E_aux_dech_W",
                             "Q_from_storage_used_W", "Q_to_storage_W"
                         ])
        array = np.array(df)
        Q_HP_max_storage_W = 0
        for i in range(gv.DAYS_IN_YEAR * gv.HOURS_IN_DAY):
            if array[i][0] > 0:
                Q_HP_max_storage_W = max(Q_HP_max_storage_W,
                                         array[i][3] + array[i][0])
            elif array[i][1] > 0:
                Q_HP_max_storage_W = max(Q_HP_max_storage_W,
                                         array[i][2] + array[i][1])

        StorageHPCost += hp.calc_Cinv_HP(Q_HP_max_storage_W, gv)
        addCosts += StorageHPCost

        print hp.calc_Cinv_HP(Q_HP_max_storage_W, gv), "HP for storage"

        # Storage
        df = pd.read_csv(locator.get_optimization_slave_storage_operation_data(
            dicoSupply.configKey),
                         usecols=["Storage_Size_m3"],
                         nrows=1)
        StorageVol_m3 = np.array(df)[0][0]
        StorageInvC += storage.calc_Cinv_storage(StorageVol_m3, gv)
        addCosts += StorageInvC
        print storage.calc_Cinv_storage(StorageVol_m3, gv), "Storage Costs"

        # Costs from distribution configuration
        print "\n COSTS FROM NETWORK CONFIGURATION"
        if gv.ZernezFlag == 1:
            NetworkCost += network.calc_Cinv_network_linear(
                gv.NetworkLengthZernez, gv) * nBuildinNtw / len(buildList)
        else:
            NetworkCost += ntwFeat.pipesCosts_DHN * nBuildinNtw / len(
                buildList)
        addCosts += NetworkCost
        print ntwFeat.pipesCosts_DHN * nBuildinNtw / len(
            buildList), "Pipes Costs"

        # HEX (1 per building in ntw)
        for (index, building_name) in zip(indCombi, buildList):
            if index == "1":
                df = pd.read_csv(
                    locator.get_optimization_substations_results_file(
                        building_name),
                    usecols=["Q_dhw_W", "Q_heating_W"])
                subsArray = np.array(df)

                Q_max_W = np.amax(subsArray[:, 0] + subsArray[:, 1])
                SubstHEXCost += hex.calc_Cinv_HEX(Q_max_W, gv)
                print hex.calc_Cinv_HEX(Q_max_W, gv), "Hex", building_name
        addCosts += SubstHEXCost

        # HEX for solar
        roof_area_m2 = np.array(
            pd.read_csv(locator.get_total_demand(), usecols=["Aroof_m2"]))

        areaAvail = 0
        for i in range(len(indCombi)):
            index = indCombi[i]
            if index == "1":
                areaAvail += roof_area_m2[i][0]

        for i in range(len(indCombi)):
            index = indCombi[i]
            if index == "1":
                share = roof_area_m2[i][0] / areaAvail
                #print share, "solar area share", buildList[i]

                Q_max_SC_Wh = solarFeat.Q_nom_SC_Wh * dicoSupply.SOLAR_PART_SC * share
                SCHEXCost += hex.calc_Cinv_HEX(Q_max_SC_Wh, gv)
                print hex.calc_Cinv_HEX(Q_max_SC_Wh,
                                        gv), "Hex SC", buildList[i]

                Q_max_PVT_Wh = solarFeat.Q_nom_PVT_Wh * dicoSupply.SOLAR_PART_PVT * share
                PVTHEXCost += hex.calc_Cinv_HEX(Q_max_PVT_Wh, gv)
                print hex.calc_Cinv_HEX(Q_max_PVT_Wh,
                                        gv), "Hex PVT", buildList[i]
        addCosts += SCHEXCost
        addCosts += PVTHEXCost

        print addCosts, "addCosts in extraCostsMain"
        # Pump operation costs
        pumpCosts = pumps.calc_Ctot_pump(
            dicoSupply, buildList,
            locator.get_optimization_network_results_folder(), ntwFeat, gv)
        addCosts += pumpCosts
        print pumpCosts, "Pump Operation costs in extraCostsMain\n"

    # import gas consumption data from:

    if indCombi.count("1") > 0:
        # import gas consumption data from:
        E_gas_PrimaryDataframe_W = pd.read_csv(
            locator.get_optimization_slave_primary_energy_by_source(
                dicoSupply.configKey),
            usecols=["E_gas_PrimaryPeakPower_W"])
        E_gas_primary_peak_power_W = float(np.array(E_gas_PrimaryDataframe_W))
        GasConnectionInvCost = ngas.calc_Cinv_gas(E_gas_primary_peak_power_W,
                                                  gv)
    else:
        GasConnectionInvCost = 0.0

    addCosts += GasConnectionInvCost
    # Save data
    results = pd.DataFrame({
        "SCInvC": [SCInvC],
        "PVTInvC": [PVTInvC],
        "BoilerAddInvC": [BoilerAddInvC],
        "StorageHEXCost": [StorageHEXCost],
        "StorageHPCost": [StorageHPCost],
        "StorageInvC": [StorageInvC],
        "StorageCostSum": [StorageInvC + StorageHPCost + StorageHEXCost],
        "NetworkCost": [NetworkCost],
        "SubstHEXCost": [SubstHEXCost],
        "DHNInvestCost": [addCosts - CostDiscBuild],
        "PVTHEXCost": [PVTHEXCost],
        "CostDiscBuild": [CostDiscBuild],
        "CO2DiscBuild": [CO2DiscBuild],
        "PrimDiscBuild": [PrimDiscBuild],
        "FurnaceInvCost": [FurnaceInvCost],
        "BoilerBInvCost": [BoilerBInvCost],
        "BoilerPInvCost": [BoilerPInvCost],
        "HPLakeInvC": [HPLakeInvC],
        "HPSewInvC": [HPSewInvC],
        "SCHEXCost": [SCHEXCost],
        "pumpCosts": [pumpCosts],
        "SumInvestCost": [addCosts],
        "GasConnectionInvCa": [GasConnectionInvCost]
    })
    results.to_csv(locator.get_optimization_slave_investment_cost_detailed(
        dicoSupply.configKey),
                   sep=',')

    return (addCosts, addCO2, addPrim)
def decentralized_main(locator, building_names, gv):
    """
    Computes the parameters for the operation of disconnected buildings
    output results in csv files.
    There is no optimization at this point. The different technologies are calculated and compared 1 to 1 to
    each technology. it is a classical combinatorial problem.

    :param locator: locator class
    :param building_names: list with names of buildings
    :param gv: global variables class
    :type locator: class
    :type building_names: list
    :type gv: class
    :return: results of operation of buildings located in locator.get_optimization_disconnected_folder
    :rtype: Nonetype

    """
    t0 = time.clock()
    geothermal_potential = pd.read_csv(locator.get_geothermal_potential(), index_col="Name")
    BestData = {}

    def calc_new_load(mdot, TsupDH, Tret, gv):
        """
        This function calculates the load distribution side of the district heating distribution.

        :param mdot: mass flow
        :param TsupDH: supply temeperature
        :param Tret: return temperature
        :param gv: global variables class
        :type mdot: float
        :type TsupDH: float
        :type Tret: float
        :type gv: class
        :return: Qload: load of the distribution
        :rtype: float
        """
        Qload = mdot * gv.cp * (TsupDH - Tret) * (1 + gv.Qloss_Disc)
        if Qload < 0:
            Qload = 0
        if Qload < -1E-5:
            print "Error in discBuildMain, negative heat requirement at hour", hour, building_name
        return Qload

    for building_name in building_names:
        print building_name
        loads = pd.read_csv(locator.get_optimization_substations_results_file(building_name),
                            usecols=["T_supply_DH_result", "T_return_DH_result", "mdot_DH_result"])
        Qload = np.vectorize(calc_new_load)(loads["mdot_DH_result"], loads["T_supply_DH_result"],
                                            loads["T_return_DH_result"], gv)
        Qannual = Qload.sum()
        Qnom = Qload.max()* (1+gv.Qmargin_Disc) # 1% reliability margin on installed capacity

        # Create empty matrices
        result = np.zeros((13,7))
        result[0][0] = 1
        result[1][1] = 1
        result[2][2] = 1
        InvCosts = np.zeros((13,1))
        resourcesRes = np.zeros((13,4))
        QannualB_GHP = np.zeros((10,1)) # For the investment costs of the boiler used with GHP
        Wel_GHP = np.zeros((10,1)) # For the investment costs of the GHP
        
        # Supply with the Boiler / FC / GHP
        Tret = loads["T_return_DH_result"].values
        TsupDH = loads["T_supply_DH_result"].values
        mdot = loads["mdot_DH_result"].values
        for hour in range(8760):

            if Tret[hour] == 0:
                Tret[hour] = TsupDH[hour]
                
            # Boiler NG
            BoilerEff = Boiler.calc_Cop_boiler(Qload[hour], Qnom, Tret[hour])
            
            Qgas = Qload[hour] / BoilerEff
            
            result[0][4] += gv.NG_PRICE * Qgas # CHF
            result[0][5] += gv.NG_BACKUPBOILER_TO_CO2_STD * Qgas * 3600E-6 # kgCO2
            result[0][6] += gv.NG_BACKUPBOILER_TO_OIL_STD * Qgas * 3600E-6 # MJ-oil-eq
            resourcesRes[0][0] += Qload[hour]
            
            if gv.DiscBioGasFlag == 1:
                result[0][4] += gv.BG_PRICE * Qgas # CHF
                result[0][5] += gv.BG_BACKUPBOILER_TO_CO2_STD * Qgas * 3600E-6 # kgCO2
                result[0][6] += gv.BG_BACKUPBOILER_TO_OIL_STD * Qgas * 3600E-6 # MJ-oil-eq
                
            # Boiler BG
            result[1][4] += gv.BG_PRICE * Qgas # CHF
            result[1][5] += gv.BG_BACKUPBOILER_TO_CO2_STD * Qgas * 3600E-6 # kgCO2
            result[1][6] += gv.BG_BACKUPBOILER_TO_OIL_STD * Qgas * 3600E-6 # MJ-oil-eq
            resourcesRes[1][1] += Qload[hour]
                
            # FC
            (FC_Effel, FC_Effth) = FC.calc_eta_FC(Qload[hour], Qnom, 1, "B")
            Qgas = Qload[hour] / (FC_Effth+FC_Effel)
            Qelec = Qgas * FC_Effel            
            
            result[2][4] += gv.NG_PRICE * Qgas - gv.ELEC_PRICE * Qelec # CHF, extra electricity sold to grid
            result[2][5] += 0.0874 * Qgas * 3600E-6 + 773 * 0.45 * Qelec * 1E-6 - gv.EL_TO_CO2 * Qelec * 3600E-6 # kgCO2
            # Bloom box emissions within the FC: 773 lbs / MWh_el (and 1 lbs = 0.45 kg)
            # http://www.carbonlighthouse.com/2011/09/16/bloom-box/
            result[2][6] += 1.51 * Qgas * 3600E-6 - gv.EL_TO_OIL_EQ * Qelec * 3600E-6 # MJ-oil-eq
            
            resourcesRes[2][0] += Qload[hour]
            resourcesRes[2][2] += Qelec
            
            # GHP
            for i in range(10):
                
                QnomBoiler = i/10 * Qnom
                QnomGHP = Qnom - QnomBoiler
                
                if Qload[hour] <= QnomGHP:
                
                    (wdot_el, qcolddot, qhotdot_missing, tsup2) = HP.calc_Cop_GHP(mdot[hour], TsupDH[hour], Tret[hour],
                                                                                  gv.TGround, gv)
                    
                    if Wel_GHP[i][0] < wdot_el:
                        Wel_GHP[i][0] = wdot_el
                    
                    result[3+i][4] += gv.ELEC_PRICE * wdot_el   # CHF
                    result[3+i][5] += gv.SMALL_GHP_TO_CO2_STD  * wdot_el   * 3600E-6 # kgCO2
                    result[3+i][6] += gv.SMALL_GHP_TO_OIL_STD  * wdot_el   * 3600E-6 # MJ-oil-eq
                    
                    resourcesRes[3+i][2] -= wdot_el
                    resourcesRes[3+i][3] += Qload[hour] - qhotdot_missing
                    
                    if qhotdot_missing > 0:
                        print "GHP unable to cover the whole demand, boiler activated!"
                        BoilerEff = Boiler.calc_Cop_boiler(qhotdot_missing, QnomBoiler, tsup2)
                        Qgas = qhotdot_missing / BoilerEff
                        
                        result[3+i][4] += gv.NG_PRICE * Qgas   # CHF
                        result[3+i][5] += gv.NG_BACKUPBOILER_TO_CO2_STD * Qgas   * 3600E-6 # kgCO2
                        result[3+i][6] += gv.NG_BACKUPBOILER_TO_OIL_STD * Qgas   * 3600E-6 # MJ-oil-eq
                        
                        QannualB_GHP[i][0] += qhotdot_missing
                        resourcesRes[3+i][0] += qhotdot_missing
    
                else:
                    #print "Boiler activated to compensate GHP", i
                    #if gv.DiscGHPFlag == 0:
                    #    print QnomGHP
                    #   QnomGHP = 0 
                    #   print "GHP not allowed 2, set QnomGHP to zero"
                        
                    TexitGHP = QnomGHP / (mdot[hour] * gv.cp) + Tret[hour]
                    (wdot_el, qcolddot, qhotdot_missing, tsup2) = HP.calc_Cop_GHP(mdot[hour], TexitGHP, Tret[hour], gv.TGround, gv)
                    
                    if Wel_GHP[i][0] < wdot_el:
                        Wel_GHP[i][0] = wdot_el
                        
                    result[3+i][4] += gv.ELEC_PRICE * wdot_el   # CHF
                    result[3+i][5] += gv.SMALL_GHP_TO_CO2_STD  * wdot_el   * 3600E-6 # kgCO2
                    result[3+i][6] += gv.SMALL_GHP_TO_OIL_STD  * wdot_el   * 3600E-6 # MJ-oil-eq
                    
                    resourcesRes[3+i][2] -= wdot_el
                    resourcesRes[3+i][3] += QnomGHP - qhotdot_missing
                    
                    if qhotdot_missing > 0:
                        print "GHP unable to cover the whole demand, boiler activated!"
                        BoilerEff = Boiler.calc_Cop_boiler(qhotdot_missing, QnomBoiler, tsup2)
                        Qgas = qhotdot_missing / BoilerEff
                        
                        result[3+i][4] += gv.NG_PRICE * Qgas   # CHF
                        result[3+i][5] += gv.NG_BACKUPBOILER_TO_CO2_STD * Qgas   * 3600E-6 # kgCO2
                        result[3+i][6] += gv.NG_BACKUPBOILER_TO_OIL_STD * Qgas   * 3600E-6 # MJ-oil-eq
                        
                        QannualB_GHP[i][0] += qhotdot_missing
                        resourcesRes[3+i][0] += qhotdot_missing
                        
                    QtoBoiler = Qload[hour] - QnomGHP
                    QannualB_GHP[i][0] += QtoBoiler
                    
                    BoilerEff = Boiler.calc_Cop_boiler(QtoBoiler, QnomBoiler, TexitGHP)
                    Qgas = QtoBoiler / BoilerEff
                    
                    result[3+i][4] += gv.NG_PRICE * Qgas   # CHF
                    result[3+i][5] += gv.NG_BACKUPBOILER_TO_CO2_STD * Qgas   * 3600E-6 # kgCO2
                    result[3+i][6] += gv.NG_BACKUPBOILER_TO_OIL_STD * Qgas   * 3600E-6 # MJ-oil-eq
                    resourcesRes[3+i][0] += QtoBoiler

        # Investment Costs / CO2 / Prim
        InvCaBoiler = Boiler.calc_Cinv_boiler(Qnom, Qannual, gv)
        InvCosts[0][0] = InvCaBoiler
        InvCosts[1][0] = InvCaBoiler
        
        InvCosts[2][0] = FC.calc_Cinv_FC(Qnom, gv)
        
        for i in range(10):
            result[3+i][0] = i/10
            result[3+i][3] = 1-i/10

            QnomBoiler = i/10 * Qnom
            
            InvCaBoiler = Boiler.calc_Cinv_boiler(QnomBoiler, QannualB_GHP[i][0], gv)
            InvCosts[3+i][0] = InvCaBoiler
            
            InvCaGHP = HP.GHP_InvCost( Wel_GHP[i][0] , gv)
            InvCosts[3+i][0] += InvCaGHP * gv.EURO_TO_CHF
        

        # Best configuration
        Best = np.zeros((13,1))
        indexBest = 0

        TotalCosts = np.zeros((13,2))
        TotalCO2 = np.zeros((13,2))
        TotalPrim = np.zeros((13,2))
        
        for i in range(13):
            TotalCosts[i][0] = TotalCO2[i][0] = TotalPrim[i][0] = i

            TotalCosts[i][1] = InvCosts[i][0] + result[i][4]
            TotalCO2[i][1] = result[i][5]
            TotalPrim[i][1] = result[i][6]
        
        CostsS = TotalCosts[np.argsort(TotalCosts[:,1])]
        CO2S = TotalCO2[np.argsort(TotalCO2[:,1])]
        PrimS = TotalPrim[np.argsort(TotalPrim[:,1])]
        
        el = len(CostsS)
        rank = 0
        Bestfound = False
        
        optsearch = np.empty(el)
        optsearch.fill(3)
        indexBest = 0
        
        # Check the GHP area constraint
        for i in range(10):
            QGHP = (1-i/10) * Qnom
            areaAvail = geothermal_potential.ix[building_name,"Area_geo"]
            Qallowed = np.ceil(areaAvail/gv.GHP_A) * gv.GHP_HmaxSize #[W_th]
            
            if Qallowed < QGHP:
                optsearch[i+3] += 1
                Best[i+3][0] = - 1
        
        while not Bestfound and rank<el:
            
            optsearch[CostsS[rank][0]] -= 1
            optsearch[CO2S[rank][0]] -= 1
            optsearch[PrimS[rank][0]] -= 1
            
            if np.count_nonzero(optsearch) != el:
                Bestfound = True
                indexBest = np.where(optsearch == 0)[0][0]
                
            rank += 1

        # get the best option according to the ranking.
        Best[indexBest][0] = 1
        Qnom_array = np.ones(len(Best[:,0])) * Qnom

        # Save results in csv file
        dico = {}
        dico[ "BoilerNG Share" ] = result[:,0]
        dico[ "BoilerBG Share" ] = result[:,1]
        dico[ "FC Share" ] = result[:,2]
        dico[ "GHP Share" ] = result[:,3]
        dico[ "Operation Costs [CHF]" ] = result[:,4]
        dico[ "CO2 Emissions [kgCO2-eq]" ] = result[:,5]
        dico[ "Primary Energy Needs [MJoil-eq]" ] = result[:,6]
        dico[ "Annualized Investment Costs [CHF]" ] = InvCosts[:,0]
        dico[ "Total Costs [CHF]" ] = TotalCosts[:,1]
        dico[ "Best configuration" ] = Best[:,0]
        dico[ "Nominal Power" ] = Qnom_array
        dico[ "QfromNG" ] = resourcesRes[:,0]
        dico[ "QfromBG" ] = resourcesRes[:,1]
        dico[ "EforGHP" ] = resourcesRes[:,2]
        dico[ "QfromGHP" ] = resourcesRes[:,3]


        results_to_csv = pd.DataFrame(dico)
        fName_result = locator.get_optimization_disconnected_folder_building_result(building_name)
        results_to_csv.to_csv(fName_result, sep= ',')
        
    
        BestComb = {}
        BestComb[ "BoilerNG Share" ] = result[indexBest,0]
        BestComb[ "BoilerBG Share" ] = result[indexBest,1]
        BestComb[ "FC Share" ] = result[indexBest,2]
        BestComb[ "GHP Share" ] = result[indexBest,3]
        BestComb[ "Operation Costs [CHF]" ] = result[indexBest,4]
        BestComb[ "CO2 Emissions [kgCO2-eq]" ] = result[indexBest,5]
        BestComb[ "Primary Energy Needs [MJoil-eq]" ] = result[indexBest,6]
        BestComb[ "Annualized Investment Costs [CHF]" ] = InvCosts[indexBest,0]
        BestComb[ "Total Costs [CHF]" ] = TotalCosts[indexBest,1]
        BestComb[ "Best configuration" ] = Best[indexBest,0]
        BestComb[ "Nominal Power" ] = Qnom
        
        BestData[building_name] = BestComb

    if 0:
        fName = locator.get_optimization_disconnected_folder_disc_op_summary()
        results_to_csv = pd.DataFrame(BestData)
        results_to_csv.to_csv(fName, sep= ',')

    print time.clock() - t0, "seconds process time for the Disconnected Building Routine \n"
def addCosts(indCombi, buildList, locator, dicoSupply, QUncoveredDesign, QUncoveredAnnual, solarFeat, ntwFeat, gv):
    """
    Computes additional costs / GHG emisions / primary energy needs
    for the individual
    
    Parameters
    ----------
    indCombi : string
        with 0 if disconnected building, 1 if connected
    buildList : list
        list of buildings in the district
    locator : string
        path to folders
    dicoSupply : class context
        with the features of the specific individual
    QuncoveredDesign : float
        hourly max of the heating uncovered demand
    QuncoveredAnnual : float
        total heating uncovered
    solarFeat / ntwFeat : class solarFeatures / ntwFeatures
    
    Returns
    -------
    (addCosts, addCO2, addPrim) : tuple
    
    """
    addCosts = 0
    addCO2 = 0
    addPrim = 0
    nBuildinNtw = 0
    
    # Add the features from the disconnected buildings
    print "\n COSTS FROM DISCONNECTED BUILDINGS"
    os.chdir(locator.pathDiscRes)
    CostDiscBuild = 0
    CO2DiscBuild = 0
    PrimDiscBuild = 0
    FurnaceInvCost = 0
    CCInvCost = 0
    BoilerBInvCost = 0
    BoilerPInvCost = 0 
    HPLakeInvC = 0
    HPSewInvC = 0
    GHPInvC = 0
    PVInvC = 0
    SCInvC = 0
    PVTInvC = 0
    BoilerAddInvC = 0
    StorageHEXCost = 0
    StorageHPCost = 0
    StorageInvC = 0
    NetworkCost = 0
    SubstHEXCost = 0
    PVTHEXCost = 0
    SCHEXCost = 0
    pumpCosts = 0
    GasConnectionInvCost = 0 
    
    for (index, buildName) in zip(indCombi, buildList):
        if index == "0":
            discFileName = "DiscOp_" + buildName + "_result.csv"
            df = pd.read_csv(discFileName)
            dfBest = df[df["Best configuration"] == 1]
            CostDiscBuild += dfBest["Total Costs [CHF]"].iloc[0] # [CHF]
            CO2DiscBuild += dfBest["CO2 Emissions [kgCO2-eq]"].iloc[0] # [kg CO2]
            PrimDiscBuild += dfBest["Primary Energy Needs [MJoil-eq]"].iloc[0] # [MJ-oil-eq]

            print  dfBest["Total Costs [CHF]"].iloc[0], buildName, "disconnected"

        else:
            nBuildinNtw += 1
    
    addCosts += CostDiscBuild
    addCO2 += CO2DiscBuild
    addPrim += PrimDiscBuild
    
    # Add the features for the network

    if indCombi.count("1") > 0:
        os.chdir(locator.pathSlaveRes)
        
        print " \n MACHINERY COSTS"
        # Add the investment costs of the energy systems
        # Furnace
        if dicoSupply.Furnace_on == 1:
            P_design = dicoSupply.Furnace_Q_max
            
            fNameSlavePP = dicoSupply.configKey + "PPActivationPattern.csv"
            dfFurnace = pd.read_csv(fNameSlavePP, usecols=["Q_Furnace"])
            arrayFurnace = np.array(dfFurnace)
            
            Q_annual =  0
            for i in range(int(np.shape(arrayFurnace)[0])):
                Q_annual += arrayFurnace[i][0]
            
            FurnaceInvCost = furnace.calc_Cinv_furnace(P_design, Q_annual, gv)
            addCosts += FurnaceInvCost
            
            print furnace.calc_Cinv_furnace(P_design, Q_annual, gv), " Furnace"
        
        # CC
        if dicoSupply.CC_on == 1:
            CC_size = dicoSupply.CC_GT_SIZE 
            CCInvCost = chp.calc_Cinv_CCT(CC_size, gv)
            addCosts += CCInvCost
            print chp.calc_Cinv_CCT(CC_size, gv), " CC"
    
        # Boiler Base
        if dicoSupply.Boiler_on == 1:
            Q_design = dicoSupply.Boiler_Q_max
            
            fNameSlavePP = dicoSupply.configKey + "PPActivationPattern.csv"
            dfBoilerBase = pd.read_csv(fNameSlavePP, usecols=["Q_BoilerBase"])
            arrayBoilerBase = np.array(dfBoilerBase)
            
            Q_annual =  0
            for i in range(int(np.shape(arrayBoilerBase)[0])):
                Q_annual += arrayBoilerBase[i][0]
                
            BoilerBInvCost = boiler.calc_Cinv_boiler(Q_design, Q_annual, gv)
            addCosts += BoilerBInvCost
            print boiler.calc_Cinv_boiler(Q_design, Q_annual, gv), " Boiler Base "
        
        # Boiler Peak
        if dicoSupply.BoilerPeak_on == 1:
            Q_design = dicoSupply.BoilerPeak_Q_max
    
            fNameSlavePP = dicoSupply.configKey + "PPActivationPattern.csv"
            dfBoilerPeak = pd.read_csv(fNameSlavePP, usecols=["Q_BoilerPeak"])
            arrayBoilerPeak = np.array(dfBoilerPeak)
            
            Q_annual =  0
            for i in range(int(np.shape(arrayBoilerPeak)[0])):
                Q_annual += arrayBoilerPeak[i][0]
            BoilerPInvCost = boiler.calc_Cinv_boiler(Q_design, Q_annual, gv)
            addCosts += BoilerPInvCost
            print boiler.calc_Cinv_boiler(Q_design, Q_annual, gv), " Boiler Peak"

        
        # HP Lake
        if dicoSupply.HP_Lake_on == 1:
            HP_Size = dicoSupply.HPLake_maxSize
            HPLakeInvC = hp.calc_Cinv_HP(HP_Size, gv)
            addCosts += HPLakeInvC
            print hp.calc_Cinv_HP(HP_Size, gv), " HP Lake"
            
        # HP Sewage
        if dicoSupply.HP_Sew_on == 1:
            HP_Size = dicoSupply.HPSew_maxSize
            HPSewInvC = hp.calc_Cinv_HP(HP_Size, gv)
            addCosts += HPSewInvC
            print hp.calc_Cinv_HP(HP_Size, gv), "HP Sewage"
            
        # GHP
        if dicoSupply.GHP_on == 1:
            fNameSlavePP = dicoSupply.configKey + "PPActivationPattern.csv"
            dfGHP = pd.read_csv(fNameSlavePP, usecols=["E_GHP"])
            arrayGHP = np.array(dfGHP)
            
            GHP_Enom = np.amax(arrayGHP)
            GHPInvC = hp.calc_Cinv_GHP(GHP_Enom, gv) * gv.EURO_TO_CHF
            addCosts += GHPInvC
            print hp.calc_Cinv_GHP(GHP_Enom, gv) * gv.EURO_TO_CHF, " GHP"
            
        # Solar technologies

        PV_peak = dicoSupply.SOLAR_PART_PV * solarFeat.SolarAreaPV * gv.nPV #kW
        PVInvC = pv.calc_Cinv_PV(PV_peak)
        addCosts += PVInvC
        print pv.calc_Cinv_PV(PV_peak), "PV peak"
        
        SC_area = dicoSupply.SOLAR_PART_SC * solarFeat.SolarAreaSC
        SCInvC = stc.calc_Cinv_SC(SC_area)
        addCosts += SCInvC
        print stc.calc_Cinv_SC(SC_area), "SC area"
        

        PVT_peak = dicoSupply.SOLAR_PART_PVT * solarFeat.SolarAreaPVT * gv.nPVT #kW
        PVTInvC = pvt.calc_Cinv_PVT(PVT_peak)
        addCosts += PVTInvC
        print pvt.calc_Cinv_PVT(PVT_peak), "PVT peak"
        
        # Back-up boiler
        BoilerAddInvC = boiler.calc_Cinv_boiler(QUncoveredDesign, QUncoveredAnnual, gv)
        addCosts += BoilerAddInvC
        print boiler.calc_Cinv_boiler(QUncoveredDesign, QUncoveredAnnual, gv), "backup boiler"
        
    
        # Hex and HP for Heat recovery
        print "\n STORAGE PART COSTS"
        if dicoSupply.WasteServersHeatRecovery == 1:
            df = pd.read_csv(locator.pathNtwRes + "/" + dicoSupply.NETWORK_DATA_FILE, usecols = ["Qcdata_netw_total"])
            array = np.array(df)
            QhexMax = np.amax(array)
            StorageHEXCost += hex.calc_Cinv_HEX(QhexMax, gv)
            
            print hex.calc_Cinv_HEX(QhexMax, gv), "Hex for data center"
            
            df = pd.read_csv(locator.pathSlaveRes + "/" + dicoSupply.configKey + "StorageOperationData.csv", usecols = ["HPServerHeatDesignArray"])
            array = np.array(df)
            QhpMax = np.amax(array)
            StorageHEXCost += hp.calc_Cinv_HP(QhpMax, gv)
            print hp.calc_Cinv_HP(QhpMax, gv), "HP for data center"
            
        if dicoSupply.WasteCompressorHeatRecovery == 1:
            df = pd.read_csv(locator.pathNtwRes + "/" + dicoSupply.NETWORK_DATA_FILE, usecols = ["Ecaf_netw_total"])
            array = np.array(df)
            QhexMax = np.amax(array)
        
            StorageHEXCost += hex.calc_Cinv_HEX(QhexMax, gv)
            print hex.calc_Cinv_HEX(QhexMax, gv), "Hex for compressed air"
            
            df = pd.read_csv(locator.pathSlaveRes + "/" + dicoSupply.configKey + "StorageOperationData.csv", usecols = ["HPCompAirDesignArray"])
            array = np.array(df)
            QhpMax = np.amax(array)

            StorageHEXCost += hp.calc_Cinv_HP(QhpMax, gv)
            print hp.calc_Cinv_HP(QhpMax, gv), "HP for compressed air"
        addCosts += StorageHEXCost
        
        # Heat pump solar to storage
        df = pd.read_csv(locator.pathSlaveRes + "/" + dicoSupply.configKey + "StorageOperationData.csv", usecols = ["HPScDesignArray", "HPpvt_designArray"])
        array = np.array(df)
        QhpMax_PVT = np.amax(array[:,1])
        QhpMax_SC = np.amax(array[:,0])
        
        StorageHPCost += hp.calc_Cinv_HP(QhpMax_PVT, gv)
        print hp.calc_Cinv_HP(QhpMax_PVT, gv), "HP for PVT"

        StorageHPCost += hp.calc_Cinv_HP(QhpMax_SC, gv)
        print hp.calc_Cinv_HP(QhpMax_SC, gv), "HP for SC"
        
        # HP for storage operation
        df = pd.read_csv(locator.pathSlaveRes + "/" + dicoSupply.configKey + "StorageOperationData.csv", usecols = ["E_aux_ch", "E_aux_dech", "Q_from_storage_used", "Q_to_storage"])
        array = np.array(df)
        QmaxHPStorage = 0
        for i in range(gv.DAYS_IN_YEAR * gv.HOURS_IN_DAY):
            if array[i][0] > 0:
                QmaxHPStorage = max(QmaxHPStorage, array[i][3] + array[i][0])
            elif array[i][1] > 0:
                QmaxHPStorage = max(QmaxHPStorage, array[i][2] + array[i][1])
        
        StorageHPCost += hp.calc_Cinv_HP(QmaxHPStorage, gv)
        addCosts += StorageHPCost

        print hp.calc_Cinv_HP(QmaxHPStorage, gv), "HP for storage"
        
        
        # Storage
        df = pd.read_csv(locator.pathSlaveRes + "/" + dicoSupply.configKey + "StorageOperationData.csv", usecols = ["Storage_Size"], nrows = 1)
        StorageVol = np.array(df)[0][0]
        StorageInvC += storage.calc_Cinv_storage(StorageVol, gv)
        addCosts += StorageInvC
        print storage.calc_Cinv_storage(StorageVol, gv), "Storage Costs"
        
        
        # Costs from network configuration
        print "\n COSTS FROM NETWORK CONFIGURATION"
        if gv.ZernezFlag == 1:
            NetworkCost += network.calc_Cinv_network_linear(gv.NetworkLengthZernez, gv) * nBuildinNtw / len(buildList)
        else:
            NetworkCost += ntwFeat.pipesCosts_DHN * nBuildinNtw / len(buildList)
        addCosts += NetworkCost
        print ntwFeat.pipesCosts_DHN * nBuildinNtw / len(buildList), "Pipes Costs"
    
        # HEX (1 per building in ntw)
        for (index, buildName) in zip(indCombi, buildList):
            if index == "1":
                
                subsFileName = buildName + "_result.csv"
                df = pd.read_csv(locator.pathSubsRes + "/" + subsFileName, usecols = ["Q_dhw", "Q_heating"])
                subsArray = np.array(df)
                
                Qmax = np.amax( subsArray[:,0] + subsArray[:,1] )
                SubstHEXCost += hex.calc_Cinv_HEX(Qmax, gv)
                print hex.calc_Cinv_HEX(Qmax, gv), "Hex", buildName
        addCosts += SubstHEXCost

        # HEX for solar
        roof_area = np.array(pd.read_csv(locator.get_total_demand(), usecols=["Aroof_m2"]))

        areaAvail = 0
        for i in range( len(indCombi) ):
            index = indCombi[i]
            if index == "1":
                areaAvail += roof_area[i][0]
                
        for i in range( len(indCombi) ):
            index = indCombi[i]
            if index == "1":
                share = roof_area[i][0] / areaAvail
                #print share, "solar area share", buildList[i]
                
                SC_Qmax = solarFeat.SC_Qnom * dicoSupply.SOLAR_PART_SC * share
                SCHEXCost += hex.calc_Cinv_HEX(SC_Qmax, gv)
                print hex.calc_Cinv_HEX(SC_Qmax, gv), "Hex SC", buildList[i]
                
                PVT_Qmax = solarFeat.PVT_Qnom * dicoSupply.SOLAR_PART_PVT * share
                PVTHEXCost += hex.calc_Cinv_HEX(PVT_Qmax, gv)
                print hex.calc_Cinv_HEX(PVT_Qmax, gv), "Hex PVT", buildList[i]
        addCosts += SCHEXCost
        addCosts += PVTHEXCost
        
        print addCosts,"addCosts in extraCostsMain"
        # Pump operation costs
        pumpCosts = pumps.calc_Ctot_pump(dicoSupply, buildList, locator.pathNtwRes, ntwFeat, gv)
        addCosts += pumpCosts
        print pumpCosts, "Pump Operation costs in extraCostsMain\n"
    
    # import gas consumption data from:

    if indCombi.count("1") > 0:
        # import gas consumption data from:
        
        FileName = locator.pathSlaveRes + "/" + dicoSupply.configKey + "PrimaryEnergyBySource.csv"
        colName = "EgasPrimaryPeakPower"
        EgasPrimaryDataframe = pd.read_csv(FileName, usecols=[colName])
        #print EgasPrimaryDataframe
        #print np.array(EgasPrimaryDataframe)
        
        #print float(np.array(EgasPrimaryDataframe))
        
        EgasPrimaryPeakPower = float(np.array(EgasPrimaryDataframe))
        GasConnectionInvCost = ngas.calc_Cinv_gas(EgasPrimaryPeakPower, gv)
    else:
        GasConnectionInvCost = 0.0
        
    addCosts += GasConnectionInvCost
    # Save data
    results = pd.DataFrame({
                            "SCInvC":[SCInvC],
                            "PVTInvC":[PVTInvC],
                            "BoilerAddInvC":[BoilerAddInvC],
                            "StorageHEXCost":[StorageHEXCost],
                            "StorageHPCost":[StorageHPCost],
                            "StorageInvC":[StorageInvC],
                            "StorageCostSum":[StorageInvC+StorageHPCost+StorageHEXCost],
                            "NetworkCost":[NetworkCost],
                            "SubstHEXCost":[SubstHEXCost],
                            "DHNInvestCost":[addCosts - CostDiscBuild],
                            "PVTHEXCost":[PVTHEXCost],
                            "CostDiscBuild":[CostDiscBuild],
                            "CO2DiscBuild":[CO2DiscBuild],
                            "PrimDiscBuild":[PrimDiscBuild],
                            "FurnaceInvCost":[FurnaceInvCost],
                            "BoilerBInvCost":[BoilerBInvCost],
                            "BoilerPInvCost":[BoilerPInvCost],
                            "HPLakeInvC":[HPLakeInvC],
                            "HPSewInvC":[HPSewInvC],
                            "SCHEXCost":[SCHEXCost],
                            "pumpCosts":[pumpCosts],
                            "SumInvestCost":[addCosts],
                            "GasConnectionInvCa":[GasConnectionInvCost]
                            })
    Name = "/" + dicoSupply.configKey + "_InvestmentCostDetailed.csv"
    results.to_csv(locator.pathSlaveRes + Name, sep=',')
     
      
    return (addCosts, addCO2, addPrim)
示例#5
0
def addCosts(indCombi, buildList, locator, dicoSupply, QUncoveredDesign,
             QUncoveredAnnual, solarFeat, ntwFeat, gv):
    """
    Computes additional costs / GHG emisions / primary energy needs
    for the individual
    
    Parameters
    ----------
    indCombi : string
        with 0 if disconnected building, 1 if connected
    buildList : list
        list of buildings in the district
    locator : string
        path to folders
    dicoSupply : class context
        with the features of the specific individual
    QuncoveredDesign : float
        hourly max of the heating uncovered demand
    QuncoveredAnnual : float
        total heating uncovered
    solarFeat / ntwFeat : class solarFeatures / ntwFeatures
    
    Returns
    -------
    (addCosts, addCO2, addPrim) : tuple
    
    """
    addCosts = 0
    addCO2 = 0
    addPrim = 0
    nBuildinNtw = 0

    # Add the features from the disconnected buildings
    print "\n COSTS FROM DISCONNECTED BUILDINGS"
    os.chdir(locator.pathDiscRes)
    CostDiscBuild = 0
    CO2DiscBuild = 0
    PrimDiscBuild = 0
    FurnaceInvCost = 0
    CCInvCost = 0
    BoilerBInvCost = 0
    BoilerPInvCost = 0
    HPLakeInvC = 0
    HPSewInvC = 0
    GHPInvC = 0
    PVInvC = 0
    SCInvC = 0
    PVTInvC = 0
    BoilerAddInvC = 0
    StorageHEXCost = 0
    StorageHPCost = 0
    StorageInvC = 0
    NetworkCost = 0
    SubstHEXCost = 0
    PVTHEXCost = 0
    SCHEXCost = 0
    pumpCosts = 0
    GasConnectionInvCost = 0

    for (index, buildName) in zip(indCombi, buildList):
        if index == "0":
            discFileName = "DiscOp_" + buildName + "_result.csv"
            df = pd.read_csv(discFileName)
            dfBest = df[df["Best configuration"] == 1]
            CostDiscBuild += dfBest["Total Costs [CHF]"].iloc[0]  # [CHF]
            CO2DiscBuild += dfBest["CO2 Emissions [kgCO2-eq]"].iloc[
                0]  # [kg CO2]
            PrimDiscBuild += dfBest["Primary Energy Needs [MJoil-eq]"].iloc[
                0]  # [MJ-oil-eq]

            print dfBest["Total Costs [CHF]"].iloc[
                0], buildName, "disconnected"

        else:
            nBuildinNtw += 1

    addCosts += CostDiscBuild
    addCO2 += CO2DiscBuild
    addPrim += PrimDiscBuild

    # Add the features for the network

    if indCombi.count("1") > 0:
        os.chdir(locator.pathSlaveRes)

        print " \n MACHINERY COSTS"
        # Add the investment costs of the energy systems
        # Furnace
        if dicoSupply.Furnace_on == 1:
            P_design = dicoSupply.Furnace_Q_max

            fNameSlavePP = dicoSupply.configKey + "PPActivationPattern.csv"
            dfFurnace = pd.read_csv(fNameSlavePP, usecols=["Q_Furnace"])
            arrayFurnace = np.array(dfFurnace)

            Q_annual = 0
            for i in range(int(np.shape(arrayFurnace)[0])):
                Q_annual += arrayFurnace[i][0]

            FurnaceInvCost = furnace.calc_Cinv_furnace(P_design, Q_annual, gv)
            addCosts += FurnaceInvCost

            print furnace.calc_Cinv_furnace(P_design, Q_annual, gv), " Furnace"

        # CC
        if dicoSupply.CC_on == 1:
            CC_size = dicoSupply.CC_GT_SIZE
            CCInvCost = chp.calc_Cinv_CCT(CC_size, gv)
            addCosts += CCInvCost
            print chp.calc_Cinv_CCT(CC_size, gv), " CC"

        # Boiler Base
        if dicoSupply.Boiler_on == 1:
            Q_design = dicoSupply.Boiler_Q_max

            fNameSlavePP = dicoSupply.configKey + "PPActivationPattern.csv"
            dfBoilerBase = pd.read_csv(fNameSlavePP, usecols=["Q_BoilerBase"])
            arrayBoilerBase = np.array(dfBoilerBase)

            Q_annual = 0
            for i in range(int(np.shape(arrayBoilerBase)[0])):
                Q_annual += arrayBoilerBase[i][0]

            BoilerBInvCost = boiler.calc_Cinv_boiler(Q_design, Q_annual, gv)
            addCosts += BoilerBInvCost
            print boiler.calc_Cinv_boiler(Q_design, Q_annual,
                                          gv), " Boiler Base "

        # Boiler Peak
        if dicoSupply.BoilerPeak_on == 1:
            Q_design = dicoSupply.BoilerPeak_Q_max

            fNameSlavePP = dicoSupply.configKey + "PPActivationPattern.csv"
            dfBoilerPeak = pd.read_csv(fNameSlavePP, usecols=["Q_BoilerPeak"])
            arrayBoilerPeak = np.array(dfBoilerPeak)

            Q_annual = 0
            for i in range(int(np.shape(arrayBoilerPeak)[0])):
                Q_annual += arrayBoilerPeak[i][0]
            BoilerPInvCost = boiler.calc_Cinv_boiler(Q_design, Q_annual, gv)
            addCosts += BoilerPInvCost
            print boiler.calc_Cinv_boiler(Q_design, Q_annual,
                                          gv), " Boiler Peak"

        # HP Lake
        if dicoSupply.HP_Lake_on == 1:
            HP_Size = dicoSupply.HPLake_maxSize
            HPLakeInvC = hp.calc_Cinv_HP(HP_Size, gv)
            addCosts += HPLakeInvC
            print hp.calc_Cinv_HP(HP_Size, gv), " HP Lake"

        # HP Sewage
        if dicoSupply.HP_Sew_on == 1:
            HP_Size = dicoSupply.HPSew_maxSize
            HPSewInvC = hp.calc_Cinv_HP(HP_Size, gv)
            addCosts += HPSewInvC
            print hp.calc_Cinv_HP(HP_Size, gv), "HP Sewage"

        # GHP
        if dicoSupply.GHP_on == 1:
            fNameSlavePP = dicoSupply.configKey + "PPActivationPattern.csv"
            dfGHP = pd.read_csv(fNameSlavePP, usecols=["E_GHP"])
            arrayGHP = np.array(dfGHP)

            GHP_Enom = np.amax(arrayGHP)
            GHPInvC = hp.calc_Cinv_GHP(GHP_Enom, gv) * gv.EURO_TO_CHF
            addCosts += GHPInvC
            print hp.calc_Cinv_GHP(GHP_Enom, gv) * gv.EURO_TO_CHF, " GHP"

        # Solar technologies

        PV_peak = dicoSupply.SOLAR_PART_PV * solarFeat.SolarAreaPV * gv.nPV  #kW
        PVInvC = pv.calc_Cinv_PV(PV_peak)
        addCosts += PVInvC
        print pv.calc_Cinv_PV(PV_peak), "PV peak"

        SC_area = dicoSupply.SOLAR_PART_SC * solarFeat.SolarAreaSC
        SCInvC = stc.calc_Cinv_SC(SC_area)
        addCosts += SCInvC
        print stc.calc_Cinv_SC(SC_area), "SC area"

        PVT_peak = dicoSupply.SOLAR_PART_PVT * solarFeat.SolarAreaPVT * gv.nPVT  #kW
        PVTInvC = pvt.calc_Cinv_PVT(PVT_peak)
        addCosts += PVTInvC
        print pvt.calc_Cinv_PVT(PVT_peak), "PVT peak"

        # Back-up boiler
        BoilerAddInvC = boiler.calc_Cinv_boiler(QUncoveredDesign,
                                                QUncoveredAnnual, gv)
        addCosts += BoilerAddInvC
        print boiler.calc_Cinv_boiler(QUncoveredDesign, QUncoveredAnnual,
                                      gv), "backup boiler"

        # Hex and HP for Heat recovery
        print "\n STORAGE PART COSTS"
        if dicoSupply.WasteServersHeatRecovery == 1:
            df = pd.read_csv(locator.pathNtwRes + "/" +
                             dicoSupply.NETWORK_DATA_FILE,
                             usecols=["Qcdata_netw_total"])
            array = np.array(df)
            QhexMax = np.amax(array)
            StorageHEXCost += hex.calc_Cinv_HEX(QhexMax, gv)

            print hex.calc_Cinv_HEX(QhexMax, gv), "Hex for data center"

            df = pd.read_csv(locator.pathSlaveRes + "/" +
                             dicoSupply.configKey + "StorageOperationData.csv",
                             usecols=["HPServerHeatDesignArray"])
            array = np.array(df)
            QhpMax = np.amax(array)
            StorageHEXCost += hp.calc_Cinv_HP(QhpMax, gv)
            print hp.calc_Cinv_HP(QhpMax, gv), "HP for data center"

        if dicoSupply.WasteCompressorHeatRecovery == 1:
            df = pd.read_csv(locator.pathNtwRes + "/" +
                             dicoSupply.NETWORK_DATA_FILE,
                             usecols=["Ecaf_netw_total"])
            array = np.array(df)
            QhexMax = np.amax(array)

            StorageHEXCost += hex.calc_Cinv_HEX(QhexMax, gv)
            print hex.calc_Cinv_HEX(QhexMax, gv), "Hex for compressed air"

            df = pd.read_csv(locator.pathSlaveRes + "/" +
                             dicoSupply.configKey + "StorageOperationData.csv",
                             usecols=["HPCompAirDesignArray"])
            array = np.array(df)
            QhpMax = np.amax(array)

            StorageHEXCost += hp.calc_Cinv_HP(QhpMax, gv)
            print hp.calc_Cinv_HP(QhpMax, gv), "HP for compressed air"
        addCosts += StorageHEXCost

        # Heat pump solar to storage
        df = pd.read_csv(locator.pathSlaveRes + "/" + dicoSupply.configKey +
                         "StorageOperationData.csv",
                         usecols=["HPScDesignArray", "HPpvt_designArray"])
        array = np.array(df)
        QhpMax_PVT = np.amax(array[:, 1])
        QhpMax_SC = np.amax(array[:, 0])

        StorageHPCost += hp.calc_Cinv_HP(QhpMax_PVT, gv)
        print hp.calc_Cinv_HP(QhpMax_PVT, gv), "HP for PVT"

        StorageHPCost += hp.calc_Cinv_HP(QhpMax_SC, gv)
        print hp.calc_Cinv_HP(QhpMax_SC, gv), "HP for SC"

        # HP for storage operation
        df = pd.read_csv(locator.pathSlaveRes + "/" + dicoSupply.configKey +
                         "StorageOperationData.csv",
                         usecols=[
                             "E_aux_ch", "E_aux_dech", "Q_from_storage_used",
                             "Q_to_storage"
                         ])
        array = np.array(df)
        QmaxHPStorage = 0
        for i in range(gv.DAYS_IN_YEAR * gv.HOURS_IN_DAY):
            if array[i][0] > 0:
                QmaxHPStorage = max(QmaxHPStorage, array[i][3] + array[i][0])
            elif array[i][1] > 0:
                QmaxHPStorage = max(QmaxHPStorage, array[i][2] + array[i][1])

        StorageHPCost += hp.calc_Cinv_HP(QmaxHPStorage, gv)
        addCosts += StorageHPCost

        print hp.calc_Cinv_HP(QmaxHPStorage, gv), "HP for storage"

        # Storage
        df = pd.read_csv(locator.pathSlaveRes + "/" + dicoSupply.configKey +
                         "StorageOperationData.csv",
                         usecols=["Storage_Size"],
                         nrows=1)
        StorageVol = np.array(df)[0][0]
        StorageInvC += storage.calc_Cinv_storage(StorageVol, gv)
        addCosts += StorageInvC
        print storage.calc_Cinv_storage(StorageVol, gv), "Storage Costs"

        # Costs from network configuration
        print "\n COSTS FROM NETWORK CONFIGURATION"
        if gv.ZernezFlag == 1:
            NetworkCost += network.calc_Cinv_network_linear(
                gv.NetworkLengthZernez, gv) * nBuildinNtw / len(buildList)
        else:
            NetworkCost += ntwFeat.pipesCosts_DHN * nBuildinNtw / len(
                buildList)
        addCosts += NetworkCost
        print ntwFeat.pipesCosts_DHN * nBuildinNtw / len(
            buildList), "Pipes Costs"

        # HEX (1 per building in ntw)
        for (index, buildName) in zip(indCombi, buildList):
            if index == "1":

                subsFileName = buildName + "_result.csv"
                df = pd.read_csv(locator.pathSubsRes + "/" + subsFileName,
                                 usecols=["Q_dhw", "Q_heating"])
                subsArray = np.array(df)

                Qmax = np.amax(subsArray[:, 0] + subsArray[:, 1])
                SubstHEXCost += hex.calc_Cinv_HEX(Qmax, gv)
                print hex.calc_Cinv_HEX(Qmax, gv), "Hex", buildName
        addCosts += SubstHEXCost

        # HEX for solar
        roof_area = np.array(
            pd.read_csv(locator.get_total_demand(), usecols=["Aroof_m2"]))

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

        for i in range(len(indCombi)):
            index = indCombi[i]
            if index == "1":
                share = roof_area[i][0] / areaAvail
                #print share, "solar area share", buildList[i]

                SC_Qmax = solarFeat.SC_Qnom * dicoSupply.SOLAR_PART_SC * share
                SCHEXCost += hex.calc_Cinv_HEX(SC_Qmax, gv)
                print hex.calc_Cinv_HEX(SC_Qmax, gv), "Hex SC", buildList[i]

                PVT_Qmax = solarFeat.PVT_Qnom * dicoSupply.SOLAR_PART_PVT * share
                PVTHEXCost += hex.calc_Cinv_HEX(PVT_Qmax, gv)
                print hex.calc_Cinv_HEX(PVT_Qmax, gv), "Hex PVT", buildList[i]
        addCosts += SCHEXCost
        addCosts += PVTHEXCost

        print addCosts, "addCosts in extraCostsMain"
        # Pump operation costs
        pumpCosts = pumps.calc_Ctot_pump(dicoSupply, buildList,
                                         locator.pathNtwRes, ntwFeat, gv)
        addCosts += pumpCosts
        print pumpCosts, "Pump Operation costs in extraCostsMain\n"

    # import gas consumption data from:

    if indCombi.count("1") > 0:
        # import gas consumption data from:

        FileName = locator.pathSlaveRes + "/" + dicoSupply.configKey + "PrimaryEnergyBySource.csv"
        colName = "EgasPrimaryPeakPower"
        EgasPrimaryDataframe = pd.read_csv(FileName, usecols=[colName])
        #print EgasPrimaryDataframe
        #print np.array(EgasPrimaryDataframe)

        #print float(np.array(EgasPrimaryDataframe))

        EgasPrimaryPeakPower = float(np.array(EgasPrimaryDataframe))
        GasConnectionInvCost = ngas.calc_Cinv_gas(EgasPrimaryPeakPower, gv)
    else:
        GasConnectionInvCost = 0.0

    addCosts += GasConnectionInvCost
    # Save data
    results = pd.DataFrame({
        "SCInvC": [SCInvC],
        "PVTInvC": [PVTInvC],
        "BoilerAddInvC": [BoilerAddInvC],
        "StorageHEXCost": [StorageHEXCost],
        "StorageHPCost": [StorageHPCost],
        "StorageInvC": [StorageInvC],
        "StorageCostSum": [StorageInvC + StorageHPCost + StorageHEXCost],
        "NetworkCost": [NetworkCost],
        "SubstHEXCost": [SubstHEXCost],
        "DHNInvestCost": [addCosts - CostDiscBuild],
        "PVTHEXCost": [PVTHEXCost],
        "CostDiscBuild": [CostDiscBuild],
        "CO2DiscBuild": [CO2DiscBuild],
        "PrimDiscBuild": [PrimDiscBuild],
        "FurnaceInvCost": [FurnaceInvCost],
        "BoilerBInvCost": [BoilerBInvCost],
        "BoilerPInvCost": [BoilerPInvCost],
        "HPLakeInvC": [HPLakeInvC],
        "HPSewInvC": [HPSewInvC],
        "SCHEXCost": [SCHEXCost],
        "pumpCosts": [pumpCosts],
        "SumInvestCost": [addCosts],
        "GasConnectionInvCa": [GasConnectionInvCost]
    })
    Name = "/" + dicoSupply.configKey + "_InvestmentCostDetailed.csv"
    results.to_csv(locator.pathSlaveRes + Name, sep=',')

    return (addCosts, addCO2, addPrim)
def discBuildOp(locator, building_names, gv):
    """
    Computes the parameters for the operation of disconnected buildings
    output results in csv files
    
    Parameters
    ----------
    locator : string
        path to folders    
    
    """
    print "Start Disconnected Building Routine \n"
    t0 = time.clock()
    geothermal_potential = pd.read_csv(locator.get_geothermal_potential, index_col="Name")
    BestData = {}

    def calc_new_load(mdot, TsupDH, Tret, gv):
        Qload = mdot * gv.cp * (TsupDH - Tret) * (1 + gv.Qloss_Disc)
        if Qload < 0:
            Qload = 0
        if Qload < -1E-5:
            print "Error in discBuildMain, negative heat requirement at hour", hour, buildName
        return Qload

    for buildName in building_names:
        fName = locator.pathSubsRes + "/" + buildName + "_result.csv"

        loads = pd.read_csv(fName, usecols=["T_supply_DH_result", "T_return_DH_result", "mdot_DH_result"])
        Qload = np.vectorize(calc_new_load)(loads["mdot_DH_result"], loads["T_supply_DH_result"], loads["T_return_DH_result"], gv)
        Qannual = Qload.sum()
        Qnom = Qload.max()* (1+gv.Qmargin_Disc) # 1% reliability margin on installed capacity

        # Create empty matrices
        result = np.zeros((13,7))
        result[0][0] = 1
        result[1][1] = 1
        result[2][2] = 1
        InvCosts = np.zeros((13,1))
        resourcesRes = np.zeros((13,4))
        QannualB_GHP = np.zeros((10,1)) # For the investment costs of the boiler used with GHP
        Wel_GHP = np.zeros((10,1)) # For the investment costs of the GHP
        
        # Supply with the Boiler / FC / GHP
        print "Operation with the Boiler / FC / GHP"

        Tret = loads["T_return_DH_result"].values
        TsupDH = loads["T_supply_DH_result"].values
        mdot = loads["mdot_DH_result"].values
        for hour in range(8760):

            if Tret[hour] == 0:
                Tret[hour] = TsupDH[hour]
                
            # Boiler NG
            BoilerEff = Boiler.calc_Cop_boiler(Qload[hour], Qnom, Tret[hour])
            
            Qgas = Qload[hour] / BoilerEff
            
            result[0][4] += gv.NG_PRICE * Qgas # CHF
            result[0][5] += gv.NG_BACKUPBOILER_TO_CO2_STD * Qgas * 3600E-6 # kgCO2
            result[0][6] += gv.NG_BACKUPBOILER_TO_OIL_STD * Qgas * 3600E-6 # MJ-oil-eq
            resourcesRes[0][0] += Qload[hour]
            
            if gv.DiscBioGasFlag == 1:
                result[0][4] += gv.BG_PRICE * Qgas # CHF
                result[0][5] += gv.BG_BACKUPBOILER_TO_CO2_STD * Qgas * 3600E-6 # kgCO2
                result[0][6] += gv.BG_BACKUPBOILER_TO_OIL_STD * Qgas * 3600E-6 # MJ-oil-eq
                
            # Boiler BG
            result[1][4] += gv.BG_PRICE * Qgas # CHF
            result[1][5] += gv.BG_BACKUPBOILER_TO_CO2_STD * Qgas * 3600E-6 # kgCO2
            result[1][6] += gv.BG_BACKUPBOILER_TO_OIL_STD * Qgas * 3600E-6 # MJ-oil-eq
            resourcesRes[1][1] += Qload[hour]
                
            # FC
            (FC_Effel, FC_Effth) = FC.calc_eta_FC(Qload[hour], Qnom, 1, "B")
            Qgas = Qload[hour] / (FC_Effth+FC_Effel)
            Qelec = Qgas * FC_Effel            
            
            result[2][4] += gv.NG_PRICE * Qgas - gv.ELEC_PRICE * Qelec # CHF, extra electricity sold to grid
            result[2][5] += 0.0874 * Qgas * 3600E-6 + 773 * 0.45 * Qelec * 1E-6 - gv.EL_TO_CO2 * Qelec * 3600E-6 # kgCO2
            # Bloom box emissions within the FC: 773 lbs / MWh_el (and 1 lbs = 0.45 kg)
            # http://www.carbonlighthouse.com/2011/09/16/bloom-box/
            result[2][6] += 1.51 * Qgas * 3600E-6 - gv.EL_TO_OIL_EQ * Qelec * 3600E-6 # MJ-oil-eq
            
            resourcesRes[2][0] += Qload[hour]
            resourcesRes[2][2] += Qelec
            
            # GHP
            for i in range(10):
                
                QnomBoiler = i/10 * Qnom
                QnomGHP = Qnom - QnomBoiler
                
                if Qload[hour] <= QnomGHP:
                
                    (wdot_el, qcolddot, qhotdot_missing, tsup2) = HP.calc_Cop_GHP(mdot[hour], TsupDH[hour], Tret[hour], gv.TGround, gv)
                    
                    if Wel_GHP[i][0] < wdot_el:
                        Wel_GHP[i][0] = wdot_el
                    
                    result[3+i][4] += gv.ELEC_PRICE * wdot_el   # CHF
                    result[3+i][5] += gv.SMALL_GHP_TO_CO2_STD  * wdot_el   * 3600E-6 # kgCO2
                    result[3+i][6] += gv.SMALL_GHP_TO_OIL_STD  * wdot_el   * 3600E-6 # MJ-oil-eq
                    
                    resourcesRes[3+i][2] -= wdot_el
                    resourcesRes[3+i][3] += Qload[hour] - qhotdot_missing
                    
                    if qhotdot_missing > 0:
                        print "GHP unable to cover the whole demand, boiler activated!"
                        BoilerEff = Boiler.calc_Cop_boiler(qhotdot_missing, QnomBoiler, tsup2)
                        Qgas = qhotdot_missing / BoilerEff
                        
                        result[3+i][4] += gv.NG_PRICE * Qgas   # CHF
                        result[3+i][5] += gv.NG_BACKUPBOILER_TO_CO2_STD * Qgas   * 3600E-6 # kgCO2
                        result[3+i][6] += gv.NG_BACKUPBOILER_TO_OIL_STD * Qgas   * 3600E-6 # MJ-oil-eq
                        
                        QannualB_GHP[i][0] += qhotdot_missing
                        resourcesRes[3+i][0] += qhotdot_missing
    
                else:
                    #print "Boiler activated to compensate GHP", i
                    #if gv.DiscGHPFlag == 0:
                    #    print QnomGHP
                    #   QnomGHP = 0 
                    #   print "GHP not allowed 2, set QnomGHP to zero"
                        
                    TexitGHP = QnomGHP / (mdot[hour] * gv.cp) + Tret[hour]
                    (wdot_el, qcolddot, qhotdot_missing, tsup2) = HP.calc_Cop_GHP(mdot[hour], TexitGHP, Tret[hour], gv.TGround, gv)
                    
                    if Wel_GHP[i][0] < wdot_el:
                        Wel_GHP[i][0] = wdot_el
                        
                    result[3+i][4] += gv.ELEC_PRICE * wdot_el   # CHF
                    result[3+i][5] += gv.SMALL_GHP_TO_CO2_STD  * wdot_el   * 3600E-6 # kgCO2
                    result[3+i][6] += gv.SMALL_GHP_TO_OIL_STD  * wdot_el   * 3600E-6 # MJ-oil-eq
                    
                    resourcesRes[3+i][2] -= wdot_el
                    resourcesRes[3+i][3] += QnomGHP - qhotdot_missing
                    
                    if qhotdot_missing > 0:
                        print "GHP unable to cover the whole demand, boiler activated!"
                        BoilerEff = Boiler.calc_Cop_boiler(qhotdot_missing, QnomBoiler, tsup2)
                        Qgas = qhotdot_missing / BoilerEff
                        
                        result[3+i][4] += gv.NG_PRICE * Qgas   # CHF
                        result[3+i][5] += gv.NG_BACKUPBOILER_TO_CO2_STD * Qgas   * 3600E-6 # kgCO2
                        result[3+i][6] += gv.NG_BACKUPBOILER_TO_OIL_STD * Qgas   * 3600E-6 # MJ-oil-eq
                        
                        QannualB_GHP[i][0] += qhotdot_missing
                        resourcesRes[3+i][0] += qhotdot_missing
                        
                    QtoBoiler = Qload[hour] - QnomGHP
                    QannualB_GHP[i][0] += QtoBoiler
                    
                    BoilerEff = Boiler.calc_Cop_boiler(QtoBoiler, QnomBoiler, TexitGHP)
                    Qgas = QtoBoiler / BoilerEff
                    
                    result[3+i][4] += gv.NG_PRICE * Qgas   # CHF
                    result[3+i][5] += gv.NG_BACKUPBOILER_TO_CO2_STD * Qgas   * 3600E-6 # kgCO2
                    result[3+i][6] += gv.NG_BACKUPBOILER_TO_OIL_STD * Qgas   * 3600E-6 # MJ-oil-eq
                    resourcesRes[3+i][0] += QtoBoiler

        print time.clock() - t0, "seconds process time for the operation \n"
        
        # Investment Costs / CO2 / Prim
        InvCaBoiler = Boiler.calc_Cinv_boiler(Qnom, Qannual, gv)
        InvCosts[0][0] = InvCaBoiler
        InvCosts[1][0] = InvCaBoiler
        
        InvCosts[2][0] = FC.calc_Cinv_FC(Qnom, gv)
        
        for i in range(10):
            result[3+i][0] = i/10
            result[3+i][3] = 1-i/10

            QnomBoiler = i/10 * Qnom
            
            InvCaBoiler = Boiler.calc_Cinv_boiler(QnomBoiler, QannualB_GHP[i][0], gv)
            InvCosts[3+i][0] = InvCaBoiler
            
            InvCaGHP = HP.GHP_InvCost( Wel_GHP[i][0] , gv)
            InvCosts[3+i][0] += InvCaGHP * gv.EURO_TO_CHF
        

        # Best configuration
        print "Find the best configuration"
        
        Best = np.zeros((13,1))
        indexBest = 0

        TotalCosts = np.zeros((13,2))
        TotalCO2 = np.zeros((13,2))
        TotalPrim = np.zeros((13,2))
        
        for i in range(13):
            TotalCosts[i][0] = TotalCO2[i][0] = TotalPrim[i][0] = i

            TotalCosts[i][1] = InvCosts[i][0] + result[i][4]
            TotalCO2[i][1] = result[i][5]
            TotalPrim[i][1] = result[i][6]
        
        CostsS = TotalCosts[np.argsort(TotalCosts[:,1])]
        CO2S = TotalCO2[np.argsort(TotalCO2[:,1])]
        PrimS = TotalPrim[np.argsort(TotalPrim[:,1])]
        
        el = len(CostsS)
        rank = 0
        Bestfound = False
        
        optsearch = np.empty(el)
        optsearch.fill(3)
        indexBest = 0
        
        # Check the GHP area constraint
        for i in range(10):
            QGHP = (1-i/10) * Qnom
            areaAvail = geothermal_potential.ix[buildName,"Area_geo"]
            Qallowed = np.ceil(areaAvail/gv.GHP_A) * gv.GHP_HmaxSize #[W_th]
            
            if Qallowed < QGHP:
                optsearch[i+3] += 1
                Best[i+3][0] = -1
        
        while not Bestfound and rank<el:
            
            optsearch[CostsS[rank][0]] -= 1
            optsearch[CO2S[rank][0]] -= 1
            optsearch[PrimS[rank][0]] -= 1
            
            if np.count_nonzero(optsearch) != el:
                Bestfound = True
                indexBest = np.where(optsearch == 0)[0][0]
                
            rank += 1

        Best[indexBest][0] = 1
        print indexBest, "Best"
        Qnom_array = np.ones(len(Best[:,0])) * Qnom

        # Save results in csv file
        print "Save the results for", buildName, "\n"
        
        dico = {}
        dico[ "BoilerNG Share" ] = result[:,0]
        dico[ "BoilerBG Share" ] = result[:,1]
        dico[ "FC Share" ] = result[:,2]
        dico[ "GHP Share" ] = result[:,3]
        dico[ "Operation Costs [CHF]" ] = result[:,4]
        dico[ "CO2 Emissions [kgCO2-eq]" ] = result[:,5]
        dico[ "Primary Energy Needs [MJoil-eq]" ] = result[:,6]
        dico[ "Annualized Investment Costs [CHF]" ] = InvCosts[:,0]
        dico[ "Total Costs [CHF]" ] = TotalCosts[:,1]
        dico[ "Best configuration" ] = Best[:,0]
        dico[ "Nominal Power" ] = Qnom_array
        dico[ "QfromNG" ] = resourcesRes[:,0]
        dico[ "QfromBG" ] = resourcesRes[:,1]
        dico[ "EforGHP" ] = resourcesRes[:,2]
        dico[ "QfromGHP" ] = resourcesRes[:,3]

        os.chdir(locator.pathDiscRes)
        fName = buildName + "_result.csv"
        results_to_csv = pd.DataFrame(dico)
        fName_result = "DiscOp_" + fName[0:(len(fName)-4)] + ".csv"
        results_to_csv.to_csv(fName_result, sep= ',')
        
    
        BestComb = {}
        BestComb[ "BoilerNG Share" ] = result[indexBest,0]
        BestComb[ "BoilerBG Share" ] = result[indexBest,1]
        BestComb[ "FC Share" ] = result[indexBest,2]
        BestComb[ "GHP Share" ] = result[indexBest,3]
        BestComb[ "Operation Costs [CHF]" ] = result[indexBest,4]
        BestComb[ "CO2 Emissions [kgCO2-eq]" ] = result[indexBest,5]
        BestComb[ "Primary Energy Needs [MJoil-eq]" ] = result[indexBest,6]
        BestComb[ "Annualized Investment Costs [CHF]" ] = InvCosts[indexBest,0]
        BestComb[ "Total Costs [CHF]" ] = TotalCosts[indexBest,1]
        BestComb[ "Best configuration" ] = Best[indexBest,0]
        BestComb[ "Nominal Power" ] = Qnom
        
        BestData[buildName] = BestComb

    if 0:
        os.chdir(locator.pathDiscRes)
        fName = "DiscOpSummary.csv"
        results_to_csv = pd.DataFrame(BestData)
        results_to_csv.to_csv(fName, sep= ',')
        
        
    print "Disconnected Building Routine Completed"
    print time.clock() - t0, "seconds process time for the Disconnected Building Routine \n"