Passed
Push — dev ( c30aa8...3dcd28 )
by
unknown
02:06 queued 12s
created

data.datasets.plotdatascn.set_epsg_network()   A

Complexity

Conditions 1

Size

Total Lines 19
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 19
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
# File description
4
"""
5
Created on Tue May 24 14:42:05 2022
6
Plotdatascn.py defines functions to plot to provide a better context of the different parameters part of
7
scenarios eGon2035 and eGon100RE .
8
@author: Alonso
9
10
""" 
11
import logging
12
import os
13
from matplotlib import pyplot as plt
14
import matplotlib as mpl
15
import pandas as pd
16
from math import sqrt, log10
17
from pyproj import Proj, transform
18
from egon.data import db
19
import egon.data.config
20
import geopandas as gpd
21
import tilemapbase
22
from math import sqrt, log10
23
from pyproj import Proj, transform
24
from matplotlib_scalebar.scalebar import ScaleBar
25
26
"""
27
Tilemapbase library could be necessary
28
to generate the figures.
29
Matplotlib_scalebar.scalebar library could be necessary
30
to generate the figures.        
31
        
32
"""
33
34
logger = logging.getLogger(__name__)
35
36
if 'READTHEDOCS' not in os.environ:
37
    from geoalchemy2.shape import to_shape
38
39
__copyright__ = ("Flensburg University of Applied Sciences, "
40
                 "Europa-Universität Flensburg, "
41
                 "Centre for Sustainable Energy Systems, "
42
                 "DLR-Institute for Networked Energy Systems")
43
__license__ = ""
44
__author__ = ""
45
46
  
47
def set_epsg_network(network):
48
    """
49
    Change EPSG from 4326 to 3857. Needed when using osm-background.
50
51
    Parameters
52
    ----------
53
    network : PyPSA network container
54
55
    Returns
56
    -------
57
    """
58
59
    inProj = Proj(init='epsg:4326')
60
    outProj = Proj(init='epsg:3857')
61
    x1, y1 = network.buses.x.values, network.buses.y.values
62
    x2, y2 = transform(inProj, outProj, x1, y1)
63
    network.buses.x, network.buses.y = x2, y2
64
    network.epsg = 3857
65
    set_epsg_network.counter = set_epsg_network.counter + 1
66
    
67
def plot_osm(x, y, zoom, alpha=0.4):
68
    """
69
    Plots openstreetmap as background of network-plots
70
71
    Parameters
72
    ----------
73
    x : array of two floats
74
        Define x-axis boundaries (lat) of osm plot
75
    y : array of two floats
76
        Define y-axis boundaries (long) of osm plot
77
    zoom : int
78
        Define zoom of osm, higher values for higher resolution
79
    alpha : float
80
        Sets osm-visibility, increase value if osm covers network-plot
81
    osm : bool or dict, e.g. {'x': [1,20], 'y': [47, 56], 'zoom' : 6}
82
        If not False, osm is set as background
83
        with the following settings as dict:
84
                'x': array of two floats, x axis boundaries (lat)
85
                'y': array of two floats, y axis boundaries (long)
86
                'zoom' : resolution of osm. The default is False.
87
88
    Returns
89
    -------
90
    """
91
92
    tilemapbase.init(create=True)
93
94
    extent = tilemapbase.Extent.from_lonlat(x[0], x[1], y[0], y[1])
95
    extent = extent.to_aspect(1.0)
96
    extent = extent.to_project_3857()
97
98
    fig, ax = plt.subplots(1,1)
99
    ax.set_zorder(1)
100
    ax.add_artist(ScaleBar(1))
101
    plt.axis('off')
102
    plotter = tilemapbase.Plotter(extent, tilemapbase.tiles.build_OSM(),
103
                                  zoom=zoom)
104
    plotter.plot(ax, alpha=alpha)
105
    #ax.plot(x, y, "ro-")
106
    return fig, ax
107
108
def plot_installedcapacity(
109
              carrier,scenario, osm = False
110
            ):
111
   """
112
    Plots color maps according to the capacity of different generators
113
    of the two existing scenarios (eGon2035 and eGon100RE)
114
    
115
116
    Parameters
117
    ----------
118
    carrier : generators
119
    The list of generators: biomass, central_biomass_CHP, central_biomass_CHP_heat,
120
    industrial_biomass_CHP, solar, solar_rooftop, wind_offshore, wind_onshore. 
121
      
122
    scenario: eGon2035, eGon100RE
123
        
124
        
125
   """
126
    
127
   #This function must be called while in the folder 
128
   #that contains the file egon-data.configuration.yaml.
129
   con = db.engine()
130
   #imports buses of Germany
131
   SQLBus = "SELECT bus_id, country FROM grid.egon_etrago_bus WHERE country='DE'" 
132
   busDE = pd.read_sql(SQLBus,con) 
133
   busDE = busDE.rename({'bus_id': 'bus'},axis=1) 
134
   #Imports grid districs
135
   sql = "SELECT bus_id, geom FROM grid.egon_mv_grid_district" 
136
   distr = gpd.GeoDataFrame.from_postgis(sql, con)
137
   distr = distr.rename({'bus_id': 'bus'},axis=1)
138
   distr = distr.set_index("bus")
139
   #merges grid districts with buses 
140
   distr = pd.merge(busDE, distr, on='bus') 
141
   #Imports generator
142
   sqlCarrier = "SELECT carrier, p_nom, bus FROM grid.egon_etrago_generator" 
143
   sqlCarrier = "SELECT * FROM grid.egon_etrago_generator"
144
   Carriers = pd.read_sql(sqlCarrier,con)
145
   Carriers = Carriers.loc[Carriers['scn_name'] == scenario]
146
   Carriers = Carriers.set_index("bus")
147
148
149
   CarrierGen = Carriers.loc[Carriers['carrier'] == carrier]
150
   #merges districts with generators 
151
   Merge = pd.merge(CarrierGen, distr, on ='bus', how="outer")  
152
153
    
154
   Merge.loc[Merge ['carrier'] != carrier, "p_nom" ] = 0
155
   Merge.loc[Merge ['country'] != "DE", "p_nom" ] = 0
156
157
   gdf = gpd.GeoDataFrame(Merge , geometry='geom')
158
   pnom=gdf['p_nom']  #
159
   #0.95 quantile is used to filter values that are too high and make noise in the plots.
160
   max_pnom=pnom.quantile(0.95) 
161
   gdf = gdf.to_crs(epsg=3857)
162
163
   
164
   # Plot osm map in background
165
   if osm != False:
166
       #if network.srid == 4326:
167
           #set_epsg_network(network)
168
       fig, ax = plot_osm(osm['x'], osm['y'], osm['zoom'])
169
170
   else:
171
       fig, ax = plt.subplots(1, 1)
172
   
173
   
174
   
175
   ax.set_axis_off();
176
   plt.title(f" {carrier} installed capacity in MW , {scenario}")
177
   cmap = mpl.cm.coolwarm
178
   
179
  
180
   norm = mpl.colors.Normalize(vmin=0, vmax=max_pnom)
181
   gdf.plot(column='p_nom', ax=ax, legend=False,  legend_kwds={'label': "p_nom(MW)",
182
183
                       'orientation': "vertical"}, cmap=cmap, norm=norm, edgecolor='black', linewidth=0.1,zorder=2)
184
   scatter = ax.collections[0]
185
   cbar=plt.colorbar(scatter, ax=ax, extend='max')
186
   cbar.set_label('p_nom(MW)', rotation=90)
187
   return 0
188
      
189
190
   
191
   
192
   
193