def normalizePop(pathX, Generation):
    """
    Normalizes the population with the min / max IN THAT GENERATION
    All 3 objectives are normalized to [0,1] 
    
    Parameters
    ----------
    pathMasterRes : string
        path to folder where checkpoints are stored
    Generation : int
        generation to extract
    pathNtwRes : string
        path to ntw result folder
    
    Returns
    -------
    popFinal : list
        normalized population
    
    """
    popFinal, eps, testedPop = sFn.readCheckPoint(pathX,
                                                  Generation,
                                                  storeData=0)

    maxCosts = 0
    minCosts = 0

    maxCO2 = 0
    minCO2 = 0

    maxPrim = 0
    minPrim = 0

    popNorm = toolbox.clone(popFinal)

    for ind in popFinal:
        if ind.fitness.values[0] < minCosts:
            minCosts = ind.fitness.values[0]
        if ind.fitness.values[0] > maxCosts:
            maxCosts = ind.fitness.values[0]

        if ind.fitness.values[1] < minCO2:
            minCO2 = ind.fitness.values[1]
        if ind.fitness.values[1] > maxCO2:
            maxCO2 = ind.fitness.values[1]

        if ind.fitness.values[2] < minPrim:
            minPrim = ind.fitness.values[2]
        if ind.fitness.values[2] > maxPrim:
            maxPrim = ind.fitness.values[2]

    for i in range(len(popFinal)):
        ind = popFinal[i]
        NormCost = (ind.fitness.values[0] - minCosts) / (maxCosts - minCosts)
        NormCO2 = (ind.fitness.values[1] - minCO2) / (maxCO2 - minCO2)
        NormPrim = (ind.fitness.values[2] - minPrim) / (maxPrim - minPrim)

        popNorm[i].fitness.values = (NormCost, NormCO2, NormPrim)

    return popFinal
def normalizePop(pathX, Generation):
    """
    Normalizes the population with the min / max IN THAT GENERATION
    All 3 objectives are normalized to [0,1] 
    
    Parameters
    ----------
    pathMasterRes : string
        path to folder where checkpoints are stored
    Generation : int
        generation to extract
    pathNtwRes : string
        path to ntw result folder
    
    Returns
    -------
    popFinal : list
        normalized population
    
    """
    popFinal, eps, testedPop = sFn.readCheckPoint(pathX, Generation, storeData = 0)

    maxCosts =0
    minCosts =0
    
    maxCO2 =0
    minCO2 =0
    
    maxPrim =0
    minPrim =0
    
    popNorm = toolbox.clone(popFinal)
    
    for ind in popFinal:
        if ind.fitness.values[0] < minCosts:
            minCosts = ind.fitness.values[0]
        if ind.fitness.values[0]  > maxCosts:
            maxCosts = ind.fitness.values[0]
            
        if ind.fitness.values[1] < minCO2:
            minCO2 = ind.fitness.values[1]
        if ind.fitness.values[1] > maxCO2:
            maxCO2 = ind.fitness.values[1]
            
        if ind.fitness.values[2] < minPrim:
            minPrim = ind.fitness.values[2]
        if ind.fitness.values[2] > maxPrim:
            maxPrim = ind.fitness.values[2]
    
    
    for i in range( len( popFinal ) ):
        ind = popFinal[i]
        NormCost = (ind.fitness.values[0] - minCosts) / (maxCosts - minCosts)
        NormCO2 = (ind.fitness.values[1] - minCO2) / (maxCO2 - minCO2)
        NormPrim = (ind.fitness.values[2] - minPrim) / (maxPrim - minPrim)
        
        popNorm[i].fitness.values = (NormCost, NormCO2, NormPrim)
            
    return popFinal
