/
prepare_sector_network.py
2561 lines (2034 loc) · 91.1 KB
/
prepare_sector_network.py
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
# coding: utf-8
import pypsa
import re
import os
import pandas as pd
import numpy as np
import xarray as xr
import networkx as nx
from itertools import product
from scipy.stats import beta
from vresutils.costdata import annuity
from build_energy_totals import build_eea_co2, build_eurostat_co2, build_co2_totals
from helper import override_component_attrs, generate_periodic_profiles, update_config_with_sector_opts
from networkx.algorithms.connectivity.edge_augmentation import k_edge_augmentation
from networkx.algorithms import complement
from pypsa.geo import haversine_pts
import logging
logger = logging.getLogger(__name__)
from types import SimpleNamespace
spatial = SimpleNamespace()
def define_spatial(nodes, options):
"""
Namespace for spatial
Parameters
----------
nodes : list-like
"""
global spatial
spatial.nodes = nodes
# biomass
spatial.biomass = SimpleNamespace()
if options["biomass_transport"]:
spatial.biomass.nodes = nodes + " solid biomass"
spatial.biomass.locations = nodes
spatial.biomass.industry = nodes + " solid biomass for industry"
spatial.biomass.industry_cc = nodes + " solid biomass for industry CC"
else:
spatial.biomass.nodes = ["EU solid biomass"]
spatial.biomass.locations = ["EU"]
spatial.biomass.industry = ["solid biomass for industry"]
spatial.biomass.industry_cc = ["solid biomass for industry CC"]
spatial.biomass.df = pd.DataFrame(vars(spatial.biomass), index=nodes)
# co2
spatial.co2 = SimpleNamespace()
if options["co2_network"]:
spatial.co2.nodes = nodes + " co2 stored"
spatial.co2.locations = nodes
spatial.co2.vents = nodes + " co2 vent"
else:
spatial.co2.nodes = ["co2 stored"]
spatial.co2.locations = ["EU"]
spatial.co2.vents = ["co2 vent"]
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"
else:
spatial.gas.nodes = ["EU gas"]
spatial.gas.locations = ["EU"]
spatial.gas.biogas = ["EU biogas"]
spatial.gas.industry = ["gas for industry"]
spatial.gas.industry_cc = ["gas for industry CC"]
spatial.gas.biogas_to_gas = ["EU biogas to gas"]
spatial.gas.df = pd.DataFrame(vars(spatial.gas), index=nodes)
# oil
spatial.oil = SimpleNamespace()
spatial.oil.nodes = ["EU oil"]
spatial.oil.locations = ["EU"]
# 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"]
# lignite
spatial.lignite = SimpleNamespace()
spatial.lignite.nodes = ["EU lignite"]
spatial.lignite.locations = ["EU"]
return spatial
from types import SimpleNamespace
spatial = SimpleNamespace()
def emission_sectors_from_opts(opts):
sectors = ["electricity"]
if "T" in opts:
sectors += [
"rail non-elec",
"road non-elec"
]
if "H" in opts:
sectors += [
"residential non-elec",
"services non-elec"
]
if "I" in opts:
sectors += [
"industrial non-elec",
"industrial processes",
"domestic aviation",
"international aviation",
"domestic navigation",
"international navigation"
]
if "A" in opts:
sectors += [
"agriculture"
]
return sectors
def get(item, investment_year=None):
"""Check whether item depends on investment year"""
if isinstance(item, dict):
return item[investment_year]
else:
return item
def co2_emissions_year(countries, opts, year):
"""
Calculate CO2 emissions in one specific year (e.g. 1990 or 2018).
"""
eea_co2 = build_eea_co2(year)
# TODO: read Eurostat data from year > 2014
# this only affects the estimation of CO2 emissions for BA, RS, AL, ME, MK
if year > 2014:
eurostat_co2 = build_eurostat_co2(year=2014)
else:
eurostat_co2 = build_eurostat_co2(year)
co2_totals = build_co2_totals(eea_co2, eurostat_co2)
sectors = emission_sectors_from_opts(opts)
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, fn):
"""
Distribute carbon budget following beta or exponential transition path.
"""
# opts?
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:])
countries = n.buses.country.dropna().unique()
e_1990 = co2_emissions_year(countries, opts, year=1990)
#emissions at the beginning of the path (last year available 2018)
e_0 = co2_emissions_year(countries, opts, year=2018)
planning_horizons = snakemake.config['scenario']['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)
if "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)
# TODO log in Snakefile
if not os.path.exists(fn):
os.makedirs(fn)
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):
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])
def make_index(c):
return prefix + c.bus0 + connector + c.bus1
topo = candidates.groupby(["bus0", "bus1"], as_index=False).mean()
topo.index = topo.apply(make_index, axis=1)
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
# TODO merge issue with PyPSA-Eur
def update_wind_solar_costs(n, costs):
"""
Update costs for wind and solar generators added with pypsa-eur to those
cost in the planning year
"""
#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', 'fixed']
n.generators.loc[n.generators.carrier=='onwind', 'capital_cost'] = costs.at['onwind', 'fixed']
#for offshore wind, need to calculated connection costs
#assign clustered bus
#map initial network -> simplified network
busmap_s = pd.read_csv(snakemake.input.busmap_s, index_col=0).squeeze()
busmap_s.index = busmap_s.index.astype(str)
busmap_s = busmap_s.astype(str)
#map simplified network -> clustered network
busmap = pd.read_csv(snakemake.input.busmap, index_col=0).squeeze()
busmap.index = busmap.index.astype(str)
busmap = busmap.astype(str)
#map initial network -> clustered network
clustermaps = busmap_s.map(busmap)
#code adapted from pypsa-eur/scripts/add_electricity.py
for connection in ['dc', 'ac']:
tech = "offwind-" + connection
profile = snakemake.input['profile_offwind_' + connection]
with xr.open_dataset(profile) as ds:
underwater_fraction = ds['underwater_fraction'].to_pandas()
connection_cost = (snakemake.config['costs']['lines']['length_factor'] *
ds['average_distance'].to_pandas() *
(underwater_fraction *
costs.at[tech + '-connection-submarine', 'fixed'] +
(1. - underwater_fraction) *
costs.at[tech + '-connection-underground', 'fixed']))
#convert to aggregated clusters with weighting
weight = ds['weight'].to_pandas()
#e.g. clusters == 37m means that VRE generators are left
#at clustering of simplified network, but that they are
#connected to 37-node network
if snakemake.wildcards.clusters[-1:] == "m":
genmap = busmap_s
else:
genmap = clustermaps
connection_cost = (connection_cost*weight).groupby(genmap).sum()/weight.groupby(genmap).sum()
capital_cost = (costs.at['offwind', 'fixed'] +
costs.at[tech + '-station', 'fixed'] +
connection_cost)
logger.info("Added connection cost of {:0.0f}-{:0.0f} Eur/MW/a to {}"
.format(connection_cost[0].min(), connection_cost[0].max(), tech))
n.generators.loc[n.generators.carrier==tech, 'capital_cost'] = capital_cost.rename(index=lambda node: node + ' ' + tech)
def add_carrier_buses(n, carrier, nodes=None):
"""
Add buses to connect e.g. coal, nuclear and oil plants
"""
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"
n.madd("Bus",
nodes,
location=location,
carrier=carrier,
unit=unit
)
#capital cost could be corrected to e.g. 0.2 EUR/kWh * annuity and O&M
n.madd("Store",
nodes + " Store",
bus=nodes,
e_nom_extendable=True,
e_cyclic=True,
carrier=carrier,
)
n.madd("Generator",
nodes,
bus=nodes,
p_nom_extendable=True,
carrier=carrier,
marginal_cost=costs.at[carrier, 'fuel']
)
# TODO: PyPSA-Eur merge issue
def remove_elec_base_techs(n):
"""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
"""
for c in n.iterate_components(snakemake.config["pypsa_eur"]):
to_keep = snakemake.config["pypsa_eur"][c.name]
to_remove = pd.Index(c.df.carrier.unique()).symmetric_difference(to_keep)
print("Removing", c.list_name, "with carrier", to_remove)
names = c.df.index[c.df.carrier.isin(to_remove)]
n.mremove(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
"""
print("drop buses from PyPSA-Eur with carrier: ", n.buses[~n.buses.carrier.isin(["AC", "DC"])].carrier.unique())
n.buses = n.buses[n.buses.carrier.isin(["AC", "DC"])]
def patch_electricity_network(n):
remove_elec_base_techs(n)
remove_non_electric_buses(n)
update_wind_solar_costs(n, costs)
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_co2_tracking(n, options):
# minus sign because opposite to how fossil fuels used:
# CH4 burning puts CH4 down, atmosphere up
n.add("Carrier", "co2",
co2_emissions=-1.)
# 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"
)
# this tracks CO2 stored, e.g. underground
n.madd("Bus",
spatial.co2.nodes,
location=spatial.co2.locations,
carrier="co2 stored",
unit="t_co2"
)
n.madd("Store",
spatial.co2.nodes,
e_nom_extendable=True,
e_nom_max=np.inf,
capital_cost=options['co2_sequestration_cost'],
carrier="co2 stored",
bus=spatial.co2.nodes
)
if options['co2_vent']:
n.madd("Link",
spatial.co2.vents,
bus0=spatial.co2.nodes,
bus1="co2 atmosphere",
carrier="co2 vent",
efficiency=1.,
p_nom_extendable=True
)
def add_co2_network(n, costs):
logger.info("Adding CO2 network.")
co2_links = create_network_topology(n, "CO2 pipeline ")
cost_onshore = (1 - co2_links.underwater_fraction) * costs.at['CO2 pipeline', 'fixed'] * co2_links.length
cost_submarine = co2_links.underwater_fraction * costs.at['CO2 submarine pipeline', 'fixed'] * co2_links.length
capital_cost = cost_onshore + cost_submarine
n.madd("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_dac(n, costs):
heat_carriers = ["urban central heat", "services urban decentral heat"]
heat_buses = n.buses.index[n.buses.carrier.isin(heat_carriers)]
locations = n.buses.location[heat_buses]
efficiency2 = -(costs.at['direct air capture', 'electricity-input'] + costs.at['direct air capture', 'compression-electricity-input'])
efficiency3 = -(costs.at['direct air capture', 'heat-input'] - costs.at['direct air capture', 'compression-heat-output'])
n.madd("Link",
heat_buses.str.replace(" heat", " DAC"),
bus0="co2 atmosphere",
bus1=spatial.co2.df.loc[locations, "nodes"].values,
bus2=locations.values,
bus3=heat_buses,
carrier="DAC",
capital_cost=costs.at['direct air capture', 'fixed'],
efficiency=1.,
efficiency2=efficiency2,
efficiency3=efficiency3,
p_nom_extendable=True,
lifetime=costs.at['direct air capture', 'lifetime']
)
def add_co2limit(n, Nyears=1., limit=0.):
logger.info(f"Adding CO2 budget limit as per unit of 1990 levels of {limit}")
countries = n.buses.country.dropna().unique()
sectors = emission_sectors_from_opts(opts)
# convert Mt to tCO2
co2_totals = 1e6 * pd.read_csv(snakemake.input.co2_totals_name, index_col=0)
co2_limit = co2_totals.loc[countries, sectors].sum().sum()
co2_limit *= limit * Nyears
n.add("GlobalConstraint",
"CO2Limit",
carrier_attribute="co2_emissions",
sense="<=",
constant=co2_limit
)
# TODO PyPSA-Eur merge issue
def average_every_nhours(n, offset):
logger.info(f'Resampling the network to {offset}')
m = n.copy(with_time=False)
snapshot_weightings = n.snapshot_weightings.resample(offset).sum()
m.set_snapshots(snapshot_weightings.index)
m.snapshot_weightings = snapshot_weightings
for c in n.iterate_components():
pnl = getattr(m, c.list_name+"_t")
for k, df in c.pnl.items():
if not df.empty:
if c.list_name == "stores" and k == "e_max_pu":
pnl[k] = df.resample(offset).min()
elif c.list_name == "stores" and k == "e_min_pu":
pnl[k] = df.resample(offset).max()
else:
pnl[k] = df.resample(offset).mean()
return m
def cycling_shift(df, steps=1):
"""Cyclic shift on index of pd.Series|pd.DataFrame by number of steps"""
df = df.copy()
new_index = np.roll(df.index, steps)
df.values[:] = df.reindex(index=new_index).values
return df
# TODO checkout PyPSA-Eur script
def prepare_costs(cost_file, USD_to_EUR, discount_rate, Nyears, lifetime):
#set all asset costs and other parameters
costs = pd.read_csv(cost_file, index_col=[0,1]).sort_index()
#correct units to MW and EUR
costs.loc[costs.unit.str.contains("/kW"), "value"] *= 1e3
costs.loc[costs.unit.str.contains("USD"), "value"] *= USD_to_EUR
#min_count=1 is important to generate NaNs which are then filled by fillna
costs = costs.loc[:, "value"].unstack(level=1).groupby("technology").sum(min_count=1)
costs = costs.fillna({"CO2 intensity" : 0,
"FOM" : 0,
"VOM" : 0,
"discount rate" : discount_rate,
"efficiency" : 1,
"fuel" : 0,
"investment" : 0,
"lifetime" : lifetime
})
annuity_factor = lambda v: annuity(v["lifetime"], v["discount rate"]) + v["FOM"] / 100
costs["fixed"] = [annuity_factor(v) * v["investment"] * Nyears for i, v in costs.iterrows()]
return costs
def add_generation(n, costs):
logger.info("adding electricity generation")
nodes = pop_layout.index
fallback = {"OCGT": "gas"}
conventionals = options.get("conventional_generation", fallback)
for generator, carrier in conventionals.items():
carrier_nodes = vars(spatial)[carrier].nodes
add_carrier_buses(n, carrier, carrier_nodes)
n.madd("Link",
nodes + " " + generator,
bus0=carrier_nodes,
bus1=nodes,
bus2="co2 atmosphere",
marginal_cost=costs.at[generator, 'efficiency'] * costs.at[generator, 'VOM'], #NB: VOM is per MWel
capital_cost=costs.at[generator, 'efficiency'] * costs.at[generator, 'fixed'], #NB: fixed cost is per MWel
p_nom_extendable=True,
carrier=generator,
efficiency=costs.at[generator, 'efficiency'],
efficiency2=costs.at[carrier, 'CO2 intensity'],
lifetime=costs.at[generator, 'lifetime']
)
def add_wave(n, wave_cost_factor):
# TODO: handle in Snakefile
wave_fn = "data/WindWaveWEC_GLTB.xlsx"
#in kW
capacity = pd.Series({"Attenuator": 750,
"F2HB": 1000,
"MultiPA": 600})
#in EUR/MW
annuity_factor = annuity(25,0.07) + 0.03
costs = 1e6 * wave_cost_factor * annuity_factor * pd.Series({"Attenuator": 2.5,
"F2HB": 2,
"MultiPA": 1.5})
sheets = pd.read_excel(wave_fn, sheet_name=["FirthForth", "Hebrides"],
usecols=["Attenuator", "F2HB", "MultiPA"],
index_col=0, skiprows=[0], parse_dates=True)
wave = pd.concat([sheets[l].divide(capacity, axis=1) for l in locations],
keys=locations,
axis=1)
for wave_type in costs.index:
n.add("Generator",
"Hebrides " + wave_type,
bus="GB4 0", # TODO this location is hardcoded
p_nom_extendable=True,
carrier="wave",
capital_cost=costs[wave_type],
p_max_pu=wave["Hebrides", wave_type]
)
def insert_electricity_distribution_grid(n, costs):
# TODO pop_layout?
# TODO options?
print("Inserting electricity distribution grid with investment cost factor of",
options['electricity_distribution_grid_cost_factor'])
nodes = pop_layout.index
cost_factor = options['electricity_distribution_grid_cost_factor']
n.madd("Bus",
nodes + " low voltage",
location=nodes,
carrier="low voltage",
unit="MWh_el"
)
n.madd("Link",
nodes + " electricity distribution grid",
bus0=nodes,
bus1=nodes + " low voltage",
p_nom_extendable=True,
p_min_pu=-1,
carrier="electricity distribution grid",
efficiency=1,
lifetime=costs.at['electricity distribution grid', 'lifetime'],
capital_cost=costs.at['electricity distribution grid', 'fixed'] * cost_factor
)
# this catches regular electricity load and "industry electricity" and
# "agriculture machinery electric" and "agriculture electricity"
loads = n.loads.index[n.loads.carrier.str.contains("electric")]
n.loads.loc[loads, "bus"] += " low voltage"
bevs = n.links.index[n.links.carrier == "BEV charger"]
n.links.loc[bevs, "bus0"] += " low voltage"
v2gs = n.links.index[n.links.carrier == "V2G"]
n.links.loc[v2gs, "bus1"] += " low voltage"
hps = n.links.index[n.links.carrier.str.contains("heat pump")]
n.links.loc[hps, "bus0"] += " low voltage"
rh = n.links.index[n.links.carrier.str.contains("resistive heater")]
n.links.loc[rh, "bus0"] += " low voltage"
mchp = n.links.index[n.links.carrier.str.contains("micro gas")]
n.links.loc[mchp, "bus1"] += " low voltage"
# set existing solar to cost of utility cost rather the 50-50 rooftop-utility
solar = n.generators.index[n.generators.carrier == "solar"]
n.generators.loc[solar, "capital_cost"] = costs.at['solar-utility', 'fixed']
if snakemake.wildcards.clusters[-1:] == "m":
simplified_pop_layout = pd.read_csv(snakemake.input.simplified_pop_layout, index_col=0)
pop_solar = simplified_pop_layout.total.rename(index = lambda x: x + " solar")
else:
pop_solar = pop_layout.total.rename(index = lambda x: x + " solar")
# add max solar rooftop potential assuming 0.1 kW/m2 and 10 m2/person,
# i.e. 1 kW/person (population data is in thousands of people) so we get MW
potential = 0.1 * 10 * pop_solar
n.madd("Generator",
solar,
suffix=" rooftop",
bus=n.generators.loc[solar, "bus"] + " low voltage",
carrier="solar rooftop",
p_nom_extendable=True,
p_nom_max=potential,
marginal_cost=n.generators.loc[solar, 'marginal_cost'],
capital_cost=costs.at['solar-rooftop', 'fixed'],
efficiency=n.generators.loc[solar, 'efficiency'],
p_max_pu=n.generators_t.p_max_pu[solar],
lifetime=costs.at['solar-rooftop', 'lifetime']
)
n.add("Carrier", "home battery")
n.madd("Bus",
nodes + " home battery",
location=nodes,
carrier="home battery",
unit="MWh_el"
)
n.madd("Store",
nodes + " home battery",
bus=nodes + " home battery",
e_cyclic=True,
e_nom_extendable=True,
carrier="home battery",
capital_cost=costs.at['home battery storage', 'fixed'],
lifetime=costs.at['battery storage', 'lifetime']
)
n.madd("Link",
nodes + " home battery charger",
bus0=nodes + " low voltage",
bus1=nodes + " home battery",
carrier="home battery charger",
efficiency=costs.at['battery inverter', 'efficiency']**0.5,
capital_cost=costs.at['home battery inverter', 'fixed'],
p_nom_extendable=True,
lifetime=costs.at['battery inverter', 'lifetime']
)
n.madd("Link",
nodes + " home battery discharger",
bus0=nodes + " home battery",
bus1=nodes + " low voltage",
carrier="home battery discharger",
efficiency=costs.at['battery inverter', 'efficiency']**0.5,
marginal_cost=options['marginal_cost_storage'],
p_nom_extendable=True,
lifetime=costs.at['battery inverter', 'lifetime']
)
def insert_gas_distribution_costs(n, costs):
# TODO options?
f_costs = options['gas_distribution_grid_cost_factor']
print("Inserting gas distribution grid with investment cost factor of", f_costs)
capital_cost = costs.loc['electricity distribution grid']["fixed"] * f_costs
# gas boilers
gas_b = n.links.index[n.links.carrier.str.contains("gas boiler") &
(~n.links.carrier.str.contains("urban central"))]
n.links.loc[gas_b, "capital_cost"] += capital_cost
# micro CHPs
mchp = n.links.index[n.links.carrier.str.contains("micro gas")]
n.links.loc[mchp, "capital_cost"] += capital_cost
def add_electricity_grid_connection(n, costs):
carriers = ["onwind", "solar"]
gens = n.generators.index[n.generators.carrier.isin(carriers)]
n.generators.loc[gens, "capital_cost"] += costs.at['electricity grid connection', 'fixed']
def add_storage_and_grids(n, costs):
logger.info("Add hydrogen storage")
nodes = pop_layout.index
n.add("Carrier", "H2")
n.madd("Bus",
nodes + " H2",
location=nodes,
carrier="H2",
unit="MWh_LHV"
)
n.madd("Link",
nodes + " H2 Electrolysis",
bus1=nodes + " H2",
bus0=nodes,
p_nom_extendable=True,
carrier="H2 Electrolysis",
efficiency=costs.at["electrolysis", "efficiency"],
capital_cost=costs.at["electrolysis", "fixed"],
lifetime=costs.at['electrolysis', 'lifetime']
)
n.madd("Link",
nodes + " H2 Fuel Cell",
bus0=nodes + " H2",
bus1=nodes,
p_nom_extendable=True,
carrier ="H2 Fuel Cell",
efficiency=costs.at["fuel cell", "efficiency"],
capital_cost=costs.at["fuel cell", "fixed"] * costs.at["fuel cell", "efficiency"], #NB: fixed cost is per MWel
lifetime=costs.at['fuel cell', 'lifetime']
)
cavern_types = snakemake.config["sector"]["hydrogen_underground_storage_locations"]
h2_caverns = pd.read_csv(snakemake.input.h2_cavern, index_col=0)
if not h2_caverns.empty and options['hydrogen_underground_storage']:
h2_caverns = h2_caverns[cavern_types].sum(axis=1)
# only use sites with at least 2 TWh potential
h2_caverns = h2_caverns[h2_caverns > 2]
# convert TWh to MWh
h2_caverns = h2_caverns * 1e6
# clip at 1000 TWh for one location
h2_caverns.clip(upper=1e9, inplace=True)
logger.info("Add hydrogen underground storage")
h2_capital_cost = costs.at["hydrogen storage underground", "fixed"]
n.madd("Store",
h2_caverns.index + " H2 Store",
bus=h2_caverns.index + " H2",
e_nom_extendable=True,
e_nom_max=h2_caverns.values,
e_cyclic=True,
carrier="H2 Store",
capital_cost=h2_capital_cost,
lifetime=costs.at["hydrogen storage underground", "lifetime"]
)
# hydrogen stored overground (where not already underground)
h2_capital_cost = costs.at["hydrogen storage tank incl. compressor", "fixed"]
nodes_overground = h2_caverns.index.symmetric_difference(nodes)
n.madd("Store",
nodes_overground + " H2 Store",
bus=nodes_overground + " H2",
e_nom_extendable=True,
e_cyclic=True,
carrier="H2 Store",
capital_cost=h2_capital_cost
)
if options["gas_network"] or options["H2_retrofit"]:
fn = snakemake.input.clustered_gas_network
gas_pipes = pd.read_csv(fn, index_col=0)
if options["gas_network"]:
logger.info("Add natural gas infrastructure, incl. LNG terminals, production and entry-points.")
if options["H2_retrofit"]:
gas_pipes["p_nom_max"] = gas_pipes.p_nom
gas_pipes["p_nom_min"] = 0.
# 0.1 EUR/MWkm/a to prefer decommissioning to address degeneracy
gas_pipes["capital_cost"] = 0.1 * gas_pipes.length
else:
gas_pipes["p_nom_max"] = np.inf
gas_pipes["p_nom_min"] = gas_pipes.p_nom
gas_pipes["capital_cost"] = gas_pipes.length * costs.at['CH4 (g) pipeline', 'fixed']
n.madd("Link",
gas_pipes.index,
bus0=gas_pipes.bus0 + " gas",
bus1=gas_pipes.bus1 + " gas",
p_min_pu=gas_pipes.p_min_pu,
p_nom=gas_pipes.p_nom,
p_nom_extendable=True,
p_nom_max=gas_pipes.p_nom_max,
p_nom_min=gas_pipes.p_nom_min,
length=gas_pipes.length,
capital_cost=gas_pipes.capital_cost,
tags=gas_pipes.name,
carrier="gas pipeline",
lifetime=costs.at['CH4 (g) pipeline', 'lifetime']
)
# remove fossil generators where there is neither
# production, LNG terminal, nor entry-point beyond system scope
fn = snakemake.input.gas_input_nodes_simplified
gas_input_nodes = pd.read_csv(fn, index_col=0)
unique = gas_input_nodes.index.unique()
gas_i = n.generators.carrier == 'gas'
internal_i = ~n.generators.bus.map(n.buses.location).isin(unique)
remove_i = n.generators[gas_i & internal_i].index
n.generators.drop(remove_i, inplace=True)
p_nom = gas_input_nodes.sum(axis=1).rename(lambda x: x + " gas")
n.generators.loc[gas_i, "p_nom_extendable"] = False
n.generators.loc[gas_i, "p_nom"] = p_nom
# add candidates for new gas pipelines to achieve full connectivity
G = nx.Graph()
gas_buses = n.buses.loc[n.buses.carrier=='gas', 'location']
G.add_nodes_from(np.unique(gas_buses.values))
sel = gas_pipes.p_nom > 1500
attrs = ["bus0", "bus1", "length"]
G.add_weighted_edges_from(gas_pipes.loc[sel, attrs].values)
# find all complement edges
complement_edges = pd.DataFrame(complement(G).edges, columns=["bus0", "bus1"])
complement_edges["length"] = complement_edges.apply(haversine, axis=1)
# apply k_edge_augmentation weighted by length of complement edges
k_edge = options.get("gas_network_connectivity_upgrade", 3)
augmentation = list(k_edge_augmentation(G, k_edge, avail=complement_edges.values))
if augmentation:
new_gas_pipes = pd.DataFrame(augmentation, columns=["bus0", "bus1"])
new_gas_pipes["length"] = new_gas_pipes.apply(haversine, axis=1)