test_to_openquake.py 10.6 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
#!/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 os
import pandas
import geopandas
from shapely.wkt import loads
from gdeexporter.to_openquake import export_to_OpenQuake_CSV
from gdeexporter.tileexposure import TileExposure


def test_export_to_OpenQuake_CSV():
    # User-defined costs and people columns
    cost_cases = {"structural": "total"}
    people_cases = {"day": "day", "night": "night", "transit": "transit"}

    # User-defined input parameters for export_to_OpenQuake_CSV
    buildings_to_export = ["OBM", "remainder"]
    output_path = os.path.join(
        os.path.dirname(__file__), "data", "temp_test_export_to_OpenQuake_CSV"
    )
    quadkeys_group = "quadkeys_list"
    occupancy_case = "residential"

    # Create temporary directory
    os.mkdir(output_path)

    # Load geometries of OBM buildings
    obm_geometries_df = pandas.read_csv(
        os.path.join(os.path.dirname(__file__), "data", "test_oq_input_OBM_geometries.csv"),
        sep=";",
    )
    obm_geometries_df.index = obm_geometries_df["osm_id"]
    del obm_geometries_df["osm_id"]
    obm_geometries_df["footprint"] = obm_geometries_df["geometry"]
    obm_geometries_all = obm_geometries_df.to_dict(orient="index")

    # Three quadtiles will be created and used to write output files
    # First quadtile has both remainder and OBM buildings, second quadtile has remainder
    # buildings only, third quadtile has OBM buildings only
    quadkeys = ["122010321033023130", "122010321033023121", "122010321033023132"]
    obm_buildings_input = [
        "test_oq_input_OBM_buildings_122010321033023130.csv",
        "",
        "test_oq_input_OBM_buildings_122010321033023132.csv",
    ]
    remainder_buildings_input = [
        "test_oq_input_remainder_buildings_122010321033023130.csv",
        "test_oq_input_remainder_buildings_122010321033023121.csv",
        "",
    ]

    # Expected names of output files
    prefix = "%s_%s" % (quadkeys_group, occupancy_case)
    expected_name_remainder_buildings = "%s_remainder.csv" % (prefix)
    expected_name_obm_buildings = "%s_OBM.csv" % (prefix)
    expected_name_geometries_quadtiles = "%s_geometries_quadtiles.gpkg" % (prefix)
    expected_name_geometries_obm = "%s_OBM_geometries_footprints.gpkg" % (prefix)

    # Two test cases will be assessed: first with export_OBM_footprints = False, and second with
    # export_OBM_footprints = True
    export_OBM_footprints_vals = [False, True]
    expected_obm_buildings_output = [
        "test_oq_expected_OBM_buildings_without_footprints_export.csv",
        "test_oq_expected_OBM_buildings_with_footprints_export.csv",
    ]
    # Remainder buildings and quadtile geometries are the same for both
    expected_remainder_buildings_output = "test_oq_expected_remainder_buildings.csv"
    expected_quadtiles_geometries_output = "test_oq_expected_tile_geometries.csv"
    expected_obm_geometries_output = "test_oq_input_OBM_geometries.csv"

    # Path to expected results
    expected_results_path = os.path.join(os.path.dirname(__file__), "data")

    # Carry out each of the two tests at a time
    for k in range(len(export_OBM_footprints_vals)):
        # Create TileExposure objects and call export_to_OpenQuake_CSV each time
        for i, quadkey in enumerate(quadkeys):
            quadtile = TileExposure(quadkey, cost_cases, people_cases)
            if obm_buildings_input[i] != "":
                quadtile.obm_buildings = pandas.read_csv(
                    os.path.join(os.path.dirname(__file__), "data", obm_buildings_input[i])
                )
                quadtile.obm_buildings_geometries = {
                    osm_id: obm_geometries_all[osm_id]
                    for osm_id in quadtile.obm_buildings["osm_id"].values
                }

            if remainder_buildings_input[i] != "":
                quadtile.remainder_buildings = pandas.read_csv(
                    os.path.join(
                        os.path.dirname(__file__), "data", remainder_buildings_input[i]
                    )
                )

            export_to_OpenQuake_CSV(
                quadtile,
                buildings_to_export,
                cost_cases,
                people_cases,
                output_path,
                quadkeys_group,
                occupancy_case,
119
                export_OBM_footprints_vals[k],
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
            )

        # Check that output files that need to be created have been created
        assert os.path.exists(os.path.join(output_path, expected_name_remainder_buildings))
        assert os.path.exists(os.path.join(output_path, expected_name_obm_buildings))
        assert os.path.exists(os.path.join(output_path, expected_name_geometries_quadtiles))
        if export_OBM_footprints_vals[k]:
            assert os.path.exists(os.path.join(output_path, expected_name_geometries_obm))
        else:
            assert not os.path.exists(os.path.join(output_path, expected_name_geometries_obm))

        # Check contents of OpenQuake CSV file for remainder buildings
        returned_remainder_buildings = pandas.read_csv(
            os.path.join(output_path, expected_name_remainder_buildings),
        )
        expected_remainder_buildings = pandas.read_csv(
            os.path.join(expected_results_path, expected_remainder_buildings_output),
        )
        assert returned_remainder_buildings.shape[0] == expected_remainder_buildings.shape[0]
        for column in expected_remainder_buildings.columns:
            assert column in returned_remainder_buildings.columns
        for row_index in range(expected_remainder_buildings.shape[0]):
            for column in expected_remainder_buildings.columns:
                if isinstance(
                    expected_remainder_buildings.loc[row_index, column], str
                ) or isinstance(expected_remainder_buildings.loc[row_index, column], int):
                    assert (
                        returned_remainder_buildings.loc[row_index, column]
                        == expected_remainder_buildings.loc[row_index, column]
                    )
                else:
                    assert round(
                        returned_remainder_buildings.loc[row_index, column], 4
                    ) == round(expected_remainder_buildings.loc[row_index, column], 4)

        # Check contents of OpenQuake CSV file for OBM buildings
        returned_obm_buildings = pandas.read_csv(
            os.path.join(output_path, expected_name_obm_buildings),
        )
        expected_obm_buildings = pandas.read_csv(
            os.path.join(expected_results_path, expected_obm_buildings_output[k]),
        )
        assert returned_obm_buildings.shape[0] == expected_obm_buildings.shape[0]
        for column in expected_obm_buildings.columns:
            assert column in returned_obm_buildings.columns
        for row_index in range(expected_obm_buildings.shape[0]):
            for column in expected_obm_buildings.columns:
                if isinstance(expected_obm_buildings.loc[row_index, column], str) or isinstance(
                    expected_obm_buildings.loc[row_index, column], int
                ):
                    assert (
                        returned_obm_buildings.loc[row_index, column]
                        == expected_obm_buildings.loc[row_index, column]
                    )
                else:
                    assert round(returned_obm_buildings.loc[row_index, column], 4) == round(
                        expected_obm_buildings.loc[row_index, column], 4
                    )

        # Check contents of file with quadtile geometries
        returned_quadtiles_geometries = geopandas.read_file(
            os.path.join(output_path, expected_name_geometries_quadtiles)
        )
        expected_quadtiles_geometries = pandas.read_csv(
            os.path.join(expected_results_path, expected_quadtiles_geometries_output),
            sep=";",
            dtype={"quadkey": str},
        )
        assert returned_quadtiles_geometries.shape[0] == expected_quadtiles_geometries.shape[0]
        for j, quadkey in enumerate(expected_quadtiles_geometries["quadkey"].values):
            assert quadkey in returned_quadtiles_geometries["quadkey"].values
            filter = returned_quadtiles_geometries["quadkey"] == quadkey
            returned_bounds = returned_quadtiles_geometries[filter]["geometry"].values[0].bounds
            expected_bounds = loads(expected_quadtiles_geometries["geometry"].values[j]).bounds
            for bound in range(4):
                assert round(returned_bounds[bound], 5) == round(expected_bounds[bound], 5)

        # Check contents of file with OBM geometries
        if export_OBM_footprints_vals[k]:
            returned_obm_geometries = geopandas.read_file(
                os.path.join(output_path, expected_name_geometries_obm)
            )

            expected_obm_geometries = pandas.read_csv(
                os.path.join(expected_results_path, expected_obm_geometries_output),
                sep=";",
                dtype={"osm_id": str},
            )
            assert returned_obm_geometries.shape[0] == expected_obm_geometries.shape[0]
            for j, osm_id in enumerate(expected_obm_geometries["osm_id"].values):
                assert osm_id in returned_obm_geometries["osm_id"].values
                filter = returned_obm_geometries["osm_id"] == osm_id
                returned_bounds = returned_obm_geometries[filter]["geometry"].values[0].bounds
                expected_bounds = loads(expected_obm_geometries["geometry"].values[j]).bounds
                for bound in range(4):
                    assert round(returned_bounds[bound], 5) == round(expected_bounds[bound], 5)

        # Delete created output files
        os.remove(os.path.join(output_path, expected_name_remainder_buildings))
        os.remove(os.path.join(output_path, expected_name_obm_buildings))
        os.remove(os.path.join(output_path, expected_name_geometries_quadtiles))
        if export_OBM_footprints_vals[k]:
            os.remove(os.path.join(output_path, expected_name_geometries_obm))

    # Delete temporary directory
    os.rmdir(output_path)