def sensAnalysis(pathX, extraCosts, extraCO2, extraPrim, solarFeat, ntwFeat, gen):

    gV = glob.globalVariables()
    step = gV.sensibilityStep

    bandwidth = sensBandwidth()

    os.chdir(pathX.pathMasterRes)
    pop, eps, testedPop = sFn.readCheckPoint(pathX, gen, 0)
    toolbox = base.Toolbox()
    
    os.chdir(pathX.pathRaw)
    buildList = sFn.extractList("Total.csv")

    ParetoResults = np.zeros( len(pop) )
    FactorResults = np.zeros((step + 1, bandwidth.nFactors * 2))

    def sensOneFactor(obj, factor_name, mini, maxi, colNumber):
        iniValue = getattr(obj, factor_name)
        index = 0
                
        for delta in np.arange(mini, maxi + 1E-5, (maxi-mini)/step):
            FactorResults[index][colNumber + 0] = delta
            if abs(delta) > 1E-10:
                setattr(obj, factor_name, iniValue * (1+delta))
    
                newpop = []
                for ind in pop:
                    newInd = toolbox.clone(ind)
                    newpop.append(newInd)
                    (costs, CO2, prim) = eI.evalInd(newInd, buildList, pathX, extraCosts, extraCO2, extraPrim, solarFeat, ntwFeat, obj)
                    newInd.fitness.values = (costs, CO2, prim)
                
                selection = sel.selectPareto(newpop)
                for i in range(len(newpop)):
                    if newpop[i] in selection:
                        ParetoResults[i] += 1
                
                FactorResults[index][colNumber + 1] = len(newpop) - len(selection)

            index += 1

        setattr(obj, factor_name, iniValue)

    
    sensOneFactor(gV, 'ELEC_PRICE', bandwidth.minElec, bandwidth.maxElec, 0)
    sensOneFactor(gV, 'NG_PRICE', bandwidth.minNG, bandwidth.maxNG, 2)
    sensOneFactor(gV, 'BG_PRICE', bandwidth.minBG, bandwidth.maxBG, 4)
    
    indexSensible = FactorResults.argmax()%(2*bandwidth.nFactors)
    if indexSensible == 1:
        mostSensitive = 'Electricity price'
    elif indexSensible == 3:
        mostSensitive = 'NG price'
    else:
        mostSensitive = 'BG price'
        
    return ParetoResults, FactorResults, mostSensitive
Exemple #4
0
def plot_pareto_scenarios(generations, headers, relative, savelocation):
    xs =[]
    ys =[]
    zs =[]
    fig = plt.figure()
    counter = 0
    for header in headers:
        pathX = sFn.pathX(header)
        pop, eps, testedPop = sFn.readCheckPoint(pathX, generations[counter], 0)
        Area_buildings = pd.read_csv(pathX.pathRaw+'//'+'Total.csv',usecols=['Af']).values.sum()
        [x, y, z] = map(np.array, zip( *[ind.fitness.values for ind in pop] ) )
        ax = fig.add_subplot(111)
        if relative == True:
            z[:] = [a / Area_buildings for a in z]
            x[:] = [b / Area_buildings for b in x]
            y[:] = [c / Area_buildings for c in y]
        xs.extend(x)
        ys.extend(y)
        zs.extend(z)
        counter +=1
        
    if relative == True:
        TAC = 'TAC [EU/m2.yr]'
        CO2 = 'CO2 [kg-CO2/m2.yr]'
        PEN = 'PEN [MJ/m2.yr]'
        ax.set_ylim([10,50])
        finallocation = savelocation+"pareto_m2.png"
    else:
        var = 1000000
        zs[:] = [x / var for x in zs]
        xs[:] = [x / var for x in xs]
        ys[:] = [x / var for x in ys]
        TAC = 'TAC [Mio EU/yr]'
        CO2 = 'CO2 [kton-CO2/yr]'
        PEN = 'PEN [TJ/yr]' 
        ax.set_xlim([2.5,7.0]) 
        finallocation = savelocation+"pareto.png"
               
    cm = plt.get_cmap('jet')
    cNorm = matplotlib.colors.Normalize(vmin=min(zs), vmax=max(zs))
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
    ax.scatter(xs, ys, c=scalarMap.to_rgba(zs), s=50, alpha =0.8)    
    ax.set_xlabel(TAC)
    ax.set_ylabel(CO2)
    

    scalarMap.set_array(zs)
    fig.colorbar(scalarMap, label=PEN)
    plt.grid(True)
    plt.rcParams['figure.figsize'] = (6,4)
    plt.rcParams.update({'font.size':12})
    plt.gcf().subplots_adjust(bottom=0.15)
    plt.savefig(finallocation)
    plt.clf()
