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

# Copyright (C) 2021:
#   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
import sqlite3
21
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


# Initialize log
logger = logging.getLogger(__name__)


class Database:
    """The Database class represents a Spatialite database. It manages the database
    connection and cursor. Upon connection, the Spatialite extension is loaded.

    Args:
        database_filepath (str):
            File path for the Spatialite database file.
        spatialite_filepath (str):
            File path of the Spatialite extension.

    Attributes:
        database_filepath (str): Spatialite database file path.
        spatialite_filepath (str): File path to the Spatialite extension.
    """

    def __init__(self, database_filepath, spatialite_filepath="mod_spatialite"):
        self.database_filepath = database_filepath
        self.spatialite_filepath = spatialite_filepath

        self.connection = None
        self.cursor = None

    def create_connection_and_cursor(self, init_spatial_metadata=True):
        """Create a database connection, loads the Spatialite extension and initializes it.

        Attributes:
            init_spatial_metadata (bool, optional):
                If set, the InitSpatialMetadata function of Spatialite is invoked
        """

        # Create SQLite database for the exposure data
        logger.debug("Connecting to database at %s" % self.database_filepath)
        self.connection = sqlite3.connect(self.database_filepath)
        logger.debug("Connection to database established")

        self.connection.enable_load_extension(True)
        sql_statement = "SELECT load_extension('%s');" % self.spatialite_filepath
        self.connection.execute(sql_statement)
        if init_spatial_metadata:
            self.connection.execute("SELECT InitSpatialMetaData(1);")
            logger.debug("Spatialite extension loaded and initialized")

        versions = self.connection.execute("SELECT sqlite_version(), spatialite_version()")
        for row in versions:
            logger.debug("SQLite version: %s" % row[0])
            logger.debug("Spatialite version: %s" % row[1])

        self.cursor = self.connection.cursor()


