-
Notifications
You must be signed in to change notification settings - Fork 4
/
hh_profiles.py
1534 lines (1279 loc) · 53.4 KB
/
hh_profiles.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
"""
Household electricity demand time series for scenarios in 2035 and 2050
Electricity demand data for households in Germany in 1-hourly resolution for
an entire year. Spatially, the data is resolved to 100 x 100 m cells and
provides individual and distinct time series for each household in a cell.
The cells are defined by the dataset Zensus 2011.
The resulting data is stored in two separate tables
* `demand.household_electricity_profiles_in_census_cells`:
Lists references and scaling parameters to time series data for each household
in a cell by identifiers. This table is fundamental for creating subsequent
data like demand profiles on MV grid level or for determining the peak load
at load area level.
The table is created by:func:`houseprofiles_in_census_cells`.
* `demand.household_electricity_profiles_hvmv_substation`:
Household electricity demand profiles aggregated at MV grid district level
in MWh. Primarily used to create the eTraGo data model.
The table is created with :func:`mv_grid_district_HH_electricity_load`.
The following datasets are used for creating the data:
* Electricity demand time series for household categories
produced by demand profile generator (DPG) from Fraunhofer IEE
(see :func:`get_iee_hh_demand_profiles_raw`)
* Spatial information about people living in households by Zensus 2011 at
federal state level
* Type of household (family status)
* Age
* Number of people
* Spatial information about number of households per ha, categorized by type
of household (family status) with 5 categories (also from Zensus 2011)
* Demand-Regio annual household demand at NUTS3 level
**What is the goal?**
To use the electricity demand time series from the `demand profile generator`
to created spatially reference household demand time series for Germany at a
resolution of 100 x 100 m cells.
**What is the challenge?**
The electricity demand time series produced by demand profile generator offer
12 different household profile categories.
To use most of them, the spatial information about the number of households
per cell (5 categories) needs to be enriched by supplementary data to match
the household demand profile categories specifications. Hence, 10 out of 12
different household profile categories can be distinguished by increasing
the number of categories of cell-level household data.
**How are these datasets combined?**
* Spatial information about people living in households by zensus (2011) at federal state NUTS1 level
:var:`df_zensus` is aggregated to be compatible to IEE household profile specifications.
* exclude kids and reduce to adults and seniors
* group as defined in :var:`HH_TYPES`
* convert data from people living in households to number of households by :var:`mapping_people_in_households`
* calculate fraction of fine household types (10) within subgroup of rough household types (5) :var:`df_dist_households`
* Spatial information about number of households per ha :var:`df_households_typ` is mapped to NUTS1 and NUTS3 level.
Data is enriched with refined household subgroups via :var:`df_dist_households` in :var:`df_zensus_cells`.
* Enriched 100 x 100 m household dataset is used to sample and aggregate household profiles. A table including
individual profile id's for each cell and scaling factor to match Demand-Regio annual sum projections for 2035 and 2050
at NUTS3 level is created in the database as `demand.household_electricity_profiles_in_census_cells`.
**What are central assumptions during the data processing?**
* Mapping zensus data to IEE household categories is not trivial. In
conversion from persons in household to number of
households, number of inhabitants for multi-person households is estimated
as weighted average in :var:`OO_factor`
* The distribution to refine household types at cell level are the same for
each federal state
* Refining of household types lead to float number of profiles drew at cell
level and need to be rounded to nearest int by np.rint().
* 100 x 100 m cells are matched to NUTS via cells centroid location
* Cells with households in unpopulated areas are removed
**Drawbacks and limitations of the data**
* The distribution to refine household types at cell level are the same for
each federal state
* Household profiles aggregated annual demand matches Demand Regio demand at
NUTS-3 level, but it is not matching the demand regio time series profile
* Due to secrecy, some census data are highly modified under certain attributes
(quantity_q = 2). This cell data is not corrected, but excluded.
* There is deviation in the Census data from table to table. The statistical
methods are not stringent. Hence, there are cases in which data contradicts.
* Census data with attribute 'HHTYP_FAM' is missing for some cells with small
amount of households. This data is generated using the average share of
household types for cells with similar household number. For some cells the
summed amount of households per type deviates from the total number with
attribute 'INSGESAMT'. As the profiles are scaled with demand-regio data at
nuts3-level the impact at a higher aggregation level is negligible.
For sake of simplicity, the data is not corrected.
Notes
-----
This module docstring is rather a dataset documentation. Once, a decision
is made in ... the content of this module docstring needs to be moved to
docs attribute of the respective dataset class.
"""
from functools import partial
from itertools import cycle, product
from pathlib import Path
import os
import random
from sqlalchemy import ARRAY, Column, Float, Integer, String
from sqlalchemy.dialects.postgresql import CHAR, INTEGER, REAL
from sqlalchemy.ext.declarative import declarative_base
import numpy as np
import pandas as pd
from egon.data import db
from egon.data.datasets import Dataset
from egon.data.datasets.zensus_mv_grid_districts import MapZensusGridDistricts
import egon.data.config
Base = declarative_base()
engine = db.engine()
# Get random seed from config
RANDOM_SEED = egon.data.config.settings()["egon-data"]["--random-seed"]
# Define mapping of census household family types to Eurostat household types
# - Adults living in households type
# - number of kids are not included even if mentioned in household type name
# **! The Eurostat data only counts adults/seniors, excluding kids <15**
# Eurostat household types are used for demand-profile-generator @iee-fraunhofer
HH_TYPES = {
"SR": [
("Einpersonenhaushalte (Singlehaushalte)", "Insgesamt", "Seniors"),
("Alleinerziehende Elternteile", "Insgesamt", "Seniors"),
],
# Single Seniors Single Parents Seniors
"SO": [
("Einpersonenhaushalte (Singlehaushalte)", "Insgesamt", "Adults")
], # Single Adults
"SK": [("Alleinerziehende Elternteile", "Insgesamt", "Adults")],
# Single Parents Adult
"PR": [
("Paare ohne Kind(er)", "2 Personen", "Seniors"),
("Mehrpersonenhaushalte ohne Kernfamilie", "2 Personen", "Seniors"),
],
# Couples without Kids Senior & same sex couples & shared flat seniors
"PO": [
("Paare ohne Kind(er)", "2 Personen", "Adults"),
("Mehrpersonenhaushalte ohne Kernfamilie", "2 Personen", "Adults"),
],
# Couples without Kids adults & same sex couples & shared flat adults
"P1": [("Paare mit Kind(ern)", "3 Personen", "Adults")],
"P2": [("Paare mit Kind(ern)", "4 Personen", "Adults")],
"P3": [
("Paare mit Kind(ern)", "5 Personen", "Adults"),
("Paare mit Kind(ern)", "6 und mehr Personen", "Adults"),
],
"OR": [
("Mehrpersonenhaushalte ohne Kernfamilie", "3 Personen", "Seniors"),
("Mehrpersonenhaushalte ohne Kernfamilie", "4 Personen", "Seniors"),
("Mehrpersonenhaushalte ohne Kernfamilie", "5 Personen", "Seniors"),
(
"Mehrpersonenhaushalte ohne Kernfamilie",
"6 und mehr Personen",
"Seniors",
),
("Paare mit Kind(ern)", "3 Personen", "Seniors"),
("Paare ohne Kind(er)", "3 Personen", "Seniors"),
("Paare mit Kind(ern)", "4 Personen", "Seniors"),
("Paare ohne Kind(er)", "4 Personen", "Seniors"),
("Paare mit Kind(ern)", "5 Personen", "Seniors"),
("Paare ohne Kind(er)", "5 Personen", "Seniors"),
("Paare mit Kind(ern)", "6 und mehr Personen", "Seniors"),
("Paare ohne Kind(er)", "6 und mehr Personen", "Seniors"),
],
# no info about share of kids
# OO, O1, O2 have the same amount, as no information about the share of kids
# within census data set. If needed the total amount can be estimated in the
# hh_tools.get_hh_dist function using multi_adjust=True option. The Eurostat
# share is then applied.
"OO": [
("Mehrpersonenhaushalte ohne Kernfamilie", "3 Personen", "Adults"),
("Mehrpersonenhaushalte ohne Kernfamilie", "4 Personen", "Adults"),
("Mehrpersonenhaushalte ohne Kernfamilie", "5 Personen", "Adults"),
(
"Mehrpersonenhaushalte ohne Kernfamilie",
"6 und mehr Personen",
"Adults",
),
("Paare ohne Kind(er)", "3 Personen", "Adults"),
("Paare ohne Kind(er)", "4 Personen", "Adults"),
("Paare ohne Kind(er)", "5 Personen", "Adults"),
("Paare ohne Kind(er)", "6 und mehr Personen", "Adults"),
],
# no info about share of kids
}
MAPPING_ZENSUS_HH_SUBGROUPS = {
1: ["SR", "SO"],
2: ["PR", "PO"],
3: ["SK"],
4: ["P1", "P2", "P3"],
5: ["OR", "OO"],
}
class IeeHouseholdLoadProfiles(Base):
__tablename__ = "iee_household_load_profiles"
__table_args__ = {"schema": "demand"}
id = Column(INTEGER, primary_key=True)
type = Column(CHAR(7), index=True)
load_in_wh = Column(ARRAY(REAL))
class HouseholdElectricityProfilesInCensusCells(Base):
__tablename__ = "egon_household_electricity_profile_in_census_cell"
__table_args__ = {"schema": "demand"}
cell_id = Column(Integer, primary_key=True)
grid_id = Column(String)
cell_profile_ids = Column(ARRAY(String, dimensions=1))
nuts3 = Column(String)
nuts1 = Column(String)
factor_2035 = Column(Float)
factor_2050 = Column(Float)
class EgonEtragoElectricityHouseholds(Base):
__tablename__ = "egon_etrago_electricity_households"
__table_args__ = {"schema": "demand"}
bus_id = Column(Integer, primary_key=True)
scn_name = Column(String, primary_key=True)
p_set = Column(ARRAY(Float))
q_set = Column(ARRAY(Float))
setup = partial(
Dataset,
name="HH Demand",
version="0.0.2.dev",
dependencies=[],
# Tasks are declared in pipeline as function is used multiple times with different args
# To differentiate these tasks PythonOperator with specific id-names are used
# PythonOperator needs to be declared in pipeline to be mapped to DAG
# tasks=[],
)
def clean(x):
"""Clean zensus household data row-wise
Clean dataset by
* converting '.' and '-' to str(0)
* removing brackets
Table can be converted to int/floats afterwards
Parameters
----------
x: pd.Series
It is meant to be used with :code:`df.applymap()`
Returns
-------
pd.Series
Re-formatted data row
"""
x = str(x).replace("-", str(0))
x = str(x).replace(".", str(0))
x = x.strip("()")
return x
def write_hh_profiles_to_db(hh_profiles):
"""Write HH demand profiles of IEE into db. One row per profile type.
The annual load profile timeseries is an array.
schema: demand
tablename: iee_household_load_profiles
Parameters
----------
hh_profiles: pd.DataFrame
It is meant to be used with :code:`df.applymap()`
Returns
-------
"""
hh_profiles = hh_profiles.rename_axis("type", axis=1)
hh_profiles = hh_profiles.rename_axis("timestep", axis=0)
hh_profiles = hh_profiles.stack().rename("load_in_wh")
hh_profiles = hh_profiles.to_frame().reset_index()
hh_profiles = hh_profiles.groupby("type").load_in_wh.apply(tuple)
hh_profiles = hh_profiles.reset_index()
IeeHouseholdLoadProfiles.__table__.drop(bind=engine, checkfirst=True)
IeeHouseholdLoadProfiles.__table__.create(bind=engine)
hh_profiles.to_sql(
name=IeeHouseholdLoadProfiles.__table__.name,
schema=IeeHouseholdLoadProfiles.__table__.schema,
con=engine,
if_exists="append",
method="multi",
chunksize=100,
index=False,
dtype={
"load_in_wh": IeeHouseholdLoadProfiles.load_in_wh.type,
"type": IeeHouseholdLoadProfiles.type.type,
"id": IeeHouseholdLoadProfiles.id.type,
},
)
def get_iee_hh_demand_profiles_raw():
"""Gets and returns household electricity demand profiles from the egon-data-bundle.
Household electricity demand profiles generated by Fraunhofer IEE.
Methodology is described in
:ref:`Erzeugung zeitlich hochaufgelöster Stromlastprofile für verschiedene
Haushaltstypen
<https://www.researchgate.net/publication/273775902_Erzeugung_zeitlich_hochaufgeloster_Stromlastprofile_fur_verschiedene_Haushaltstypen>`_.
It is used and further described in the following theses by:
* Jonas Haack:
"Auswirkungen verschiedener Haushaltslastprofile auf PV-Batterie-Systeme" (confidential)
* Simon Ruben Drauz
"Synthesis of a heat and electrical load profile for single and multi-family houses used for subsequent
performance tests of a multi-component energy system",
http://dx.doi.org/10.13140/RG.2.2.13959.14248
Returns
-------
pd.DataFrame
Table with profiles in columns and time as index. A pd.MultiIndex is
used to distinguish load profiles from different EUROSTAT household
types.
"""
data_config = egon.data.config.datasets()
pa_config = data_config["hh_demand_profiles"]
def ve(s):
raise (ValueError(s))
dataset = egon.data.config.settings()["egon-data"]["--dataset-boundary"]
file_section = (
"path"
if dataset == "Everything"
else "path_testmode"
if dataset == "Schleswig-Holstein"
else ve(f"'{dataset}' is not a valid dataset boundary.")
)
file_path = pa_config["sources"]["household_electricity_demand_profiles"][
file_section
]
download_directory = os.path.join(
"data_bundle_egon_data", "household_electricity_demand_profiles"
)
hh_profiles_file = (
Path(".") / Path(download_directory) / Path(file_path).name
)
df_hh_profiles = pd.read_hdf(hh_profiles_file)
return df_hh_profiles
def set_multiindex_to_profiles(hh_profiles):
"""The profile id is split into type and number and set as multiindex.
Parameters
----------
hh_profiles: pd.DataFrame
Profiles
Returns
-------
hh_profiles: pd.DataFrame
Profiles with Multiindex
"""
# set multiindex to HH_types
hh_profiles.columns = pd.MultiIndex.from_arrays(
[hh_profiles.columns.str[:2], hh_profiles.columns.str[3:]]
)
# Cast profile ids into tuple of type and int
hh_profiles.columns = pd.MultiIndex.from_tuples(
[(a, int(b)) for a, b in hh_profiles.columns]
)
return hh_profiles
def get_zensus_households_raw():
"""Get zensus age x household type data from egon-data-bundle
Dataset about household size with information about the categories:
* family type
* age class
* household size
for Germany in spatial resolution of federal states.
Data manually selected and retrieved from:
https://ergebnisse2011.zensus2022.de/datenbank/online
For reproducing data selection, please do:
* Search for: "1000A-3016"
* or choose topic: "Bevölkerung kompakt"
* Choose table code: "1000A-3016" with title "Personen: Alter (11 Altersklassen) - Größe des
privaten Haushalts - Typ des privaten Haushalts (nach Familien/Lebensform)"
- Change setting "GEOLK1" to "Bundesländer (16)"
Data would be available in higher resolution
("Landkreise und kreisfreie Städte (412)"), but only after registration.
The downloaded file is called 'Zensus2011_Personen.csv'.
Returns
-------
pd.DataFrame
Pre-processed zensus household data
"""
data_config = egon.data.config.datasets()
pa_config = data_config["hh_demand_profiles"]
file_path = pa_config["sources"]["zensus_household_types"]["path"]
download_directory = os.path.join(
"data_bundle_egon_data", "zensus_households"
)
households_file = (
Path(".") / Path(download_directory) / Path(file_path).name
)
households_raw = pd.read_csv(
households_file,
sep=";",
decimal=".",
skiprows=5,
skipfooter=7,
index_col=[0, 1],
header=[0, 1],
encoding="latin1",
engine="python",
)
return households_raw
def create_missing_zensus_data(
df_households_typ, df_missing_data, missing_cells
):
"""
There is missing data for specific attributes in the zensus dataset because
of secrecy reasons. Some cells with only small amount of households are
missing with the attribute HHTYP_FAM. However the total amount of households
is known with attribute INSGESAMT. The missing data is generated as average
share of the household types for cell groups with the same amount of
households.
Parameters
----------
df_households_typ: pd.DataFrame
Zensus households data
df_missing_data: pd.DataFrame
number of missing cells of group of amount of households
missing_cells: dict
dictionary with lists of grids of the missing cells grouped by amount of
households in cell
Returns
----------
df_average_split: pd.DataFrame
generated dataset of missing cells
"""
# grid_ids of missing cells grouped by amount of households
missing_grid_ids = {
group: list(df.grid_id)
for group, df in missing_cells.groupby("quantity")
}
# Grid ids for cells with low household numbers
df_households_typ = df_households_typ.set_index("grid_id", drop=True)
hh_in_cells = df_households_typ.groupby("grid_id")["quantity"].sum()
hh_index = {
i: hh_in_cells.loc[hh_in_cells == i].index
for i in df_missing_data.households.values
}
df_average_split = pd.DataFrame()
for hh_size, index in hh_index.items():
# average split of household types in cells with low household numbers
split = (
df_households_typ.loc[index].groupby("characteristics_code").sum()
/ df_households_typ.loc[index].quantity.sum()
)
split = split.quantity * hh_size
# correct rounding
difference = int(split.sum() - split.round().sum())
if difference > 0:
# add to any row
split = split.round()
random_row = split.sample()
split[random_row.index] = random_row + difference
elif difference < 0:
# subtract only from rows > 0
split = split.round()
random_row = split[split > 0].sample()
split[random_row.index] = random_row + difference
else:
split = split.round()
# Dataframe with average split for each cell
temp = pd.DataFrame(
product(zip(split, range(1, 6)), missing_grid_ids[hh_size]),
columns=["tuple", "grid_id"],
)
temp = pd.DataFrame(temp.tuple.tolist()).join(temp.grid_id)
temp = temp.rename(columns={0: "hh_5types", 1: "characteristics_code"})
temp = temp.dropna()
temp = temp[(temp["hh_5types"] != 0)]
# append for each cell group of households
df_average_split = pd.concat(
[df_average_split, temp], ignore_index=True
)
df_average_split["hh_5types"] = df_average_split["hh_5types"].astype(int)
return df_average_split
def get_hh_dist(df_zensus, hh_types):
"""
Group zensus data to fit Demand-Profile-Generator (DPG) format.
For more information look at the respective publication:
https://www.researchgate.net/publication/273775902_Erzeugung_zeitlich_hochaufgeloster_Stromlastprofile_fur_verschiedene_Haushaltstypen
Parameters
----------
df_zensus: pd.DataFrame
Zensus households data
hh_types: dict
Mapping of zensus groups to DPG groups
Returns
----------
df_hh_types: pd.DataFrame
distribution of people by household type and regional-resolution
.. warning::
Data still needs to be converted from amount of people to amount
of households
"""
# Cat O1 and O2 are removed as their share with/without kids is not clearly
# derivable without any further information. OO will therefore represent
# all multihousehold groups but the seniors.
adjust = {
"SR": 1,
"SO": 1,
"SK": 1,
"PR": 1,
"PO": 1,
"P1": 1,
"P2": 1,
"P3": 1,
"OR": 1,
"OO": 1,
"O1": 0,
"O2": 0,
}
df_hh_types = pd.DataFrame(
(
{
hhtype: adjust[hhtype] * df_zensus.loc[countries, codes].sum()
for hhtype, codes in hh_types.items()
}
for countries in df_zensus.index
),
index=df_zensus.index,
)
# drop zero columns
df_hh_types = df_hh_types.loc[:, (df_hh_types != 0).any(axis=0)]
return df_hh_types.T
def inhabitants_to_households(
df_people_by_householdtypes_abs, mapping_people_in_households
):
"""
Convert number of inhabitant to number of household types
Takes the distribution of peoples living in types of households to
calculate a distribution of household types by using a people-in-household
mapping.
Results are rounded to int (ceiled) to full households.
Parameters
----------
df_people_by_householdtypes_abs: pd.DataFrame
Distribution of people living in households
mapping_people_in_households: dict
Mapping of people living in certain types of households
Returns
----------
df_households_by_type: pd.DataFrame
Distribution of households type
.. warning::
By ceiling to full integers of people a small deviation is introduced.
"""
# compare categories and remove form mapping if to many
diff = set(df_people_by_householdtypes_abs.index) ^ set(
mapping_people_in_households.keys()
)
if bool(diff):
for key in diff:
mapping_people_in_households = dict(mapping_people_in_households)
del mapping_people_in_households[key]
print(f"Removed {diff} from mapping!")
# divide amount of people by people in household types
df_households_by_type = df_people_by_householdtypes_abs.div(
mapping_people_in_households, axis=0
)
# Number of people gets adjusted to integer values by ceiling
# This introduces a small deviation
df_households_by_type = df_households_by_type.apply(np.ceil)
return df_households_by_type
def process_nuts1_census_data(df_census_households_raw):
"""Make data compatible with household demand profile categories
Groups, removes and reorders categories which are not needed to fit data to household types of
IEE electricity demand time series generated by demand-profile-generator (DPG).
* Kids (<15) are excluded as they are also excluded in DPG origin dataset
* Adults (15<65)
* Seniors (<65)
Parameters
----------
df_census_households_raw: pd.DataFrame
cleaned zensus household type x age category data
Returns
-------
pd.DataFrame
Aggregated zensus household data on NUTS-1 level
"""
# Clean data to int only
df_census_households = df_census_households_raw.applymap(clean).applymap(int)
# Group data to fit Load Profile Generator categories
# define kids/adults/seniors
kids = ["Unter 3", "3 - 5", "6 - 14"] # < 15
adults = [
"15 - 17",
"18 - 24",
"25 - 29",
"30 - 39",
"40 - 49",
"50 - 64",
] # 15 < x <65
seniors = ["65 - 74", "75 und älter"] # >65
# sum groups of kids, adults and seniors and concat
df_kids = (
df_census_households.loc[:, (slice(None), kids)].groupby(level=0, axis=1).sum()
)
df_adults = (
df_census_households.loc[:, (slice(None), adults)].groupby(level=0, axis=1).sum()
)
df_seniors = (
df_census_households.loc[:, (slice(None), seniors)].groupby(level=0, axis=1).sum()
)
df_census_households = pd.concat(
[df_kids, df_adults, df_seniors],
axis=1,
keys=["Kids", "Adults", "Seniors"],
names=["age", "persons"],
)
# reduce column names to state only
mapping_state = {
i: i.split()[1] for i in df_census_households.index.get_level_values(level=0)
}
# rename index
df_census_households = df_census_households.rename(index=mapping_state, level=0)
# rename axis
df_census_households = df_census_households.rename_axis(["state", "type"])
# unstack
df_census_households = df_census_households.unstack()
# reorder levels
df_census_households = df_census_households.reorder_levels(
order=["type", "persons", "age"], axis=1
)
return df_census_households
def refine_census_data_at_cell_level(df_zensus):
"""The zensus data is processed to define the number and type of households
per zensus cell. Two subsets of the zensus data are merged to fit the
IEE profiles specifications. For this, the dataset 'HHTYP_FAM' is
converted from people living in households to number of households of
specific size using the category 'HHGROESS_KLASS' wherever the amount
of people is not trivial (OR, OO). Kids are not counted. Missing data
in 'HHTYP_FAM' is substituted in :func:`create_missing_zensus_data`.
Parameters
----------
df_zensus: pd.DataFrame
Aggregated zensus household data on NUTS-1 level
Returns
-------
pd.DataFrame
Number of hh types per census cell and scaling factors
"""
# hh_tools.get_hh_dist without eurostat adjustment for O1-03 Groups in
# absolute values
df_hh_types_nad_abs = get_hh_dist(df_zensus, HH_TYPES)
# Get household size for each census cell grouped by
# As this is only used to estimate size of households for OR, OO
# The hh types 1 P and 2 P households are dropped
df_hh_size = db.select_dataframe(
sql="""
SELECT characteristics_text, SUM(quantity) as summe
FROM society.egon_destatis_zensus_household_per_ha as egon_d
WHERE attribute = 'HHGROESS_KLASS' AND quantity_q < 2
GROUP BY characteristics_text """,
index_col="characteristics_text",
)
df_hh_size = df_hh_size.drop(index=["1 Person", "2 Personen"])
# Define/ estimate number of persons (w/o kids) for each household category
# For categories S* and P* it's clear; for multi-person households (OO,OR)
# the number is estimated as average by taking remaining persons
OO_factor = (
sum(df_hh_size["summe"] * [3, 4, 5, 6]) / df_hh_size["summe"].sum()
)
mapping_people_in_households = {
"SR": 1,
"SO": 1,
"SK": 1, # kids are excluded
"PR": 2,
"PO": 2,
"P1": 2, # kids are excluded
"P2": 2, # ""
"P3": 2, # ""
"OR": OO_factor,
"OO": OO_factor,
}
# Determine number of persons living in each household type
df_dist_households = inhabitants_to_households(
df_hh_types_nad_abs, mapping_people_in_households
)
# Calculate fraction of fine household types within subgroup of
# rough household types
for value in MAPPING_ZENSUS_HH_SUBGROUPS.values():
df_dist_households.loc[value] = df_dist_households.loc[value].div(
df_dist_households.loc[value].sum()
)
# Retrieve information about households for each census cell
# Only use cell-data which quality (quantity_q<2) is acceptable
df_households_typ = db.select_dataframe(
sql="""
SELECT grid_id, attribute, characteristics_code, characteristics_text, quantity
FROM society.egon_destatis_zensus_household_per_ha
WHERE attribute = 'HHTYP_FAM' AND quantity_q <2"""
)
df_households_typ = df_households_typ.drop(
columns=["attribute", "characteristics_text"]
)
# Missing data is detected
df_missing_data = db.select_dataframe(
sql="""
SELECT count(joined.quantity_gesamt) as amount, joined.quantity_gesamt as households
FROM(
SELECT t2.grid_id, quantity_gesamt, quantity_sum_fam,
(quantity_gesamt-(case when quantity_sum_fam isnull then 0 else quantity_sum_fam end))
as insgesamt_minus_fam
FROM (
SELECT grid_id, SUM(quantity) as quantity_sum_fam
FROM society.egon_destatis_zensus_household_per_ha
WHERE attribute = 'HHTYP_FAM'
GROUP BY grid_id) as t1
Full JOIN (
SELECT grid_id, sum(quantity) as quantity_gesamt
FROM society.egon_destatis_zensus_household_per_ha
WHERE attribute = 'INSGESAMT'
GROUP BY grid_id) as t2 ON t1.grid_id = t2.grid_id
) as joined
WHERE quantity_sum_fam isnull
Group by quantity_gesamt """
)
missing_cells = db.select_dataframe(
sql="""
SELECT t12.grid_id, t12.quantity
FROM (
SELECT t2.grid_id, (case when quantity_sum_fam isnull then quantity_gesamt end) as quantity
FROM (
SELECT grid_id, SUM(quantity) as quantity_sum_fam
FROM society.egon_destatis_zensus_household_per_ha
WHERE attribute = 'HHTYP_FAM'
GROUP BY grid_id) as t1
Full JOIN (
SELECT grid_id, sum(quantity) as quantity_gesamt
FROM society.egon_destatis_zensus_household_per_ha
WHERE attribute = 'INSGESAMT'
GROUP BY grid_id) as t2 ON t1.grid_id = t2.grid_id
) as t12
WHERE quantity is not null"""
)
# Missing cells are substituted by average share of cells with same amount
# of households.
df_average_split = create_missing_zensus_data(
df_households_typ, df_missing_data, missing_cells
)
df_households_typ = df_households_typ.rename(
columns={"quantity": "hh_5types"}
)
df_households_typ = pd.concat(
[df_households_typ, df_average_split], ignore_index=True
)
# Census cells with nuts3 and nuts1 information
df_grid_id = db.select_dataframe(
sql="""
SELECT pop.grid_id, pop.id as cell_id, vg250.vg250_nuts3 as nuts3, lan.nuts as nuts1, lan.gen
FROM society.destatis_zensus_population_per_ha_inside_germany as pop
LEFT JOIN boundaries.egon_map_zensus_vg250 as vg250
ON (pop.id=vg250.zensus_population_id)
LEFT JOIN boundaries.vg250_lan as lan
ON (LEFT(vg250.vg250_nuts3, 3)=lan.nuts)
WHERE lan.gf = 4 """
)
df_grid_id = df_grid_id.drop_duplicates()
df_grid_id = df_grid_id.reset_index(drop=True)
# Merge household type and size data with considered (populated) census
# cells how='inner' is used as ids of unpopulated areas are removed
# df_grid_id or earliers tables. See here:
# https://github.com/openego/eGon-data/blob/59195926e41c8bd6d1ca8426957b97f33ef27bcc/src/egon/data/importing/zensus/__init__.py#L418-L449
df_households_typ = pd.merge(
df_households_typ,
df_grid_id,
left_on="grid_id",
right_on="grid_id",
how="inner",
)
# Merge Zensus nuts1 level household data with zensus cell level 100 x 100 m
# by refining hh-groups with MAPPING_ZENSUS_HH_SUBGROUPS
df_zensus_cells = pd.DataFrame()
for (country, code), df_country_type in df_households_typ.groupby(
["gen", "characteristics_code"]
):
# iterate over zenus_country subgroups
for typ in MAPPING_ZENSUS_HH_SUBGROUPS[code]:
df_country_type["hh_type"] = typ
df_country_type["factor"] = df_dist_households.loc[typ, country]
df_country_type["hh_10types"] = (
df_country_type["hh_5types"]
* df_dist_households.loc[typ, country]
)
df_zensus_cells = df_zensus_cells.append(
df_country_type, ignore_index=True
)
df_zensus_cells = df_zensus_cells.sort_values(
by=["grid_id", "characteristics_code"]
).reset_index(drop=True)
return df_zensus_cells
def get_cell_demand_profile_ids(df_cell, pool_size):
"""
Generates tuple of hh_type and zensus cell ids
Takes a random sample of profile ids for given cell:
* if pool size >= sample size: without replacement
* if pool size < sample size: with replacement
The number of households are rounded to the nearest integer if float.
Parameters
----------
df_cell: pd.DataFrame
Household type information for a single zensus cell
pool_size: int
Number of available profiles to select from
Returns
-------
list of tuple
List of (`hh_type`, `cell_id`)
"""
# maybe use instead
# np.random.default_rng().integers(low=0, high=pool_size[hh_type], size=sq)
# instead of random.sample use random.choices() if with replacement
# list of sample ids per hh_type in cell
cell_profile_ids = [
(hh_type, random.sample(range(pool_size[hh_type]), k=sq))
if pool_size[hh_type] >= sq
else (hh_type, random.choices(range(pool_size[hh_type]), k=sq))
for hh_type, sq in zip(
df_cell["hh_type"],
np.rint(df_cell["hh_10types"].values).astype(int),
)
]
# format to lists of tuples (hh_type, id)
cell_profile_ids = [
list(zip(cycle([hh_type]), ids)) for hh_type, ids in cell_profile_ids
]
# reduce to list
cell_profile_ids = [a for b in cell_profile_ids for a in b]
return cell_profile_ids
# can be parallelized with grouping df_zensus_cells by grid_id/nuts3/nuts1
def allocate_hh_demand_profiles_to_cells(df_zensus_cells, df_iee_profiles):
"""
Allocates household demand profiles to each census cell.
A table including the demand profile ids for each cell is created by using
:func:`get_cell_demand_profile_ids`. Household profiles are randomly sampled
for each cell. The profiles are not replaced to the pool within a cell but
after. The number of households are rounded to the nearest integer if float.
This results in a small deviation for the course of the aggregated profiles.
Parameters
----------
df_zensus_cells: pd.DataFrame
Household type parameters. Each row representing one household. Hence,
multiple rows per zensus cell.
df_iee_profiles: pd.DataFrame
Household load profile data
* Index: Times steps as serial integers
* Columns: pd.MultiIndex with (`HH_TYPE`, `id`)
Returns
-------
pd.DataFrame
Tabular data with one row represents one zensus cell.
The column `cell_profile_ids` contains
a list of tuples (see :func:`get_cell_demand_profile_ids`) providing a
reference to the actual load profiles that are associated with this
cell.
"""
df_hh_profiles_in_census_cells = pd.DataFrame(
index=df_zensus_cells.grid_id.unique(),
columns=[
"cell_profile_ids",
"cell_id",
"nuts3",
"nuts1",
"factor_2035",