Exemple #5
0
def normalizePop(locator, Generation):
    """
    Normalizes the population with the min / max IN THAT GENERATION
    All 3 objectives are normalized to [0,1] 

    :param locator: inputlocator set to scenario
    :param Generation: generation to extract
    :type locator: string
    :type Generation: int
    :return: normalized population
    :rtype: list
    """
    popFinal, eps, testedPop, ntwList, fitness = sFn.readCheckPoint(
        locator, Generation, storeData=0)

    maxCosts = 0
    minCosts = 0

    maxCO2 = 0
    minCO2 = 0

    maxPrim = 0
    minPrim = 0

    popNorm = toolbox.clone(popFinal)

    for ind in popFinal:
        if ind.fitness.values[0] < minCosts:
            minCosts = ind.fitness.values[0]
        if ind.fitness.values[0] > maxCosts:
            maxCosts = ind.fitness.values[0]

        if ind.fitness.values[1] < minCO2:
            minCO2 = ind.fitness.values[1]
        if ind.fitness.values[1] > maxCO2:
            maxCO2 = ind.fitness.values[1]

        if ind.fitness.values[2] < minPrim:
            minPrim = ind.fitness.values[2]
        if ind.fitness.values[2] > maxPrim:
            maxPrim = ind.fitness.values[2]

    for i in range(len(popFinal)):
        ind = popFinal[i]
        NormCost = (ind.fitness.values[0] - minCosts) / (maxCosts - minCosts)
        NormCO2 = (ind.fitness.values[1] - minCO2) / (maxCO2 - minCO2)
        NormPrim = (ind.fitness.values[2] - minPrim) / (maxPrim - minPrim)

        popNorm[i].fitness.values = (NormCost, NormCO2, NormPrim)

    return popFinal
def plot_buildings_connected_scenarios(scenarios, generations, headers):
    counter = 0
    data = [1, 2, 3, 4]
    colors = ['b', 'r', 'y', 'c']
    fig = plt.figure()
    for header in headers:
        pathX = sFn.pathX(header)
        BuildCon = []
        BuildCon2 = []
        for i in range(generations[counter]):
            i += 1
            pop, eps, testedPop, ntwList, fitness = sFn.readCheckPoint(
                pathX, i, 0)
            buildCon = []
            buildCon2 = []
            for ind in pop:
                buildCon.extend([np.average(ind[21:]) * 100])
                buildCon2.append([np.average(ind[21:]) * 100])

            BuildCon.extend(buildCon)
            BuildCon2.append(np.average(buildCon2))

        data[counter] = BuildCon

        # individual lines per generation
        xList = [1 + x for x in range(len(BuildCon2))]
        ax = fig.add_subplot(111)
        ax.plot(xList, BuildCon2, colors[counter], label=scenarios)
        ax.set_xlim(1, generations[counter])
        ax.set_ylabel('Percentage of buildings connected (%)')
        ax.set_xlabel('Generation No.')
        #ax.set_xticks(np.arange(1,generations[counter]+1,2))
        counter += 1
    plt.legend(scenarios, loc='upper left')
    plt.rcParams['figure.figsize'] = (6, 4)
    plt.rcParams['font.size'] = 12
    plt.show()

    # box plot with all data)
    fig = plt.figure(figsize=(6, 4))
    plt.rcParams['font.size'] = 12
    plt.boxplot(data, 1, 'rs', 0)
    plt.yticks([1, 2, 3, 4], scenarios)
    plt.xlabel("Percentage of buildings connected (%)")
    plt.show()
    return data
def plot_buildings_connected_scenarios(scenarios, generations, headers):
    counter =0    
    data = [1,2,3,4]  
    colors = ['b','r','y','c']
    fig = plt.figure()
    for header in headers:
        pathX = sFn.pathX(header)
        BuildCon = []
        BuildCon2 = []
        for i in range(generations[counter]):
            i += 1
            pop, eps, testedPop = sFn.readCheckPoint(pathX, i, 0)
            buildCon = []
            buildCon2 = []
            for ind in pop:
                buildCon.extend([np.average(ind[21:])*100])
                buildCon2.append([np.average(ind[21:])*100])
                
            BuildCon.extend(buildCon)
            BuildCon2.append(np.average(buildCon2))
            
        data[counter] = BuildCon
    
        # individual lines per generation
        xList = [ 1 + x for x in range(len(BuildCon2)) ]
        ax = fig.add_subplot(111)
        ax.plot(xList, BuildCon2, colors[counter], label=scenarios)
        ax.set_xlim(1,generations[counter])
        ax.set_ylabel('Percentage of buildings connected (%)')
        ax.set_xlabel('Generation No.')
        #ax.set_xticks(np.arange(1,generations[counter]+1,2))
        counter +=1
    plt.legend(scenarios, loc='upper left')        
    plt.rcParams['figure.figsize'] = (6,4)
    plt.rcParams['font.size'] = 12
    plt.show()
    
    # box plot with all data)
    fig = plt.figure(figsize = (6,4))
    plt.rcParams['font.size'] = 12
    plt.boxplot(data,1,'rs',0)  
    plt.yticks([1, 2, 3, 4], scenarios)
    plt.xlabel("Percentage of buildings connected (%)")
    plt.show()
    return data 
