Skip to content

Commit 3df607b

Browse files
committed
Fix tests litpop and finance. Don't set geometry in litpop init
1 parent c6e21fb commit 3df607b

File tree

6 files changed

+74
-35
lines changed

6 files changed

+74
-35
lines changed

climada/entity/exposures/litpop.py

Lines changed: 47 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -124,13 +124,15 @@ def set_country(self, countries, **args):
124124
To use population count alone: [0, 1].
125125
fin_mode (str, optional): define what total country economic value
126126
is to be used as an asset base and distributed to the grid:
127-
- gdp: gross-domestic product (Source: World Bank)
128-
- income_group: gdp multiplied by country's income group+1
129-
- nfw: non-financial wealth (Source: Credit Suisse, of households only)
130-
- tw: total wealth (Source: Credit Suisse, of households only)
131-
- pc: produced capital (Source: World Bank), incl. manufactured or
127+
- 'gdp': gross-domestic product (Source: World Bank)
128+
- 'income_group': gdp multiplied by country's income group+1
129+
- 'nfw': non-financial wealth (Source: Credit Suisse, of households only)
130+
- 'tw': total wealth (Source: Credit Suisse, of households only)
131+
- 'pc': produced capital (Source: World Bank), incl. manufactured or
132132
built assets such as machinery, equipment, and physical structures
133133
(pc is in constant 2014 USD)
134+
- 'norm': normalized by country
135+
- 'none': LitPop per pixel is returned unchanged
134136
admin1_calc (boolean): distribute admin1-level GDP if available?
135137
(default False)
136138
conserve_cntrytotal (boolean): given admin1_calc, conserve national
@@ -209,11 +211,13 @@ def set_country(self, countries, **args):
209211

