Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Features/plot scalar resources #50

Merged
merged 44 commits into from
Nov 24, 2021
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
5e6f7fc
Add script for plotting of scalar resources
jnnr Jul 14, 2021
a4deffd
Add todos
jnnr Jul 14, 2021
a57e4f1
Prepare data for plot
jnnr Jul 19, 2021
664a14f
New way to plot scalar resource
juliusmeier Jul 23, 2021
f3f9c77
Move legend in foreground
juliusmeier Jul 26, 2021
9df911d
Implement german legend names
juliusmeier Jul 27, 2021
3fbf7e4
Add snakerule plot_all_resources
juliusmeier Jul 27, 2021
86d69ea
Black
juliusmeier Jul 27, 2021
0277239
Flake8
juliusmeier Jul 27, 2021
d18e0ba
Add documentation
juliusmeier Aug 17, 2021
44a67bc
Merge branch 'dev' into features/plot-scalar-resources
juliusmeier Sep 21, 2021
cb2be63
Add boolean to turn on/off german translation and move code
juliusmeier Sep 23, 2021
aca2492
Black
juliusmeier Sep 23, 2021
a5608ac
Merge branch 'dev' into features/plot-scalar-resources
juliusmeier Sep 23, 2021
fd5fe66
Change documentation
juliusmeier Oct 11, 2021
79617b3
Show plotting script in docs
jnnr Oct 26, 2021
f1166a1
Name script more generically
jnnr Oct 26, 2021
822204f
Use oemof-B3 color dict
jnnr Oct 26, 2021
8305cba
Use function from oemoflex that has become internal
jnnr Oct 26, 2021
5ea48bd
Merge remote-tracking branch 'origin/dev' into features/plot-scalar-r…
jnnr Oct 26, 2021
3e4a103
Apply isort to sort imports
juliusmeier Oct 27, 2021
86d3a5f
Use load_b3_scalars
juliusmeier Oct 27, 2021
0d0ed3b
Fix typo in prepare_conv_pp.py
juliusmeier Oct 28, 2021
078865d
Make script specific to conv pp and add documentation
juliusmeier Oct 28, 2021
ddae071
Adapt Snakerule
juliusmeier Oct 28, 2021
3cbf535
Black
juliusmeier Oct 28, 2021
7d188e3
Avoid loading of scalar templates, use custom data process functions …
juliusmeier Oct 31, 2021
f99c5f1
Adapt Snakerule
juliusmeier Oct 31, 2021
ada50f0
Generalize function interface
jnnr Nov 4, 2021
b7fa29b
Drop argument color_keys as it changes only the colors, not the order
jnnr Nov 4, 2021
34f24d5
Simply pass unit to plot function
jnnr Nov 4, 2021
a829b97
Pass the axes through the plotting function
jnnr Nov 4, 2021
102c399
Clean up
jnnr Nov 4, 2021
41b8e9c
Drop obsolete color_keys from preparation
jnnr Nov 4, 2021
8ef702a
Rearrange processing steps
jnnr Nov 4, 2021
6ee5905
Map labels and color dict first, then pivot
jnnr Nov 4, 2021
b7b31bf
Import German labels from oemof_b3
jnnr Nov 4, 2021
ee5c276
Translate mapping outside function
jnnr Nov 4, 2021
7268565
Move dictionary definition to top of script
jnnr Nov 4, 2021
9ea10b3
Allow to select var_name to plot
jnnr Nov 4, 2021
a40585e
Merge branch 'dev' into features/plot-scalar-resources
jnnr Nov 22, 2021
726f2dd
Plot heat dispatch
jnnr Nov 22, 2021
a5a861e
Update labels and colors for heat
jnnr Nov 22, 2021
129d519
Allow to stack bars
jnnr Nov 24, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Snakefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ examples = [
'more_renewables_less_fossil'
]

resources = ['conv_pp_scalar']

# Target rules

rule run_all_examples:
Expand All @@ -18,6 +20,10 @@ rule report_all_examples:
input:
expand("results/{scenario}/report/", scenario=examples)

rule plot_all_resources:
input:
expand("results/_resources/plots/{resource}.png", resource=resources)

