database_storage.py 15.1 KB
Newer Older
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
#!/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
from gdeimporter.tools.database import Database


logger = logging.getLogger()


class DatabaseStorage:
    """This class contains methods used to store values to the Global Dynamic Exposure (GDE)
    database.
    """

    @staticmethod
    def store_number_OBM_and_remainder_buildings(
        data_unit_id,
        occupancy_case,
        aggregated_source_id,
        data_unit_tiles,
        db_gde_tiles_config,
        db_table,
    ):
        """This function writes to the table with name 'db_table' in the database whose
        credentials are indicated in 'db_gde_tiles_config' the number of OBM and remainder
        buildings in each data-unit tile contained in 'data_unit_tiles', all of which are
        associated with 'data_unit_id', 'occupancy_case' and 'aggregated_source_id'.

        Args:
            data_unit_id (str):
47
48
                 ID of the data unit for which the number of OBM and remainder buildings will be
                 stored.
49
50
            occupancy_case (str):
                Name of the occupancy case (e.g. "residential", "commercial", "industrial")
51
                for which the number of OBM and remainder buildings will be stored.
52
            aggregated_source_id (int):
53
54
                ID of the source of the aggregated exposure model for which the number of OBM
                and remainder buildings will be stored.
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
            data_unit_tiles:
                Pandas DataFrame with data-unit tiles. It contains the following columns:
                    quadkey (str):
                        String indicating the quadkey of a tile.
                    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.
                    remainder_buildings (float):
                        Number of remainder buildings in the data-unit tile.
                    complete (bool):
                        True if the tile is OSM-complete, False if it is OSM-incomplete.
            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.
                    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.
                    remainder_buildings (float):
                        Number of remainder buildings in the data-unit tile as per the
                        aggregated exposure model with ID 'aggregated_source_id'.
        """

        sql_commands = {}

        sql_commands["query"] = "SELECT COUNT(*) FROM %s"
        sql_commands["query"] += " WHERE (quadkey='%s' AND data_unit_id='%s' "
        sql_commands["query"] += " AND occupancy_case='%s' AND aggregated_source_id='%s');"

        sql_commands["update"] = "UPDATE %s SET (obm_buildings, remainder_buildings)"
        sql_commands["update"] += " = (%s,%s)"
        sql_commands["update"] += " WHERE (quadkey='%s' AND data_unit_id='%s' "
        sql_commands["update"] += " AND occupancy_case='%s' AND aggregated_source_id='%s');"

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

        for i, quadkey in enumerate(data_unit_tiles["quadkey"].to_numpy()):
            db_gde_tiles.cursor.execute(
                sql_commands["query"]
                % (db_table, quadkey, data_unit_id, occupancy_case, aggregated_source_id)
            )
            exec_result = db_gde_tiles.cursor.fetchall()

            if exec_result[0][0] == 1:  # One entry exists (expected)
                db_gde_tiles.cursor.execute(
                    sql_commands["update"]
                    % (
                        db_table,
                        data_unit_tiles["obm_buildings"].to_numpy()[i],
                        data_unit_tiles["remainder_buildings"].to_numpy()[i],
                        quadkey,
                        data_unit_id,
                        occupancy_case,
                        aggregated_source_id,
                    )
                )
            else:
                logger.error(
                    "DatabaseStorage.store_number_OBM_and_remainder_buildings() has found "
                    "either more than one entry or no entry for quadkey='%s' AND "
                    "data_unit_id='%s' AND occupancy_case='%s' AND aggregated_source_id='%s'. "
                    "Numbers of OBM and remainder buildings were not stored "
                    "for this data-unit tile."
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
                    % (quadkey, data_unit_id, occupancy_case, aggregated_source_id)
                )

        db_gde_tiles.close_connection()

        return

    @staticmethod
    def store_OBM_building_classes(
        data_unit_id,
        occupancy_case,
        aggregated_source_id,
        obm_buildings_building_classes,
        db_gde_tiles_config,
        db_table,
    ):
        """This function writes to the table with name 'db_table' in the database whose
        credentials are indicated in 'db_gde_tiles_config' the building classes and associated
        probabilities for each of the OBM buildings in 'obm_buildings_building_classes'.
        Reference to the corresponding 'data_unit_id', 'occupancy_case' and
        'aggregated_source_id' is needed to be able (at a later stage) to retrieve attributes of
        the building classes.

        Args:
            data_unit_id (str):
                 ID of the data unit associated with the OBM buildings in
                 'obm_buildings_building_classes'.
            occupancy_case (str):
                Name of the occupancy case (e.g. "residential", "commercial", "industrial")
                of the OBM buildings in 'obm_buildings_building_classes'.
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model associated with the building
                classes of the OBM buildings in 'obm_buildings_building_classes'.
            obm_buildings_building_classes (dict):
                Dictionary containing the building classes and their probabilities for each OBM
                building. Dictionary keys correspond to the OSM ID of the building. Each key
                contains a Pandas DataFrame with 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.
                    probabilities (float):
                        Probabilities of the building belonging to the building class (defined
                        by 'building_class_name', 'settlement_type' and 'occupancy_subtype').
            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.
                    building_class_names (array of str):
                        Building class as per the GEM Building Taxonomy.
                    settlement_types (array of enum):
                        Type of settlement within the Data Unit. Possible values: "urban",
                        "rural", "big_city", "all".
                    occupancy_subtypes (array of str):
                        Details on the occupancy, if relevant to characterise the building
                        class.
                    probabilities (array of float):
                        Probabilities of the OBM building belonging to each building class.
        """

        sql_commands = {}

        sql_commands["query"] = "SELECT COUNT(*) FROM %s "
        sql_commands["query"] += "WHERE (osm_id=%s AND aggregated_source_id=%s);"

        sql_commands["update"] = "UPDATE %s SET (occupancy_case, data_unit_id, "
        sql_commands["update"] += "building_class_names, settlement_types, occupancy_subtypes, "
        sql_commands["update"] += "probabilities) = ('%s','%s','%s','%s','%s','%s')"
        sql_commands["update"] += " WHERE (osm_id=%s AND aggregated_source_id=%s);"

        sql_commands["insert"] = "INSERT INTO %s(osm_id, aggregated_source_id, occupancy_case, "
        sql_commands["insert"] += "data_unit_id, building_class_names, settlement_types, "
        sql_commands["insert"] += "occupancy_subtypes, probabilities) "
        sql_commands["insert"] += "VALUES (%s, %s, '%s', '%s', '%s', '%s', '%s', '%s');"

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

        for osm_id in obm_buildings_building_classes.keys():
            building_classes = obm_buildings_building_classes[osm_id]

            db_gde_tiles.cursor.execute(
                sql_commands["query"] % (db_table, osm_id, aggregated_source_id)
            )
            number_entries = db_gde_tiles.cursor.fetchall()[0][0]

            if number_entries == 1:  # One entry exists for this OSM ID --> update
                db_gde_tiles.cursor.execute(
                    sql_commands["update"]
                    % (
                        db_table,
                        occupancy_case,
                        data_unit_id,
                        '{"%s"}'
                        % (
                            '", "'.join(
                                list(building_classes["building_class_name"].to_numpy())
                            )
                        ),
                        '{"%s"}'
                        % ('", "'.join(list(building_classes["settlement_type"].to_numpy()))),
                        '{"%s"}'
                        % ('", "'.join(list(building_classes["occupancy_subtype"].to_numpy()))),
                        '{"%s"}'
                        % (
                            '", "'.join(
                                list(building_classes["probabilities"].to_numpy().astype(str))
                            )
                        ),
                        osm_id,
                        aggregated_source_id,
                    )
                )
            elif number_entries == 0:  # Entry does not exist yet for this OSM ID --> insert
                db_gde_tiles.cursor.execute(
                    sql_commands["insert"]
                    % (
                        db_table,
                        osm_id,
                        aggregated_source_id,
                        occupancy_case,
                        data_unit_id,
                        '{"%s"}'
                        % (
                            '", "'.join(
                                list(building_classes["building_class_name"].to_numpy())
                            )
                        ),
                        '{"%s"}'
                        % ('", "'.join(list(building_classes["settlement_type"].to_numpy()))),
                        '{"%s"}'
                        % ('", "'.join(list(building_classes["occupancy_subtype"].to_numpy()))),
                        '{"%s"}'
                        % (
                            '", "'.join(
                                list(building_classes["probabilities"].to_numpy().astype(str))
                            )
                        ),
                    )
                )
            else:  # this should not occur
                logger.error(
                    "DatabaseStorage.store_OBM_building_classes() has found more than one "
                    "entry for osm_id=%s and aggregated_source_id=%s. "
                    "Building classes for this building were not stored."
                    % (osm_id, aggregated_source_id)
315
316
317
318
319
                )

        db_gde_tiles.close_connection()

        return