Passed
Pull Request — dev (#1037)
by
unknown
01:39
created

disagg_households_power()   B

Complexity

Conditions 5

Size

Total Lines 74
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 74
rs 8.8373
c 0
b 0
f 0
cc 5
nop 5

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
"""The central module containing all code dealing with importing and
2
adjusting data from demandRegio
3
4
"""
5
from pathlib import Path
6
7
from sqlalchemy import ARRAY, Column, Float, ForeignKey, Integer, String
8
from sqlalchemy.ext.declarative import declarative_base
9
import numpy as np
10
import pandas as pd
11
12
from egon.data import db
13
from egon.data.datasets import Dataset
14
from egon.data.datasets.demandregio.install_disaggregator import (
15
    clone_and_install,
16
)
17
from egon.data.datasets.scenario_parameters import (
18
    EgonScenario,
19
    get_sector_parameters,
20
)
21
import egon.data.config
22
import egon.data.datasets.scenario_parameters.parameters as scenario_parameters
23
24
try:
25
    from disaggregator import config, data, spatial
26
27
except ImportError as e:
28
    pass
29
30
# will be later imported from another file ###
31
Base = declarative_base()
32
33
34
class DemandRegio(Dataset):
35
    def __init__(self, dependencies):
36
        super().__init__(
37
            name="DemandRegio",
38
            version="0.0.5",
39
            dependencies=dependencies,
40
            tasks=(
41
                clone_and_install,
42
                create_tables,
43
                {
44
                    insert_household_demand,
45
                    insert_society_data,
46
                    insert_cts_ind_demands,
47
                },
48
            ),
49
        )
50
51
52
class EgonDemandRegioHH(Base):
53
    __tablename__ = "egon_demandregio_hh"
54
    __table_args__ = {"schema": "demand"}
55
    nuts3 = Column(String(5), primary_key=True)
56
    hh_size = Column(Integer, primary_key=True)
57
    scenario = Column(String, ForeignKey(EgonScenario.name), primary_key=True)
58
    year = Column(Integer)
59
    demand = Column(Float)
60
61
62
class EgonDemandRegioCtsInd(Base):
63
    __tablename__ = "egon_demandregio_cts_ind"
64
    __table_args__ = {"schema": "demand"}
65
    nuts3 = Column(String(5), primary_key=True)
66
    wz = Column(Integer, primary_key=True)
67
    scenario = Column(String, ForeignKey(EgonScenario.name), primary_key=True)
68
    year = Column(Integer)
69
    demand = Column(Float)
70
71
72
class EgonDemandRegioPopulation(Base):
73
    __tablename__ = "egon_demandregio_population"
74
    __table_args__ = {"schema": "society"}
75
    nuts3 = Column(String(5), primary_key=True)
76
    year = Column(Integer, primary_key=True)
77
    population = Column(Float)
78
79
80
class EgonDemandRegioHouseholds(Base):
81
    __tablename__ = "egon_demandregio_household"
82
    __table_args__ = {"schema": "society"}
83
    nuts3 = Column(String(5), primary_key=True)
84
    hh_size = Column(Integer, primary_key=True)
85
    year = Column(Integer, primary_key=True)
86
    households = Column(Integer)
87
88
89
class EgonDemandRegioWz(Base):
90
    __tablename__ = "egon_demandregio_wz"
91
    __table_args__ = {"schema": "demand"}
92
    wz = Column(Integer, primary_key=True)
93
    sector = Column(String(50))
94
    definition = Column(String(150))
95
96
97
class EgonDemandRegioTimeseriesCtsInd(Base):
98
    __tablename__ = "egon_demandregio_timeseries_cts_ind"
99
    __table_args__ = {"schema": "demand"}
100
    wz = Column(Integer, primary_key=True)
101
    year = Column(Integer, primary_key=True)
102
    slp = Column(String(50))
103
    load_curve = Column(ARRAY(Float()))
104
105
106
def create_tables():
107
    """Create tables for demandregio data
108
    Returns
109
    -------
110
    None.
111
    """
112
    db.execute_sql("CREATE SCHEMA IF NOT EXISTS demand;")
113
    db.execute_sql("CREATE SCHEMA IF NOT EXISTS society;")
114
    engine = db.engine()
115
    EgonDemandRegioHH.__table__.create(bind=engine, checkfirst=True)
116
    EgonDemandRegioCtsInd.__table__.create(bind=engine, checkfirst=True)
117
    EgonDemandRegioPopulation.__table__.create(bind=engine, checkfirst=True)
118
    EgonDemandRegioHouseholds.__table__.create(bind=engine, checkfirst=True)
119
    EgonDemandRegioWz.__table__.create(bind=engine, checkfirst=True)
120
    EgonDemandRegioTimeseriesCtsInd.__table__.drop(
121
        bind=engine, checkfirst=True
122
    )
123
    EgonDemandRegioTimeseriesCtsInd.__table__.create(
124
        bind=engine, checkfirst=True
125
    )
126
127
128
def data_in_boundaries(df):
129
    """Select rows with nuts3 code within boundaries, used for testmode
130
131
    Parameters
132
    ----------
133
    df : pandas.DataFrame
134
        Data for all nuts3 regions
135
136
    Returns
137
    -------
138
    pandas.DataFrame
139
        Data for nuts3 regions within boundaries
140
141
    """
142
    engine = db.engine()
143
144
    df = df.reset_index()
145
146
    # Change nuts3 region names to 2016 version
147
    nuts_names = {"DEB16": "DEB1C", "DEB19": "DEB1D"}
148
    df.loc[df.nuts3.isin(nuts_names), "nuts3"] = df.loc[
149
        df.nuts3.isin(nuts_names), "nuts3"
150
    ].map(nuts_names)
151
152
    df = df.set_index("nuts3")
153
154
    return df[
155
        df.index.isin(
156
            pd.read_sql(
157
                "SELECT DISTINCT ON (nuts) nuts FROM boundaries.vg250_krs",
158
                engine,
159
            ).nuts
160
        )
161
    ]
162
163
164
def insert_cts_ind_wz_definitions():
165
    """Insert demandregio's definitions of CTS and industrial branches
166
167
    Returns
168
    -------
169
    None.
170
171
    """
172
173
    source = egon.data.config.datasets()["demandregio_cts_ind_demand"][
174
        "sources"
175
    ]
176
177
    target = egon.data.config.datasets()["demandregio_cts_ind_demand"][
178
        "targets"
179
    ]["wz_definitions"]
180
181
    engine = db.engine()
182
183
    for sector in source["wz_definitions"]:
184
185
        file_path = (
186
            Path(".")
187
            / "data_bundle_egon_data"
188
            / "WZ_definition"
189
            / source["wz_definitions"][sector]
190
        )
191
192
        if sector == "CTS":
193
            delimiter = ";"
194
        else:
195
            delimiter = ","
196
        df = (
197
            pd.read_csv(file_path, delimiter=delimiter, header=None)
198
            .rename({0: "wz", 1: "definition"}, axis="columns")
199
            .set_index("wz")
200
        )
201
        df["sector"] = sector
202
        df.to_sql(
203
            target["table"],
204
            engine,
205
            schema=target["schema"],
206
            if_exists="append",
207
        )
208
209
210
def match_nuts3_bl():
211
    """Function that maps the federal state to each nuts3 region
212
213
    Returns
214
    -------
215
    df : pandas.DataFrame
216
        List of nuts3 regions and the federal state of Germany.
217
218
    """
219
220
    engine = db.engine()
221
222
    df = pd.read_sql(
223
        "SELECT DISTINCT ON (boundaries.vg250_krs.nuts) "
224
        "boundaries.vg250_krs.nuts, boundaries.vg250_lan.gen "
225
        "FROM boundaries.vg250_lan, boundaries.vg250_krs "
226
        " WHERE ST_CONTAINS("
227
        "boundaries.vg250_lan.geometry, "
228
        "boundaries.vg250_krs.geometry)",
229
        con=engine,
230
    )
231
232
    df.gen[df.gen == "Baden-Württemberg (Bodensee)"] = "Baden-Württemberg"
233
    df.gen[df.gen == "Bayern (Bodensee)"] = "Bayern"
234
235
    return df.set_index("nuts")
236
237
238
def adjust_ind_pes(ec_cts_ind):
239
    """
240
    Adjust electricity demand of industrial consumers due to electrification
241
    of process heat based on assumptions of pypsa-eur-sec.
242
243
    Parameters
244
    ----------
245
    ec_cts_ind : pandas.DataFrame
246
        Industrial demand without additional electrification
247
248
    Returns
249
    -------
250
    ec_cts_ind : pandas.DataFrame
251
        Industrial demand with additional electrification
252
253
    """
254
255
    pes_path = (
256
        Path(".") / "data_bundle_egon_data" / "pypsa_eur_sec" / "resources"
257
    )
258
259
    sources = egon.data.config.datasets()["demandregio_cts_ind_demand"][
260
        "sources"
261
    ]["new_consumers_2050"]
262
263
    # Extract today's industrial demand from pypsa-eur-sec
264
    demand_today = pd.read_csv(
265
        pes_path / sources["pes-demand-today"],
266
        header=None,
267
    ).transpose()
268
269
    # Filter data
270
    demand_today[1].fillna("carrier", inplace=True)
271
    demand_today = demand_today[
272
        (demand_today[0] == "DE") | (demand_today[1] == "carrier")
273
    ].drop([0, 2], axis="columns")
274
275
    demand_today = (
276
        demand_today.transpose()
277
        .set_index(0)
278
        .transpose()
279
        .set_index("carrier")
280
        .transpose()
281
        .loc["electricity"]
282
        .astype(float)
283
    )
284
285
    # Calculate future industrial demand from pypsa-eur-sec
286
    # based on production and energy demands per carrier ('sector ratios')
287
    prod_tomorrow = pd.read_csv(pes_path / sources["pes-production-tomorrow"])
288
289
    prod_tomorrow = prod_tomorrow[prod_tomorrow["kton/a"] == "DE"].set_index(
290
        "kton/a"
291
    )
292
293
    sector_ratio = (
294
        pd.read_csv(pes_path / sources["pes-sector-ratios"])
295
        .set_index("MWh/tMaterial")
296
        .loc["elec"]
297
    )
298
299
    demand_tomorrow = prod_tomorrow.multiply(
300
        sector_ratio.div(1000)
301
    ).transpose()["DE"]
302
303
    # Calculate changes of electrical demand per sector in pypsa-eur-sec
304
    change = pd.DataFrame(
305
        (demand_tomorrow / demand_today)
306
        / (demand_tomorrow / demand_today).sum()
307
    )
308
309
    # Drop rows without changes
310
    change = change[~change[0].isnull()]
311
312
    # Map industrial branches of pypsa-eur-sec to WZ2008 used in demandregio
313
    change["wz"] = change.index.map(
314
        {
315
            "Alumina production": 24,
316
            "Aluminium - primary production": 24,
317
            "Aluminium - secondary production": 24,
318
            "Ammonia": 20,
319
            "Basic chemicals (without ammonia)": 20,
320
            "Cement": 23,
321
            "Ceramics & other NMM": 23,
322
            "Electric arc": 24,
323
            "Food, beverages and tobacco": 10,
324
            "Glass production": 23,
325
            "Integrated steelworks": 24,
326
            "Machinery Equipment": 28,
327
            "Other Industrial Sectors": 32,
328
            "Other chemicals": 20,
329
            "Other non-ferrous metals": 24,
330
            "Paper production": 17,
331
            "Pharmaceutical products etc.": 21,
332
            "Printing and media reproduction": 18,
333
            "Pulp production": 17,
334
            "Textiles and leather": 13,
335
            "Transport Equipment": 29,
336
            "Wood and wood products": 16,
337
        }
338
    )
339
340
    # Group by WZ2008
341
    shares_per_wz = change.groupby("wz")[0].sum()
342
343
    # Calculate addtional demands needed to meet future demand of pypsa-eur-sec
344
    addtional_mwh = shares_per_wz.multiply(
345
        demand_tomorrow.sum() * 1000000 - ec_cts_ind.sum().sum()
346
    )
347
348
    # Calulate overall industrial demand for eGon100RE
349
    final_mwh = addtional_mwh + ec_cts_ind[addtional_mwh.index].sum()
350
351
    # Linear scale the industrial demands per nuts3 and wz to meet final demand
352
    ec_cts_ind[addtional_mwh.index] *= (
353
        final_mwh / ec_cts_ind[addtional_mwh.index].sum()
354
    )
355
356
    return ec_cts_ind
357
358
359
def adjust_cts_ind_nep(ec_cts_ind, sector):
360
    """Add electrical demand of new largescale CTS und industrial consumers
361
    according to NEP 2021, scneario C 2035. Values per federal state are
362
    linear distributed over all CTS branches and nuts3 regions.
363
364
    Parameters
365
    ----------
366
    ec_cts_ind : pandas.DataFrame
367
        CTS or industry demand without new largescale consumers.
368
369
    Returns
370
    -------
371
    ec_cts_ind : pandas.DataFrame
372
        CTS or industry demand including new largescale consumers.
373
374
    """
375
    sources = egon.data.config.datasets()["demandregio_cts_ind_demand"][
376
        "sources"
377
    ]
378
379
    file_path = (
380
        Path(".")
381
        / "data_bundle_egon_data"
382
        / "nep2035_version2021"
383
        / sources["new_consumers_2035"]
384
    )
385
386
    # get data from NEP per federal state
387
    new_con = pd.read_csv(file_path, delimiter=";", decimal=",", index_col=0)
388
389
    # match nuts3 regions to federal states
390
    groups = ec_cts_ind.groupby(match_nuts3_bl().gen)
391
392
    # update demands per federal state
393
    for group in groups.indices.keys():
394
        g = groups.get_group(group)
395
        data_new = g.mul(1 + new_con[sector][group] * 1e6 / g.sum().sum())
396
        ec_cts_ind[ec_cts_ind.index.isin(g.index)] = data_new
397
398
    return ec_cts_ind
399
400
401
def disagg_households_power(
402
    scenario, year, weight_by_income=False, original=False, **kwargs
403
):
404
    """
405
    Perform spatial disaggregation of electric power in [GWh/a] by key and
406
    possibly weight by income.
407
    Similar to disaggregator.spatial.disagg_households_power
408
409
410
    Parameters
411
    ----------
412
    by : str
413
        must be one of ['households', 'population']
414
    weight_by_income : bool, optional
415
        Flag if to weight the results by the regional income (default False)
416
    orignal : bool, optional
417
        Throughput to function households_per_size,
418
        A flag if the results should be left untouched and returned in
419
        original form for the year 2011 (True) or if they should be scaled to
420
        the given `year` by the population in that year (False).
421
422
    Returns
423
    -------
424
    pd.DataFrame or pd.Series
425
    """
426
    # source: survey of energieAgenturNRW
427
    demand_per_hh_size = pd.DataFrame(
428
        index=range(1, 7),
429
        data={
430
            "weighted DWH": [2290, 3202, 4193, 4955, 5928, 5928],
431
            "without DHW": [1714, 2812, 3704, 4432, 5317, 5317],
432
        },
433
    )
434
435
    # Bottom-Up: Power demand by household sizes in [MWh/a] for each scenario
436
    if scenario in ["eGon2021", "eGon2035"]:
437
        # chose demand per household size from survey including weighted DHW
438
        power_per_HH = demand_per_hh_size["weighted DWH"] / 1e3
439
440
        # calculate demand per nuts3
441
        df = (
442
            data.households_per_size(original=original, year=year)
443
            * power_per_HH
444
        )
445
446
        if scenario == "eGon2035":
447
            # scale to fit demand of NEP 2021 scebario C 2035 (119TWh)
448
            df *= 119000000 / df.sum().sum()
449
450
    elif scenario == "eGon100RE":
451
452
        # chose demand per household size from survey without DHW
453
        power_per_HH = demand_per_hh_size["without DHW"] / 1e3
454
455
        # calculate demand per nuts3 in 2011
456
        df_2011 = data.households_per_size(year=2011) * power_per_HH
457
458
        # scale demand per hh-size to meet demand without heat
459
        # according to JRC in 2011 (136.6-(20.14+9.41) TWh)
460
        power_per_HH *= (136.6 - (20.14 + 9.41)) * 1e6 / df_2011.sum().sum()
461
462
        # calculate demand per nuts3 in 2050
463
        df = data.households_per_size(year=year) * power_per_HH
464
465
    else:
466
        print(
467
            f"Electric demand per household size for scenario {scenario} "
468
            "is not specified."
469
        )
470
471
    if weight_by_income:
472
        df = spatial.adjust_by_income(df=df)
0 ignored issues
show
introduced by
The variable df does not seem to be defined for all execution paths.
Loading history...
473
474
    return df
475
476
477
def insert_hh_demand(scenario, year, engine):
478
    """Calculates electrical demands of private households using demandregio's
479
    disaggregator and insert results into the database.
480
481
    Parameters
482
    ----------
483
    scenario : str
484
        Name of the corresponing scenario.
485
    year : int
486
        The number of households per region is taken from this year.
487
488
    Returns
489
    -------
490
    None.
491
492
    """
493
    targets = egon.data.config.datasets()["demandregio_household_demand"][
494
        "targets"
495
    ]["household_demand"]
496
    # get demands of private households per nuts and size from demandregio
497
    ec_hh = disagg_households_power(scenario, year)
498
499
    # Select demands for nuts3-regions in boundaries (needed for testmode)
500
    ec_hh = data_in_boundaries(ec_hh)
501
502
    # insert into database
503
    for hh_size in ec_hh.columns:
504
        df = pd.DataFrame(ec_hh[hh_size])
505
        df["year"] = year
506
        df["scenario"] = scenario
507
        df["hh_size"] = hh_size
508
        df = df.rename({hh_size: "demand"}, axis="columns")
509
        df.to_sql(
510
            targets["table"],
511
            engine,
512
            schema=targets["schema"],
513
            if_exists="append",
514
        )
515
516
517
def insert_cts_ind(scenario, year, engine, target_values):
518
    """Calculates electrical demands of CTS and industry using demandregio's
519
    disaggregator, adjusts them according to resulting values of NEP 2021 or
520
    JRC IDEES and insert results into the database.
521
522
    Parameters
523
    ----------
524
    scenario : str
525
        Name of the corresponing scenario.
526
    year : int
527
        The number of households per region is taken from this year.
528
    target_values : dict
529
        List of target values for each scenario and sector.
530
531
    Returns
532
    -------
533
    None.
534
535
    """
536
537
    targets = egon.data.config.datasets()["demandregio_cts_ind_demand"][
538
        "targets"
539
    ]
540
541
    for sector in ["CTS", "industry"]:
542
        # get demands per nuts3 and wz of demandregio
543
        ec_cts_ind = spatial.disagg_CTS_industry(
544
            use_nuts3code=True, source="power", sector=sector, year=year
545
        ).transpose()
546
547
        ec_cts_ind.index = ec_cts_ind.index.rename("nuts3")
548
549
        # exclude mobility sector from GHD
550
        ec_cts_ind = ec_cts_ind.drop(columns=49, errors="ignore")
551
552
        # scale values according to target_values
553
        if sector in target_values[scenario].keys():
554
            ec_cts_ind *= (
555
                target_values[scenario][sector] * 1e3 / ec_cts_ind.sum().sum()
556
            )
557
558
        # include new largescale consumers according to NEP 2021
559
        if scenario == "eGon2035":
560
            ec_cts_ind = adjust_cts_ind_nep(ec_cts_ind, sector)
561
        # include new industrial demands due to sector coupling
562
        if (scenario == "eGon100RE") & (sector == "industry"):
563
            ec_cts_ind = adjust_ind_pes(ec_cts_ind)
564
565
        # Select demands for nuts3-regions in boundaries (needed for testmode)
566
        ec_cts_ind = data_in_boundaries(ec_cts_ind)
567
568
        # insert into database
569
        for wz in ec_cts_ind.columns:
570
            df = pd.DataFrame(ec_cts_ind[wz])
571
            df["year"] = year
572
            df["wz"] = wz
573
            df["scenario"] = scenario
574
            df = df.rename({wz: "demand"}, axis="columns")
575
            df.index = df.index.rename("nuts3")
576
            df.to_sql(
577
                targets["cts_ind_demand"]["table"],
578
                engine,
579
                targets["cts_ind_demand"]["schema"],
580
                if_exists="append",
581
            )
582
583
584
def insert_household_demand():
585
    """Insert electrical demands for households according to
586
    demandregio using its disaggregator-tool in MWh
587
588
    Returns
589
    -------
590
    None.
591
592
    """
593
    targets = egon.data.config.datasets()["demandregio_household_demand"][
594
        "targets"
595
    ]
596
    engine = db.engine()
597
598
    for t in targets:
599
        db.execute_sql(
600
            f"DELETE FROM {targets[t]['schema']}.{targets[t]['table']};"
601
        )
602
603
    for scn in ["eGon2021", "eGon2035", "eGon100RE"]:
604
605
        year = scenario_parameters.global_settings(scn)["population_year"]
606
607
        # Insert demands of private households
608
        insert_hh_demand(scn, year, engine)
609
610
611
def insert_cts_ind_demands():
612
    """Insert electricity demands per nuts3-region in Germany according to
613
    demandregio using its disaggregator-tool in MWh
614
615
    Returns
616
    -------
617
    None.
618
619
    """
620
    targets = egon.data.config.datasets()["demandregio_cts_ind_demand"][
621
        "targets"
622
    ]
623
    engine = db.engine()
624
625
    for t in targets:
626
        db.execute_sql(
627
            f"DELETE FROM {targets[t]['schema']}.{targets[t]['table']};"
628
        )
629
630
    insert_cts_ind_wz_definitions()
631
632
    for scn in ["eGon2021", "eGon2035", "eGon100RE"]:
633
634
        year = scenario_parameters.global_settings(scn)["population_year"]
635
636
        if year > 2035:
637
            year = 2035
638
639
        # target values per scenario in MWh
640
        target_values = {
641
            # according to NEP 2021
642
            # new consumers will be added seperatly
643
            "eGon2035": {"CTS": 135300, "industry": 225400},
644
            # CTS: reduce overall demand from demandregio (without traffic)
645
            # by share of heat according to JRC IDEES, data from 2011
646
            # industry: no specific heat demand, use data from demandregio
647
            "eGon100RE": {"CTS": (1 - (5.96 + 6.13) / 154.64) * 125183.403},
648
            # no adjustments for status quo
649
            "eGon2021": {},
650
        }
651
652
        insert_cts_ind(scn, year, engine, target_values)
653
654
    # Insert load curves per wz
655
    timeseries_per_wz()
656
657
658
def insert_society_data():
659
    """Insert population and number of households per nuts3-region in Germany
660
    according to demandregio using its disaggregator-tool
661
662
    Returns
663
    -------
664
    None.
665
666
    """
667
    targets = egon.data.config.datasets()["demandregio_society"]["targets"]
668
    engine = db.engine()
669
670
    for t in targets:
671
        db.execute_sql(
672
            f"DELETE FROM {targets[t]['schema']}.{targets[t]['table']};"
673
        )
674
675
    target_years = np.append(
676
        get_sector_parameters("global").population_year.values, 2018
677
    )
678
679
    for year in target_years:
680
        df_pop = pd.DataFrame(data.population(year=year))
681
        df_pop["year"] = year
682
        df_pop = df_pop.rename({"value": "population"}, axis="columns")
683
        # Select data for nuts3-regions in boundaries (needed for testmode)
684
        df_pop = data_in_boundaries(df_pop)
685
        df_pop.to_sql(
686
            targets["population"]["table"],
687
            engine,
688
            schema=targets["population"]["schema"],
689
            if_exists="append",
690
        )
691
692
    for year in target_years:
693
        df_hh = pd.DataFrame(data.households_per_size(year=year))
694
        # Select data for nuts3-regions in boundaries (needed for testmode)
695
        df_hh = data_in_boundaries(df_hh)
696
        for hh_size in df_hh.columns:
697
            df = pd.DataFrame(df_hh[hh_size])
698
            df["year"] = year
699
            df["hh_size"] = hh_size
700
            df = df.rename({hh_size: "households"}, axis="columns")
701
            df.to_sql(
702
                targets["household"]["table"],
703
                engine,
704
                schema=targets["household"]["schema"],
705
                if_exists="append",
706
            )
707
708
709
def insert_timeseries_per_wz(sector, year):
710
    """Insert normalized electrical load time series for the selected sector
711
712
    Parameters
713
    ----------
714
    sector : str
715
        Name of the sector. ['CTS', 'industry']
716
    year : int
717
        Selected weather year
718
719
    Returns
720
    -------
721
    None.
722
723
    """
724
    targets = egon.data.config.datasets()["demandregio_cts_ind_demand"][
725
        "targets"
726
    ]
727
728
    if sector == "CTS":
729
        profiles = (
730
            data.CTS_power_slp_generator("SH", year=year).resample("H").sum()
731
        )
732
        wz_slp = config.slp_branch_cts_power()
733
    elif sector == "industry":
734
        profiles = (
735
            data.shift_load_profile_generator(state="SH", year=year)
736
            .resample("H")
737
            .sum()
738
        )
739
        wz_slp = config.shift_profile_industry()
740
741
    else:
742
        print(f"Sector {sector} is not valid.")
743
744
    df = pd.DataFrame(
745
        index=wz_slp.keys(), columns=["slp", "load_curve", "year"]
0 ignored issues
show
introduced by
The variable wz_slp does not seem to be defined for all execution paths.
Loading history...
746
    )
747
748
    df.index.rename("wz", inplace=True)
749
750
    df.slp = wz_slp.values()
751
752
    df.year = year
753
754
    df.load_curve = profiles[df.slp].transpose().values.tolist()
0 ignored issues
show
introduced by
The variable profiles does not seem to be defined for all execution paths.
Loading history...
755
756
    db.execute_sql(
757
        f"""
758
                   DELETE FROM {targets['timeseries_cts_ind']['schema']}.
759
                   {targets['timeseries_cts_ind']['table']}
760
                   WHERE wz IN (
761
                       SELECT wz FROM {targets['wz_definitions']['schema']}.
762
                       {targets['wz_definitions']['table']}
763
                       WHERE sector = '{sector}')
764
                   """
765
    )
766
767
    df.to_sql(
768
        targets["timeseries_cts_ind"]["table"],
769
        schema=targets["timeseries_cts_ind"]["schema"],
770
        con=db.engine(),
771
        if_exists="append",
772
    )
773
774
775
def timeseries_per_wz():
776
    """Calcultae and insert normalized timeseries per wz for cts and industry
777
778
    Returns
779
    -------
780
    None.
781
782
    """
783
784
    years = get_sector_parameters("global").weather_year.unique()
785
786
    for year in years:
787
788
        for sector in ["CTS", "industry"]:
789
790
            insert_timeseries_per_wz(sector, int(year))
791