tutorial6utilities.py 10.1 KB
Newer Older
vs2788's avatar
vs2788 committed
1 2 3 4 5 6 7 8 9 10
import yaml
import pypsa
import numpy as np
import xarray as xr
import pandas as pd

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
from sklearn.cluster import KMeans, SpectralClustering
sp2668's avatar
sp2668 committed
11
from mpl_toolkits.basemap import Basemap
vs2788's avatar
vs2788 committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77


### FUNCTIONS

def plot_clusters(network, y_pred,X,lim_fig="None"):
    colors_choice=['b', 'g', 'r', 'c', 'y', 'violet','purple','k','chartreuse','indianred','pink','orange','gray','yellow','springgreen','indigo','brown','silver','aqua']*(int(max(y_pred)/19)+1)
    colors_list = [ colors_choice[x] for x in y_pred]

    fig, ax = plt.subplots()
    fig.set_size_inches(15,15)

    if lim_fig!= "None":
        ax.set_xlim(lim_fig[0])
        ax.set_ylim(lim_fig[1])

    network.plot(bus_sizes=0.01,
                        line_colors=pd.concat(dict(Line=pd.Series('red', index=network.lines.index),
                                                   Link=pd.Series('violet', index=network.links.index))),
                                line_widths=pd.concat(dict(Line=network.lines['s_nom']/1000,Link=network.links['p_nom']/1000)))

    plt.scatter(X[:, 0], X[:, 1], c=colors_list,s=100)
    plt.show()

def plot_network(network,option="AC_DC",basemap="no"):
    fig, ax = plt.subplots()
    fig.set_size_inches(15,15)


    if basemap=="yes":
        long_min=-10
        long_max=30
        lat_min=35
        lat_max=72
        map = Basemap(llcrnrlon=long_min,
                llcrnrlat=lat_min,
                urcrnrlon=long_max,
                urcrnrlat=lat_max,resolution='l')
        map.drawcoastlines(linewidth=0.25)
        map.drawcountries(linewidth=0.25)
    else:
        ax.set_ylim([35,72])

    if option=="AC_DC":
        network.plot(bus_sizes=5,
             line_colors=pd.concat(dict(Line=pd.Series('red', index=network.lines.index),
                                        Link=pd.Series('violet', index=network.links.index))),
                         line_widths=pd.concat(dict(Line=network.lines['s_nom']/1500,Link=network.links['p_nom']/1500)))

        red_line = mlines.Line2D([], [], color='red',label='AC')
        violet_line=mlines.Line2D([], [], color='violet',label='DC')

        plt.legend(handles=[red_line,violet_line])
    else:
        voltage_colors = {132.0: 'blue', 220.0: 'green', 300.0: 'orange', 380.0: 'red'}
        network.plot(bus_sizes=5,
                    line_colors=pd.concat(dict(Line=network.lines['v_nom'].map(voltage_colors),
                                               Link=pd.Series('violet', index=network.links.index))),
                            line_widths=pd.concat(dict(Line=network.lines['s_nom']/1000,Link=network.links['p_nom']/1000)))

        blue_line = mlines.Line2D([], [], color='blue',label='132 kV')
        green_line = mlines.Line2D([], [], color='green',label='220 kV')
        orange_line = mlines.Line2D([], [], color='orange',label='300 kV')
        red_line = mlines.Line2D([], [], color='red',label='380 kV')
        violet_line=mlines.Line2D([], [], color='violet',label='DC')

        plt.legend(handles=[blue_line,green_line,orange_line,red_line,violet_line])
sp2668's avatar
sp2668 committed
78

vs2788's avatar
vs2788 committed
79 80 81 82 83 84 85 86 87 88 89 90 91
def find_kmeans_busmap(n_clusters, n, n_weightings, **kwargs):
    kmeans = KMeans(init='k-means++', n_clusters=n_clusters, ** kwargs)

    kmeans.fit(n[["x","y"]].values)

    return pd.Series(data=kmeans.predict(n[["x","y"]]),
                      index=n.index).astype(str)

def weighting(network):

    load = (network.loads_t.p_set.mean()
                   .groupby(network.loads.bus).sum()
                   .reindex(network.buses.index, fill_value=0.))
sp2668's avatar
sp2668 committed
92

vs2788's avatar
vs2788 committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    return load