def buildingConnection(generation, locator):
    BuildCon = []
    nInd = []

    for i in range(generation):
        i += 1
        pop, eps, testedPop, ntwList, fitness = sFn.readCheckPoint(
            locator, i, 0)
        buildCon = []

        for ind in pop:
            buildCon.append(np.average(ind[21:]))

        BuildCon.append(np.average(buildCon))
        nInd.append(len(pop))

    # Plotting the number of connected buildings vs the generations
    fig = plt.figure()
    ax = fig.add_subplot(111, xlim=(1, generation), ylim=(0.1))
    xList = [1 + x for x in range(len(BuildCon))]
    ax.plot(xList, BuildCon)
    ax.set_xlim(1, generation)
    ax.set_ylabel('Averaged building connection')
    ax.set_xlabel('Generation')
    ax.set_xticks(np.arange(1, generation + 1, 2))
    plt.show()

    # Plotting the number of individuals vs the generations
    fig = plt.figure()
    ax = fig.add_subplot(111, xlim=(1, generation))
    xList = [1 + x for x in range(len(nInd))]
    ax.plot(xList, nInd)
    ax.set_xlim(1, generation)
    ax.set_ylabel('Number of individuals in the Pareto front')
    ax.set_xlabel('Generation')
    ax.set_xticks(np.arange(1, generation + 1, 2))
    plt.show()

    return BuildCon, nInd
def buildingConnection(generation, pathX):
    BuildCon = []
    nInd = []

    for i in range(generation):
        i += 1
        pop, eps, testedPop = sFn.readCheckPoint(pathX, i, 0)
        buildCon = []

        for ind in pop:
            buildCon.append(np.average(ind[21:]))

        BuildCon.append(np.average(buildCon))
        nInd.append(len(pop))

    # Plotting the number of connected buildings vs the generations
    fig = plt.figure()
    ax = fig.add_subplot(111, xlim = (1,generation), ylim = (0.1))
    xList = [ 1 + x for x in range(len(BuildCon)) ]
    ax.plot(xList, BuildCon)
    ax.set_xlim(1,generation)
    ax.set_ylabel('Averaged building connection')
    ax.set_xlabel('Generation')
    ax.set_xticks(np.arange(1,generation+1,2))
    plt.show()

    # Plotting the number of individuals vs the generations
    fig = plt.figure()
    ax = fig.add_subplot(111, xlim = (1,generation))
    xList = [ 1 + x for x in range(len(nInd)) ]
    ax.plot(xList, nInd)
    ax.set_xlim(1,generation)
    ax.set_ylabel('Number of individuals in the Pareto front')
    ax.set_xlabel('Generation')
    ax.set_xticks(np.arange(1,generation+1,2))
    plt.show()

    return BuildCon, nInd
