Skip to content

Commit f14bd6b

Browse files
emanuel-schmidschmideThomas Vogt
authored
Feature/fix rasterio read netcdf (CLIMADA-project#65)
* climada.util.coordinates: slightly increased readability of read_raster * tests_runner: enable specific test selection * tests: allow small discrepancy * conda environment: update rasterio to 1.1.5 - and bear the consequences * config: suppress FutureWarning * conda environment: fix cfgrib dependency * Reduce size of demo file for TCs in Florida * Reduce size of MAT demo file for TCs in Florida * Reduce size of MAT demo file for WS in ERA40 * litpop: fix several issues with updated SparseArray and SparseDataFrame * conda: make sure matplotlib and matplotlib-base have a matching version * open_street_map: turn FutureWarning and DeprecationWarning off temporarily, to save the logs from being flooded * Update requirements/env_climada.yml * Update requirements/env_climada.yml * dependencies: sync setup.py + cosmetics in env_climada.yml: proj 7.0.0 from the default channel logs with batch echo on Co-authored-by: schmide <[email protected]> Co-authored-by: Thomas Vogt <[email protected]>
1 parent 907fe43 commit f14bd6b

File tree

13 files changed

+172
-157
lines changed

13 files changed

+172
-157
lines changed

climada/entity/exposures/gpw_import.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def get_box_gpw(**parameters):
134134
135135
Returns
136136
-------
137-
tile_temp : pandas SparseArray
137+
tile_temp : pandas.arrays.SparseArray
138138
GPW data
139139
lon : list
140140
List with longitudinal infomation on the GPW data. Same
@@ -210,7 +210,7 @@ def get_box_gpw(**parameters):
210210
LOGGER.error('Error: Matrix has an invalid number of dimensions \
211211
(more than 2). Could not continue operation.')
212212
raise TypeError
213-
tile_temp = pd.SparseArray(
213+
tile_temp = pd.arrays.SparseArray(
214214
tile_temp.reshape((tile_temp.size,), order='F'),
215215
fill_value=0)
216216
del arr1

climada/entity/exposures/litpop.py

Lines changed: 75 additions & 53 deletions
Large diffs are not rendered by default.

climada/entity/exposures/open_street_map.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import os
1515
import time
16+
import logging
1617
from functools import partial
1718

1819
#matplotlib.use('Qt5Agg', force=True)
@@ -562,10 +563,14 @@ def _get_midpoints(highValueArea):
562563
High_Value_Area_gdf.loc[index, "Midpoint"] = \
563564
High_Value_Area_gdf.loc[index, "geometry"].centroid.wkt
564565
s = shape(High_Value_Area_gdf.loc[index, "geometry"])
566+
# turn warnings off, otherwise Future and Deprecation warnings are flooding the logs
567+
logging.captureWarnings(True)
565568
proj = partial(pyproj.transform, pyproj.Proj(init='epsg:4326'),
566569
pyproj.Proj(init='epsg:3857'))
567570
High_Value_Area_gdf.loc[index, "projected_area"] = transform(proj, s).area
568-
571+
# turn warnings on again
572+
logging.captureWarnings(False)
573+
569574
# change active geometry from polygons to midpoints
570575
from shapely.wkt import loads
571576
High_Value_Area_gdf = High_Value_Area_gdf.rename(columns={'geometry': 'geo_polys',

climada/entity/exposures/test/test_litpop_unit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def test_mask_from_shape(self):
106106
curr_shp = lp._get_country_shape(curr_country, 0)
107107
mask = lp._mask_from_shape(curr_shp, resolution=60)
108108
self.assertEqual(mask.sp_index.indices.size, 5591)
109-
self.assertTrue(mask.values.max())
109+
self.assertTrue(mask.sp_values.max())
110110
self.assertIn(140 and 7663, mask.sp_index.indices)
111111

112112
def test_litpop_box2coords(self):

climada/hazard/emulator/stats.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ def haz_max_events(hazard, min_thresh=0):
144144
LOGGER.info("Condensing %d hazards to %d max events ...", inten.shape[0], exp_hazards.size)
145145
inten = inten[exp_hazards]
146146
inten_max_ids = np.asarray(inten.argmax(axis=1)).ravel()
147-
inten_max = inten[range(inten.shape[0]), inten_max_ids].todense()
147+
inten_max = inten[range(inten.shape[0]), inten_max_ids]
148148
dates = hazard.date[exp_hazards]
149149
dates = [datetime.date.fromordinal(d) for d in dates]
150150
return pd.DataFrame({

climada/test/test_LitPop.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ def test_gpw_import(self):
178178
self.assertEqual(len(gpw), 323)
179179
self.assertIn(np.around(max(gpw)), [103070.0, 137840.0])
180180
self.assertEqual(type(gpw),
181-
type(pd.SparseArray(data=1, fill_value=0)))
181+
type(pd.arrays.SparseArray(data=1, fill_value=0)))
182182
self.assertAlmostEqual(lat[0], -27.3164)
183183
self.assertAlmostEqual(lat[1], 0.083333333)
184184
self.assertAlmostEqual(lon[0], 30.78291)

climada/test/test_drought_integr.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ def test_switzerland(self):
5555
self.assertEqual(hazard_set.size, 114)
5656
self.assertEqual(hazard_set.centroids.size, 130)
5757
self.assertEqual(exposure_agrar.latitude.values.size, 766 / 2)
58-
self.assertEqual(exposure_agrar.value[3], 1720024.4)
59-
self.assertEqual(damages_drought, 61995472.555223145)
58+
self.assertAlmostEqual(exposure_agrar.value[3], 1720024.4)
59+
self.assertAlmostEqual(damages_drought, 61995472.555223145)
6060

6161

6262
# Execute Tests

climada/util/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333

3434
from climada.util.constants import SOURCE_DIR
3535

36+
3637
WORKING_DIR = os.getcwd()
3738
WINDOWS_END = WORKING_DIR[0:3]
3839
UNIX_END = '/'

climada/util/coordinates.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1093,40 +1093,48 @@ def read_raster(file_name, band=None, src_crs=None, window=None, geometry=None,
10931093

10941094
with rasterio.Env():
10951095
with rasterio.open(file_name, 'r') as src:
1096-
src_crs = src.crs if src_crs is None else src_crs
1097-
if not src_crs:
1098-
src_crs = rasterio.crs.CRS.from_dict(DEF_CRS)
10991096
dst_meta = src.meta.copy()
11001097

11011098
if dst_crs or transform:
11021099
LOGGER.debug('Reprojecting ...')
1100+
1101+
src_crs = src.crs if src_crs is None else src_crs
1102+
if not src_crs:
1103+
src_crs = rasterio.crs.CRS.from_dict(DEF_CRS)
11031104
transform = (transform, width, height) if transform else None
11041105
inten = _read_raster_reproject(src, src_crs, dst_meta, band=band,
11051106
geometry=geometry, dst_crs=dst_crs,
11061107
transform=transform, resampling=resampling)
11071108
else:
1108-
trans = dst_meta['transform']
11091109
if geometry:
11101110
inten, trans = rasterio.mask.mask(src, geometry, crop=True, indexes=band)
11111111
if dst_meta['nodata'] and np.isnan(dst_meta['nodata']):
11121112
inten[np.isnan(inten)] = 0
11131113
else:
11141114
inten[inten == dst_meta['nodata']] = 0
1115+
11151116
else:
11161117
masked_array = src.read(band, window=window, masked=True)
11171118
inten = masked_array.data
11181119
inten[masked_array.mask] = 0
1120+
11191121
if window:
11201122
trans = rasterio.windows.transform(window, src.transform)
1123+
else:
1124+
trans = dst_meta['transform']
1125+
11211126
dst_meta.update({
11221127
"height": inten.shape[1],
11231128
"width": inten.shape[2],
11241129
"transform": trans,
11251130
})
1131+
11261132
if not dst_meta['crs']:
11271133
dst_meta['crs'] = rasterio.crs.CRS.from_dict(DEF_CRS)
1134+
11281135
intensity = inten[range(len(band)), :]
11291136
dst_shape = (len(band), dst_meta['height'] * dst_meta['width'])
1137+
11301138
return dst_meta, intensity.reshape(dst_shape)
11311139

11321140
def read_raster_bounds(path, bounds, res=None, bands=None):

climada/util/test/test_coordinates.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ def test_get_land_geometry_all_pass(self):
270270
"""get_land_geometry with all earth."""
271271
res = get_land_geometry(resolution=110)
272272
self.assertIsInstance(res, shapely.geometry.multipolygon.MultiPolygon)
273-
self.assertEqual(res.area, 21496.99098799273)
273+
self.assertAlmostEqual(res.area, 21496.99098799273)
274274

275275
def test_on_land_pass(self):
276276
"""check point on land with 1:50.000.000 resolution."""

0 commit comments

Comments
 (0)