-
Notifications
You must be signed in to change notification settings - Fork 446
Expand file tree
/
Copy pathbase_network.py
More file actions
1674 lines (1368 loc) · 53 KB
/
Copy pathbase_network.py
File metadata and controls
1674 lines (1368 loc) · 53 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
# SPDX-FileCopyrightText: Contributors to PyPSA-Eur <https://github.com/pypsa/pypsa-eur>
#
# SPDX-License-Identifier: MIT
"""
Creates the network topology from a `ENTSO-E map extract.
<https://github.com/PyPSA/GridKit/tree/master/entsoe>`_ (March 2022)
or `OpenStreetMap data <https://www.openstreetmap.org/>`_ (Aug 2024)
as a PyPSA
network.
Description
-----------
Creates the network topology from an ENTSO-E map extract, and create Voronoi shapes for each bus representing both onshore and offshore regions.
"""
import logging
import multiprocessing as mp
import warnings
from functools import partial
from itertools import chain, product
import geopandas as gpd
import networkx as nx
import numpy as np
import pandas as pd
import pypsa
import shapely
import shapely.prepared
import shapely.wkt
import yaml
from packaging.version import Version, parse
from scipy.sparse import csgraph
from scipy.spatial import KDTree
from shapely.geometry import Point
from tqdm import tqdm
from scripts._helpers import (
REGION_COLS,
configure_logging,
get_snapshots,
set_scenario_config,
)
PD_GE_2_2 = parse(pd.__version__) >= Version("2.2")
logger = logging.getLogger(__name__)
def _get_oid(df):
if "tags" in df.columns:
return df.tags.str.extract(r'"oid"=>"(\d+)"', expand=False)
else:
return pd.Series(np.nan, df.index)
def _get_country(df):
if "tags" in df.columns:
return df.tags.str.extract('"country"=>"([A-Z]{2})"', expand=False)
else:
return pd.Series(np.nan, df.index)
def _find_closest_links(links, new_links, distance_upper_bound=1.5):
treecoords = np.asarray(
[
np.asarray(shapely.wkt.loads(s).coords)[[0, -1]].flatten()
for s in links.geometry
]
)
querycoords = np.vstack(
[new_links[["x1", "y1", "x2", "y2"]], new_links[["x2", "y2", "x1", "y1"]]]
)
tree = KDTree(treecoords)
dist, ind = tree.query(querycoords, distance_upper_bound=distance_upper_bound)
found_b = ind < len(links)
found_i = np.arange(len(new_links) * 2)[found_b] % len(new_links)
return (
pd.DataFrame(
dict(D=dist[found_b], i=links.index[ind[found_b] % len(links)]),
index=new_links.index[found_i],
)
.sort_values(by="D")[lambda ds: ~ds.index.duplicated(keep="first")]
.sort_index()["i"]
)
def _load_buses(buses, europe_shape, countries, config):
buses = (
pd.read_csv(
buses,
quotechar="'",
true_values=["t"],
false_values=["f"],
dtype=dict(bus_id="str"),
)
.set_index("bus_id")
.rename(columns=dict(voltage="v_nom"))
)
if "station_id" in buses.columns:
buses.drop("station_id", axis=1, inplace=True)
buses["carrier"] = buses.pop("dc").map({True: "DC", False: "AC"})
buses["under_construction"] = buses.under_construction.where(
lambda s: s.notnull(), False
).astype(bool)
europe_shape = gpd.read_file(europe_shape).loc[0, "geometry"]
europe_shape_prepped = shapely.prepared.prep(europe_shape)
buses_in_europe_b = buses[["x", "y"]].apply(
lambda p: europe_shape_prepped.contains(Point(p)), axis=1
)
buses_in_countries_b = (
buses.country.isin(countries)
if "country" in buses
else pd.Series(True, buses.index)
)
v_nom_min = min(config["electricity"]["voltages"])
v_nom_max = max(config["electricity"]["voltages"])
buses_with_v_nom_to_keep_b = (
(v_nom_min <= buses.v_nom) & (buses.v_nom <= v_nom_max)
| (buses.v_nom.isnull())
| (
buses.carrier == "DC"
) # Keeping all DC buses from the input dataset independent of voltage (e.g. 150 kV connections)
)
logger.info(f"Removing buses outside of range AC {v_nom_min} - {v_nom_max} V")
return pd.DataFrame(
buses.loc[buses_in_europe_b & buses_in_countries_b & buses_with_v_nom_to_keep_b]
)
def _load_transformers(buses, transformers):
transformers = pd.read_csv(
transformers,
quotechar="'",
true_values=["t"],
false_values=["f"],
dtype=dict(transformer_id="str", bus0="str", bus1="str"),
).set_index("transformer_id")
transformers = _remove_dangling_branches(transformers, buses)
return transformers
def _load_converters_from_eg(buses, converters):
converters = pd.read_csv(
converters,
quotechar="'",
true_values=["t"],
false_values=["f"],
dtype=dict(converter_id="str", bus0="str", bus1="str"),
).set_index("converter_id")
converters = _remove_dangling_branches(converters, buses)
converters["carrier"] = "B2B"
return converters
def _load_converters_from_raw(buses, converters):
converters = pd.read_csv(
converters,
quotechar="'",
true_values=["t"],
false_values=["f"],
dtype=dict(converter_id="str", bus0="str", bus1="str"),
).set_index("converter_id")
converters = _remove_dangling_branches(converters, buses)
converters["carrier"] = ""
return converters
def _load_links_from_eg(buses, links):
links = pd.read_csv(
links,
quotechar="'",
true_values=["t"],
false_values=["f"],
dtype=dict(link_id="str", bus0="str", bus1="str", under_construction="bool"),
).set_index("link_id")
links["length"] /= 1e3
# Skagerrak Link is connected to 132kV bus which is removed in _load_buses.
# Connect to neighbouring 380kV bus
links.loc[links.bus1 == "6396", "bus1"] = "6398"
links = _remove_dangling_branches(links, buses)
# Add DC line parameters
links["carrier"] = "DC"
return links
def _load_links_from_raw(buses, links):
links = pd.read_csv(
links,
quotechar="'",
true_values=["t"],
false_values=["f"],
dtype=dict(
link_id="str",
bus0="str",
bus1="str",
voltage="int",
p_nom="float",
),
).set_index("link_id")
links["length"] /= 1e3
links = _remove_dangling_branches(links, buses)
# Add DC line parameters
links["carrier"] = "DC"
return links
def _load_lines(buses, lines):
lines = (
pd.read_csv(
lines,
quotechar="'",
true_values=["t"],
false_values=["f"],
dtype=dict(
line_id="str",
bus0="str",
bus1="str",
underground="bool",
under_construction="bool",
),
)
.set_index("line_id")
.rename(columns=dict(voltage="v_nom", circuits="num_parallel"))
)
lines["length"] /= 1e3
lines["carrier"] = "AC"
lines = _remove_dangling_branches(lines, buses)
return lines
def _apply_parameter_corrections(n, parameter_corrections):
with open(parameter_corrections) as f:
corrections = yaml.safe_load(f)
if corrections is None:
return
for component, attrs in corrections.items():
df = n.components[component].static
oid = _get_oid(df)
if attrs is None:
continue
for attr, repls in attrs.items():
for i, r in repls.items():
if i == "oid":
r = oid.map(repls["oid"]).dropna()
elif i == "index":
r = pd.Series(repls["index"])
else:
raise NotImplementedError()
inds = r.index.intersection(df.index)
df.loc[inds, attr] = r[inds].astype(df[attr].dtype)
def _reconnect_crimea(lines):
logger.info("Reconnecting Crimea to the Ukrainian grid.")
lines_to_crimea = pd.DataFrame(
{
"bus0": ["3065", "3181", "3181"],
"bus1": ["3057", "3055", "3057"],
"v_nom": [300, 300, 300],
"num_parallel": [1, 1, 1],
"length": [140, 120, 140],
"carrier": ["AC", "AC", "AC"],
"underground": [False, False, False],
"under_construction": [False, False, False],
},
index=["Melitopol", "Liubymivka left", "Luibymivka right"],
)
return pd.concat([lines, lines_to_crimea])
def _set_electrical_parameters_lines_eg(lines, config):
v_noms = config["electricity"]["voltages"]
linetypes = config["lines"]["types"]
for v_nom in v_noms:
lines.loc[lines["v_nom"] == v_nom, "type"] = linetypes[v_nom]
lines["s_max_pu"] = config["lines"]["s_max_pu"]
return lines
def _set_electrical_parameters_lines_raw(lines, config):
if lines.empty:
lines["type"] = []
return lines
v_noms = config["electricity"]["voltages"]
linetypes = _get_linetypes_config(config["lines"]["types"], v_noms)
lines["carrier"] = "AC"
lines["dc"] = False
lines.loc[:, "type"] = lines.v_nom.apply(
lambda x: _get_linetype_by_voltage(x, linetypes)
)
lines["s_max_pu"] = config["lines"]["s_max_pu"]
return lines
def _set_lines_s_nom_from_linetypes(n):
n.lines["s_nom"] = (
np.sqrt(3)
* n.lines["type"].map(n.line_types.i_nom)
* n.lines["v_nom"]
* n.lines["num_parallel"]
)
def _set_electrical_parameters_links_eg(links, config, links_p_nom):
if links.empty:
return links
p_max_pu = config["links"].get("p_max_pu", 1.0)
p_min_pu = config["links"].get("p_min_pu", -p_max_pu)
links["p_max_pu"] = p_max_pu
links["p_min_pu"] = p_min_pu
links_p_nom = pd.read_csv(links_p_nom)
# filter links that are not in operation anymore
removed_b = links_p_nom.Remarks.str.contains("Shut down|Replaced", na=False)
links_p_nom = links_p_nom[~removed_b]
# find closest link for all links in links_p_nom
links_p_nom["j"] = _find_closest_links(links, links_p_nom)
links_p_nom = links_p_nom.groupby(["j"], as_index=False).agg({"Power (MW)": "sum"})
p_nom = links_p_nom.dropna(subset=["j"]).set_index("j")["Power (MW)"]
# Don't update p_nom if it's already set
p_nom_unset = (
p_nom.drop(links.index[links.p_nom.notnull()], errors="ignore")
if "p_nom" in links
else p_nom
)
links.loc[p_nom_unset.index, "p_nom"] = p_nom_unset
return links
def _set_electrical_parameters_links_raw(links, config):
if links.empty:
return links
p_max_pu = config["links"].get("p_max_pu", 1.0)
p_min_pu = config["links"].get("p_min_pu", -p_max_pu)
links["p_max_pu"] = p_max_pu
links["p_min_pu"] = p_min_pu
links["carrier"] = "DC"
links["dc"] = True
return links
def _set_electrical_parameters_converters(converters, config):
p_max_pu = config["links"].get("p_max_pu", 1.0)
p_min_pu = config["links"].get("p_min_pu", -p_max_pu)
converters["p_max_pu"] = p_max_pu
converters["p_min_pu"] = p_min_pu
# if column "p_nom" does not exist, set to 2000
if "p_nom" not in converters:
converters["p_nom"] = 2000
# Converters are combined with links
converters["under_construction"] = False
converters["underground"] = False
converters["dc"] = False # ToDo Find a better assumption
return converters
def _set_electrical_parameters_transformers(transformers, config):
config = config["transformers"]
## Add transformer parameters
transformers["x"] = config.get("x", 0.1)
if "s_nom" not in transformers:
transformers["s_nom"] = config.get("s_nom", 2000)
transformers["type"] = config.get("type", "")
return transformers
def _remove_dangling_branches(branches, buses):
return pd.DataFrame(
branches.loc[branches.bus0.isin(buses.index) & branches.bus1.isin(buses.index)]
)
def _remove_unconnected_components(network, threshold=6):
_, labels = csgraph.connected_components(network.adjacency_matrix(), directed=False)
component = pd.Series(labels, index=network.buses.index)
component_sizes = component.value_counts()
components_to_remove = component_sizes.loc[component_sizes < threshold]
logger.info(
f"Removing {len(components_to_remove)} unconnected network components with less than {components_to_remove.max()} buses. In total {components_to_remove.sum()} buses."
)
return network[component == component_sizes.index[0]]
def _set_countries_and_substations(n, config, country_shapes, offshore_shapes):
buses = n.buses
def buses_in_shape(shape):
shape = shapely.prepared.prep(shape)
return pd.Series(
np.fromiter(
(
shape.contains(Point(x, y))
for x, y in buses.loc[:, ["x", "y"]].values
),
dtype=bool,
count=len(buses),
),
index=buses.index,
)
countries = config["countries"]
country_shapes = gpd.read_file(country_shapes).set_index("name")["geometry"]
# reindexing necessary for supporting empty geo-dataframes
offshore_shapes = gpd.read_file(offshore_shapes)
offshore_shapes = offshore_shapes.reindex(columns=["name", "geometry"]).set_index(
"name"
)["geometry"]
substation_b = buses["symbol"].str.contains(
"substation|converter station", case=False
)
def prefer_voltage(x, which):
index = x.index
if len(index) == 1:
return pd.Series(index, index)
key = (
x.index[0]
if x["v_nom"].isnull().all()
else getattr(x["v_nom"], "idx" + which)()
)
return pd.Series(key, index)
compat_kws = dict(include_groups=False) if PD_GE_2_2 else {}
gb = buses.loc[substation_b].groupby(
["x", "y"], as_index=False, group_keys=False, sort=False
)
bus_map_low = gb.apply(prefer_voltage, "min", **compat_kws)
lv_b = (bus_map_low == bus_map_low.index).reindex(buses.index, fill_value=False)
bus_map_high = gb.apply(prefer_voltage, "max", **compat_kws)
hv_b = (bus_map_high == bus_map_high.index).reindex(buses.index, fill_value=False)
onshore_b = pd.Series(False, buses.index)
offshore_b = pd.Series(False, buses.index)
for country in countries:
onshore_shape = country_shapes[country]
onshore_country_b = buses_in_shape(onshore_shape)
onshore_b |= onshore_country_b
buses.loc[onshore_country_b, "country"] = country
if country not in offshore_shapes.index:
continue
offshore_country_b = buses_in_shape(offshore_shapes[country])
offshore_b |= offshore_country_b
buses.loc[offshore_country_b, "country"] = country
# Only accept buses as low-voltage substations (where load is attached), if
# they have at least one connection which is not under_construction
has_connections_b = pd.Series(False, index=buses.index)
for b, df in product(("bus0", "bus1"), (n.lines, n.links)):
has_connections_b |= ~df.groupby(b).under_construction.min()
buses["onshore_bus"] = onshore_b
buses["substation_lv"] = (
lv_b & onshore_b & (~buses["under_construction"]) & has_connections_b
)
buses["substation_off"] = (offshore_b | (hv_b & onshore_b)) & (
~buses["under_construction"]
)
c_nan_b = buses.country.fillna("na") == "na"
if c_nan_b.sum() > 0:
c_tag = _get_country(buses.loc[c_nan_b])
c_tag.loc[~c_tag.isin(countries)] = np.nan
n.buses.loc[c_nan_b, "country"] = c_tag
c_tag_nan_b = n.buses.country.isnull()
# Nearest country in path length defines country of still homeless buses
# Work-around until commit 705119 lands in pypsa release
n.transformers["length"] = 0.0
graph = n.graph(weight="length")
n.transformers.drop("length", axis=1, inplace=True)
for b in n.buses.index[c_tag_nan_b]:
df = (
pd.DataFrame(
dict(
pathlength=nx.single_source_dijkstra_path_length(
graph, b, cutoff=200
)
)
)
.join(n.buses.country)
.dropna()
)
assert not df.empty, (
f"No buses with defined country within 200km of bus `{b}`"
)
n.buses.at[b, "country"] = df.loc[df.pathlength.idxmin(), "country"]
logger.warning(
f"{c_nan_b.sum()} buses are not in any country or offshore shape,"
f" {c_nan_b.sum() - c_tag_nan_b.sum()} have been assigned from the tag of the entsoe map,"
" the rest from the next bus in terms of pathlength."
)
return buses
def _replace_b2b_converter_at_country_border_by_link(n):
# Affects only the B2B converter in Lithuania at the Polish border at the moment
buscntry = n.buses.country
linkcntry = n.links.bus0.map(buscntry)
converters_i = n.links.index[
(n.links.carrier == "B2B") & (linkcntry == n.links.bus1.map(buscntry))
]
def findforeignbus(G, i):
cntry = linkcntry.at[i]
for busattr in ("bus0", "bus1"):
b0 = n.links.at[i, busattr]
for b1 in G[b0]:
if buscntry[b1] != cntry:
return busattr, b0, b1
return None, None, None
for i in converters_i:
G = n.graph()
busattr, b0, b1 = findforeignbus(G, i)
if busattr is not None:
comp, line = next(iter(G[b0][b1]))
if comp != "Line":
logger.warning(
f"Unable to replace B2B `{i}` expected a Line, but found a {comp}"
)
continue
n.links.at[i, busattr] = b1
n.links.at[i, "p_nom"] = min(
n.links.at[i, "p_nom"], n.lines.at[line, "s_nom"]
)
n.links.at[i, "carrier"] = "DC"
n.links.at[i, "underwater_fraction"] = 0.0
n.links.at[i, "length"] = n.lines.at[line, "length"]
n.remove("Line", line)
n.remove("Bus", b0)
logger.info(
f"Replacing B2B converter `{i}` together with bus `{b0}` and line `{line}` by an HVDC tie-line {linkcntry.at[i]}-{buscntry.at[b1]}"
)
def _set_links_underwater_fraction(n, offshore_shapes):
if n.links.empty:
return
if not hasattr(n.links, "geometry"):
n.links["underwater_fraction"] = 0.0
else:
offshore_shape = gpd.read_file(offshore_shapes).union_all()
links = gpd.GeoSeries(n.links.geometry.dropna().map(shapely.wkt.loads))
n.links["underwater_fraction"] = (
links.intersection(offshore_shape).length / links.length
)
def _adjust_capacities_of_under_construction_branches(n, config):
lines_mode = config["lines"].get("under_construction", "undef")
if lines_mode == "zero":
n.lines.loc[n.lines.under_construction, "num_parallel"] = 0.0
n.lines.loc[n.lines.under_construction, "s_nom"] = 0.0
elif lines_mode == "remove":
n.remove("Line", n.lines.index[n.lines.under_construction])
elif lines_mode != "keep":
logger.warning(
"Unrecognized configuration for `lines: under_construction` = `{}`. Keeping under construction lines."
)
links_mode = config["links"].get("under_construction", "undef")
if links_mode == "zero":
n.links.loc[n.links.under_construction, "p_nom"] = 0.0
elif links_mode == "remove":
n.remove("Link", n.links.index[n.links.under_construction])
elif links_mode != "keep":
logger.warning(
"Unrecognized configuration for `links: under_construction` = `{}`. Keeping under construction links."
)
if lines_mode == "remove" or links_mode == "remove":
# We might need to remove further unconnected components
n = _remove_unconnected_components(n)
return n
def _set_shapes(n, country_shapes, offshore_shapes):
# Write the geodataframes country_shapes and offshore_shapes to the network.shapes component
country_shapes = gpd.read_file(country_shapes).rename(columns={"name": "idx"})
country_shapes["type"] = "country"
offshore_shapes = gpd.read_file(offshore_shapes).rename(columns={"name": "idx"})
offshore_shapes["type"] = "offshore"
all_shapes = pd.concat([country_shapes, offshore_shapes], ignore_index=True)
n.add(
"Shape",
all_shapes.index,
geometry=all_shapes.geometry,
idx=all_shapes.idx,
type=all_shapes["type"],
)
def base_network(
buses,
converters,
transformers,
lines,
links,
links_p_nom,
europe_shape,
country_shapes,
offshore_shapes,
countries,
parameter_corrections,
config,
):
base_network = config["electricity"].get("base_network")
osm_version = config["data"]["osm"]["version"]
assert base_network in {"entsoegridkit", "osm", "tyndp"}, (
f"base_network must be either 'entsoegridkit', 'osm' or 'tyndp', but got '{base_network}'"
)
if base_network == "entsoegridkit":
warnings.warn(
"The 'entsoegridkit' base network is deprecated and will be removed in future versions. Please use 'osm' instead.",
DeprecationWarning,
)
logger_str = (
f"Creating base network using {base_network}"
+ (f" v{osm_version}" if base_network == "osm" else "")
+ "."
)
logger.info(logger_str)
buses = _load_buses(buses, europe_shape, countries, config)
transformers = _load_transformers(buses, transformers)
lines = _load_lines(buses, lines)
if base_network == "entsoegridkit":
links = _load_links_from_eg(buses, links)
converters = _load_converters_from_eg(buses, converters)
# Optionally reconnect Crimea
if (config["lines"].get("reconnect_crimea", True)) & (
"UA" in config["countries"]
):
lines = _reconnect_crimea(lines)
# Set electrical parameters of lines and links
lines = _set_electrical_parameters_lines_eg(lines, config)
links = _set_electrical_parameters_links_eg(links, config, links_p_nom)
elif base_network in {"osm", "tyndp"}:
links = _load_links_from_raw(buses, links)
converters = _load_converters_from_raw(buses, converters)
# Set electrical parameters of lines and links
lines = _set_electrical_parameters_lines_raw(lines, config)
links = _set_electrical_parameters_links_raw(links, config)
else:
raise ValueError(
"base_network must be either 'entsoegridkit', 'osm', or 'tyndp'"
)
# Set electrical parameters of transformers and converters
transformers = _set_electrical_parameters_transformers(transformers, config)
converters = _set_electrical_parameters_converters(converters, config)
n = pypsa.Network()
n.name = (
f"PyPSA-Eur ({base_network}"
+ (f" v{osm_version}" if base_network == "osm" else "")
+ ")"
)
time = get_snapshots(snakemake.params.snapshots, snakemake.params.drop_leap_day)
n.set_snapshots(time)
n.add("Bus", buses.index, **buses)
n.add("Line", lines.index, **lines)
n.add("Transformer", transformers.index, **transformers)
n.add("Link", links.index, **links)
n.add("Link", converters.index, **converters)
_set_lines_s_nom_from_linetypes(n)
if config["electricity"].get("base_network") == "entsoegridkit":
_apply_parameter_corrections(n, parameter_corrections)
n = _remove_unconnected_components(n)
_set_countries_and_substations(n, config, country_shapes, offshore_shapes)
_set_links_underwater_fraction(n, offshore_shapes)
_replace_b2b_converter_at_country_border_by_link(n)
n = _adjust_capacities_of_under_construction_branches(n, config)
_set_shapes(n, country_shapes, offshore_shapes)
# Add carriers if they are present in buses.carriers
carriers_in_buses = set(n.buses.carrier.dropna().unique())
carriers = carriers_in_buses.intersection({"AC", "DC"})
if carriers:
n.add("Carrier", carriers)
return n
def _get_linetypes_config(line_types, voltages):
"""
Return the dictionary of linetypes for selected voltages. The dictionary is
a subset of the dictionary line_types, whose keys match the selected
voltages.
Parameters
----------
line_types : dict
Dictionary of linetypes: keys are nominal voltages and values are linetypes.
voltages : list
List of selected voltages.
Returns
-------
Dictionary of linetypes for selected voltages.
"""
# get voltages value that are not available in the line types
vnoms_diff = set(voltages).symmetric_difference(set(line_types.keys()))
if vnoms_diff:
logger.warning(
f"Voltages {vnoms_diff} not in the {line_types} or {voltages} list."
)
return {k: v for k, v in line_types.items() if k in voltages}
def _get_linetype_by_voltage(v_nom, d_linetypes):
"""
Return the linetype of a specific line based on its voltage v_nom.
Parameters
----------
v_nom : float
The voltage of the line.
d_linetypes : dict
Dictionary of linetypes: keys are nominal voltages and values are linetypes.
Returns
-------
The linetype of the line whose nominal voltage is closest to the line voltage.
"""
v_nom_min, line_type_min = min(
d_linetypes.items(),
key=lambda x: abs(x[0] - v_nom),
)
return line_type_min
def voronoi(points, outline, crs=4326):
"""
Create Voronoi polygons from a set of points within an outline.
"""
pts = gpd.GeoSeries(
gpd.points_from_xy(points.x, points.y),
index=points.index,
crs=crs,
)
voronoi = pts.voronoi_polygons(extend_to=outline).clip(outline)
# can be removed with shapely 2.1 where order is preserved
# https://github.com/shapely/shapely/issues/2020
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UserWarning)
pts = gpd.GeoDataFrame(geometry=pts)
voronoi = gpd.GeoDataFrame(geometry=voronoi)
joined = gpd.sjoin_nearest(pts, voronoi, how="right")
return joined.dissolve(by="name").reindex(points.index).squeeze()
def process_onshore_regions(
adm: str,
buses: pd.DataFrame,
admin_shapes: gpd.GeoDataFrame,
crs: str,
) -> gpd.GeoDataFrame:
country = admin_shapes.loc[adm, "country"]
c_b = buses.admin == adm
onshore_shape = admin_shapes.loc[adm, "geometry"]
onshore_locs = (
buses.loc[c_b & buses.onshore_bus]
.sort_values(by="substation_lv", ascending=False) # preference for substations
.drop_duplicates(subset=["x", "y", "country"], keep="first")[
["x", "y", "country"]
]
.rename_axis("name")
)
onshore_regions_adm = gpd.GeoDataFrame(
{
"name": onshore_locs.index,
"x": onshore_locs["x"],
"y": onshore_locs["y"],
"geometry": voronoi(onshore_locs, onshore_shape),
"country": country,
},
crs=crs,
)
return onshore_regions_adm
def process_offshore_regions(
buses: pd.DataFrame,
offshore_shapes: gpd.GeoDataFrame,
countries: list[str],
crs: str,
) -> list[gpd.GeoDataFrame]:
offshore_regions = []
tqdm_kwargs = dict(
ascii=False,
unit=" regions",
total=len(countries),
desc="Building offshore regions",
)
for country in tqdm(countries, **tqdm_kwargs):
if country not in offshore_shapes.index:
continue
c_b = buses.country == country
offshore_shape = offshore_shapes[country]
offshore_locs = buses.loc[c_b & buses.substation_off, ["x", "y"]].rename_axis(
"name"
)
offshore_regions_c = gpd.GeoDataFrame(
{
"name": offshore_locs.index,
"x": offshore_locs["x"],
"y": offshore_locs["y"],
"geometry": voronoi(offshore_locs, offshore_shape),
"country": country,
},
crs=crs,
)
sel = offshore_regions_c.to_crs(3035).area > 10 # m2
offshore_regions_c = offshore_regions_c.loc[sel]
offshore_regions.append(offshore_regions_c)
return offshore_regions
def build_bus_shapes(
n: pypsa.Network,
admin_shapes: gpd.GeoDataFrame,
offshore_shapes: str,
countries: list[str],
) -> tuple[
list[gpd.GeoDataFrame], list[gpd.GeoDataFrame], gpd.GeoDataFrame, gpd.GeoDataFrame
]:
"""
Build onshore and offshore regions for buses in the network.
Parameters
----------
n (pypsa.Network) : The network for which the bus shapes will be built.
admin_shapes (gpd.GeoDataFrame) : GeoDataFrame with administrative region shapes indexed by name.
offshore_shapes (str) : Path to the file containing offshore shapes.
countries (list[str]) : List of country codes to process.
Returns
-------
tuple[list[gpd.GeoDataFrame], list[gpd.GeoDataFrame], gpd.GeoDataFrame, gpd.GeoDataFrame]
A tuple containing:
- List of GeoDataFrames for each onshore region
- List of GeoDataFrames for each offshore region
- Combined GeoDataFrame of all onshore shapes
- Combined GeoDataFrame of all offshore shapes
"""
offshore_shapes = gpd.read_file(offshore_shapes)
offshore_shapes = offshore_shapes.reindex(columns=REGION_COLS).set_index("name")[
"geometry"
]
buses = n.buses[
["x", "y", "country", "onshore_bus", "substation_lv", "substation_off"]
].copy()
buses["geometry"] = gpd.points_from_xy(buses["x"], buses["y"])
buses = gpd.GeoDataFrame(buses, geometry="geometry", crs="EPSG:4326")
buses["admin"] = ""
# Map buses per country
for country in countries:
buses_subset = buses.loc[buses["country"] == country]
buses.loc[buses_subset.index, "admin"] = gpd.sjoin_nearest(
buses_subset.to_crs(epsg=3857),
admin_shapes.loc[admin_shapes["country"] == country].to_crs(epsg=3857),
how="left",
)["admin_right"]
# Create Voronoi polygons for each administrative region.
# If administrative clustering is deactivated, voronoi cells are created on a country level.
admin_regions = sorted(
set(buses.admin.unique()).intersection(admin_shapes.index.unique())
)
# Onshore regions
nprocesses = snakemake.threads
tqdm_kwargs = dict(
ascii=False,
unit=" regions",
total=len(admin_regions),
desc="Building onshore regions",
)
func = partial(
process_onshore_regions,
buses=buses,
admin_shapes=admin_shapes,
crs=n.crs.name,
)
with mp.Pool(processes=nprocesses) as pool:
onshore_regions = list(tqdm(pool.imap(func, admin_regions), **tqdm_kwargs))
onshore_shapes = pd.concat(onshore_regions, ignore_index=True).set_crs(n.crs)
logger.info(f"In total {len(onshore_shapes)} onshore regions.")
# Offshore regions
offshore_regions = process_offshore_regions(
buses,
offshore_shapes,
countries,
n.crs.name,
)
if offshore_regions:
offshore_shapes = pd.concat(offshore_regions, ignore_index=True).set_crs(n.crs)
else:
offshore_shapes = gpd.GeoDataFrame(
columns=["name", "geometry"], crs=n.crs