Exemple #10
0
def normalize_epsIndicator(locator, generation):
    """
    Calculates the normalized epsilon indicator
    For all generations, the population are normalized with regards to the
    min / max over ALL generations

    :param locator: inputlocator set to scenario
    :param generation: generation up to which data are extracted
    :type locator: string
    :type generation: int
    :return: epsAll, normalized epsilon indicator from the beginning of the master to generation
    :rtype: list
    """
    epsAll = []
    allPop = []
    allPopNorm = []

    # Load the population
    i = 1
    while i < generation + 1:
        pop, eps, testedPop, ntwList, fitness = sFn.readCheckPoint(locator,
                                                                   i,
                                                                   storeData=0)
        i += 1
        allPop.append(pop)

    # Find the max and min
    maxCosts = 0
    minCosts = 0

    maxCO2 = 0
    minCO2 = 0

    maxPrim = 0
    minPrim = 0

    for i in range(generation):
        popScaned = allPop[i]

        for ind in popScaned:
            if ind.fitness.values[0] < minCosts:
                minCosts = ind.fitness.values[0]
            if ind.fitness.values[0] > maxCosts:
                maxCosts = ind.fitness.values[0]

            if ind.fitness.values[1] < minCO2:
                minCO2 = ind.fitness.values[1]
            if ind.fitness.values[1] > maxCO2:
                maxCO2 = ind.fitness.values[1]

            if ind.fitness.values[2] < minPrim:
                minPrim = ind.fitness.values[2]
            if ind.fitness.values[2] > maxPrim:
                maxPrim = ind.fitness.values[2]

    # Normalize
    for k in range(generation):
        popScaned = allPop[k]
        popNorm = toolbox.clone(popScaned)

        for i in range(len(popScaned)):
            ind = popScaned[i]
            NormCost = (ind.fitness.values[0] - minCosts) / (maxCosts -
                                                             minCosts)
            NormCO2 = (ind.fitness.values[1] - minCO2) / (maxCO2 - minCO2)
            NormPrim = (ind.fitness.values[2] - minPrim) / (maxPrim - minPrim)

            popNorm[i].fitness.values = (NormCost, NormCO2, NormPrim)

        allPopNorm.append(popNorm)

    # Compute the eps indicator
    for i in range(generation - 1):
        frontOld = allPopNorm[i]
        frontNew = allPopNorm[i + 1]
        epsAll.append(eI.epsIndicator(frontOld, frontNew))

    return epsAll
def normalize_epsIndicator(pathX, generation):
    """
    Calculates the normalized epsilon indicator
    For all generations, the populations are normalized with regards to the
    min / max over ALL generations
    
    Parameters
    ----------
    pathMasterRes : string
        path to folder where checkpoints are stored
    generation : int
        generation up to which data are extracted
    pathNtwRes : string
        path to ntw result folder
    
    Returns
    -------
    epsAll : list
        normalized epsilon indicator from the beginning of the EA to generation
    
    """
    epsAll = []
    allPop = []
    allPopNorm = []
    
    # Load the populations
    i = 1
    while i < generation+1:
        pop, eps, testedPop = sFn.readCheckPoint(pathX, i, storeData = 0)
        i+=1
        allPop.append(pop)
        
    # Find the max and min
    maxCosts =0
    minCosts =0
    
    maxCO2 =0
    minCO2 =0
    
    maxPrim =0
    minPrim =0
    
    for i in range(generation):
        popScaned = allPop[i]
        
        for ind in popScaned:
            if ind.fitness.values[0] < minCosts:
                minCosts = ind.fitness.values[0]
            if ind.fitness.values[0]  > maxCosts:
                maxCosts = ind.fitness.values[0]
                
            if ind.fitness.values[1] < minCO2:
                minCO2 = ind.fitness.values[1]
            if ind.fitness.values[1] > maxCO2:
                maxCO2 = ind.fitness.values[1]
                
            if ind.fitness.values[2] < minPrim:
                minPrim = ind.fitness.values[2]
            if ind.fitness.values[2] > maxPrim:
                maxPrim = ind.fitness.values[2]
    
    # Normalize
    for k in range(generation):
        popScaned = allPop[k]
        popNorm = toolbox.clone(popScaned)
    
        for i in range( len( popScaned ) ):
            ind = popScaned[i]
            NormCost = (ind.fitness.values[0] - minCosts) / (maxCosts - minCosts)
            NormCO2 = (ind.fitness.values[1] - minCO2) / (maxCO2 - minCO2)
            NormPrim = (ind.fitness.values[2] - minPrim) / (maxPrim - minPrim)
            
            popNorm[i].fitness.values = (NormCost, NormCO2, NormPrim)
        
        allPopNorm.append(popNorm)
    
    # Compute the eps indicator
    for i in range(generation-1):
        frontOld = allPopNorm[i]
        frontNew = allPopNorm[i+1]
        epsAll.append(eI.epsIndicator(frontOld, frontNew))
    
    return epsAll
