Skip to content

Commit f710f59

Browse files
author
schmide
committed
Merge branch 'develop' into main
2 parents d5099d4 + c1cd18a commit f710f59

File tree

7 files changed

+104
-18
lines changed

7 files changed

+104
-18
lines changed

climada/entity/exposures/gpw_import.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import logging
88
import subprocess
99

10-
import gdal
10+
from osgeo import gdal
1111
import pandas as pd
1212
from scipy import ndimage as nd
1313
import numpy as np

climada/entity/exposures/litpop.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
import shapefile
3131
from matplotlib import pyplot as plt
3232
from iso3166 import countries as iso_cntry
33-
import gdal
33+
from osgeo import gdal
3434
from cartopy.io import shapereader
3535

3636
from climada import CONFIG
@@ -1892,7 +1892,7 @@ def to_sparse_dataframe(ndarr):
18921892
----------
18931893
ndarr : numpy.ndarray
18941894
2 dimensional
1895-
1895+
18961896
Returns
18971897
-------
18981898
sparse dataframe : pandas.DataFrame

climada/hazard/test/test_tc_surge_bathtub.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def __init__(self, bounds, res_deg):
4444
res_deg : float
4545
Resolution in degrees
4646
"""
47-
lat = np.arange(bounds[1] + 0.5 * res_deg, bounds[3], res_deg)
47+
lat = np.arange(bounds[3] - 0.5 * res_deg, bounds[1], -res_deg)
4848
lon = np.arange(bounds[0] + 0.5 * res_deg, bounds[2], res_deg)
4949
self.shape = (lat.size, lon.size)
5050
self.transform = rasterio.Affine(res_deg, 0, bounds[0], 0, -res_deg, bounds[3])
@@ -69,9 +69,9 @@ def __enter__(self):
6969
'nodata': -32767.0,
7070
}
7171

72-
# In Windows, unlike Unix, the temporary file cannot be opened before it is closed
72+
# In Windows, unlike Unix, the temporary file cannot be opened before it is closed.
7373
# Therefore it is closed right after creation and only the path/name is kept.
74-
tmpfile = tempfile.NamedTemporaryFile()
74+
tmpfile = tempfile.NamedTemporaryFile(delete=False)
7575
self.topo_path = tmpfile.name
7676
tmpfile.close()
7777
with rasterio.open(self.topo_path, 'w', **dst_meta) as dst:
@@ -107,14 +107,14 @@ def test_fraction_on_land(self):
107107

108108
# check valid range and order of magnitude
109109
self.assertTrue(np.all((fraction >= 0) & (fraction <= 1)))
110-
np.testing.assert_array_equal(fraction[dist_coast > 4000], 0)
111-
np.testing.assert_array_equal(fraction[dist_coast < -2000], 1)
110+
np.testing.assert_array_equal(fraction[dist_coast > 1000], 0)
111+
np.testing.assert_array_equal(fraction[dist_coast < -1000], 1)
112112

113113
# check individual known pixel values
114-
self.assertEqual(fraction[28, 13], 0.0)
115-
self.assertEqual(fraction[26, 11], 0.0625)
116-
self.assertEqual(fraction[26, 12], 0.7)
117-
self.assertEqual(fraction[23, 14], 1.0)
114+
self.assertAlmostEqual(fraction[24, 10], 0.0)
115+
self.assertAlmostEqual(fraction[22, 11], 0.21)
116+
self.assertAlmostEqual(fraction[22, 12], 0.93)
117+
self.assertAlmostEqual(fraction[21, 14], 1.0)
118118

119119

120120
def test_surge_from_track(self):
@@ -172,13 +172,14 @@ def test_surge_from_track(self):
172172
fraction = surge_haz.fraction.toarray().reshape(shape)
173173

174174
# check valid range and order of magnitude
175-
self.assertTrue(np.all(inten >= 0))
176-
self.assertTrue(np.all(inten <= 10))
177-
self.assertTrue(np.all((fraction >= 0) & (fraction <= 1)))
175+
np.testing.assert_array_equal(inten >= 0, True)
176+
np.testing.assert_array_equal(inten <= 10, True)
177+
np.testing.assert_array_equal((fraction >= 0) & (fraction <= 1), True)
178+
np.testing.assert_array_equal(inten[fraction == 0], 0)
178179

179180
# check individual known pixel values
180-
self.assertAlmostEqual(inten[14, 26], max(-0.125 + slr, 0), places=2)
181-
self.assertAlmostEqual(inten[14, 34] - slr, 0.592, places=2)
181+
self.assertAlmostEqual(inten[9, 31], max(-0.391 + slr, 0), places=2)
182+
self.assertAlmostEqual(inten[14, 34] - slr, 3.637, places=2)
182183

183184

184185
# Execute Tests

climada/util/__init__.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
1919
init util
2020
"""
21+
import logging
2122
from pint import UnitRegistry
2223