class JapanDatabase(Database):
    """The JapanDatabase class represents a Spatialite database for the Japan
    exposure model. It is derived from the generic Database class.

    Args:
        database_filepath (str):
            File path for the Spatialite database file.
        spatialite_filepath (str):
            File path of the Spatialite extension.

    Attributes:
        database_filepath (str): Spatialite database file path.
        spatialite_filepath (str): File path to the Spatialite extension.
    """

    def __init__(self, database_filepath, spatialite_filepath="mod_spatialite"):
        Database.__init__(self, database_filepath, spatialite_filepath)

    def create_tables(self):
        """
        Creates all necessary tables in the database. These are:
            District : Stores the districts with their IDs, names and geometries
        """

        # Create table District
        sql_statement = "CREATE TABLE District ("
        sql_statement += "id          INTEGER PRIMARY KEY AUTOINCREMENT, "
        sql_statement += "admin_id    TEXT, "
        sql_statement += "admin_name  TEXT)"
        self.connection.execute(sql_statement)
        sql_statement = "SELECT AddGeometryColumn('District', 'geom', 4326, "
        sql_statement += "'MULTIPOLYGON', 'XY')"
        self.connection.execute(sql_statement)
        logger.debug("Table District created")

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
        # Create table DwellingNumber
        sql_statement = "CREATE TABLE DwellingNumber ("
        sql_statement += "id                        INTEGER PRIMARY KEY AUTOINCREMENT, "
        sql_statement += "district_id               INTEGER, "
        sql_statement += "building_type_id          INTEGER, "
        sql_statement += "construction_material_id  INTEGER, "
        sql_statement += "number_stories_id         INTEGER, "
        sql_statement += "number_dwelling           REAL)"
        self.connection.execute(sql_statement)
        logger.debug("Table DwellingNumber created")

        # Create table BuildingType
        sql_statement = "CREATE TABLE BuildingType ("
        sql_statement += "id           INTEGER PRIMARY KEY, "
        sql_statement += "description  TEXT)"
        self.connection.execute(sql_statement)

        # Create table ConstructionMaterial
        sql_statement = "CREATE TABLE ConstructionMaterial ("
        sql_statement += "id           INTEGER PRIMARY KEY, "
        sql_statement += "description  TEXT)"
        self.connection.execute(sql_statement)

        # Create table NumberStories
        sql_statement = "CREATE TABLE NumberStories ("
        sql_statement += "id           INTEGER PRIMARY KEY, "
        sql_statement += "description  TEXT)"
        self.connection.execute(sql_statement)

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
    def insert_district(self, admin_id, admin_name, geom):
        """
        Inserts the ID, name, and geometry of a district to the District table.

        Args:
            admin_id (str):
                ID of the administrative district
            admin_name (str):
                Name of the administrative district
            geom (multipolygon):
                Geometry (Spatialite) of the district boundary
        """

        sql_statement = "INSERT INTO District "
        sql_statement += "(admin_id, admin_name, geom) "
        sql_statement += "VALUES ('%s', '%s', %s)" % (admin_id, admin_name, geom)
        self.cursor.execute(sql_statement)

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
    def insert_dwelling_number(
        self,
        district_id,
        building_type_id,
        construction_material_id,
        number_stories_id,
        number_dwelling,
    ):
        """
        Inserts a full dataset to the BuildingNumber table.

        Args:
            district_id (int):
                ID of the district. Corresponds to District.id
            building_type_id (int):
                ID of the building type. Corresponds to BuildingType.id
            construction_material_id (int):
                ID of the construction material. Corresponds to ConstructionMaterial.id
            number_stories_id (int):
                ID of the number of stories type. Corresponds to NumberStories.id
            number_dwelling (float):
                Number of buildings for the combination of the other parameters
        """

        sql_statement = "INSERT INTO DwellingNumber "
        sql_statement += "(district_id, building_type_id, construction_material_id, "
        sql_statement += "number_stories_id, number_dwelling) "
        sql_statement += "VALUES (%d, %d, %d, %d, %f)" % (
            district_id,
            building_type_id,
            construction_material_id,
            number_stories_id,
            number_dwelling,
        )
        self.cursor.execute(sql_statement)

    def insert_building_type(self, building_type_id, description):
        """
        Inserts a building-type description to the BuildingType table.

        Args:
            building_type_id (int):
                ID of the building type
            description (str):
                Description of the building type
        """

        sql_statement = "INSERT INTO BuildingType "
        sql_statement += "(id, description) "
        sql_statement += "VALUES (%d, '%s')" % (building_type_id, description)
        self.cursor.execute(sql_statement)

    def insert_construction_material(self, construction_material_id, description):
        """
        Inserts a construction-material description to the ConstructionMaterial table.

        Args:
            construction_material_id (int):
                ID of the construction material
            description (str):
                Description of the construction material
        """

        sql_statement = "INSERT INTO ConstructionMaterial "
        sql_statement += "(id, description) "
        sql_statement += "VALUES (%d, '%s')" % (construction_material_id, description)
        self.cursor.execute(sql_statement)

    def insert_number_stories(self, number_stories_id, description):
        """
        Inserts a story-number description to the NumberStories table.

        Args:
            number_stories_id (int):
                ID of the number of stories entry
            description (str):
                Description of the number of stories entry
        """

        sql_statement = "INSERT INTO NumberStories "
        sql_statement += "(id, description) "
        sql_statement += "VALUES (%d, '%s')" % (number_stories_id, description)
        self.cursor.execute(sql_statement)

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
    def read_districts_and_boundaries(self, district_boundary_filepath):
        """
        Imports all districts and boundaries from a prepared geopackage file
        ('estat_bound_municipal`). The function opens this file as Spatialite database
        and copies all necessary district and boundary information into the `District` table.

        Args:
            district_boundary_filepath (str):
                File path to the boundary file
        """

        boundary_db = Database(district_boundary_filepath, self.spatialite_filepath)
        boundary_db.create_connection_and_cursor()

        sql_statement = "SELECT key_code_ward, "
        sql_statement += "CITY_NAME, "
        sql_statement += "AsWKT(CastAutomagic(geom)) "
        sql_statement += "FROM estat_bound_municipal"
        boundary_db.cursor.execute(sql_statement)
        for row in boundary_db.cursor:
            self.insert_district(
                row[0],
                row[1],
                "ST_Transform(CastToMultiPolygon(GeomFromText('%s', 4612)), 4326)" % row[2],
            )
            logger.debug("District %d with boundary added" % row[0])
        self.connection.commit()
        logger.info("Districts and boundaries added")
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

    def import_exposure_data(self, dwelling_numbers_filepath):
        """
        Imports all exposure data from the Excel files provided by E-Stat, Japan. The following
        files are needed:
            List of numbers of dwellings by municipality (dwelling_numbers_filepath)

        Args:
            dwelling_numbers_filepath (str):
                File path to the file of number_of_dwellings)
        """

        building_type_list = []
        number_stories_list = []
        construction_material_list = [
            "0_Total",
            "1_Wooden",
            "101_Wooden (excluding wooden and fire-proofed)",
            "102_Wooden and fire-proofed",
            "2_Non-wooden",
        ]

        dwelling_numbers_input = pandas.read_excel(
            dwelling_numbers_filepath, header=10, usecols=[4, 5, 7, 9, 10, 11, 12, 13, 14]
        )
        for index, row in dwelling_numbers_input.iterrows():
            admin_id = int((row["Area classification"].split("_"))[0])

            # Identify district_id based on admin_id from the District table
            sql_statement = "SELECT id FROM District "
            sql_statement += "WHERE admin_id = %d" % admin_id
            self.cursor.execute(sql_statement)
            result = self.cursor.fetchone()
            if result is None:  # Only data for which a district exist matter
                continue
            district_id = result[0]

            # Get ID of building type
            building_type = row["Type of building"]
            if building_type not in building_type_list:
                building_type_list.append(building_type)
            building_type_id = building_type_list.index(building_type)

            # Get ID of number of stories
            number_stories = row["Stories of building"]
            if number_stories not in number_stories_list:
                number_stories_list.append(number_stories)
            number_stories_id = number_stories_list.index(number_stories)

            # Insert building numbers for each construction material
            for material_id in range(5):
                dwelling_number = float(str(row[4 + material_id]).replace("-", "0"))
                self.insert_dwelling_number(
                    district_id,
                    building_type_id,
                    material_id,
                    number_stories_id,
                    dwelling_number,
                )

        # Add the building types to the database
        for building_type in building_type_list:
            building_type_id = building_type_list.index(building_type)
            self.insert_building_type(building_type_id, building_type)

        # Add the number of stories to the database
        for number_stories in number_stories_list:
            number_stories_id = number_stories_list.index(number_stories)
            self.insert_number_stories(number_stories_id, number_stories)

        # Add the number of stories to the database
        for construction_material in construction_material_list:
            construction_material_id = construction_material_list.index(construction_material)
            self.insert_construction_material(construction_material_id, construction_material)

        self.connection.commit()