210212
for cntry_iso, cntry_val in country_info.items():
211213
if fin_mode == 'pc':
212-
_, total_asset_val = world_bank_wealth_account(cntry_iso, \
214+
total_asset_val = world_bank_wealth_account(cntry_iso, \
213215
reference_year, \
214-
no_land=True)
216+
no_land=True)[1]
215217
# here, total_asset_val is Produced Capital "pc"
216218
# no_land=True returns value w/o the mark-up of 24% for land value
219+
elif fin_mode in ['norm', 'none']:
220+
total_asset_val = 1
217221
else:
218222
_, total_asset_val = gdp(cntry_iso, reference_year, shp_file)
219223
cntry_val.append(total_asset_val)
@@ -227,7 +231,9 @@ def set_country(self, countries, **args):
227231
points2check=all_coords)
228232
litpop_curr = litpop_data[mask.sp_index.indices]
229233
lon, lat = zip(*np.array(all_coords)[mask.sp_index.indices])
230-
if admin1_calc == 1:
234+
if fin_mode=='none':
235+
LOGGER.info('fin_mode=none --> no downscaling; admin1_calc is ignored')
236+
elif admin1_calc == 1:
231237
litpop_curr = _calc_admin1(curr_country,\
232238
country_info[curr_country],
233239
admin1_info[curr_country],\
@@ -255,8 +261,9 @@ def set_country(self, countries, **args):
255261
self.plot_log(admin1_plot=0)
256262
LOGGER.info("Creating the LitPop exposure took "\
257263
+ str(round(time.time() - start_time, 2)) +"s")
264+
265+
# self.set_geometry_points()
258266
self.check()
259-
self.set_geometry_points()
260267

261268
@staticmethod
262269
def _set_one_country(cntry_info, litpop_data, lon, lat, curr_country):
@@ -1026,7 +1033,7 @@ def _get_gdp2asset_factor(cntry_info, ref_year, shp_file, fin_mode='income_group
10261033
for cntry_iso, cntry_val in cntry_info.items():
10271034
_, inc_grp = income_group(cntry_iso, ref_year, shp_file)
10281035
cntry_val.append(inc_grp+1)
1029-
elif fin_mode in ['gdp', 'pc']:
1036+
elif fin_mode in ['gdp', 'pc', 'none', 'norm']:
10301037
for cntry_iso, cntry_val in cntry_info.items():
10311038
cntry_val.append(1)
10321039
elif fin_mode == 'nfw' or fin_mode == 'tw':
@@ -1811,20 +1818,6 @@ def admin1_validation(country, methods, exponents, **args):
18111818
LOGGER.error('Country parameter data type not recognised. '\
18121819
+ 'Operation aborted.')
18131820
raise TypeError
1814-
all_coords = _litpop_box2coords(cut_bbox, resolution, 1)
1815-
# Get LitPop, Lit and Pop, etc:
1816-
nightlights = _get_box_blackmarble(cut_bbox,\
1817-
resolution=resolution, return_coords=0)
1818-
gpw = gpw_import._get_box_gpw(cut_bbox=cut_bbox, resolution=resolution,\
1819-
return_coords=0, reference_year=reference_year)
1820-
bm_temp = np.ones(nightlights.shape)
1821-
1822-
# Lit = Lit + 1 if Population is included, c.f. int(exponents[1]>0):
1823-
bm_temp[nightlights.sp_index.indices] = (np.array(nightlights.sp_values, \
1824-
dtype='uint16')+int(exponents[1]>0))
1825-
nightlights = pd.SparseArray(bm_temp, fill_value=int(exponents[1]>0))
1826-
del bm_temp
1827-
18281821
shp_file = shapereader.natural_earth(resolution='10m',
18291822
category='cultural',
18301823
name='admin_0_countries')
@@ -1836,9 +1829,31 @@ def admin1_validation(country, methods, exponents, **args):
18361829
_get_gdp2asset_factor(country_info, reference_year, shp_file, fin_mode=fin_mode)
18371830

18381831
curr_shp = _get_country_shape(country_list[0], 0)
1832+
1833+
all_coords = _litpop_box2coords(cut_bbox, resolution, 1)
18391834
mask = _mask_from_shape(curr_shp, resolution=resolution,\
18401835
points2check=all_coords)
1841-
nightlights = nightlights[mask.sp_index.indices]
1836+
1837+
1838+
# Get LitPop, Lit and Pop, etc:
1839+
nightlights = _get_box_blackmarble(cut_bbox,\
1840+
resolution=resolution, return_coords=0)
1841+
1842+
bm_temp = np.ones(nightlights.shape)
1843+
1844+
# Lit = Lit + 1 if Population is included, c.f. int(exponents[1]>0):
1845+
bm_temp[nightlights.sp_index.indices] = (np.array(nightlights.sp_values, \
1846+
dtype='uint16'))
1847+
del nightlights
1848+
1849+
nightlights0 = pd.SparseArray(bm_temp, fill_value=0)
1850+
nightlights0 = nightlights0[mask.sp_index.indices]
1851+
nightlights1 = pd.SparseArray(bm_temp+1, fill_value=1)
1852+
del bm_temp
1853+
nightlights1 = nightlights1[mask.sp_index.indices]
1854+
1855+
gpw = gpw_import._get_box_gpw(cut_bbox=cut_bbox, resolution=resolution,\
1856+
return_coords=0, reference_year=reference_year)
18421857
gpw = gpw[mask.sp_index.indices]
18431858

18441859
lon, lat = zip(*np.array(all_coords)[mask.sp_index.indices])
@@ -1854,8 +1869,13 @@ def admin1_validation(country, methods, exponents, **args):
18541869
LOGGER.info('Loop through methods...')
18551870
for i in np.arange(0, len(methods)):
18561871
LOGGER.info('%s :', methods[i])
1857-
_data = _LitPop_multiply_box(nightlights, gpw, \
1858-
x=exponents[i][0], y=exponents[i][1])
1872+
if exponents[i][1]==0: # Lit only, use Lit in [0, 255]
1873+
_data = _LitPop_multiply_box(nightlights0, gpw, \
1874+
x=exponents[i][0], y=0)
1875+
else: # Pop is used, use Lit+1 in [1, 256]
1876+
_data = _LitPop_multiply_box(nightlights1, gpw, \
1877+
x=exponents[i][0], y=exponents[i][1])
1878+
18591879
_, rho[i*n_scores:(i*n_scores)+n_scores], adm0[methods[i]], adm1[methods[i]] = \
18601880
_calc_admin1(country_list[0],\
18611881
country_info[country_list[0]], admin1_info[country_list[0]],\

climada/test/test_LitPop.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,22 @@ def test_switzerland30_pass(self):
5656
self.assertTrue(ent.region_id.max() == 756)
5757
self.assertTrue(np.int(ent.value.sum().round()) == 3343726398023)
5858

59+
def test_switzerland30_normPopulation_pass(self):
60+
"""Create LitPop entity for Switzerland on 30 arcsec:"""
61+
country_name = ['CHE']
62+
resolution = 30
63+
exp = [0, 1]
64+
fin_mode = 'norm'
65+
ent = LitPop()
66+
with self.assertLogs('climada.entity.exposures.litpop', level='INFO') as cm:
67+
ent.set_country(country_name, res_arcsec=resolution, exponent=exp,\
68+
fin_mode=fin_mode, reference_year=2015)
69+
# print(cm)
70+
self.assertIn('Generating LitPop data at a resolution of 30 arcsec', cm.output[0])
71+
self.assertTrue(ent.region_id.min() == 756)
72+
self.assertTrue(ent.region_id.max() == 756)
73+
self.assertTrue(np.int((1000*ent.value.sum()).round()) == 1000)
74+
5975
def test_suriname30_nfw_pass(self):
6076
"""Create LitPop entity for Suriname for non-finanical wealth:"""
6177
country_name = ['SUR']
@@ -77,8 +93,8 @@ def test_switzerland300_pc2016_pass(self):
7793
ref_year = 2016
7894
adm1 = True
7995
cons = True
80-
_, comparison_total_val = world_bank_wealth_account(country_name[0], ref_year, \
81-
no_land=1)
96+
comparison_total_val = world_bank_wealth_account(country_name[0], ref_year, \
97+
no_land=1)[1]
8298
ent = LitPop()
8399
with self.assertLogs('climada.entity.exposures.litpop', level='INFO') as cm:
84100
ent.set_country(country_name, res_arcsec=resolution, \
@@ -95,7 +111,8 @@ def test_switzerland300_pc2013_pass(self):
95111
fin_mode = 'pc'
96112
resolution = 300
97113
ref_year = 2013
98-
_, comparison_total_val = world_bank_wealth_account(country_name[0], ref_year, no_land=1)
114+
comparison_total_val = world_bank_wealth_account(country_name[0], \
115+
ref_year, no_land=1)[1]
99116
ent = LitPop()
100117
with self.assertLogs('climada.entity.exposures.litpop', level='INFO') as cm:
101118
ent.set_country(country_name, res_arcsec=resolution, \

climada/util/test/test_finance.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -140,11 +140,12 @@ def test_pca_DEU_2010_pass(self):
140140
""" Test Processed Capital value Germany 2010."""
141141
ref_year = 2010
142142
cntry_iso = 'DEU'
143-
res_year, res_val = world_bank_wealth_account(cntry_iso, ref_year, no_land=0)
144-
res_year_noland, res_val_noland = world_bank_wealth_account(cntry_iso, ref_year, no_land=1)
143+
res_year, res_val, q = world_bank_wealth_account(cntry_iso, ref_year, no_land=0)
144+
res_year_noland, res_val_noland, q = world_bank_wealth_account(cntry_iso, ref_year, no_land=1)
145145
ref_val = 17675048450284.9
146146
ref_val_noland = 14254071330874.9
147147
self.assertEqual(res_year, ref_year)
148+
self.assertEqual(q, 1)
148149
self.assertEqual(res_val, ref_val)
149150
self.assertEqual(res_year_noland, ref_year)
150151
self.assertEqual(res_val_noland, ref_val_noland)
@@ -153,7 +154,7 @@ def test_pca_CHE_2008_pass(self):
153154
ref_year = 2008
154155
cntry_iso = 'CHE'
155156
var_name = 'NW.PCA.PC'
156-
res_year, res_val = world_bank_wealth_account(cntry_iso, ref_year, \
157+
res_year, res_val, _ = world_bank_wealth_account(cntry_iso, ref_year, \
157158
variable_name=var_name, no_land=0)
158159
ref_val = 328398.7
159160
self.assertEqual(res_year, ref_year)
@@ -163,7 +164,7 @@ def test_tow_IND_1985_pass(self):
163164
ref_year = 1985
164165
cntry_iso = 'IND'
165166
var_name = 'NW.TOW.TO'
166-
res_year, res_val = world_bank_wealth_account(cntry_iso, ref_year, \
167+
res_year, res_val, _ = world_bank_wealth_account(cntry_iso, ref_year, \
167168
variable_name=var_name)
168169
ref_val = 5415188681962.3
169170
self.assertEqual(res_year, ref_year)
@@ -172,8 +173,9 @@ def test_pca_CUB_2015_pass(self):
172173
""" Test Processed Capital value Cuba 2015 (missing value)."""
173174
ref_year = 2015
174175
cntry_iso = 'CUB'
175-
res_year, res_val = world_bank_wealth_account(cntry_iso, ref_year, no_land=1)
176+
res_year, res_val, q = world_bank_wealth_account(cntry_iso, ref_year, no_land=1)
176177
ref_val = 108675762920.0
178+
self.assertEqual(q, 0)
177179
self.assertEqual(res_year, ref_year)
178180
self.assertEqual(res_val, ref_val)
179181

data/system/GSDP/FRA_GSDP.xls

0 Bytes
Binary file not shown.

data/system/GSDP/MEX_GSDP.xls

0 Bytes
Binary file not shown.

data/system/GSDP/ZAF_GSDP.xls

0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)