-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapper.py
More file actions
1753 lines (1620 loc) · 52.1 KB
/
mapper.py
File metadata and controls
1753 lines (1620 loc) · 52.1 KB
1
2
3
4
5
6
7
8
9
10
11
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import abc, namedtuple
from csv import DictWriter, field_size_limit as csv_field_size_limit
from contextlib import contextmanager
from dataclasses import asdict, astuple, dataclass, fields, replace
from datetime import datetime
from functools import reduce
from itertools import chain, groupby
from pathlib import Path
from pprint import pformat as pf
from tempfile import TemporaryDirectory as TD
from typing import Tuple
import json
import re
import sys
import textwrap
from frictionless import Detector, Package, Resource
from loguru import logger
from oemof.solph import (
Bus,
EnergySystem as ES,
Flow,
GenericStorage as Storage,
Investment,
Model,
Sink,
Source,
Transformer,
processing,
)
from oemof.tools.economics import annuity
import click
import pandas as pd
import plotly.graph_objects as plt
csv_field_size_limit(sys.maxsize)
DE = [
"BB",
"BE",
"BW",
"BY",
"HB",
"HE",
"HH",
"MV",
"NI",
"NW",
"RP",
"SH",
"SL",
"SN",
"ST",
"TH",
]
def slurp(path):
with open(path) as f:
return json.load(f)
def rs2df(rs):
"""Convert time dependent optimization results to a dataframe.
The resulting dataframe has rows indexed by the timeindex and columns
which are a two level MultiIndex, where the label of the source node is
the first level and the label of the target node is the second level.
"""
def label(o):
return getattr(o, "label", str(o))
d = {
(label(k[0]), label(k[1]), name): rs[k]["sequences"][name]
for k in rs
for name in rs[k]["sequences"]
}
return (
pd.DataFrame.from_dict(d)
.sort_index(axis="columns")
.rename_axis(columns=["source", "target", "values"])
)
def throw(exception):
raise exception
return "This should never be reached."
def sankey(df):
idx = pd.IndexSlice
sums = df.sum()
if len(sums.index.levshape) > 2:
sums = sums.droplevel(list(range(2, len(sums.index.levshape))))
sums = sums.drop("None", level=1)
deletable = [
k
for k in sums.index
if len(sums.loc[idx[k[0], :]]) == 1
if len(sums.get(idx[:, k[0]], [])) == 1
if list(sums.loc[idx[k[0], :]]) == list(sums.loc[idx[:, k[0]]])
]
for key in deletable:
sums = sums.set_axis(
sums.index.map(lambda k: (k[0], key[1]) if k[1] == key[0] else k)
)
sums = sums.drop(key)
compressable = [
k
for k in sums.index
if len(sums.loc[(k[0],)]) == 1
if len(sums.loc[idx[:, k[1]]]) == 1
]
for key in compressable:
if sums.get(idx[:, key[0]]) is None:
# keep = 0
def keep(k):
if key[1] == k[0]:
return (key[0], k[1])
return k
elif sums.get(idx[key[1],]) is None:
# keep = 1
def keep(k):
if k[1] == key[0]:
return (k[0], key[1])
return k
else:
raise ValueError(
f"Can't decide whether to keep source or target of {key}."
)
sums = sums.drop(key)
sums = sums.set_axis(sums.index.map(keep))
# Transform 'energy flow, XY -> AB: transmission, hvac / electricity,
# electricity' nodes into flows from "('XY', 'electricity')" to "('AB',
# 'electricity')" with a label of "transmission, hvac".
# Remember to redirect the losses and "energy flow (both directions)"
# flows, though.
sums = sums.drop([k for k in sums.index if "(both directions)" in k[1]])
for key in [k for k in sums.index if "energy flow" in k[1]]:
sums = sums.drop(key)
sums = sums.set_axis(
sums.index.map(lambda k: (key[0], k[1]) if k[0] == key[1] else k)
)
def parse(label):
if ": " in label:
detail, regions, t1, t2, v1, v2 = re.split(", | / |: ", label)
key = Key(
region=tuple(regions.split(" -> ")),
technology=(t1, t2),
vectors=(v1, v2),
year=-1,
)
key["detail"] = detail
else: # should be "(region, vector)" or "((region,), vector)"
region, detail = re.match(
"\(([^()]*|\([^()]*,\)), '([^()]*)'\)", label
).groups()
region = re.sub("[()',']", "", region)
key = Key(
region=(re.sub("[()',']", "", region),),
technology=None,
vectors=None,
year=-1,
)
key["detail"] = detail
return key
def label(key):
if ": " in key:
match = re.search("^([^,]*), ", key)
return (match[1], key.replace(match[0], ""))
# if re.search("'([^']* expansion limit)'")
return (key, None)
labels = list(set(parse(l)["detail"] for p in sums.index for l in p))
l2i = {l: i for i, l in enumerate(labels)}
color = "rgba(44, 160, 44, {})"
figure = plt.Figure(
data=[
plt.Sankey(
node=dict(
pad=15,
thickness=15,
line=dict(color="black", width=0.5),
label=labels,
color=color.format(0.8),
),
link=dict(
source=[l2i[parse(k[0])["detail"]] for k in sums.index],
target=[l2i[parse(k[1])["detail"]] for k in sums.index],
value=list(sums),
label=[
(l0 + " | " + l1)
if l0 != "None"
and l1 != "None"
and l0 != l1
and "DE:" not in l0
and "DE:" not in l1
else l0
if l0 != "None"
else l1
if l1 != "None"
else None
for k in sums.index
for l0 in [str(label(k[0])[1])]
for l1 in [str(label(k[1])[1])]
],
color=color.format(0.4),
),
)
]
)
figure.update_layout(title_text="Energy System Flows", font_size=10)
return figure
def invest(carry, mapping):
if mapping[0].year == 2016 or (
"capital costs" not in mapping[1]
and "expansion limit" not in mapping[1]
):
return {
"nominal_storage_capacity"
if mapping[0].technology[0] == "storage"
else "nominal_value": mapping[1].get("installed capacity", 0)
* mapping[1].get("E2P ratio", 1)
}
optionals = (
{"maximum": mapping[1]["expansion limit"]}
if "expansion limit" in mapping[1]
and mapping[1]["expansion limit"] != 999999.0
else {}
)
ratios = {}
if "E2P ratio" in mapping[1]:
ratio = 1 / mapping[1]["E2P ratio"]
# TODO: Figure out whether these have to be multiplied with
# `mapping[1]["input ratio"]` or `mapping[1]["output ratio"]`
# respectively. See also the corresponding TODO at storage
# construction.
ratios["invest_relation_input_capacity"] = ratio
ratios["invest_relation_output_capacity"] = ratio
# TODO: Retrieve the lifetime of 40 years for transmissions lines
# from the data instead of hardcoding it. Same with the WACC
# of 0.07 in the line below.
lifetime = (
0
if mapping[0]["technology"] == ("photovoltaics", "unknown")
else mapping[1]["lifetime"]
if len(mapping[0].regions) == 1
else 40
)
wacc = 0.07
key = Key(**{**mapping[0], "year": None})
existing = (
[
carry[k][interval]
for k in carry
if type(k) is Key
if k.technology[0] == "photovoltaics"
if k.technology[1] != "unknown"
if key.regions == k.regions
for interval in carry[k]
if pd.to_datetime(str(mapping[0].year)) in interval
]
if mapping[0]["technology"] == ("photovoltaics", "unknown")
else [
carry[key][k]
for k in carry.get(key, {})
if pd.to_datetime(str(mapping[0].year)) in k
]
)
ep_costs = (
annuity(
mapping[1].get(
"capital costs",
# TODO: Retrieve the capital costs of 446.39 for
# transmission lines from the data instead of
# hardcoding it here.
0
if len(mapping[0].regions) == 1
else 446.39
if mapping[0]["technology"] == ("transmission", "hvac")
else 1
if mapping[0]["technology"] == ("transmission", "DC")
else "capital costs" in mapping[1]
or throw(
Exception(
'Unable to determine "capital costs" for:'
f"\n{pf(mapping)}"
)
),
)
* mapping[1].get(
"distance",
1
if mapping[0]["technology"][0] != "transmission"
else "distance" in mapping[1]
or throw(
Exception(
'Unable to determine "distance" for:'
f"\n{pf(mapping)}"
)
),
)
/ (
# For some reason, all storage capital costs (CCs) are in
# €/MW, except for for batteries and salt caverns, which
# are in €/MWh.
# Therefore the CCs for every non-battery storage have to
# be divided by the E2P ratio, which is in hours, in order
# to account for the fact that our storage capacities are
# in MWh.
# TODO: This should really be done based on
# "capital costs"' unit of measure.
mapping[1].get("E2P ratio", 1)
if mapping[0].technology[1] not in ["battery", "salt cavern"]
else 1
),
lifetime,
wacc,
)
if "capital costs" in mapping[1] or len(mapping[0].regions) == 2
else 0
)
return {
**ratios,
"investment": Investment(
ep_costs=ep_costs,
existing=sum(existing)
+ (
mapping[1].get("installed capacity", 0)
* mapping[1].get("E2P ratio", 1)
),
**optionals,
lifetime=lifetime,
),
}
@dataclass(eq=True, frozen=True)
class Key(dict):
region: Tuple[str]
technology: Tuple[str, str]
vectors: Tuple[str, str]
year: int
@classmethod
def from_dictionary(cls, d):
# Repair the "NS" region. This one seems to be a typo.
# Should be "NI" instead.
if "NS" in d["region"]:
d["region"] = [("NI" if r == "NS" else r) for r in d["region"]]
arguments = dict(
region=tuple(sorted(d["region"])),
technology=(d["technology"], d["technology_type"]),
vectors=(d["input_energy_vector"], d["output_energy_vector"]),
year=(
d["year"]
if "year" in d
else pd.to_datetime(str(d["timeindex_start"])).year
),
)
return cls(**arguments)
@property
def regions(self):
"""`regions` is an alias of `region`.
`region` is the key used in the original JSON data, but since it's a
tuple, even if mostly with just one entry, `regions` is a less
confusing name.
"""
return self.region
def __post_init__(self):
names = [field.name for field in fields(self)]
for name in names:
self[name] = getattr(self, name)
def __str__(self):
return (
f"{', '.join(self.regions)}, {self.year}"
f"; {', '.join(self.technology)}; {', '.join(self.vectors)}"
)
def reducer(dictionary, value):
key = Key.from_dictionary(value)
# Expand parameters which are applied to multiple regions by having more
# than two regions in the "region" key (two regions would mean
# ["source", "target"] instead), to a list copies of the same parameter
# with only one "region".
keys = (
[replace(key, region=(kr,)) for kr in key.region]
if len(key.region) > 2
else [key]
)
parameter = value["parameter_name"]
for key in keys:
if key in dictionary:
if parameter in dictionary[key] and (
dictionary[key][parameter]
!= (value["value"] if "value" in value else value["series"])
or dictionary[key]["units"][parameter] != value["unit"]
):
first = dictionary[key][parameter]
first = (
first
if not isinstance(first, abc.Sized) or len(first) > 53
else "Series omitted..."
)
first = f"{first}{dictionary[key]['units'][parameter]}"
dupes = dictionary.get("dupes", {})
dupes[key] = dupes.get(key, {})
dupes[key][parameter] = dupes[key].get(parameter, [first])
dupes[key][parameter].append(
f"{value.get('value', 'Series omitted...')}{value['unit']}"
)
dictionary["dupes"] = dupes
continue
else:
dictionary[key] = {"units": {}}
dictionary[key][value["parameter_name"]] = (
value["value"] if "value" in value else value["series"]
)
dictionary[key]["units"][value["parameter_name"]] = value["unit"]
return dictionary
def duplicates(mappings):
if not "dupes" in mappings:
return False
dupes = mappings["dupes"]
output = "\n\n".join(
[
f"{k}\n"
+ "\n".join([f"{n}: " + ", ".join(dupes[k][n]) for n in dupes[k]])
for k in dupes
]
)
debug = textwrap.indent(output, " ")
logger.debug(f"Dupes:\n\n{output}")
return True
def from_json(path):
logger.info("Reading JSON.")
base = {"concrete": slurp(path)}
for mapping in base:
logger.debug(
f"\n{mapping} top-level keys/lengths:"
f"\n{pf([(k, len(base[mapping][k])) for k in base[mapping]])}"
)
# Time series boundaries
tsbs = {
mapping: set(
[
(ts["timeindex_start"], ts["timeindex_stop"])
for ts in base[mapping]["oed_timeseries"]
]
)
for mapping in base
}
for mapping in base:
logger.debug(f"\n{mapping} time series boundaries:" f"\n{pf(tsbs)}")
reduced = reduce(
reducer,
chain(
base["concrete"]["oed_scalars"], base["concrete"]["oed_timeseries"]
),
{},
)
assert not duplicates(reduced), (
"\n Duplicate parameter specifications."
"\n Use `--verbosity='debug'` to get a list."
)
result = {
mapping: {
"base": base[mapping],
"timeseries boundaries": tsbs[mapping],
}
for mapping in base
}
years = sorted(
pd.to_datetime(ts).year for tsb in tsbs["concrete"] for ts in tsb
)
result = {}
result.update(
{
year: {k: reduced[k] for k in reduced if k.year == year}
for year in years
}
)
# assertion: len(o.region) == 2
# => o.technology == ('transmission', 'hvac')
# and o.vectors == ('electricity', 'electricity')
#
# len(o.region) > 2 => 16 (DE) or 18
return result
@dataclass(eq=True, frozen=True)
class Label:
regions: Tuple[str]
technology: Tuple[str, str]
vectors: Tuple[str, str]
name: str
def __str__(self):
return (
f"{self.name}, {' -> '.join(self.regions)}:"
f" {', '.join(self.technology)} / {', '.join(self.vectors)}"
)
def __iter__(self):
return astuple(self).__iter__()
def label(mapping, name):
return Label(
mapping[0].regions, mapping[0].technology, mapping[0].vectors, name
)
def demands(buses, mappings):
return [
Sink(
label=label(demand, "demand"),
inputs={
buses[(demand[0].regions[0], demand[0].vectors[0])]: Flow(
fix=demand[1]["demand"], nominal_value=1
)
},
)
for demand in find(mappings, "demand")
]
def transmission(buses, carry, line, penalties, ratios):
loss_bus = Bus(label=label(line, "losses"))
loss = Sink(
label=label(line, "loss-sink"),
inputs={loss_bus: Flow(variable_costs=penalties["transmission"])},
)
flow_bus = Bus(label=label(line, "flow-bus"))
flow = Sink(
label=label(line, "energy flow (both directions)"),
inputs={flow_bus: Flow(min=0, **invest(carry, line))},
)
lines = [
Transformer(
label=replace(label(line, "energy flow"), regions=regions,),
inputs={source: Flow()},
outputs={flow_bus: Flow(), loss_bus: Flow(), target: Flow()},
conversion_factors={
flow_bus: ratios[regions[0]]["ir"],
loss_bus: 1 - ratios[regions[1]]["or"],
source: ratios[regions[0]]["ir"],
target: ratios[regions[1]]["or"],
},
)
for regions in [line[0].regions, tuple(reversed(line[0].regions))]
for source in [buses[(regions[0], line[0].vectors[0])]]
for target in [buses[(regions[1], line[0].vectors[1])]]
]
return lines + [flow_bus, flow, loss_bus, loss]
def lines(buses, carry, mappings, penalties):
ratios = {
ratio[0].regions[0]: {
"ir": ratio[1]["input ratio"],
"or": ratio[1]["output ratio"],
}
for ratio in find(
mappings,
"input ratio",
"output ratio",
technology=("transmission", "hvac"),
vectors=("electricity", "electricity"),
)
+ find(
mappings,
"input ratio",
"output ratio",
technology=("transmission", "DC"),
vectors=("electricity", "electricity"),
)
}
return [
node
for line in find(mappings, technology=("transmission", "hvac"))
+ find(mappings, technology=("transmission", "DC"))
if len(line[0].regions) == 2
for node in transmission(buses, carry, line, penalties, ratios)
]
def trades(buses, mappings):
imports = find(mappings, technology=("transmission", "trade import"))
exports = find(mappings, technology=("transmission", "trade export"))
sinks = [
Sink(
label=label(trade, "export"),
inputs={
buses[(trade[0].regions[0], trade[0].vectors[0])]: Flow(
fix=trade[1]["trade volume"], nominal_value=1
)
},
)
for trade in exports
]
sources = [
Source(
label=label(trade, "import"),
outputs={
buses[(trade[0].regions[0], trade[0].vectors[0])]: Flow(
fix=trade[1]["trade volume"],
nominal_value=trade[1]["installed capacity"],
)
},
)
for trade in imports
]
return sinks + sources
def fixed(buses, carry, mappings):
sources = [
Source(
label=label(source, "electricity generation"),
outputs={
auxiliary_bus: Flow(
fix=source[1]["capacity factor"],
**invest(carry, source),
variable_costs=source[1].get("variable costs", 0),
)
},
)
for source in find(mappings, "capacity factor")
for renewables in [buses[("DE", "renewables")]]
for auxiliary_bus in [Bus(label=label(source, "auxiliary-bus"))]
for transformer in [
Transformer(
label=label(source, "splitter",),
inputs={auxiliary_bus: Flow()},
outputs={
buses[
(source[0].regions[0], source[0].vectors[1])
]: Flow(),
renewables: Flow(),
**(
{buses[(source[0].regions, "photovoltaics")]: Flow()}
if source[0].technology[0] == "photovoltaics"
and (source[0].regions, "photovoltaics") in buses
else {}
),
},
)
]
]
return (
sources
+ [o for source in sources for o in source.outputs]
+ [t for source in sources for o in source.outputs for t in o.outputs]
)
def flexible(buses, carry, mappings):
limits = find(mappings, "natural domestic limit")
limit_buses = {
(l[0].regions, l[0].vectors[0]): Bus(label=label(l, "limit bus"))
for l in limits
}
limit_sinks = {
(l[0].regions, l[0].vectors[0]): Sink(
label=label(l, "limit sink"),
inputs={
limit_buses[(l[0].regions, l[0].vectors[0])]: Flow(
nominal_value=l[1]["natural domestic limit"]
* (pow(10, 9) / 3600),
summed_max=1,
)
},
)
for l in limits
}
fueled = chain(
find(mappings, "emission factor"),
find(mappings, technology=("geothermal", "unknown"),),
)
co2c = find(mappings, vectors=("unknown", "co2"))[0][1]["emission costs"]
sources = [
Source(
label=label(f, "electricity generation"),
outputs={
source_bus: Flow(
**invest(carry, f),
variable_costs=(
f[1]["variable costs"]
+ (1 / f[1]["output ratio"])
* (
f[1].get("emission factor", 0) * co2c
+ f[1].get("fuel costs", 0)
)
),
)
},
)
for f in fueled
for source_bus in [Bus(label=label(f, "auxiliary-bus"))]
for renewables in [buses[("DE", "renewables")]]
for transformer in [
Transformer(
label=label(f, "auxiliary-transformer"),
inputs={source_bus: Flow()},
outputs={
buses[(f[0].regions[0], f[0].vectors[1])]: Flow(),
buses[("DE", "co2")]: Flow(),
**(
{renewables: Flow()}
if "geothermal" in f[0].technology
else {}
),
**(
{buses[("DE", "waste")]: Flow()}
if "waste" in f[0].vectors
else {}
),
**(
{limit_buses[(f[0].regions, f[0].vectors[0])]: Flow()}
if (f[0].regions, f[0].vectors[0]) in limit_buses
else {}
),
},
conversion_factors={
buses[("DE", "co2")]: 1
* f[1].get("emission factor", 0)
/ f[1]["output ratio"],
**(
{buses[("DE", "waste")]: 1 / f[1]["output ratio"]}
if "waste" in f[0].vectors
else {}
),
**(
{
limit_buses[(f[0].regions, f[0].vectors[0])]: (
1 / f[1]["output ratio"]
)
}
if (f[0].regions, f[0].vectors[0]) in limit_buses
else {}
),
},
)
]
]
return (
sources
+ [b for source in sources for b in source.outputs]
+ [t for source in sources for b in source.outputs for t in b.outputs]
+ list(limit_buses.values())
+ list(limit_sinks.values())
)
def storages(buses, carry, mappings, penalties):
return [
Storage(
label=label(storage, "storage"),
**investment,
initial_storage_level=0,
inflow_conversion_factor=storage[1]["input ratio"],
outflow_conversion_factor=storage[1]["output ratio"],
inputs={
buses[(storage[0].regions[0], storage[0].vectors[0])]: Flow(
**nv,
variable_costs=storage[1].get("variable costs", 0)
+ penalties["storage"],
)
},
outputs={
buses[(storage[0].regions[0], storage[0].vectors[1])]: Flow(
**nv, variable_costs=0,
)
},
)
for storage in find(mappings, "E2P ratio")
for investment in [invest(carry, storage)]
# TODO: Figure out whether these nominal values have to be multiplied
# with `storage[1]["input ratio"]` or
# `storage[1]["output ratio"]` respectively.
for nv in [
{"nominal_value": storage[1].get("installed capacity", 0)}
if "investment" not in investment
else {}
]
]
def build(carry, mappings, penalties, timesteps, year):
logger.info("Building the energy system.")
es = ES(
timeindex=pd.date_range(
f"{year}-01-01T00:00:00", f"{year}-12-31T23:00:00", freq="1h"
)[0:timesteps]
)
rvs = set(
(region, vector)
for m in mappings
for region in m.region
for vector in m.vectors
if not vector == "unknown"
)
buses = {rv: Bus(label=rv) for rv in rvs}
pv_regions = {
r
for m in mappings
for r in m.region
if r in DE
if Key(
(r,),
("photovoltaics", "unknown"),
("solar radiation", "electricity"),
year,
)
in mappings
}
buses.update(
{
((r,), "photovoltaics"): Bus(label=(r, "photovoltaics"))
for r in pv_regions
}
)
sinks = [
Sink(
label=((r,), "pv expansion limit"),
inputs={
buses[((r,), "photovoltaics")]: Flow(
**invest(carry, (key, mappings[key]))
)
},
)
for r in pv_regions
for key in [
Key(
(r,),
("photovoltaics", "unknown"),
("solar radiation", "electricity"),
year,
)
]
]
demand_sinks = demands(buses, mappings)
total_demand = sum(
v for sink in demand_sinks for v in list(sink.inputs.values())[0].fix
)
renewables = ("DE", "renewables")
buses[renewables] = buses.get(renewables, Bus(label=renewables))
renewables = buses[renewables]
found = find(mappings, "renewable share")
renewables.share = found[0][1]["renewable share"] if found else 0
es.add(
*buses.values(),
*sinks,
Sink(
label=("DE", "renewable share"),
inputs={
renewables: Flow(
nominal_value=total_demand, summed_min=renewables.share
)
},
),
)
waste = find(mappings, ("waste", "unknown"))
assert len(waste) == 1
waste = waste[0]
assert waste[0].region[0] == "DE"
assert waste[0].vectors[0] == "waste"
es.add(
Sink(
label=label(waste, "waste"),
inputs={
buses[(waste[0].region[0], waste[0].vectors[0])]: Flow(
nominal_value=waste[1]["natural domestic limit"],
summed_max=1,
)
},
)
)
co2 = find(mappings, ("unknown", "co2"))
assert len(co2) == 1
co2 = co2[0]
assert co2[0].region[0] == "DE"
assert co2[0].vectors[1] == "co2"
remaining = (
carry["emission budget"]
- pd.Series(carry["emissions"], index=range(2016, year), dtype=float)
.interpolate()
.sum()
)
co2limit = (
co2[1].get("emission limit")
if remaining == float("inf")
else min(remaining, co2[1].get("emission limit", float("inf")))
)
es.add(
Sink(
label=label(co2, "CO2"),
inputs={
buses[(co2[0].region[0], co2[0].vectors[1])]: Flow(
nominal_value=co2limit, summed_max=1
)
},
)
)
Source.slack_costs = sum(
max(p[1][f"{c} costs"] for p in find(mappings, f"{c} costs"))
for c in ["variable", "fixed", "capital"]
)
es.add(
*[
Source(
label=Label(
regions=(rv[0],),
technology=("ALL", "ALL"),
vectors=(rv[1], rv[1]),
name="slack",
),
outputs={buses[rv]: Flow(variable_costs=Source.slack_costs)},
)
for rv in buses
if rv[1] == "electricity"
]
)
es.add(*demand_sinks)
es.add(*lines(buses, carry, mappings, penalties))
es.add(*trades(buses, mappings))
es.add(*fixed(buses, carry, mappings))
es.add(*flexible(buses, carry, mappings))
es.add(*storages(buses, carry, mappings, penalties))
renewable_auxiliary_buses = [
bus
for transformer in buses[("DE", "renewables")].inputs
for bus in transformer.inputs
]
for bus in renewable_auxiliary_buses:
assert tuple(bus.label)[-1] == "auxiliary-bus"
es.add(
Sink(
label=Label(
regions=("DE",),
technology=("renewables", "unknown"),
vectors=("electricity", "electricity"),
name="curtailment",
),
inputs={bus: Flow() for bus in renewable_auxiliary_buses},
)
)
return es
@contextmanager
def temporary(path):
path = Path(path)
yield path
def export(
carry,
export_prefix,
mappings,
meta,
penalties,
results,
tags,
temporary_directory,
year,
):