database_queries.py 49.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python3

# Copyright (C) 2022:
#   Helmholtz-Zentrum Potsdam Deutsches GeoForschungsZentrum GFZ
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.

import logging
20
21
import numpy
import pandas
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
from gdeimporter.tools.database import Database


logger = logging.getLogger()


class DatabaseQueries:
    """This class contains methods used to query the OpenBuildingMap (OBM) and Global Dynamic
    Exposure (GDE) databases.
    """

    @staticmethod
    def retrieve_aggregated_source_id_and_format(model_name, db_gde_tiles_config, db_table):
        """This function retrieves the ID of the aggregated exposure model source whose name is
        'model_name'.

        Args:
            model_name (str):
                Name of the source whose ID is to be retrieved.
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which information on the aggregated_sources is stored. The keys of the
                dictionary need to be:
                    host (str):
                        SQL database host address.
                    dbname (str):
                        Name of the SQL database.
                    port (int):
                        Port where the SQL database can be found.
                    username (str):
                        User name to connect to the SQL database.
                    password (str):
                        Password associated with self.username.
            db_table (str):
                Name of the table of the SQL database where the aggregated_sources are stored.
                It is assumed that this table contains, at least, the following fields:
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
                    name (str):
                        Name of the source of the aggregated exposure model.

        Returns:
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model with name 'model_name'. If
                'model_name' is not found, 'aggregated_source_id' is -999.
            aggregated_source_format (str):
                Format of the aggregated exposure model with name 'model_name'. If 'model_name'
                is not found, 'aggregated_source_format' is "UNKNOWN".
        """

        sql_query = "SELECT aggregated_source_id, format FROM %s WHERE name='%s';"

        db_gde_tiles = Database(**db_gde_tiles_config)
        db_gde_tiles.create_connection_and_cursor()

        db_gde_tiles.cursor.execute(sql_query % (db_table, model_name))
        exec_result = db_gde_tiles.cursor.fetchall()

        db_gde_tiles.close_connection()

        if len(exec_result) == 1:  # Entry exists --> retrieve
            aggregated_source_id = exec_result[0][0]
            aggregated_source_format = exec_result[0][1]
        else:  # More than one entries found, this is an error
            logger.error(
                "Error in retrieve_aggregated_source_id_and_format: "
                "more than one or no entry found for name = %s" % (model_name)
            )
            aggregated_source_id = -999
            aggregated_source_format = "UNKNOWN"

        return aggregated_source_id, aggregated_source_format

    @staticmethod
    def retrieve_all_exposure_entities_of_aggregated_source_id(
        aggregated_source_id, db_gde_tiles_config, db_table
    ):
        """This function retrieves the 3-character codes of all exposure entities associated
        with 'aggregated_source_id' in 'db_table' of the database whose credentials are given by
        'db_gde_tiles_config'.

        Args:
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model to be run.
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which information on exposure entities is stored. The keys of the dictionary
                need to be:
                    host (str):
                        SQL database host address.
                    dbname (str):
                        Name of the SQL database.
                    port (int):
                        Port where the SQL database can be found.
                    username (str):
                        User name to connect to the SQL database.
                    password (str):
                        Password associated with self.username.
            db_table (str):
                Name of the table of the SQL database from which the exposure entities can be
                retrieved. It is assumed that this table contains, at least, the following
                fields:
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
                    exposure_entity (str):
                        3-character code of the exposure entity.

        Returns:
            exposure_entities (list of str):
                List of 3-character codes of the exposure entities associated with
                'aggregated_source_id'.
        """

        sql_query = "SELECT DISTINCT(exposure_entity) FROM %s WHERE aggregated_source_id=%s;"

        db_gde_tiles = Database(**db_gde_tiles_config)
        db_gde_tiles.create_connection_and_cursor()

        db_gde_tiles.cursor.execute(sql_query % (db_table, aggregated_source_id))
        exec_result = db_gde_tiles.cursor.fetchall()

        db_gde_tiles.close_connection()

        if len(exec_result) > 0:
            exposure_entities = [exec_result[i][0] for i in range(len(exec_result))]
        else:
            exposure_entities = []

        return exposure_entities

    @staticmethod
    def retrieve_quadkeys_by_exposure_entity_aggregated_source_id(
        exposure_entity, aggregated_source_id, db_gde_tiles_config, db_table
    ):
        """
        This function retrives all quadkeys associated with 'exposure_entity' and
        'aggregated_source_id' in 'db_table' of the database whose credentials are given in
        'db_gde_tiles_config'.

        Args:
            exposure_entity (str):
                3-character code of the exposure entity for which the data unit IDs and
                geometries will be retrieved.
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model for which the data unit IDs
                and geometries will be retrieved.
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which information on the data units is stored. The keys of the dictionary need
                to be:
                    host (str):
                        SQL database host address.
                    dbname (str):
                        Name of the SQL database.
                    port (int):
                        Port where the SQL database can be found.
                    username (str):
                        User name to connect to the SQL database.
                    password (str):
                        Password associated with self.username.
            db_table (str):
                Name of the table of the SQL database where the data units are stored. It is
                assumed that this table contains, at least, the following fields:
                    quadkey (str):
                        String indicating the quadkey of a tile.
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
                    exposure_entity (str):
                        3-character code of the exposure entity.

        Returns:
            quadkeys (list of str):
                List of all quadkeys associated with 'exposure_entity' and
                'aggregated_source_id'.
        """

        sql_query = "SELECT DISTINCT(quadkey) FROM %s "
        sql_query += "WHERE exposure_entity='%s' AND aggregated_source_id=%s;"

        db_gde_tiles = Database(**db_gde_tiles_config)
        db_gde_tiles.create_connection_and_cursor()

        db_gde_tiles.cursor.execute(
            sql_query % (db_table, exposure_entity, aggregated_source_id)
        )
        exec_result = db_gde_tiles.cursor.fetchall()

        db_gde_tiles.close_connection()

        if len(exec_result) > 0:
            quadkeys = [exec_result[i][0] for i in range(len(exec_result))]
        else:
            quadkeys = []

        return quadkeys

    @staticmethod
    def retrieve_quadkeys_by_data_unit_id_aggregated_source_id(
        data_unit_id, aggregated_source_id, db_gde_tiles_config, db_table
    ):
        """
        This function retrives all quadkeys associated with 'data_unit_id' and
        'aggregated_source_id' in 'db_table' of the database whose credentials are given in
        'db_gde_tiles_config'.

        Args:
            data_unit_id (str):
                 ID of the data unit for which the quadkeys will be retrieved.
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model for which the data unit IDs
                and geometries will be retrieved.
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which information on the data units is stored. The keys of the dictionary need
                to be:
                    host (str):
                        SQL database host address.
                    dbname (str):
                        Name of the SQL database.
                    port (int):
                        Port where the SQL database can be found.
                    username (str):
                        User name to connect to the SQL database.
                    password (str):
                        Password associated with self.username.
            db_table (str):
                Name of the table of the SQL database where the data units are stored. It is
                assumed that this table contains, at least, the following fields:
                    quadkey (str):
                        String indicating the quadkey of a tile.
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
                    data_unit_id (str):
                        ID of the data unit.

        Returns:
            quadkeys (list of str):
                List of all quadkeys associated with 'data_unit_id' and 'aggregated_source_id'.
        """

        sql_query = "SELECT DISTINCT(quadkey) FROM %s "
        sql_query += "WHERE data_unit_id='%s' AND aggregated_source_id=%s;"

        db_gde_tiles = Database(**db_gde_tiles_config)
        db_gde_tiles.create_connection_and_cursor()

        db_gde_tiles.cursor.execute(sql_query % (db_table, data_unit_id, aggregated_source_id))
        exec_result = db_gde_tiles.cursor.fetchall()

        db_gde_tiles.close_connection()

        if len(exec_result) > 0:
            quadkeys = [exec_result[i][0] for i in range(len(exec_result))]
        else:
            quadkeys = []

        return quadkeys
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

    @staticmethod
    def retrieve_data_unit_ids(
        quadkey,
        aggregated_source_id,
        exposure_entities,
        occupancy_case,
        db_gde_tiles_config,
        db_table,
    ):
        """
        This function retrieves the data unit IDs associated with 'quadkey',
        'aggregated_source_id', 'occupancy_case' and any of the exposure entities listed in
        'exposure_entities' in the table 'db_table' of the database whose credentials are given
        by 'db_gde_tiles_config'.

        Args:
            quadkey (str):
                Quadkey of the zoom level 18 data-unit tile for which the data unit IDs will be
                retrieved.
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model for which the data unit IDs
                will be retrieved.
            exposure_entities (list of str):
                List of names of the exposure entities for which the data unit IDs will be
                retrieved.
            occupancy_case (str):
                Name of the occupancy case (e.g. "residential", "commercial", "industrial")
                for which the data unit IDs will be retrieved.
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which information on the data-unit tiles is stored. The keys of the dictionary
                need to be:
                    host (str):
                        SQL database host address.
                    dbname (str):
                        Name of the SQL database.
                    port (int):
                        Port where the SQL database can be found.
                    username (str):
                        User name to connect to the SQL database.
                    password (str):
                        Password associated with self.username.
            db_table (str):
                Name of the table of the SQL database where the data-unit tiles are stored. It
                is assumed that this table contains, at least, the following fields:
                    quadkey (str):
                        String indicating the quadkey of a tile.
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
                    occupancy_case (enum):
                        SQL enumerated type describing the building occupancy cases.
                    exposure_entity (str):
                        3-char identifier of the exposure entity. If a country, ISO3 code.
                    data_unit_id (str):
                        ID of the data unit.

        Returns:
            data_unit_ids (list of str):
                List of data unit IDs associated with the query.
        """

        if not isinstance(exposure_entities, list):
            logger.warning(
                "'exposure_entities' passed to retrieve_data_unit_ids is not a list: "
                "results of the query are likely invalid"
            )

        # Convert exposure entities into a string to feed in to the query
        exposure_entities_aux = [
            "exposure_entity='%s'" % (exposure_entities[i])
            for i in range(len(exposure_entities))
        ]
        exposure_entities_condition = " OR ".join(exposure_entities_aux)

        sql_query = "SELECT data_unit_id FROM %s "
        sql_query += "WHERE (quadkey='%s' AND aggregated_source_id=%s AND occupancy_case='%s' "
        sql_query += "AND (%s));"

        db_gde_tiles = Database(**db_gde_tiles_config)
        db_gde_tiles.create_connection_and_cursor()

        db_gde_tiles.cursor.execute(
            sql_query
            % (
                db_table,
                quadkey,
                aggregated_source_id,
                occupancy_case,
                exposure_entities_condition,
            )
        )
        exec_result = db_gde_tiles.cursor.fetchall()

        db_gde_tiles.close_connection()

        if len(exec_result) > 0:  # Entries exist --> retrieve
            data_unit_ids = [exec_result[i][0] for i in range(len(exec_result))]
        else:
            data_unit_ids = []

        return data_unit_ids

    @staticmethod
    def get_numbers_buildings_for_data_unit_tile(
        quadkey,
        aggregated_source_id,
        occupancy_case,
        data_unit_id,
        db_gde_tiles_config,
        db_table,
    ):
        """This function retrieves the number of remainder, aggregated and total buildings of
        the data-unit tile defined by the combination of 'quadkey', 'aggregated_source_id',
        'occupancy_case' and 'data_unit_id' from the table 'db_table' of the database whose
        credentials are given by 'db_gde_tiles_config'.

        Args:
            quadkey (str):
                Quadkey of the zoom level 18 data-unit tile for which the number of buildings
                will be retrieved.
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model for which the number of
                buildings will be retrieved.
            occupancy_case (str):
                Name of the occupancy case (e.g. "residential", "commercial", "industrial")
                for which the number of buildings will be retrieved.
            data_unit_id (str):
                ID of the data unit for which the number of buildings will be retrieved.
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which information on the data-unit tiles is stored. The keys of the dictionary
                need to be:
                    host (str):
                        SQL database host address.
                    dbname (str):
                        Name of the SQL database.
                    port (int):
                        Port where the SQL database can be found.
                    username (str):
                        User name to connect to the SQL database.
                    password (str):
                        Password associated with self.username.
            db_table (str):
                Name of the table of the SQL database where the data-unit tiles are stored. It
                is assumed that this table contains, at least, the following fields:
                    quadkey (str):
                        String indicating the quadkey of a tile.
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
                    occupancy_case (enum):
                        SQL enumerated type describing the building occupancy cases.
                    exposure_entity (str):
                        3-char identifier of the exposure entity. If a country, ISO3 code.
                    data_unit_id (str):
                        ID of the data unit.
                    aggregated_buildings (float):
                        Number of buildings in the data-unit tile as per the aggregated exposure
                        model with ID 'aggregated_source_id'.
                    obm_buildings (int):
                        Number of OBM buildings in the data-unit tile as per the aggregated
                        exposure model with ID 'aggregated_source_id'.
                    remainder_buildings (float):
                        Number of remainder buildings in the data-unit tile as per the
                        aggregated exposure model with ID 'aggregated_source_id'.

        Returns:
            number_aggregated (float):
                Number of aggregated buildings in the data-unit tile.
            number_obm (float):
                Number of OBM buildings in the data-unit tile.
            number_remainder (float):
                Number of remainder buildings in the data-unit tile.
        """

        sql_query = "SELECT aggregated_buildings, obm_buildings, remainder_buildings "
        sql_query += "FROM %s WHERE (quadkey='%s' AND aggregated_source_id=%s "
        sql_query += "AND occupancy_case ='%s' AND data_unit_id='%s');"

        db_gde_tiles = Database(**db_gde_tiles_config)
        db_gde_tiles.create_connection_and_cursor()

        db_gde_tiles.cursor.execute(
            sql_query % (db_table, quadkey, aggregated_source_id, occupancy_case, data_unit_id)
        )
        exec_result = db_gde_tiles.cursor.fetchall()

        db_gde_tiles.close_connection()

        if len(exec_result) == 1:  # Entry found
            number_aggregated = exec_result[0][0]
            number_obm = exec_result[0][1]
            number_remainder = exec_result[0][2]
        elif len(exec_result) == 0:  # No entry found
            number_aggregated = -999.9
            number_obm = -999
            number_remainder = -999.9
        else:  # More than one entries found, this is an error
            # This should not happen, as the database should not allow two entries with the
            # same primary key
            number_aggregated = -999.9
            number_obm = -999
            number_remainder = -999.9
            logger.error(
                "ERROR in get_numbers_buildings_for_data_unit_tile: "
                "more than one entry found for quadkey='%s' AND aggregated_source_id=%s "
                "AND occupancy_case ='%s' AND data_unit_id='%s' "
                % (quadkey, aggregated_source_id, occupancy_case, data_unit_id)
            )

        return number_aggregated, number_obm, number_remainder

    @staticmethod
    def get_building_classes_of_data_unit(
        data_unit_id, occupancy_case, aggregated_source_id, db_gde_tiles_config, db_table
    ):
        """This function retrieves the building classes and proportions as per
        'aggregated_source_id' associated with a data unit with 'data_unit_id' and
        'occupancy_case', from 'db_table' of the database whose credentials are given in
        'db_gde_tiles_config'. The building classes are defined in terms of three parameters:
        the building_class_name, the settlement_type and the occupancy_subtype.

        Args:
            data_unit_id (str):
                ID of the data unit for which the building classes and their proportions will be
                retrieved.
            occupancy_case (str):
                Name of the occupancy case (e.g. "residential", "commercial", "industrial")
                for which the building classes and their proportions will be retrieved.
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model for which the building classes
                and their proportions will be retrieved.
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which information on the data unit buildings is stored. The keys of the
                dictionary need to be:
                    host (str):
                        SQL database host address.
                    dbname (str):
                        Name of the SQL database.
                    port (int):
                        Port where the SQL database can be found.
                    username (str):
                        User name to connect to the SQL database.
                    password (str):
                        Password associated with self.username.
            db_table (str):
                Name of the table of the SQL database where the data-unit buildings are stored.
                It is assumed that this table contains, at least, the following fields:
                    building_class_name (str):
                        Building class as per the GEM Building Taxonomy.
                    settlement_type (enum):
                        Type of settlement within the data unit. Possible values: "urban",
                        "rural", "big_city", "all".
                    occupancy_subtype (str):
                        Details on the occupancy, if relevant to characterise the building
                        class.
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
                    occupancy_case (enum):
                        SQL enumerated type describing the building occupancy cases.
                    data_unit_id (str):
                        ID of the data unit.
                    proportions (float):
                        Proportions in which the building class (defined by
                        'building_class_name', 'settlement_type' and 'occupancy_subtype') is
                        present in the data unit.
                    census_people_per_building (float):
                        Number of census-derived people per building (i.e. not accounting for
                        time of the day).
                    total_cost_per_building (float):
                        Total replacement cost per building, including costs of structural and
                        non-structural components as well as contents.

        Returns:
            building_classes (Pandas DataFrame):
                DataFrame containing the building classes and their proportions. It comprises
                the following columns:
                    building_class_name (str):
                        Building class as per the GEM Building Taxonomy.
                    settlement_type (str):
                        Type of settlement within the data unit. Possible values: "urban",
                        "rural", "big_city", "all".
                    occupancy_subtype (str):
                        Details on the occupancy, if relevant to characterise the building
                        class.
                    proportions (float):
                        Proportions in which the building class (defined by
                        'building_class_name', 'settlement_type' and 'occupancy_subtype') is
                        present in the data unit.
                    census_people_per_building (float):
                        Number of census-derived people per building (i.e. not accounting for
                        time of the day).
                    total_cost_per_building (float):
                        Total replacement cost per building, including costs of structural and
                        non-structural components as well as contents.
        """

        sql_query = "SELECT building_class_name, settlement_type, occupancy_subtype, "
        sql_query += "proportions, census_people_per_building, total_cost_per_building FROM %s "
        sql_query += "WHERE (data_unit_id='%s' AND occupancy_case='%s' AND "
        sql_query += "aggregated_source_id=%s);"

        db_gde_tiles = Database(**db_gde_tiles_config)
        db_gde_tiles.create_connection_and_cursor()

        db_gde_tiles.cursor.execute(
            sql_query % (db_table, data_unit_id, occupancy_case, aggregated_source_id)
        )
        exec_result = db_gde_tiles.cursor.fetchall()

        db_gde_tiles.close_connection()

        if len(exec_result) > 0:  # Entries exist --> retrieve
            building_class_names = numpy.array(
                [exec_result[i][0] for i in range(len(exec_result))], dtype="str"
            )
            settlement_types = numpy.array(
                [exec_result[i][1] for i in range(len(exec_result))], dtype="str"
            )
            occupancy_subtypes = numpy.array(
                [exec_result[i][2] for i in range(len(exec_result))], dtype="str"
            )
            proportions = numpy.array(
                [exec_result[i][3] for i in range(len(exec_result))], dtype="float"
            )
            census_people_per_building = numpy.array(
                [exec_result[i][4] for i in range(len(exec_result))], dtype="float"
            )
            total_cost_per_building = numpy.array(
                [exec_result[i][5] for i in range(len(exec_result))], dtype="float"
            )

            if abs(proportions.sum() - 1.0) > 1e-5:
                warning_message = (
                    "DatabaseQueries.get_building_classes_of_data_unit: the sum of proportions "
                    "of building classes found for 'data_unit_id'=%s, 'occupancy_case'=%s and "
                    "'aggregated_source_id'=%s is different from 1.0; actual value is %s."
                    % (
                        data_unit_id,
                        occupancy_case,
                        aggregated_source_id,
                        "{:.6f}".format(proportions.sum()),
                    )
                )
                logger.warning(warning_message)

        else:  # No entries found
            building_class_names = numpy.array([], dtype="str")
            settlement_types = numpy.array([], dtype="str")
            occupancy_subtypes = numpy.array([], dtype="str")
            proportions = numpy.array([], dtype="float")
            census_people_per_building = numpy.array([], dtype="float")
            total_cost_per_building = numpy.array([], dtype="float")

        building_classes = pandas.DataFrame(
            {
                "building_class_name": building_class_names,
                "settlement_type": settlement_types,
                "occupancy_subtype": occupancy_subtypes,
                "proportions": proportions,
                "census_people_per_building": census_people_per_building,
                "total_cost_per_building": total_cost_per_building,
            }
        )

        return building_classes

    @staticmethod
    def get_exposure_entities_costs_assumptions(
        cost_cases,
        exposure_entity,
        occupancy_case,
        aggregated_source_id,
        db_gde_tiles_config,
        db_table,
    ):
        """
        This function retrieves the factors by which the total replacement cost of a building
        can be multiplied to disaggregate it into the cost of structural and non-structural
        components, as well as contents. The factors retrieved are those indicated in the
        'cost_cases' dictionary, whose keys are names of relevance for the output (user-defined)
        and whose values can be any of the three cases existing in the
        'exposure_entities_costs_assumptions' table of the GDE Tiles database ("structural",
        "non-structural", "contents"), as well as "total". The factor for "total" is 1.

        Args:
            cost_cases (dict):
                Dictionary containing indications on the sort of costs to retrieve. The names of
                the keys can be arbitrary, but the values can only be "structural",
                "non-structural", "contents" or "total".
            exposure_entity (str):
                3-char identifier of the exposure entity for which the cost assumptions will be
                retrieved. If a country, ISO3 code.
            occupancy_case (str):
                Name of the occupancy case (e.g. "residential", "commercial", "industrial")
                for which the cost assumptions will be retrieved.
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model for which the building classes
                and their proportions will be retrieved.
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which information on the cost assumptions is stored. The keys of the dictionary
                need to be:
                    host (str):
                        SQL database host address.
                    dbname (str):
                        Name of the SQL database.
                    port (int):
                        Port where the SQL database can be found.
                    username (str):
                        User name to connect to the SQL database.
                    password (str):
                        Password associated with self.username.
            db_table (str):
                Name of the table of the SQL database where information on the cost assumptions
                is stored. It is assumed that this table contains, at least, the following
                fields:
                    exposure_entity (str):
                        3-character code of the exposure entity.
                    occupancy_case (enum):
                        SQL enumerated type describing the building occupancy cases.
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
                    structural (float):
                        Factor to obtain the cost of the structural components.
                    non_structural (float):
                        Factor to obtain the cost of the non-structural components.
                    contents (float):
                        Factor to obtain the cost of the building contents.

        Returns:
            cost_assumptions (dict):
                Dictionary with the same keys as the input 'cost_cases' and whose values are the
                retrieved factors.
        """

        # Retrieving all fields and then sorting out as per 'cost_cases' as it is simpler
        sql_query = "SELECT structural, non_structural, contents FROM %s "
        sql_query += "WHERE (exposure_entity='%s' AND occupancy_case='%s' AND "
        sql_query += "aggregated_source_id='%s');"

        db_gde_tiles = Database(**db_gde_tiles_config)
        db_gde_tiles.create_connection_and_cursor()

        db_gde_tiles.cursor.execute(
            sql_query % (db_table, exposure_entity, occupancy_case, aggregated_source_id)
        )
        exec_result = db_gde_tiles.cursor.fetchall()

        db_gde_tiles.close_connection()

        retrieved = {}
        if len(exec_result) == 1:  # Entries exist --> retrieve
            retrieved["structural"] = exec_result[0][0]
            retrieved["non_structural"] = exec_result[0][1]
            retrieved["contents"] = exec_result[0][2]
            retrieved["total"] = 1.0
        else:
            logger.error(
                "ERROR in get_exposure_entities_costs_assumptions: "
                "more than one entry or no entry found for exposure_entity='%s' "
                "AND occupancy_case ='%s' AND aggregated_source_id='%s' "
                % (exposure_entity, occupancy_case, aggregated_source_id)
            )
            retrieved["structural"] = 0.0
            retrieved["non_structural"] = 0.0
            retrieved["contents"] = 0.0
            retrieved["total"] = 0.0

        cost_assumptions = {}
        for cost_case_key in cost_cases.keys():
            cost_assumptions[cost_case_key] = retrieved[cost_cases[cost_case_key]]

        return cost_assumptions

    @staticmethod
    def get_exposure_entities_population_time_distribution(
        people_cases,
        exposure_entity,
        occupancy_case,
        aggregated_source_id,
        db_gde_tiles_config,
        db_table,
    ):
        """
        This function retrieves the factors by which the census population per building can be
        multiplied to obtain an estimate of the people in the buildings at a certain time of the
        day. The factors retrieved are those indicated in the 'people_cases' dictionary, whose
        keys are names of relevance for the output (user-defined) and whose values can be any of
        the three cases existing in the 'exposure_entities_population_time_distribution' table
        of the GDE Tiles database ("day", "night", "transit"), as well as "census" and
        "average". The factor for "census" is 1, while that for "average" is the average of
        "day", "night", "transit".

        Args:
            people_cases (dict):
                Dictionary containing indications on the times of the day to retrieve. The names
                of the keys can be arbitrary, but the values can only be "day", "night",
                "transit", "census" or "average".
            exposure_entity (str):
                3-char identifier of the exposure entity for which the factors for the
                distribution of the popupation in time will be retrieved. If a country, ISO3
                code.
            occupancy_case (str):
                Name of the occupancy case (e.g. "residential", "commercial", "industrial")
                for which the factors for the distribution of the popupation in time will be
                retrieved.
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model for which the factors for the
                distribution of the popupation in time will be retrieved.
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which information on the distribution of the population at different times of
                the day is stored. The keys of the dictionary need to be:
                    host (str):
                        SQL database host address.
                    dbname (str):
                        Name of the SQL database.
                    port (int):
                        Port where the SQL database can be found.
                    username (str):
                        User name to connect to the SQL database.
                    password (str):
                        Password associated with self.username.
            db_table (str):
                Name of the table of the SQL database where information on the cost assumptions
                is stored. It is assumed that this table contains, at least, the following
                fields:
                    exposure_entity (str):
                        3-character code of the exposure entity.
                    occupancy_case (enum):
                        SQL enumerated type describing the building occupancy cases.
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
                    day (float):
                        Factor to obtain the number of people expected to be inside the
                        buildings during the day (approx. 10 am to 6 pm).
                    night (float):
                        Factor to obtain the number of people expected to be inside the
                        buildings during the night (approx. 10 pm to 6 am).
                    transit (float):
                        Factor to obtain the number of people expected to be inside the
                        buildings during transit times (approx. 6 am to 10 am and 6 pm to 10
                        pm).

        Returns:
            people_distribution (dict):
                Dictionary with the same keys as the input 'people_cases' and whose values are
                the retrieved factors.
        """

        # Retrieving all fields and then sorting out as per 'cost_cases' as it is simpler
        sql_query = "SELECT day, night, transit FROM %s "
        sql_query += "WHERE (exposure_entity='%s' AND occupancy_case='%s' AND "
        sql_query += "aggregated_source_id='%s');"

        db_gde_tiles = Database(**db_gde_tiles_config)
        db_gde_tiles.create_connection_and_cursor()

        db_gde_tiles.cursor.execute(
            sql_query % (db_table, exposure_entity, occupancy_case, aggregated_source_id)
        )
        exec_result = db_gde_tiles.cursor.fetchall()

        db_gde_tiles.close_connection()

        retrieved = {}
        if len(exec_result) == 1:  # Entries exist --> retrieve
            retrieved["day"] = exec_result[0][0]
            retrieved["night"] = exec_result[0][1]
            retrieved["transit"] = exec_result[0][2]
            retrieved["census"] = 1.0
            retrieved["average"] = (
                retrieved["day"] + retrieved["night"] + retrieved["transit"]
            ) / 3.0
        else:
            logger.error(
                "ERROR in get_exposure_entities_population_time_distribution: "
                "more than one entry or no entry found for exposure_entity='%s' "
                "AND occupancy_case ='%s' AND aggregated_source_id='%s' "
                % (exposure_entity, occupancy_case, aggregated_source_id)
            )
            retrieved["day"] = 0.0
            retrieved["night"] = 0.0
            retrieved["transit"] = 0.0
            retrieved["census"] = 0.0
            retrieved["average"] = 0.0

        people_distribution = {}
        for people_case_key in people_cases.keys():
            people_distribution[people_case_key] = retrieved[people_cases[people_case_key]]

        return people_distribution

    @staticmethod
    def get_GDE_buildings(
        quadkey,
        data_unit_id,
        occupancy_case,
        aggregated_source_id,
        get_footprints,
        db_gde_tiles_config,
        db_table,
    ):
        """
        This function retrieves and returns all the GDE-processed OBM buildings from the table
        'db_table' of the database whose credentials are given by 'db_gde_tiles_config' that are
        associated with 'quadkey', 'data_unit_id', 'occupancy_case' and 'aggregated_source_id'.
        If 'get_footprints' is True, it also returns the centroids and footprints of
        these buildings. If no buildings are found for the input selection criteria, the output
        'obm_buildings' is a Pandas DataFrame with column structure but no rows and
        'obm_geometries' is an empty dictionary.

        Args:
            quadkey (str):
                Quadkey of the zoom-level 18 tile for which the GDE buildings will be retrieved.
            data_unit_id (str):
                ID of the data unit for which the GDE buildings will be retrieved.
            occupancy_case (str):
                Name of the occupancy case (e.g. "residential", "commercial", "industrial")
                for which the GDE buildings will be retrieved.
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model for which the GDE buildings
                will be retrieved.
            get_footprints (bool):
                If True, the geometries and centroids of the GDE buildings will be retrieved and
                returned, if False, they will not.
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which information on the GDE buildings is stored. The keys of the
                dictionary need to be:
                    host (str):
                        SQL database host address.
                    dbname (str):
                        Name of the SQL database.
                    port (int):
                        Port where the SQL database can be found.
                    username (str):
                        User name to connect to the SQL database.
                    password (str):
                        Password associated with self.username.
            db_table (str):
                Name of the table of the SQL database where the GDE buildings are stored. It is
                assumed that this table contains, at least, the following fields:
                    osm_id (int):
                        ID of the OBM building.
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
                    occupancy_case (enum):
                        SQL enumerated type describing the building occupancy cases.
                    data_unit_id (str):
                        ID of the data unit the OBM building belongs to.
                    quadkey (str):
                        Quadkey of the zoom-level 18 tile to which the centroid of the building
                        belongs.
                    building_class_names (array of str):
                        Building class as per the GEM Building Taxonomy.
                    settlement_types (list of str):
                        Type of settlements within the data unit. Possible values: "urban",
                        "rural", "big_city", "all".
                    occupancy_subtypes (list of str):
                        Details on the occupancy, if relevant to characterise the building
                        classes.
                    probabilities (array of float):
                        Probabilities of the OBM building belonging to each building class.
                    geometry (PSQL geometry):
                        Footprint of the OBM building.

        Returns:
            obm_buildings (Pandas DataFrame):
                DataFrame containing the GDE building classes and their probabilities. It
                comprises the following columns:
                    osm_id (int):
                        ID of the OBM building (several rows of the DataFrame can correspond to
                        the same OpenStreetMap ID).
                    building_class_name (str):
                        Building class as per the GEM Building Taxonomy.
                    settlement_type (str):
                        Type of settlement within the data unit. Possible values: "urban",
                        "rural", "big_city", "all".
                    occupancy_subtype (str):
                        Details on the occupancy, if relevant to characterise the building
                        class.
                    probabilities (float):
                        Probabilities of the building class (defined by 'building_class_name',
                        'settlement_type' and 'occupancy_subtype') being the correct class of
                        the OBM building with 'osm_id'.

            obm_geometries (dict):
                Dictionary in which each key is a unique 'osm_id' from 'obm_buildings', with the
                following subkeys (only if 'get_footprints' is set to True):
                    centroid (str):
                        Centroid of the OBM building in Well-Known Text format.
                    footprint (str):
                        Footprint of the OBM building in Well-Known Text format.
                If 'get_footprints' is False, 'obm_geometries' is an empty dictionary.
        """

        sql_query = "SELECT osm_id, building_class_names, settlement_types, occupancy_subtypes,"
        sql_query += " probabilities, ST_AsText(ST_Centroid(geometry)), ST_AsText(geometry)"
        sql_query += " FROM %s WHERE(quadkey='%s' AND data_unit_id='%s' AND occupancy_case='%s'"
        sql_query += " AND aggregated_source_id=%s);"

        db_gde_tiles = Database(**db_gde_tiles_config)
        db_gde_tiles.create_connection_and_cursor()

        db_gde_tiles.cursor.execute(
            sql_query % (db_table, quadkey, data_unit_id, occupancy_case, aggregated_source_id)
        )
        exec_result = db_gde_tiles.cursor.fetchall()

        db_gde_tiles.close_connection()

        if len(exec_result) > 0:  # Entries exist --> retrieve
            raw_osm_ids = numpy.array(
                [exec_result[i][0] for i in range(len(exec_result))], dtype="int"
            )
            raw_building_class_names = numpy.array(
                [exec_result[i][1] for i in range(len(exec_result))], dtype="object"
            )
            raw_settlement_types = numpy.array(
For faster browsing, not all history is shown. View entire blame