def P_nom_re(network,w_s=2.5,w_onw=0.2,w_ofw=0.1):

    network.generators.loc[network.generators['carrier'] == 'solar',"p_nom_max"]=network.generators.loc[network.generators['carrier'] == 'solar',"weight"]*w_s
    network.generators.loc[network.generators['carrier'] == 'onwind',"p_nom_max"]=network.generators.loc[network.generators['carrier'] == 'onwind',"weight"]*w_onw
    network.generators.loc[network.generators['carrier'] == 'offwind',"p_nom_max"]=network.generators.loc[network.generators['carrier'] == 'offwind',"weight"]*w_ofw

    network.generators.loc[network.generators['carrier'] == 'solar',"p_nom"]=network.generators.loc[network.generators['carrier'] == 'solar',"weight"]*w_s
    network.generators.loc[network.generators['carrier'] == 'onwind',"p_nom"]=network.generators.loc[network.generators['carrier'] == 'onwind',"weight"]*w_onw
    network.generators.loc[network.generators['carrier'] == 'offwind',"p_nom"]=network.generators.loc[network.generators['carrier'] == 'offwind',"weight"]*w_ofw

def lopf_d_h(network,day,hour):
    network.set_snapshots(pd.DatetimeIndex(start=hour.format(day), end=hour.format(day), freq='H'))

    # solve linear optimal power flow
    network.lopf(network.snapshots[0],
                     solver_name='glpk')

def plot_line_loading(network):
    fig, ax = plt.subplots()
    ax.set_ylim([35,72])
    fig.set_size_inches(15,15)
    loading = network.lines_t.p0.loc[network.snapshots[0]]/network.lines.s_nom/0.7
    loading=loading.fillna(0)
    loading=loading.append(pd.Series(1))
    loading_dc = network.links_t.p0.loc[network.snapshots[0]]/network.links.p_nom/0.7
    loading_dc=loading_dc.fillna(0)
    loading_dc=loading_dc.append(pd.Series(1))
    #print(loading_dc)
    #print(pd.concat(dict(Line=abs(loading),Link=abs(loading_dc))))
    #network.plot(line_colors=abs(loading),line_cmap=plt.cm.jet,title="Line loading",
    #             line_widths=pd.concat(dict(Line=network.lines['s_nom']/1500,Link=network.links['p_nom']/1500)))
    network.plot(line_colors=pd.concat(dict(Line=abs(loading),Link=abs(loading_dc))),
                 line_cmap= dict(Line=plt.cm.jet,Link=plt.cm.jet),
                 line_widths=pd.concat(dict(Line=network.lines['s_nom']/1500,Link=network.links['p_nom']/1500)))
    Z = [[0,0],[max(abs(loading)),0]]
    CS3 = plt.contourf(Z,  cmap=plt.cm.jet)
    plt.colorbar(fraction=0.01, pad=0.01)
sp2668's avatar
sp2668 committed
133

vs2788's avatar
vs2788 committed
134 135 136 137 138
def plot_bus_status(network):
    fig, ax = plt.subplots()
    ax.set_ylim([35,72])
    fig.set_size_inches(15,15)

sp2668's avatar
sp2668 committed
139
    bus_status= pd.DataFrame({'status': network.loads_t.p_set.values[0]*-1,
vs2788's avatar
vs2788 committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
                          'pmax':network.loads_t.p_set.values[0]*0,
                          'p':network.loads_t.p_set.values[0]*0,
                          'ponpmax':network.loads_t.p_set.values[0]*0})
    for i in bus_status.index:
        #print(bus_status.loc[i].values[0],p_nc.generators.loc[p_nc.generators["bus"]==i].index)
        #print(i)
        try:
            for j in network.generators.loc[network.generators["bus"]==str(i)].index:
                #bus_status.loc[i].values[0]+=p_nc.generators.loc[j].p_nom*p_nc.generators_t.p_max_pu[j].values[0]
                bus_status.status.loc[i]+=network.generators_t.p[j].values[0]
                bus_status.p.loc[i]+=network.generators_t.p[j].values[0]
                bus_status.pmax.loc[i]+=network.generators.p_nom[j]

            bus_status.ponpmax.loc[i]=bus_status.p.loc[i]/bus_status.pmax.loc[i]
        except:
            print(i)
sp2668's avatar
sp2668 committed
156

vs2788's avatar
vs2788 committed
157
    bus_color=(bus_status.status/p_nc_25.loads_t.p_set.values[0]).values
sp2668's avatar
sp2668 committed
158