def normalize_epsIndicator(pathX, generation):
    """
    Calculates the normalized epsilon indicator
    For all generations, the populations are normalized with regards to the
    min / max over ALL generations
    
    Parameters
    ----------
    pathMasterRes : string
        path to folder where checkpoints are stored
    generation : int
        generation up to which data are extracted
    pathNtwRes : string
        path to ntw result folder
    
    Returns
    -------
    epsAll : list
        normalized epsilon indicator from the beginning of the EA to generation
    
    """
    epsAll = []
    allPop = []
    allPopNorm = []

    # Load the populations
    i = 1
    while i < generation + 1:
        pop, eps, testedPop = sFn.readCheckPoint(pathX, i, storeData=0)
        i += 1
        allPop.append(pop)

    # Find the max and min
    maxCosts = 0
    minCosts = 0

    maxCO2 = 0
    minCO2 = 0

    maxPrim = 0
    minPrim = 0

    for i in range(generation):
        popScaned = allPop[i]

        for ind in popScaned:
            if ind.fitness.values[0] < minCosts:
                minCosts = ind.fitness.values[0]
            if ind.fitness.values[0] > maxCosts:
                maxCosts = ind.fitness.values[0]

            if ind.fitness.values[1] < minCO2:
                minCO2 = ind.fitness.values[1]
            if ind.fitness.values[1] > maxCO2:
                maxCO2 = ind.fitness.values[1]

            if ind.fitness.values[2] < minPrim:
                minPrim = ind.fitness.values[2]
            if ind.fitness.values[2] > maxPrim:
                maxPrim = ind.fitness.values[2]

    # Normalize
    for k in range(generation):
        popScaned = allPop[k]
        popNorm = toolbox.clone(popScaned)

        for i in range(len(popScaned)):
            ind = popScaned[i]
            NormCost = (ind.fitness.values[0] - minCosts) / (maxCosts -
                                                             minCosts)
            NormCO2 = (ind.fitness.values[1] - minCO2) / (maxCO2 - minCO2)
            NormPrim = (ind.fitness.values[2] - minPrim) / (maxPrim - minPrim)

            popNorm[i].fitness.values = (NormCost, NormCO2, NormPrim)

        allPopNorm.append(popNorm)

    # Compute the eps indicator
    for i in range(generation - 1):
        frontOld = allPopNorm[i]
        frontNew = allPopNorm[i + 1]
        epsAll.append(eI.epsIndicator(frontOld, frontNew))

    return epsAll