rule clean:
shell:
"""
Expand Down Expand Up @@ -82,6 +88,15 @@ rule plot_dispatch:
shell:
"python scripts/plot_dispatch.py {input} {output}"

rule plot_scalar_resources:
input:
data="results/_resources/{resource}.csv",
script="scripts/plot_scalar_resources.py"
output:
"results/_resources/plots/{resource}.png"
shell:
"python {input.script} {input.data} {output}"

rule report:
input:
template="report/report.md",
Expand Down
137 changes: 137 additions & 0 deletions scripts/plot_scalar_resources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
r"""
Inputs
-------
resources : str
path of input file with data in scalar resources template format as .csv
target : str
path of output file with prepared data as .csv

Outputs
---------
matplotlib.figure.Figure
plotted scalar resources

Description
-------------
The script takes data in the format of the scalar resources template, prepares the
data and plots the data.
"""
import sys
import os
import pandas as pd
import matplotlib.pyplot as plt
import oemoflex.tools.plots as plots
from oemoflex.tools.plots import colors_odict

if __name__ == "__main__":
resources = sys.argv[1]

target = sys.argv[2]

target_dir = os.path.dirname(target)

# create the directory plotted where all plots are saved
if not os.path.exists(target_dir):
os.makedirs(target_dir)

def load_scalars(path):
df = pd.read_csv(path, sep=",", index_col=0)
return df

# Load scalar data
scalars = load_scalars(resources)
jnnr marked this conversation as resolved.
Show resolved Hide resolved

# GENERAL
unit_dict = {"capacity_net_el": "W"}
carrier_dict = {
"biomass": "Biomass",
"ch4": "CH4",
"hard coal": "Hard coal",
"oil": "Oil",
"lignite": "Lignite",
"other": "Other",
}

german_labels = {
"Biomass": "Biomasse",
"CH4": "Erdgas",
"Hard coal": "Steinkohle",
"Oil": "Öl",
"Lignite": "Braunkohle",
"Other": "Andere",
}

# User input
var_name = "capacity_net_el"
conv_number = 1000 * 1000
juliusmeier marked this conversation as resolved.
Show resolved Hide resolved

def prepare_conv_pp_scalars(var_name, conv_number, carrier_dict=carrier_dict):
# select var_name to be plotted
selected_df = scalars[scalars["var_name"] == var_name].copy()

# CONV_PP specific
jnnr marked this conversation as resolved.
Show resolved Hide resolved
selected_df.loc[(selected_df["region"] != "Berlin"), "region"] = "Brandenburg"
# capitalize carrier names
selected_df["carrier"].replace(carrier_dict, inplace=True)
# aggregate carriers in regions
selected_df_agg = selected_df.groupby(
["scenario", "region", "carrier", "var_name"]
).sum()
selected_df_agg.reset_index(inplace=True)

# apply pivot table
df_pivot = pd.pivot_table(
selected_df_agg,
index=["region"],
columns="carrier",
values="var_value",
)

# colors
color_keys = df_pivot.columns
juliusmeier marked this conversation as resolved.
Show resolved Hide resolved
german_color_dict = {}
for key in color_keys:
german_color_dict[german_labels[key]] = colors_odict[key]
df_pivot.rename(columns=german_labels, inplace=True)
german_color_keys = df_pivot.columns
# convert to SI unit:
if conv_number:
df_pivot *= conv_number

return df_pivot, german_color_keys, german_color_dict

def plot_scalar_resources(df, color_keys, color_dict, unit_dict):
alpha = 0.3
fontsize = 14
plt.rcParams.update({"font.size": fontsize})

fig, ax = plt.subplots(figsize=(12, 6))
# apply EngFormatter if power is plotted
if unit_dict[var_name] == "W":
ax = plots.eng_format(ax, "W")
df.plot.bar(
ax=ax,
color=[color_dict[key] for key in color_keys],
width=0.8,
zorder=2,
stacked=False,
rot=0,
)

for spine in ["top", "left", "right"]:
ax.spines[spine].set_visible(False)
ax.spines["bottom"].set_alpha(alpha)
ax.tick_params(axis="both", length=0, pad=7)

ax.grid(axis="y", zorder=1, color="black", alpha=alpha)
ax.set_xlabel(xlabel=None)
ax.legend(labels=german_labels)
plt.legend(title=None, frameon=True, framealpha=1)

plt.tight_layout()
plt.savefig(target, bbox_inches="tight")

df_pivot, german_color_keys, german_color_dict = prepare_conv_pp_scalars(
var_name=var_name, conv_number=conv_number
)
plot_scalar_resources(df_pivot, german_color_keys, german_color_dict, unit_dict)