Passed
Pull Request — dev (#855)
by
unknown
01:35
created

data.datasets.plotdatascn   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 191
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 82
dl 0
loc 191
rs 10
c 0
b 0
f 0

3 Functions

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