to_geosummary.py 7.06 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
#!/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 os
import mercantile
import numpy
import pandas
import geopandas
import pyproj
from shapely.geometry import Polygon
from copy import deepcopy


logger = logging.getLogger()


def export_to_GeoSummary(
    quadtile,
    buildings_to_export,
    cost_cases,
    people_cases,
    output_path,
    quadkeys_group,
    occupancy_case,
    export_OBM_footprints=False,
):
    """This method exports the contents of a TileExposure object into a GeoPackage (GPKG) file
    that summarises relevant values of the tile. If the file exists, it appends to it the data
    associated with this 'quadtile'; otherwise, it creates it.

    Args:
        quadtile (TileExposure object):
            Instance of gdeexporter.tileexposure.TileExposure.
        buildings_to_export (list of str):
            List of types of buildings to export. Currently supported values: OBM, remainder,
            aggregated.
        cost_cases (dict):
            Dictionary whose keys indicate the columns of the buildings attributes of 'quadtile'
            (e.g. quadtile.obm_buildings, quadtile.remainder_buildings, etc) that are associated
            with the replacement costs of the building.
        people_cases (dict):
            Dictionary whose keys indicate the columns of the buildings attributes of 'quadtile'
            (e.g. quadtile.obm_buildings, quadtile.remainder_buildings, etc) that are associated
            with the number of people in the building.
        output_path (str):
            Path to which the output files will be saved.
        quadkeys_group (str):
            Name of the quadkey group that the 'quadtile' is part of. It is used for file naming
            and assigning incremental IDs to the rows of the OpenQuake CSV files.
        occupancy_case (str):
            Occupancy case to which the buildings of 'quadtile' belong. It is used for file
            naming and assigning incremental IDs to the rows of the OpenQuake CSV files.
        export_OBM_footprints (bool):
            Unused. Default: False.

    Returns:
        This method writes one GeoPackage (GPKG) file with name pattern
        [quadkeys_group]_[occupancy_case]_geosummary_tiles.gpkg, where 'quadkeys_group' and
        'occupancy_case' are as defined in the arguments. It contains the following fields:
            - quadkey (str): Quadkey of the tile.
            - geometry (geometry): Geometry of the tile.
            - [occupancy_case]_number_data_units: Number of data units associated with this
            quadtile and occupancy case.
            - [occupancy_case]_[building_type]_buildings: Number of buildings in the tile of the
            type 'building_type' (each of the elements of 'buildings_to_export') and of this
            'occupancy_case'.
            - [occupancy_case]_[building_type]_XXX: Fields in which 'occupancy_case' and
            'building_type' have the same meaning as above, and XXX refers to:
                - Columns associated with building replacement costs, whose name and contents
                are user-defined ('cost_cases').
                - Columns associated with the number of people in the building at different
                times of the day, whose names and contents are user-defined ('people_cases').
            In all of the cost- and people-cases columns, the values stored correspond to the
            sum of all buildings in the tile of the corresponding 'occupancy_case' and
            'building_type' ('[occupancy_case]_[building_type]_buildings' field).
    """

    # Retrieve quadtile's geometry and centroid
    tile = mercantile.quadkey_to_tile(quadtile.quadkey)
    tile_bounds = mercantile.bounds(tile)
    tile_geometry = Polygon(
        [
            (tile_bounds.west, tile_bounds.south),
            (tile_bounds.east, tile_bounds.south),
            (tile_bounds.east, tile_bounds.north),
            (tile_bounds.west, tile_bounds.north),
        ]
    )

    # Start GeoPandas DataFrame with summary of values for the tile
    geosummary = geopandas.GeoDataFrame(
        {
            "quadkey": pandas.Series([quadtile.quadkey], dtype=str),
            "geometry": [tile_geometry],
        },
        geometry=[tile_geometry],
    )
    geosummary.crs = pyproj.CRS("epsg:4326")

    data_unit_ids = []

    for building_type in buildings_to_export:
        field_id_prefix = "%s_%s" % (occupancy_case, building_type)

        # Identify the attribute of 'quadtile' that 'building_type' corresponds to
        attribute_name = "%s_buildings" % (building_type.lower())
        if hasattr(quadtile, attribute_name):  # check if attribute exists
            data = deepcopy(getattr(quadtile, attribute_name))

            # Create additional output columns
            geosummary["%s_buildings" % (field_id_prefix)] = data["number"].to_numpy().sum()

            for col_name in cost_cases:
                geosummary["%s_%s" % (field_id_prefix, col_name)] = (
                    data[col_name].to_numpy().sum()
                )

            for col_name in people_cases:
                geosummary["%s_%s" % (field_id_prefix, col_name)] = (
                    data[col_name].to_numpy().sum()
                )

            data_unit_ids.extend(data["data_unit_id"].unique())

        else:  # because all columns need to be created (so as to be able to append to the GPKG)

            # Create additional output columns
            geosummary["%s_buildings" % (field_id_prefix)] = 0.0

            for col_name in cost_cases:
                geosummary["%s_%s" % (field_id_prefix, col_name)] = 0.0

            for col_name in people_cases:
                geosummary["%s_%s" % (field_id_prefix, col_name)] = 0.0

    unique_data_unit_ids = numpy.unique(numpy.array(data_unit_ids))
    geosummary["%s_number_data_units" % (occupancy_case)] = len(unique_data_unit_ids)

    filename_geosummary = "%s_%s_geosummary_tiles.gpkg" % (quadkeys_group, occupancy_case)
    if os.path.exists(os.path.join(output_path, filename_geosummary)):  # append
        geosummary.to_file(
            os.path.join(output_path, filename_geosummary), index=False, driver="GPKG", mode="a"
        )
    else:  # create
        geosummary.to_file(
            os.path.join(output_path, filename_geosummary), index=False, driver="GPKG"
        )

    if export_OBM_footprints:
        pass  # Nothing to be done, input argument kept for compatibility with other formats

    return