database_storage.py 21.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
                    % (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,
157
        obm_buildings_quadkeys_geometry,
158
159
160
161
162
163
164
165
        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
166
167
168
169
170
        the building classes. All existing entries for this combination of 'data_unit_id' AND
        'occupancy_case' AND 'aggregated_source_id' are first erased. If an entry existed for a
        particular OSM ID and 'aggregated_source_id' but it belonged to a different
        'data_unit_id' and/or 'occupancy_case', both 'data_unit_id' and 'occupancy_case' are
        updated to the new values passed to this method.
171
172
173
174
175
176
177
178
179
180
181

        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'.
182
183
184
185
186
187
188
189
190
191
192
193
            obm_buildings_quadkeys_geometry (Pandas DataFrame):
                DataFrame indicating the footprints and quadkeys associated with the centroids
                of the OBM buildings in 'obm_buildings_building_classes'. It is assumed to have
                at least the following columns:
                    osm_id (int):
                        OpenStreetMap (OSM) ID of the building. If the building is represented
                        by a relation, this is the ID of the relation.
                    quadkey (str):
                        String indicating the quadkey of the tile to which the centroid of the
                        building belongs.
                    geometry (str):
                        Footprint of the building in Well-Known Text format and EPSG:4326.
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
            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.
234
235
236
                    quadkey (str):
                        Quadkey of the zoom-level 18 tile to which the centroid of the building
                        belongs.
237
238
239
240
241
242
243
244
245
246
                    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.
247
248
                    geometry (PSQL geometry):
                        Footprint of the OBM building.
249
250
251
252
        """

        sql_commands = {}

253
254
255
        sql_commands["delete_previous"] = "DELETE FROM %s WHERE (data_unit_id='%s' AND "
        sql_commands["delete_previous"] += "occupancy_case='%s' AND aggregated_source_id=%s);"

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

259
        sql_commands["update"] = "UPDATE %s SET (occupancy_case, data_unit_id, quadkey, "
260
        sql_commands["update"] += "building_class_names, settlement_types, occupancy_subtypes, "
261
262
263
        sql_commands["update"] += "probabilities, geometry) = "
        sql_commands["update"] += "('%s','%s','%s','%s','%s','%s','%s','%s') "
        sql_commands["update"] += "WHERE (osm_id=%s AND aggregated_source_id=%s);"
264
265

        sql_commands["insert"] = "INSERT INTO %s(osm_id, aggregated_source_id, occupancy_case, "
266
267
268
269
        sql_commands["insert"] += "data_unit_id, quadkey, building_class_names, "
        sql_commands["insert"] += "settlement_types, occupancy_subtypes, probabilities, "
        sql_commands["insert"] += "geometry) VALUES ( "
        sql_commands["insert"] += "%s, %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');"
270
271
272
273

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

274
275
276
277
278
279
280
        # Delete all existing entries for this combination of
        # (data_unit_id AND occupancy_case AND aggregated_source_id)
        db_gde_tiles.cursor.execute(
            sql_commands["delete_previous"]
            % (db_table, data_unit_id, occupancy_case, aggregated_source_id)
        )

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
        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,
296
297
298
                        obm_buildings_quadkeys_geometry.loc[
                            obm_buildings_quadkeys_geometry["osm_id"] == osm_id, "quadkey"
                        ].to_numpy()[0],
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
                        '{"%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))
                            )
                        ),
315
316
317
                        obm_buildings_quadkeys_geometry.loc[
                            obm_buildings_quadkeys_geometry["osm_id"] == osm_id, "geometry"
                        ].to_numpy()[0],
318
319
320
321
322
323
324
325
326
327
328
329
330
                        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,
331
332
333
                        obm_buildings_quadkeys_geometry.loc[
                            obm_buildings_quadkeys_geometry["osm_id"] == osm_id, "quadkey"
                        ].to_numpy()[0],
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
                        '{"%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))
                            )
                        ),
350
351
352
                        obm_buildings_quadkeys_geometry.loc[
                            obm_buildings_quadkeys_geometry["osm_id"] == osm_id, "geometry"
                        ].to_numpy()[0],
353
354
355
356
357
358
359
360
                    )
                )
            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)
361
362
363
364
365
                )

        db_gde_tiles.close_connection()

        return
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

    @staticmethod
    def delete_old_database_entries(
        db_gde_tiles_config,
        db_table,
        exposure_entity,
        occupancy_case,
        aggregated_source_id,
    ):
        """This function deletes all entries associated with this combination of
        'exposure_entity, 'occupancy_case' and 'aggregated_source_id' from table 'db_table' of
        the database whose credentials are indicated in 'db_gde_tiles_config'.

        The function assumes that the table 'db_table' contains a field called 'data_unit_id'
        and that the IDs of the data units start with the 3-character code of the exposure
        entities. It searches for 'exposure_entity' under this assumption.

        Args:
            db_gde_tiles_config (dict):
                Dictionary containing the credentials needed to connect to the SQL database in
                which table 'db_table' exists. 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 whose contents will be erased (for this
                particular combination of 'exposure_entity, 'occupancy_case' and
                'aggregated_source_id'). It is assumed that this table contains, at least, the
                following fields:
                    data_unit_id (str):
                        ID of the data units, whose first 3 characters are the code of the
                        exposure entities to which they belong.
                    occupancy_case (enum):
                        SQL enumerated type describing the building occupancy cases.
                    aggregated_source_id (int):
                        ID of the source of the aggregated exposure model.
            exposure_entity (str):
                3-character code of the exposure entity whose entries will be deleted.
            occupancy_case (str):
                Name of the occupancy case (e.g. "residential", "commercial", "industrial")
                whose entries will be deleted.
            aggregated_source_id (int):
                ID of the source of the aggregated exposure model whose entries will be deleted.
        """

        sql_command = "DELETE FROM %s WHERE (occupancy_case='%s' AND aggregated_source_id='%s' "
        sql_command += "AND strpos(data_unit_id, '%s') > 0);"

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

        db_gde_tiles.cursor.execute(
            sql_command
            % (
                db_table,
                occupancy_case,
                str(aggregated_source_id),
                exposure_entity,
            )
        )

        db_gde_tiles.close_connection()

        return