forked from open-energy-transition/pypsa-eur
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathprepare_sector_network.py
More file actions
executable file
·7857 lines (6904 loc) · 268 KB
/
Copy pathprepare_sector_network.py
File metadata and controls
executable file
·7857 lines (6904 loc) · 268 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: Open Energy Transition gGmbH and contributors to PyPSA-Eur <https://github.com/pypsa/pypsa-eur>
#
# SPDX-License-Identifier: MIT
"""
Adds all sector-coupling components to the network, including demand and supply
technologies for the buildings, transport and industry sectors.
"""
import logging
import os
from itertools import product
from types import SimpleNamespace
import geopandas as gpd
import networkx as nx
import numpy as np
import pandas as pd
import pypsa
import xarray as xr
from networkx.algorithms import complement
from networkx.algorithms.connectivity.edge_augmentation import k_edge_augmentation
from pypsa.geo import haversine_pts
from scipy.stats import beta
from scripts._helpers import (
configure_logging,
get,
make_index,
set_scenario_config,
update_config_from_wildcards,
)
from scripts.add_electricity import (
attach_load,
calculate_annuity,
flatten,
load_costs,
sanitize_carriers,
sanitize_locations,
)
from scripts.build_energy_totals import (
build_co2_totals,
build_eea_co2,
build_eurostat,
build_eurostat_co2,
)
from scripts.build_transport_demand import transport_degree_factor
from scripts.definitions.heat_sector import HeatSector
from scripts.definitions.heat_system import HeatSystem
from scripts.prepare_network import maybe_adjust_costs_and_potentials
spatial = SimpleNamespace()
logger = logging.getLogger(__name__)
def define_spatial(nodes, options, offshore_buses_fn=None, buses_h2_file=None):
"""
Namespace for spatial.
Parameters
----------
nodes : list-like
Nodes to define spatial data for
options : dict
Configuration options containing at least:
- biomass_spatial : bool
- co2_spatial : bool
- gas_network : bool
- ammonia : bool
- h2_topology_tyndp : bool
- methanol : dict
- regional_oil_demand : bool
- regional_coal_demand : bool
buses_h2_file : str
Path to the file containing TYNDP H2 buses information.
offshore_buses_fn : str
Path to the file containing offshore bus data.
"""
spatial.nodes = nodes
# offshore hubs
if options["offshore_hubs_tyndp"]["enable"] and offshore_buses_fn:
spatial.offshore_hubs = SimpleNamespace()
offshore_buses = pd.read_csv(offshore_buses_fn, index_col=0)
offshore_buses_h2 = offshore_buses.set_index(offshore_buses.index + " H2")
spatial.offshore_hubs.nodes = offshore_buses.index
spatial.offshore_hubs.nodes_h2 = offshore_buses_h2.index
spatial.offshore_hubs.carrier = pd.Series("AC_OH", index=offshore_buses.index)
spatial.offshore_hubs.carrier_h2 = pd.Series(
"H2_OH", index=offshore_buses_h2.index
)
spatial.offshore_hubs.x = offshore_buses.x
spatial.offshore_hubs.y = offshore_buses.y
spatial.offshore_hubs.x_h2 = offshore_buses_h2.x
spatial.offshore_hubs.y_h2 = offshore_buses_h2.y
spatial.offshore_hubs.locations = offshore_buses.location
spatial.offshore_hubs.locations_h2 = offshore_buses_h2.location
spatial.offshore_hubs.country = offshore_buses.location.str[:2]
spatial.offshore_hubs.country_h2 = offshore_buses_h2.location.str[:2]
spatial.offshore_hubs.type = offshore_buses.type
spatial.offshore_hubs.type_h2 = offshore_buses_h2.type
# biomass
spatial.biomass = SimpleNamespace()
spatial.msw = SimpleNamespace()
if options.get("biomass_spatial", options["biomass_transport"]):
spatial.biomass.nodes = nodes + " solid biomass"
spatial.biomass.nodes_unsustainable = nodes + " unsustainable solid biomass"
spatial.biomass.bioliquids = nodes + " unsustainable bioliquids"
spatial.biomass.locations = nodes
spatial.biomass.industry = nodes + " solid biomass for industry"
spatial.biomass.industry_cc = nodes + " solid biomass for industry CC"
spatial.msw.nodes = nodes + " municipal solid waste"
spatial.msw.locations = nodes
else:
spatial.biomass.nodes = ["EU solid biomass"]
spatial.biomass.nodes_unsustainable = ["EU unsustainable solid biomass"]
spatial.biomass.bioliquids = ["EU unsustainable bioliquids"]
spatial.biomass.locations = ["EU"]
spatial.biomass.industry = ["solid biomass for industry"]
spatial.biomass.industry_cc = ["solid biomass for industry CC"]
spatial.msw.nodes = ["EU municipal solid waste"]
spatial.msw.locations = ["EU"]
spatial.biomass.df = pd.DataFrame(vars(spatial.biomass), index=nodes)
spatial.msw.df = pd.DataFrame(vars(spatial.msw), index=nodes)
# co2
spatial.co2 = SimpleNamespace()
if options["co2_spatial"]:
spatial.co2.nodes = nodes + " co2 stored"
spatial.co2.locations = nodes
spatial.co2.vents = nodes + " co2 vent"
spatial.co2.process_emissions = nodes + " process emissions"
else:
spatial.co2.nodes = ["co2 stored"]
spatial.co2.locations = ["EU"]
spatial.co2.vents = ["co2 vent"]
spatial.co2.process_emissions = ["process emissions"]
spatial.co2.df = pd.DataFrame(vars(spatial.co2), index=nodes)
# gas
spatial.gas = SimpleNamespace()
if options["gas_network"]:
spatial.gas.nodes = nodes + " gas"
spatial.gas.locations = nodes
spatial.gas.biogas = nodes + " biogas"
spatial.gas.industry = nodes + " gas for industry"
spatial.gas.industry_cc = nodes + " gas for industry CC"
spatial.gas.biogas_to_gas = nodes + " biogas to gas"
spatial.gas.biogas_to_gas_cc = nodes + " biogas to gas CC"
else:
spatial.gas.nodes = ["EU gas"]
spatial.gas.locations = ["EU"]
spatial.gas.biogas = ["EU biogas"]
spatial.gas.industry = ["gas for industry"]
spatial.gas.biogas_to_gas = ["EU biogas to gas"]
if options.get("biomass_spatial", options["biomass_transport"]):
spatial.gas.biogas_to_gas_cc = nodes + " biogas to gas CC"
else:
spatial.gas.biogas_to_gas_cc = ["EU biogas to gas CC"]
if options.get("co2_spatial", options["co2_network"]):
spatial.gas.industry_cc = nodes + " gas for industry CC"
else:
spatial.gas.industry_cc = ["gas for industry CC"]
spatial.gas.df = pd.DataFrame(vars(spatial.gas), index=nodes)
# ammonia
if options["ammonia"]:
spatial.ammonia = SimpleNamespace()
if options["ammonia"] == "regional":
spatial.ammonia.nodes = nodes + " NH3"
spatial.ammonia.locations = nodes
else:
spatial.ammonia.nodes = ["EU NH3"]
spatial.ammonia.locations = ["EU"]
spatial.ammonia.df = pd.DataFrame(vars(spatial.ammonia), index=nodes)
# hydrogen
spatial.h2 = SimpleNamespace()
spatial.h2.nodes = nodes + " H2"
spatial.h2.locations = nodes
# hydrogen tyndp
if options["h2_topology_tyndp"] and buses_h2_file:
spatial.h2_tyndp = SimpleNamespace()
buses_h2 = gpd.read_file(buses_h2_file).set_index("bus_id")
spatial.h2_tyndp.nodes = pd.Index(
(buses_h2.index + " Z1").append(buses_h2.index + " Z2")
)
spatial.h2_tyndp.locations = pd.Index(np.tile(buses_h2.index + " Z2", 2))
spatial.h2_tyndp.country = pd.Index(np.tile(buses_h2.country, 2))
spatial.h2_tyndp.x = pd.Index(np.tile(buses_h2.x, 2))
spatial.h2_tyndp.y = pd.Index(np.tile(buses_h2.y, 2))
spatial.h2_tyndp.df = pd.DataFrame(
vars(spatial.h2_tyndp),
index=pd.Index((buses_h2.index + " Z1").append(buses_h2.index + " Z2")),
)
# methanol
# beware: unlike other carriers, uses locations rather than locations+carriername
# this allows to avoid separation between nodes and locations
spatial.methanol = SimpleNamespace()
spatial.methanol.nodes = ["EU methanol"]
spatial.methanol.locations = ["EU"]
if options["methanol"]["regional_methanol_demand"]:
spatial.methanol.demand_locations = nodes
spatial.methanol.industry = nodes + " industry methanol"
spatial.methanol.shipping = nodes + " shipping methanol"
else:
spatial.methanol.demand_locations = ["EU"]
spatial.methanol.shipping = ["EU shipping methanol"]
spatial.methanol.industry = ["EU industry methanol"]
# oil
spatial.oil = SimpleNamespace()
spatial.oil.nodes = ["EU oil"]
spatial.oil.locations = ["EU"]
if options["regional_oil_demand"]:
spatial.oil.demand_locations = nodes
spatial.oil.naphtha = nodes + " naphtha for industry"
spatial.oil.non_sequestered_hvc = nodes + " non-sequestered HVC"
spatial.oil.kerosene = nodes + " kerosene for aviation"
spatial.oil.shipping = nodes + " shipping oil"
spatial.oil.agriculture_machinery = nodes + " agriculture machinery oil"
spatial.oil.land_transport = nodes + " land transport oil"
else:
spatial.oil.demand_locations = ["EU"]
spatial.oil.naphtha = ["EU naphtha for industry"]
spatial.oil.non_sequestered_hvc = ["EU non-sequestered HVC"]
spatial.oil.kerosene = ["EU kerosene for aviation"]
spatial.oil.shipping = ["EU shipping oil"]
spatial.oil.agriculture_machinery = ["EU agriculture machinery oil"]
spatial.oil.land_transport = ["EU land transport oil"]
# uranium
spatial.uranium = SimpleNamespace()
spatial.uranium.nodes = ["EU uranium"]
spatial.uranium.locations = ["EU"]
# coal
spatial.coal = SimpleNamespace()
spatial.coal.nodes = ["EU coal"]
spatial.coal.locations = ["EU"]
if options["regional_coal_demand"]:
spatial.coal.demand_locations = nodes
spatial.coal.industry = nodes + " coal for industry"
else:
spatial.coal.demand_locations = ["EU"]
spatial.coal.industry = ["EU coal for industry"]
# lignite
spatial.lignite = SimpleNamespace()
spatial.lignite.nodes = ["EU lignite"]
spatial.lignite.locations = ["EU"]
# deep geothermal
spatial.geothermal_heat = SimpleNamespace()
spatial.geothermal_heat.nodes = ["EU enhanced geothermal systems"]
spatial.geothermal_heat.locations = ["EU"]
return spatial
spatial = SimpleNamespace()
def determine_emission_sectors(options):
sectors = ["electricity"]
if options["transport"]:
sectors += ["rail non-elec", "road non-elec"]
if options["heating"]:
sectors += ["residential non-elec", "services non-elec"]
if options["industry"]:
sectors += [
"industrial non-elec",
"industrial processes",
"domestic aviation",
"international aviation",
"domestic navigation",
"international navigation",
]
if options["agriculture"]:
sectors += ["agriculture"]
return sectors
def co2_emissions_year(
countries, input_eurostat, options, emissions_scope, input_co2, year
):
"""
Calculate CO2 emissions in one specific year (e.g. 1990 or 2018).
"""
eea_co2 = build_eea_co2(input_co2, year, emissions_scope)
eurostat = build_eurostat(input_eurostat, countries)
# this only affects the estimation of CO2 emissions for BA, RS, AL, ME, MK, XK
eurostat_co2 = build_eurostat_co2(eurostat, year)
co2_totals = build_co2_totals(countries, eea_co2, eurostat_co2)
sectors = determine_emission_sectors(options)
co2_emissions = co2_totals.loc[countries, sectors].sum().sum()
# convert MtCO2 to GtCO2
co2_emissions *= 0.001
return co2_emissions
# TODO: move to own rule with sector-opts wildcard?
def build_carbon_budget(
o,
input_eurostat,
fn,
emissions_scope,
input_co2,
options,
countries,
planning_horizons,
):
"""
Distribute carbon budget following beta or exponential transition path.
"""
if "be" in o:
# beta decay
carbon_budget = float(o[o.find("cb") + 2 : o.find("be")])
be = float(o[o.find("be") + 2 :])
if "ex" in o:
# exponential decay
carbon_budget = float(o[o.find("cb") + 2 : o.find("ex")])
r = float(o[o.find("ex") + 2 :])
e_1990 = co2_emissions_year(
countries,
input_eurostat,
options,
emissions_scope,
input_co2,
year=1990,
)
# emissions at the beginning of the path (last year available 2018)
e_0 = co2_emissions_year(
countries,
input_eurostat,
options,
emissions_scope,
input_co2,
year=2018,
)
if not isinstance(planning_horizons, list):
planning_horizons = [planning_horizons]
t_0 = planning_horizons[0]
if "be" in o:
# final year in the path
t_f = t_0 + (2 * carbon_budget / e_0).round(0)
def beta_decay(t):
cdf_term = (t - t_0) / (t_f - t_0)
return (e_0 / e_1990) * (1 - beta.cdf(cdf_term, be, be))
# emissions (relative to 1990)
co2_cap = pd.Series({t: beta_decay(t) for t in planning_horizons}, name=o)
elif "ex" in o:
T = carbon_budget / e_0
m = (1 + np.sqrt(1 + r * T)) / T
def exponential_decay(t):
return (e_0 / e_1990) * (1 + (m + r) * (t - t_0)) * np.exp(-m * (t - t_0))
co2_cap = pd.Series(
{t: exponential_decay(t) for t in planning_horizons}, name=o
)
else:
raise ValueError("Transition path must be either beta or exponential decay")
# TODO log in Snakefile
csvs_folder = fn.rsplit("/", 1)[0]
if not os.path.exists(csvs_folder):
os.makedirs(csvs_folder)
co2_cap.to_csv(fn, float_format="%.3f")
def add_lifetime_wind_solar(n, costs):
"""
Add lifetime for solar and wind generators.
"""
for carrier in ["solar", "onwind", "offwind"]:
gen_i = n.generators.index.str.contains(carrier)
n.generators.loc[gen_i, "lifetime"] = costs.at[carrier, "lifetime"]
def haversine(p, n):
coord0 = n.buses.loc[p.bus0, ["x", "y"]].values
coord1 = n.buses.loc[p.bus1, ["x", "y"]].values
return 1.5 * haversine_pts(coord0, coord1)
def create_network_topology(
n, prefix, carriers=["DC"], connector=" -> ", bidirectional=True
):
"""
Create a network topology from transmission lines and link carrier
selection.
Parameters
----------
n : pypsa.Network
prefix : str
carriers : list-like
connector : str
bidirectional : bool, default True
True: one link for each connection
False: one link for each connection and direction (back and forth)
Returns
-------
pd.DataFrame with columns bus0, bus1, length, underwater_fraction
"""
ln_attrs = ["bus0", "bus1", "length"]
lk_attrs = ["bus0", "bus1", "length", "underwater_fraction"]
lk_attrs = n.links.columns.intersection(lk_attrs)
candidates = pd.concat(
[n.lines[ln_attrs], n.links.loc[n.links.carrier.isin(carriers), lk_attrs]]
).fillna(0)
# base network topology purely on location not carrier
candidates["bus0"] = candidates.bus0.map(n.buses.location)
candidates["bus1"] = candidates.bus1.map(n.buses.location)
positive_order = candidates.bus0 < candidates.bus1
candidates_p = candidates[positive_order]
swap_buses = {"bus0": "bus1", "bus1": "bus0"}
candidates_n = candidates[~positive_order].rename(columns=swap_buses)
candidates = pd.concat([candidates_p, candidates_n])
topo = candidates.groupby(["bus0", "bus1"], as_index=False).mean()
topo.index = topo.apply(make_index, axis=1, prefix=prefix, connector=connector)
if not bidirectional:
topo_reverse = topo.copy()
topo_reverse.rename(columns=swap_buses, inplace=True)
topo_reverse.index = topo_reverse.apply(make_index, axis=1)
topo = pd.concat([topo, topo_reverse])
return topo
def create_h2_topology_tyndp(n, fn_h2_network):
"""
Create a TYNDP H2 network topology from the TYNDP H2 reference grid.
Parameters
----------
n : pypsa.Network
Network to create H2 topology for
fn_h2_network : str
Pointing to the input TYNDP H2 reference grid csv file
Returns
-------
pd.DataFrame with columns bus0, bus1, length, underwater_fraction
"""
# load H2 pipes
h2_pipes = pd.read_csv(fn_h2_network, index_col=0)
h2_pipes = h2_pipes.assign(
bus0=h2_pipes.bus0 + " H2 Z2", bus1=h2_pipes.bus1 + " H2 Z2"
)
h2_pipes["length"] = h2_pipes.apply(haversine, axis=1, args=(n,))
return h2_pipes
def update_wind_solar_costs(
n: pypsa.Network,
costs: pd.DataFrame,
profiles: dict[str, str],
landfall_lengths: dict = None,
line_length_factor: int | float = 1,
) -> None:
"""
Update costs for wind and solar generators added with pypsa-eur to those
cost in the planning year.
Parameters
----------
n : pypsa.Network
Network to update generator costs
costs : pd.DataFrame
Cost assumptions DataFrame
line_length_factor : int | float, optional
Factor to multiply line lengths by, by default 1
landfall_lengths : dict, optional
Dictionary of landfall lengths per technology, by default None
profiles : dict[str, str]
Dictionary mapping technology names to profile file paths
e.g. {'offwind-dc': 'path/to/profile.nc'}
"""
if landfall_lengths is None:
landfall_lengths = {}
# NB: solar costs are also manipulated for rooftop
# when distribution grid is inserted
n.generators.loc[n.generators.carrier == "solar", "capital_cost"] = costs.at[
"solar-utility", "capital_cost"
]
n.generators.loc[n.generators.carrier == "onwind", "capital_cost"] = costs.at[
"onwind", "capital_cost"
]
# for offshore wind, need to calculated connection costs
for key, fn in profiles.items():
tech = key[len("profile_") :]
landfall_length = landfall_lengths.get(tech, 0.0)
if tech not in n.generators.carrier.values:
continue
with xr.open_dataset(fn) as ds:
# if-statement for compatibility with old profiles
if "year" in ds.indexes:
ds = ds.sel(year=ds.year.min(), drop=True)
ds = ds.stack(bus_bin=["bus", "bin"])
distance = ds["average_distance"].to_pandas()
distance.index = distance.index.map(flatten)
submarine_cost = costs.at[tech + "-connection-submarine", "capital_cost"]
underground_cost = costs.at[
tech + "-connection-underground", "capital_cost"
]
connection_cost = line_length_factor * (
distance * submarine_cost + landfall_length * underground_cost
)
# Take 'offwind-float' capital cost for 'float', and 'offwind' capital cost for the rest ('ac' and 'dc')
midtech = tech.split("-", 2)[1]
if midtech == "float":
capital_cost = (
costs.at[tech, "capital_cost"]
+ costs.at[tech + "-station", "capital_cost"]
+ connection_cost
)
else:
capital_cost = (
costs.at["offwind", "capital_cost"]
+ costs.at[tech + "-station", "capital_cost"]
+ connection_cost
)
logger.info(
f"Added connection cost of {connection_cost.min():0.0f}-{connection_cost.max():0.0f} Eur/MW/a to {tech}"
)
n.generators.loc[n.generators.carrier == tech, "capital_cost"] = (
capital_cost.rename(index=lambda node: node + " " + tech)
)
def add_carrier_buses(
n: pypsa.Network,
carrier: str,
costs: pd.DataFrame,
spatial: SimpleNamespace,
options: dict,
cf_industry: dict | None = None,
nodes: pd.Index | list | set | None = None,
) -> None:
"""
Add buses and associated components for a specific carrier to the network.
Creates a new carrier type in the network and adds corresponding buses, stores,
and potentially generators depending on the carrier type. Special handling is
implemented for fossil fuels, particularly oil which may include refining processes.
Parameters
----------
n : pypsa.Network
The PyPSA network container object
carrier : str
Name of the energy carrier (e.g., 'gas', 'oil', 'coal', 'nuclear')
costs : pd.DataFrame
DataFrame containing cost assumptions for different technologies and fuels
spatial : SimpleNamespace
Namespace containing spatial information for different carriers, including
nodes and locations
options : dict
Configuration dictionary, must contain 'fossil_fuels' boolean
cf_industry : dict, optional
Dictionary of industrial conversion factors, must contain 'oil_refining_emissions'
if carrier is 'oil'
nodes : pd.Index or list or set, optional
Nodes where the carrier should be added. If None, nodes are taken from
spatial data for the carrier
Returns
-------
None
Modifies the network object in-place by adding new components
Notes
-----
- For gas carriers, energy is tracked in MWh_LHV (Lower Heating Value)
- For other carriers, energy is tracked in MWh_th (thermal)
- Special handling is implemented for oil refining emissions
- Storage costs are technology-specific and based on volumetric capacity
"""
if nodes is None:
nodes = vars(spatial)[carrier].nodes
location = vars(spatial)[carrier].locations
# skip if carrier already exists
if carrier in n.carriers.index:
return
if not isinstance(nodes, pd.Index):
nodes = pd.Index(nodes)
n.add("Carrier", carrier)
unit = "MWh_LHV" if carrier == "gas" else "MWh_th"
# Calculate carrier-specific storage costs
if carrier == "gas":
capital_cost = costs.at["gas storage", "capital_cost"]
elif carrier == "oil":
# based on https://www.engineeringtoolbox.com/fuels-higher-calorific-values-d_169.html
mwh_per_m3 = 44.9 * 724 * 0.278 * 1e-3 # MJ/kg * kg/m3 * kWh/MJ * MWh/kWh
capital_cost = (
costs.at["General liquid hydrocarbon storage (product)", "capital_cost"]
/ mwh_per_m3
)
elif carrier == "methanol":
# based on https://www.engineeringtoolbox.com/fossil-fuels-energy-content-d_1298.html
mwh_per_m3 = 5.54 * 791 * 1e-3 # kWh/kg * kg/m3 * MWh/kWh
capital_cost = (
costs.at["General liquid hydrocarbon storage (product)", "capital_cost"]
/ mwh_per_m3
)
else:
capital_cost = 0.1
n.add("Bus", nodes, location=location, carrier=carrier, unit=unit)
n.add(
"Store",
nodes + " Store",
bus=nodes,
e_nom_extendable=True,
e_cyclic=True,
carrier=carrier,
capital_cost=capital_cost,
)
fossils = ["coal", "gas", "oil", "lignite"]
if options["fossil_fuels"] and carrier in fossils:
suffix = ""
if carrier == "oil" and cf_industry["oil_refining_emissions"] > 0:
n.add(
"Bus",
nodes + " primary",
location=location,
carrier=carrier + " primary",
unit=unit,
)
n.add(
"Link",
nodes + " refining",
bus0=nodes + " primary",
bus1=nodes,
bus2="co2 atmosphere",
location=location,
carrier=carrier + " refining",
p_nom=1e6,
efficiency=1
- (
cf_industry["oil_refining_emissions"]
/ costs.at[carrier, "CO2 intensity"]
),
efficiency2=cf_industry["oil_refining_emissions"],
)
suffix = " primary"
n.add(
"Generator",
nodes + suffix,
bus=nodes + suffix,
p_nom_extendable=True,
carrier=carrier + suffix,
marginal_cost=costs.at[carrier, "fuel"],
)
# TODO: PyPSA-Eur merge issue
def remove_elec_base_techs(n: pypsa.Network, carriers_to_keep: dict) -> None:
"""
Remove conventional generators (e.g. OCGT) and storage units (e.g.
batteries and H2) from base electricity-only network, since they're added
here differently using links.
Parameters
----------
n : pypsa.Network
Network to remove components from
carriers_to_keep : dict
Dictionary specifying which carriers to keep for each component type
e.g. {'Generator': ['hydro'], 'StorageUnit': ['PHS']}
"""
for c in n.iterate_components(carriers_to_keep):
to_keep = carriers_to_keep[c.name]
to_remove = pd.Index(c.df.carrier.unique()).symmetric_difference(to_keep)
if to_remove.empty:
continue
logger.info(f"Removing {c.list_name} with carrier {list(to_remove)}")
names = c.df.index[c.df.carrier.isin(to_remove)]
n.remove(c.name, names)
n.carriers.drop(to_remove, inplace=True, errors="ignore")
# TODO: PyPSA-Eur merge issue
def remove_non_electric_buses(n):
"""
Remove buses from pypsa-eur with carriers which are not AC buses.
"""
if to_drop := list(n.buses.query("carrier not in ['AC', 'DC']").carrier.unique()):
logger.info(f"Drop buses from PyPSA-Eur with carrier: {to_drop}")
n.buses = n.buses[n.buses.carrier.isin(["AC", "DC"])]
def patch_electricity_network(n, costs, carriers_to_keep, profiles, landfall_lengths):
remove_elec_base_techs(n, carriers_to_keep)
remove_non_electric_buses(n)
update_wind_solar_costs(
n, costs, landfall_lengths=landfall_lengths, profiles=profiles
)
n.loads["carrier"] = "electricity"
n.buses["location"] = n.buses.index
n.buses["unit"] = "MWh_el"
# remove trailing white space of load index until new PyPSA version after v0.18.
n.loads.rename(lambda x: x.strip(), inplace=True)
n.loads_t.p_set.rename(lambda x: x.strip(), axis=1, inplace=True)
def add_eu_bus(n, x=-5.5, y=46):
"""
Add EU bus to the network.
This cosmetic bus serves as a reference point for the location of
the EU buses in the plots and summaries.
"""
n.add("Bus", "EU", location="EU", x=x, y=y, carrier="none")
n.add("Carrier", "none")
def add_co2_tracking(n, costs, options, sequestration_potential_file=None):
"""
Add CO2 tracking components to the network including atmospheric CO2,
CO2 storage, and sequestration infrastructure.
Parameters
----------
n : pypsa.Network
The PyPSA network container object
costs : pd.DataFrame
Cost assumptions for different technologies, must include
'CO2 storage tank' with 'capital_cost' column
options : dict
Configuration options containing at least:
- regional_co2_sequestration_potential: dict with keys
- enable: bool
- max_size: float
- years_of_storage: float
- co2_sequestration_cost: float
- co2_sequestration_lifetime: float
- co2_vent: bool
sequestration_potential_file : str, optional
Path to CSV file containing regional CO2 sequestration potentials.
Required if options['regional_co2_sequestration_potential']['enable'] is True.
Returns
-------
None
Modifies the network object in-place by adding CO2-related components.
Notes
-----
Adds several components to track CO2:
- Atmospheric CO2 store
- CO2 storage tanks
- CO2 sequestration infrastructure
- Optional CO2 venting facilities
"""
# minus sign because opposite to how fossil fuels used:
# CH4 burning puts CH4 down, atmosphere up
n.add("Carrier", "co2", co2_emissions=-1.0)
# this tracks CO2 in the atmosphere
n.add("Bus", "co2 atmosphere", location="EU", carrier="co2", unit="t_co2")
# can also be negative
n.add(
"Store",
"co2 atmosphere",
e_nom_extendable=True,
e_min_pu=-1,
carrier="co2",
bus="co2 atmosphere",
)
# add CO2 tanks
n.add(
"Bus",
spatial.co2.nodes,
location=spatial.co2.locations,
carrier="co2 stored",
unit="t_co2",
)
n.add(
"Store",
spatial.co2.nodes,
e_nom_extendable=True,
capital_cost=costs.at["CO2 storage tank", "capital_cost"],
carrier="co2 stored",
e_cyclic=True,
bus=spatial.co2.nodes,
)
n.add("Carrier", "co2 stored")
# this tracks CO2 sequestered, e.g. underground
sequestration_buses = pd.Index(spatial.co2.nodes).str.replace(
" stored", " sequestered"
)
n.add(
"Bus",
sequestration_buses,
location=spatial.co2.locations,
carrier="co2 sequestered",
unit="t_co2",
)
n.add(
"Link",
sequestration_buses,
bus0=spatial.co2.nodes,
bus1=sequestration_buses,
carrier="co2 sequestered",
efficiency=1.0,
p_nom_extendable=True,
)
if options["regional_co2_sequestration_potential"]["enable"]:
if sequestration_potential_file is None:
raise ValueError(
"sequestration_potential_file must be provided when "
"regional_co2_sequestration_potential is enabled"
)
upper_limit = (
options["regional_co2_sequestration_potential"]["max_size"] * 1e3
) # Mt
annualiser = options["regional_co2_sequestration_potential"]["years_of_storage"]
e_nom_max = pd.read_csv(sequestration_potential_file, index_col=0).squeeze()
e_nom_max = (
e_nom_max.reindex(spatial.co2.locations)
.fillna(0.0)
.clip(upper=upper_limit)
.mul(1e6)
/ annualiser
) # t
e_nom_max = e_nom_max.rename(index=lambda x: x + " co2 sequestered")
else:
e_nom_max = np.inf
n.add(
"Store",
sequestration_buses,
e_nom_extendable=True,
e_nom_max=e_nom_max,
capital_cost=options["co2_sequestration_cost"],
marginal_cost=-0.1,
bus=sequestration_buses,
lifetime=options["co2_sequestration_lifetime"],
carrier="co2 sequestered",
)
n.add("Carrier", "co2 sequestered")
if options["co2_vent"]:
n.add(
"Link",
spatial.co2.vents,
bus0=spatial.co2.nodes,
bus1="co2 atmosphere",
carrier="co2 vent",
efficiency=1.0,
p_nom_extendable=True,
)
def add_co2_network(n, costs, co2_network_cost_factor=1.0):
"""
Add CO2 transport network to the PyPSA network.
Creates a CO2 pipeline network with both onshore and submarine pipeline segments,
considering different costs for each type. The network allows bidirectional flow
and is extendable.
Parameters
----------
n : pypsa.Network
The PyPSA network container object
costs : pd.DataFrame
Cost assumptions for different technologies. Must contain entries for
'CO2 pipeline' and 'CO2 submarine pipeline' with 'capital_cost' and 'lifetime'
columns
co2_network_cost_factor : float, optional
Factor to scale the capital costs of the CO2 network, default 1.0
Returns
-------
None
Modifies the network object in-place by adding CO2 pipeline links
Notes
-----
The function creates bidirectional CO2 pipeline links between nodes, with costs
depending on the underwater fraction of the pipeline. The network topology is
created using the create_network_topology helper function.
"""
logger.info("Adding CO2 network.")
co2_links = create_network_topology(n, "CO2 pipeline ")
if "underwater_fraction" not in co2_links.columns:
co2_links["underwater_fraction"] = 0.0
cost_onshore = (
(1 - co2_links.underwater_fraction)
* costs.at["CO2 pipeline", "capital_cost"]
* co2_links.length
)
cost_submarine = (
co2_links.underwater_fraction
* costs.at["CO2 submarine pipeline", "capital_cost"]
* co2_links.length
)
capital_cost = cost_onshore + cost_submarine
capital_cost *= co2_network_cost_factor
n.add(
"Link",
co2_links.index,
bus0=co2_links.bus0.values + " co2 stored",
bus1=co2_links.bus1.values + " co2 stored",
p_min_pu=-1,
p_nom_extendable=True,
length=co2_links.length.values,
capital_cost=capital_cost.values,
carrier="CO2 pipeline",
lifetime=costs.at["CO2 pipeline", "lifetime"],
)
def add_allam_gas(
n: pypsa.Network,
costs: pd.DataFrame,
pop_layout: pd.DataFrame,