tileexposure.py 18.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/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
import pandas
from copy import deepcopy


logger = logging.getLogger()

# Empty DataFrame
BUILDINGS = pandas.DataFrame(
    {
        "building_class_name": pandas.Series(dtype="str"),
        "number": pandas.Series(dtype="float"),
        "data_unit_id": pandas.Series(dtype="str"),
    }
)


class TileExposure:
    """This class represents the exposure of a tile of zoom level 18.

    Attributes:
        self.quadkey (str):
            Quadkey of the zoom level 18 tile.
        self.obm_buildings (Pandas DataFrame):
            DataFrame with the OBM buildings that belong to the tile, in terms of:
                osm_id (int):
                    OpenStreetMap ID of the building.
                building_class_name (str):
                    Name of the building class as per the GEM Building Taxonomy v3.0.
                number (float):
                    Probability of the building (identified by its OSM ID) belonging to the
                    building class.
                Columns associated with building replacement costs (float):
                    Names and contents are user-defined. Values correspond to values per
                    building multiplied by the probability of the building class corresponding
                    to the particular building (identified by its OSM ID).
                Columns associated with the number of people in the building at different times
                of the day (float):
                    Names and contents are user-defined. Values correspond to values per
                    building multiplied by the probability of the building class corresponding
                    to the particular building (identified by its OSM ID).
                data_unit_id (str):
                    ID of the data unit the building belongs to.
        self.obm_buildings_geometries (dict):
            Dictionary in which each key is a unique 'osm_id' from self.obm_buildings, with the
            following subkeys:
                centroid (str):
                    Centroid of the OBM building in Well-Known Text format.
                footprint (str) (only if instructed to retrieve footprints by the user):
                    Footprint of the OBM building in Well-Known Text format.
        self.remainder_buildings (Pandas DataFrame):
            DataFrame with the remainder buildings that belong to the tile, in terms of:
                building_class_name (str):
                    Name of the building class as per the GEM Building Taxonomy v3.0.
                number (float):
                    Number of buildings of this building class.
                Columns associated with building replacement costs (float):
                    Names and contents are user-defined. Values correspond to values per
                    building multiplied by the number of buildings of the class.
                Columns associated with the number of people in the building at different times
                of the day (float):
                    Names and contents are user-defined. Values correspond to values per
                    building multiplied by the number of buildings of the class.
                data_unit_id (str):
                    ID of the data unit the buildings belong to.
        self.aggregated_buildings (Pandas DataFrame):
            DataFrame with the remainder buildings that belong to the tile, in terms of the same
            fields described for self.remainder_buildings.
        self.total_buildings (Pandas DataFrame):
            DataFrame with the total buildings that belong to the tile (aggregation of remainder
            and OBM buildings), in terms of the same fields described for
            self.remainder_buildings.
    """

    def __init__(self, quadkey, cost_cases, people_cases):
        """
        Args:
            quadkey (str):
                Quadkey of the zoom level 18 tile.
            cost_cases (dict):
                Dictionary containing indications on the sort of costs to output.
            people_cases (dict):
                Dictionary containing indications on the time of the day for which the number of
                people in the buildings is to be output.
        """

        self.quadkey = quadkey
        self.obm_buildings = self._create_empty_building_dataframes(
            cost_cases, people_cases, additional_cols={"osm_id": "str"}
        )
        self.obm_buildings_geometries = {}
        self.remainder_buildings = self._create_empty_building_dataframes(
            cost_cases, people_cases
        )
        self.aggregated_buildings = self._create_empty_building_dataframes(
            cost_cases, people_cases
        )
        self.total_buildings = self._create_empty_building_dataframes(cost_cases, people_cases)

    def _create_empty_building_dataframes(self, cost_cases, people_cases, additional_cols={}):
        """
        Args:
            cost_cases (dict):
                Dictionary containing indications on the sort of costs to output.
            people_cases (dict):
                Dictionary containing indications on the time of the day for which the number of
                people in the buildings is to be output.
            additional_cols (dict):
                Dictionary containing names (keys) and data types (values) of any other column
                that the output is required to have.
        """

        empty_buildings = deepcopy(BUILDINGS)
        for cost_case in cost_cases:
            empty_buildings[cost_case] = pandas.Series(dtype="float")
        for people_case in people_cases:
            empty_buildings[people_case] = pandas.Series(dtype="float")
        for col in additional_cols:
            empty_buildings[col] = pandas.Series(dtype=additional_cols[col])

        return empty_buildings

    def append_lumped_buildings(
        self,
        lumped_building_case,
        building_classes,
        number_buildings,
        cost_assumptions,
        people_distribution,
        data_unit_id,
    ):
        """
        This function appends buildings to the case of lumped buildings indicated by
        'lumped_building_case', which can be either "aggregated_buildings" or
        "remainder_buildings". The building classes and their proportions are as indicated in
        'building_classes' and the total number of aggregated or remainder buildings is
        indicated by 'number_buildings'. The dictionaries 'cost_assumptions' and
        'people_distribution' indicate the desired disaggregation of replacement costs and
        distribution of people at different times of the day. The output costs and number of
        people correspond to the total number of buildings.

        Args:
            lumped_building_case (str):
                Case of lumped buildings to which buildings will be updated. These can be:
                "aggregated_buildings" or "remainder_buildings".
            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.
            number_buildings (float):
                Number of aggregated or remainder buildings.
            cost_assumptions (dict):
                Dictionary containing 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.
            people_distribution (dict):
                Dictionary containing 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.
            data_unit_id (str):
                 ID of the data unit that the buildings belong to.
        """

        lumped_buildings = pandas.DataFrame(
            {
                "building_class_name": building_classes["building_class_name"],
                "number": number_buildings * building_classes["proportions"],
                "data_unit_id": [data_unit_id for i in range(building_classes.shape[0])],
            }
        )
        for cost_case in cost_assumptions:
            lumped_buildings[cost_case] = pandas.Series(
                cost_assumptions[cost_case]
                * building_classes["total_cost_per_building"]
                * lumped_buildings["number"],
                dtype="float",
            )
        for people_case in people_distribution:
            lumped_buildings[people_case] = pandas.Series(
                people_distribution[people_case]
                * building_classes["census_people_per_building"]
                * lumped_buildings["number"],
                dtype="float",
            )

        updated_lumped_buildings = pandas.concat(
            [getattr(self, lumped_building_case), lumped_buildings],
            ignore_index=True,
        )

        setattr(self, lumped_building_case, updated_lumped_buildings)

    def append_OBM_buildings(
        self,
        obm_buildings,
        building_classes,
        cost_assumptions,
        people_distribution,
        data_unit_id,
    ):
        """
        This function appends the buildings from 'obm_buildings' to self.obm_buildings. The
        total replacement cost and number of census people per building are retrieved from
        'building_classes', as a function of the building class, which is defined by the columns
        building_class_name', 'settlement_type' and 'occupancy_subtype' present in both input
        DataFrames. It is assumed that the buildings in 'obm_buildings' and the building classes
        in 'building_classes' are consistent with each other in terms of belonging to the same
        occupancy case, data unit ID and aggregated source ID. This assumption implies that all
        building classes from 'obm_buildings' will be found in 'building_classes' (apart from
        overall consistency). The dictionaries 'cost_assumptions' and 'people_distribution'
        indicate the desired disaggregation of replacement costs and distribution of people at
        different times of the day. The output costs and number of people correspond to the
        probability of the building belonging to each building class (as per the probabilities
        input via 'obm_buildings').

        Args:
            obm_buildings (Pandas DataFrame):
                DataFrame containing the OBM 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'.
            building_classes (Pandas DataFrame):
                DataFrame containing the building classes associated with 'obm_buildings' and
                their total replacement cost per building and census number of people per
                building. It comprises at least 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.
                    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.
            cost_assumptions (dict):
                Dictionary containing 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.
            people_distribution (dict):
                Dictionary containing 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.
            data_unit_id (str):
                 ID of the data unit that the buildings belong to.
        """

        # Set multiindex for building_classes, drop "proportions" columns if exists
        building_classes_copy = deepcopy(building_classes)
        if "proportions" in building_classes_copy.columns:
            building_classes_copy = building_classes_copy.drop(columns=["proportions"])
        building_classes_copy = building_classes_copy.set_index(
            ["building_class_name", "settlement_type", "occupancy_subtype"]
        )

        # Join 'obm_buildings' and 'building_classes_copy' to assign
        # 'census_people_per_building' and 'total_cost_per_building' to each row in
        # 'obm_buildings'
        obm_buildings_expanded = obm_buildings.join(
            building_classes_copy,
            on=["building_class_name", "settlement_type", "occupancy_subtype"],
        )

        # Identify any cases in which the building class of 'obm_buildings' was not found in
        # 'building_classes'
        which_nans = (
            obm_buildings_expanded["census_people_per_building"].isnull().values
        )  # boolean array
        osm_ids_without_costs_or_people = list(
            obm_buildings_expanded.loc[which_nans, "osm_id"].to_numpy().astype(str)
        )

        if len(osm_ids_without_costs_or_people) > 0:
            # Need to log an error if a building class is not found
            # (and costs/people cannot be assigned)
            logger.error(
                "TileExposure.append_OBM_buildings: input 'building_classes' does not cover "
                "all building classes contained in input 'obm_buildings'; the following OSM "
                "IDs have NULL values of costs and number of people: %s"
                % (", ".join(osm_ids_without_costs_or_people))
            )

        # Transform 'obm_buildings_expanded' to the output format (self.obm_buildings)
        obm_buildings_expanded = obm_buildings_expanded.rename(
            columns={"probabilities": "number"}
        )
        obm_buildings_expanded["data_unit_id"] = [
            data_unit_id for i in range(obm_buildings_expanded.shape[0])
        ]

        for cost_case in cost_assumptions:
            obm_buildings_expanded[cost_case] = pandas.Series(
                cost_assumptions[cost_case]
                * obm_buildings_expanded["total_cost_per_building"]
                * obm_buildings_expanded["number"],
                dtype="float",
            )
        for people_case in people_distribution:
            obm_buildings_expanded[people_case] = pandas.Series(
                people_distribution[people_case]
                * obm_buildings_expanded["census_people_per_building"]
                * obm_buildings_expanded["number"],
                dtype="float",
            )

        # Drop unnecessary columns
        obm_buildings_expanded = obm_buildings_expanded.drop(
            columns=[
                "total_cost_per_building",
                "census_people_per_building",
                "settlement_type",
                "occupancy_subtype",
            ]
        )

        updated_obm_buildings = pandas.concat(
            [getattr(self, "obm_buildings"), obm_buildings_expanded],
            ignore_index=True,
        )

        setattr(self, "obm_buildings", updated_obm_buildings)