vs2788's avatar
vs2788 committed
159 160 161 162 163 164 165 166 167 168 169
    #print(loading_dc)
    #print(pd.concat(dict(Line=abs(loading),Link=abs(loading_dc))))
    #network.plot(line_colors=abs(loading),line_cmap=plt.cm.jet,title="Line loading",
    #             line_widths=pd.concat(dict(Line=network.lines['s_nom']/1500,Link=network.links['p_nom']/1500)))
    network.plot(bus_colors=bus_color,
                 bus_sizes=400,
                 bus_cmap= plt.cm.jet,
                 line_widths=pd.concat(dict(Line=network.lines['s_nom']/1500,Link=network.links['p_nom']/1500)))
    Z = [[min(bus_color),0],[max(bus_color),0]]
    CS3 = plt.contourf(Z,  cmap=plt.cm.jet)
    plt.colorbar(fraction=0.01, pad=0.01)
sp2668's avatar
sp2668 committed
170

vs2788's avatar
vs2788 committed
171 172 173 174 175 176 177 178 179 180
def plot_line_loading_bus_status(network):
    fig, ax = plt.subplots()
    ax.set_ylim([35,72])
    fig.set_size_inches(15,15)
    loading = network.lines_t.p0.loc[network.snapshots[0]]/network.lines.s_nom/0.7
    loading=loading.fillna(0)
    loading=loading.append(pd.Series(1))
    loading_dc = network.links_t.p0.loc[network.snapshots[0]]/network.links.p_nom/0.7
    loading_dc=loading_dc.fillna(0)
    loading_dc=loading_dc.append(pd.Series(1))
sp2668's avatar
sp2668 committed
181 182

    bus_status= pd.DataFrame({'status': network.loads_t.p_set.values[0]*-1,
vs2788's avatar
vs2788 committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
                          'pmax':network.loads_t.p_set.values[0]*0,
                          'p':network.loads_t.p_set.values[0]*0,
                          'ponpmax':network.loads_t.p_set.values[0]*0})
    for i in bus_status.index:
        #print(bus_status.loc[i].values[0],p_nc.generators.loc[p_nc.generators["bus"]==i].index)
        #print(i)
        try:
            for j in network.generators.loc[network.generators["bus"]==str(i)].index:
                #bus_status.loc[i].values[0]+=p_nc.generators.loc[j].p_nom*p_nc.generators_t.p_max_pu[j].values[0]
                bus_status.status.loc[i]+=network.generators_t.p[j].values[0]
                bus_status.p.loc[i]+=network.generators_t.p[j].values[0]
                bus_status.pmax.loc[i]+=network.generators.p_nom[j]

            bus_status.ponpmax.loc[i]=bus_status.p.loc[i]/bus_status.pmax.loc[i]
        except:
sp2668's avatar
sp2668 committed
198 199
            print("Error at {}".format(i))

vs2788's avatar
vs2788 committed
200 201
    bus_color=(bus_status.status/network.loads_t.p_set.values[0]).values
    bus_color[bus_color>1.5]=1.5
sp2668's avatar
sp2668 committed
202 203


vs2788's avatar
vs2788 committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    #print(loading_dc)
    #print(pd.concat(dict(Line=abs(loading),Link=abs(loading_dc))))
    #network.plot(line_colors=abs(loading),line_cmap=plt.cm.jet,title="Line loading",
    #             line_widths=pd.concat(dict(Line=network.lines['s_nom']/1500,Link=network.links['p_nom']/1500)))
    network.plot(bus_colors=bus_color,
                 #bus_sizes=400,
                 bus_sizes=network.loads_t.p_set.values[0]/500**(0.5),
                 bus_cmap= plt.cm.jet,
                 line_colors=pd.concat(dict(Line=abs(loading),Link=abs(loading_dc))),
                 line_cmap= dict(Line=plt.cm.jet,Link=plt.cm.jet),
                 line_widths=pd.concat(dict(Line=network.lines['s_nom']/500,Link=network.links['p_nom']/500)))
    Z = [[0,0],[max(abs(loading)),0]]
    CS3 = plt.contourf(Z,  cmap=plt.cm.jet)
    plt.colorbar(fraction=0.01, pad=0.06)
    Z2 = [[min(bus_color),0],[max(bus_color),0]]
    CS4 = plt.contourf(Z2,  cmap=plt.cm.jet)
sp2668's avatar
sp2668 committed
220
    plt.colorbar(fraction=0.01, pad=0.01)