2324
from .config import *
@@ -26,3 +27,37 @@
2627
from .save import *
2728

2829
ureg = UnitRegistry()
30+
31+
class log_level:
32+
"""Context manager that sets all loggers with names starting with
33+
name_prefix (default is "") to a given specified level.
34+
35+
Examples
36+
--------
37+
Set ALL loggers temporarily to the level 'WARNING'
38+
>>> with log_level(level='WARNING'):
39+
>>> ...
40+
41+
Set all the climada loggers temporarily to the level 'ERROR'
42+
>>> with log_level(level='ERROR', name_prefix='climada'):
43+
>>> ...
44+
45+
"""
46+
47+
def __init__(self, level, name_prefix=""):
48+
self.level = level
49+
self.loggers = {
50+
name: (logger, logger.level)
51+
for name, logger in logging.root.manager.loggerDict.items()
52+
if isinstance(logger, logging.Logger) and name.startswith(name_prefix)
53+
}
54+
if name_prefix == "":
55+
self.loggers[""] = (logging.getLogger(), logging.getLogger().level)
56+
57+
def __enter__(self):
58+
for logger, _ in self.loggers.values():
59+
logger.setLevel(self.level)
60+
61+
def __exit__(self, exception_type, exception, traceback):
62+
for logger, previous_level in self.loggers.values():
63+
logger.setLevel(previous_level)

climada/util/plot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ def add_shapes(axis):
343343
name='admin_0_countries')
344344
shp = shapereader.Reader(shp_file)
345345
for geometry in shp.geometries():
346-
axis.add_geometries([geometry], crs=ccrs.PlateCarree(), facecolor='',
346+
axis.add_geometries([geometry], crs=ccrs.PlateCarree(), facecolor='none',
347347
edgecolor='black')
348348

349349
def add_populated_places(axis, extent, proj=ccrs.PlateCarree()):

climada/util/test/test__init__.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
This file is part of CLIMADA.
3+
4+
Copyright (C) 2017 ETH Zurich, CLIMADA contributors listed in AUTHORS.
5+
6+
CLIMADA is free software: you can redistribute it and/or modify it under the
7+
terms of the GNU Lesser General Public License as published by the Free
8+
Software Foundation, version 3.
9+
10+
CLIMADA is distributed in the hope that it will be useful, but WITHOUT ANY
11+
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
12+
PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
13+
14+
You should have received a copy of the GNU Lesser General Public License along
15+
with CLIMADA. If not, see <https://www.gnu.org/licenses/>.
16+
17+
---
18+
19+
Test config module.
20+
"""
21+
import unittest
22+
import logging
23+
24+
from climada.util import log_level
25+
26+
class TestUtilInit(unittest.TestCase):
27+
"""Test util __init__ methods"""
28+
29+
def test_log_level_pass(self):
30+
"""Test log level context manager passes"""
31+
#Check loggers are set to level
32+
with self.assertLogs('climada', level='INFO') as cm:
33+
with log_level('WARNING'):
34+
logging.getLogger('climada').info('info')
35+
logging.getLogger('climada').error('error')
36+
self.assertEqual(cm.output, ['ERROR:climada:error'])
37+
#Check if only climada loggers level change
38+
with self.assertLogs('matplotlib', level='DEBUG') as cm:
39+
with log_level('ERROR', name_prefix='climada'):
40+
logging.getLogger('climada').info('info')
41+
logging.getLogger('matplotlib').debug('debug')
42+
self.assertEqual(cm.output, ['DEBUG:matplotlib:debug'])
43+
44+
# Execute Tests
45+
if __name__ == "__main__":
46+
TESTS = unittest.TestLoader().loadTestsFromTestCase(TestUtilInit)
47+
unittest.TextTestRunner(verbosity=2).run(TESTS)

requirements/env_docs.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,9 +208,12 @@ dependencies:
208208
- zipp=3.4.1=pyhd8ed1ab_0
209209
- zlib=1.2.11=h516909a_1010
210210
- zstd=1.4.9=ha95c52a_0
211+
- nb_conda
212+
- nb_conda_kernels
211213
- pip:
212214
- bitstring==3.1.7
213215
- overpy==0.4
214216
- pybufrkit==0.2.18
217+
- ipython
215218
- nbsphinx
216219

0 commit comments

Comments
 (0)