Exemple #13
0
def sensAnalysis(locator, extraCosts, extraCO2, extraPrim, solarFeat, ntwFeat, gen):
    """
    :param locator: path to input locator
    :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 solarFeat: solar features call to class
    :param ntwFeat: network features call to class
    :param gen: generation on which the sensitivity analysis is performed
    :type locator: string
    :type extraCosts: float
    :type extraCO2: float
    :type extraPrim: float
    :type solarFeat: class
    :type ntwFeat: class
    :type gen: int
    :return: returns the most sensitive parameter among the group provided
    :rtype: string
    """

    gV = glob.GlobalVariables()
    step = gV.sensibilityStep
    bandwidth = sensBandwidth()
    os.chdir(locator.get_optimization_master_results_folder())
    pop, eps, testedPop, ntwList, fitness = sFn.readCheckPoint(locator, gen, 0)
    toolbox = base.Toolbox()

    total_demand = pd.read_csv(locator.get_total_demand())
    buildList = total_demand.Name.values
    FactorResults = np.zeros((step + 1, bandwidth.nFactors * 2))

    def sensOneFactor(obj, factor_name, mini, maxi, colNumber):
        iniValue = getattr(obj, factor_name)
        index = 0
                
        for delta in np.arange(mini, maxi + 1E-5, (maxi-mini)/step):
            FactorResults[index][colNumber + 0] = delta
            if abs(delta) > 1E-10:
                setattr(obj, factor_name, iniValue * (1+delta))
    
                newpop = []
                for ind in pop:
                    newInd = toolbox.clone(ind)
                    newpop.append(newInd)
                    (costs, CO2, prim) = eI.evaluation_main(newInd, buildList, locator, solarFeat, ntwFeat, obj,,
                    newInd.fitness.values = (costs, CO2, prim)

            index += 1

        setattr(obj, factor_name, iniValue)

    sensOneFactor(gV, 'ELEC_PRICE', bandwidth.minElec, bandwidth.maxElec, 0)
    sensOneFactor(gV, 'NG_PRICE', bandwidth.minNG, bandwidth.maxNG, 2)
    sensOneFactor(gV, 'BG_PRICE', bandwidth.minBG, bandwidth.maxBG, 4)
    
    indexSensible = FactorResults.argmax()%(2*bandwidth.nFactors)
    if indexSensible == 1:
        mostSensitive = 'Electricity price'
    elif indexSensible == 3:
        mostSensitive = 'NG price'
    else:
        mostSensitive = 'BG price'

    print FactorResults
    print mostSensitive
    return mostSensitive

gen = 4

def run_as_script(scenario_path=None):

    import cea.globalvar
    import pandas as pd
    import cea.optimization.distribution.network_opt_main as network_opt
    from cea.optimization.preprocessing.preprocessing_main import preproccessing
    gv = cea.globalvar.GlobalVariables()

    if scenario_path is None:
        scenario_path = gv.scenario_reference

    locator = cea.inputlocator.InputLocator(scenario_path=scenario_path)
    total_demand = pd.read_csv(locator.get_total_demand())
    building_names = total_demand.Name.values
    gv.num_tot_buildings = total_demand.Name.count()
    weather_file = locator.get_default_weather()
    extraCosts, extraCO2, extraPrim, solarFeat = preproccessing(locator, total_demand, building_names,
                                                                   weather_file, gv)
    ntwFeat = network_opt.network_opt_main()
    sensAnalysis(locator, extraCosts, extraCO2, extraPrim, solarFeat, ntwFeat, gen)
    print 'sensitivity analysis succeeded'

if __name__ == '__main__':
    run_as_script(r'C:\reference-case-zug\baseline')
def plot_pareto_scenarios(locator, generations, relative):
    '''
    This function plots a pareto curve for a certan checkpoint number. The checkpoint number is equivalent
    to the Generation number to be mapped

    :param locator:
    :param generations:
    :param headers:
    :param relative:
    :param savelocation:
    :return:
    '''

    # create local variables
    xs = []
    ys = []
    zs = []
    fig = plt.figure()
    savelocation = locator.get_optimization_plots_folder()

    # read the checkpoint
    counter = 0
    #for scenario in scenarios:
    pop, eps, testedPop, ntwList, fitness = sFn.readCheckPoint(
        locator, generations, 0)

    # get floor area of buildings and estimate relative parameters
    Area_buildings = pd.read_csv(locator.get_total_demand(),
                                 usecols=['Af_m2']).values.sum()
    [x, y, z] = map(np.array, zip(*[ind.fitness.values for ind in pop]))
    ax = fig.add_subplot(111)
    if relative == True:
        z[:] = [a / Area_buildings for a in z]
        x[:] = [b / Area_buildings for b in x]
        y[:] = [c / Area_buildings for c in y]
    xs.extend(x)
    ys.extend(y)
    zs.extend(z)
    counter += 1

    if relative == True:
        TAC = 'TAC [EU/m2.yr]'
        CO2 = 'CO2 [kg-CO2/m2.yr]'
        PEN = 'PEN [MJ/m2.yr]'
        ax.set_ylim([10, 50])
        finallocation = os.path.join(savelocation, "pareto_m2.png")
    else:
        var = 1000000
        zs[:] = [x / var for x in zs]
        xs[:] = [x / var for x in xs]
        ys[:] = [x / var for x in ys]
        TAC = 'TAC [Mio EU/yr]'
        CO2 = 'CO2 [kton-CO2/yr]'
        PEN = 'PEN [TJ/yr]'
        ax.set_xlim([2.5, 7.0])
        finallocation = os.path.join(savelocation, "pareto.png")

    cm = plt.get_cmap('jet')
    cNorm = matplotlib.colors.Normalize(vmin=min(zs), vmax=max(zs))
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
    ax.scatter(xs, ys, c=scalarMap.to_rgba(zs), s=50, alpha=0.8)
    ax.set_xlabel(TAC)
    ax.set_ylabel(CO2)

    scalarMap.set_array(zs)
    fig.colorbar(scalarMap, label=PEN)
    plt.grid(True)
    plt.rcParams['figure.figsize'] = (6, 4)
    plt.rcParams.update({'font.size': 12})
    plt.gcf().subplots_adjust(bottom=0.15)
    plt.savefig(finallocation)
    plt.clf()
Exemple #15
0
def sensAnalysis(locator, extraCosts, extraCO2, extraPrim, solarFeat, ntwFeat,
                 gen):
    """
    :param locator: path to input locator
    :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 solarFeat: solar features call to class
    :param ntwFeat: network features call to class
    :param gen: generation on which the sensitivity analysis is performed
    :type locator: string
    :type extraCosts: float
    :type extraCO2: float
    :type extraPrim: float
    :type solarFeat: class
    :type ntwFeat: class
    :type gen: int
    :return: returns the most sensitive parameter among the group provided
    :rtype: string
    """

    gV = glob.GlobalVariables()
    step = gV.sensibilityStep
    bandwidth = sensBandwidth()
    os.chdir(locator.get_optimization_master_results_folder())
    pop, eps, testedPop, ntwList, fitness = sFn.readCheckPoint(locator, gen, 0)
    toolbox = base.Toolbox()

    total_demand = pd.read_csv(locator.get_total_demand())
    buildList = total_demand.Name.values
    FactorResults = np.zeros((step + 1, bandwidth.nFactors * 2))

    def sensOneFactor(obj, factor_name, mini, maxi, colNumber):
        iniValue = getattr(obj, factor_name)
        index = 0

        for delta in np.arange(mini, maxi + 1E-5, (maxi - mini) / step):
            FactorResults[index][colNumber + 0] = delta
            if abs(delta) > 1E-10:
                setattr(obj, factor_name, iniValue * (1 + delta))

                newpop = []
                for ind in pop:
                    newInd = toolbox.clone(ind)
                    newpop.append(newInd)
                    (costs, CO2, prim) = eI.evaluation_main(
                        newInd, buildList, locator, extraCosts, extraCO2,
                        extraPrim, solarFeat, ntwFeat, obj)
                    newInd.fitness.values = (costs, CO2, prim)

            index += 1

        setattr(obj, factor_name, iniValue)

    sensOneFactor(gV, 'ELEC_PRICE', bandwidth.minElec, bandwidth.maxElec, 0)
    sensOneFactor(gV, 'NG_PRICE', bandwidth.minNG, bandwidth.maxNG, 2)
    sensOneFactor(gV, 'BG_PRICE', bandwidth.minBG, bandwidth.maxBG, 4)

    indexSensible = FactorResults.argmax() % (2 * bandwidth.nFactors)
    if indexSensible == 1:
        mostSensitive = 'Electricity price'
    elif indexSensible == 3:
        mostSensitive = 'NG price'
    else:
        mostSensitive = 'BG price'

    print FactorResults
    print mostSensitive
    return mostSensitive
def sensAnalysis(pathX, extraCosts, extraCO2, extraPrim, solarFeat, ntwFeat,
                 gen):

    gV = glob.globalVariables()
    step = gV.sensibilityStep

    bandwidth = sensBandwidth()

    os.chdir(pathX.pathMasterRes)
    pop, eps, testedPop = sFn.readCheckPoint(pathX, gen, 0)
    toolbox = base.Toolbox()

    os.chdir(pathX.pathRaw)
    buildList = sFn.extractList("Total.csv")

    ParetoResults = np.zeros(len(pop))
    FactorResults = np.zeros((step + 1, bandwidth.nFactors * 2))

    def sensOneFactor(obj, factor_name, mini, maxi, colNumber):
        iniValue = getattr(obj, factor_name)
        index = 0

        for delta in np.arange(mini, maxi + 1E-5, (maxi - mini) / step):
            FactorResults[index][colNumber + 0] = delta
            if abs(delta) > 1E-10:
                setattr(obj, factor_name, iniValue * (1 + delta))

                newpop = []
                for ind in pop:
                    newInd = toolbox.clone(ind)
                    newpop.append(newInd)
                    (costs, CO2, prim) = eI.evalInd(newInd, buildList, pathX,
                                                    extraCosts, extraCO2,
                                                    extraPrim, solarFeat,
                                                    ntwFeat, obj)
                    newInd.fitness.values = (costs, CO2, prim)

                selection = sel.selectPareto(newpop)
                for i in range(len(newpop)):
                    if newpop[i] in selection:
                        ParetoResults[i] += 1

                FactorResults[index][colNumber +
                                     1] = len(newpop) - len(selection)

            index += 1

        setattr(obj, factor_name, iniValue)

    sensOneFactor(gV, 'ELEC_PRICE', bandwidth.minElec, bandwidth.maxElec, 0)
    sensOneFactor(gV, 'NG_PRICE', bandwidth.minNG, bandwidth.maxNG, 2)
    sensOneFactor(gV, 'BG_PRICE', bandwidth.minBG, bandwidth.maxBG, 4)

    indexSensible = FactorResults.argmax() % (2 * bandwidth.nFactors)
    if indexSensible == 1:
        mostSensitive = 'Electricity price'
    elif indexSensible == 3:
        mostSensitive = 'NG price'
    else:
        mostSensitive = 'BG price'

    return ParetoResults, FactorResults, mostSensitive