Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove Tag attribute from DiscRates #755

Merged
merged 4 commits into from
Jul 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 6 additions & 19 deletions climada/entity/disc_rates/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import xlsxwriter

import climada.util.checker as u_check
from climada.util.tag import Tag
import climada.util.finance as u_fin
import climada.util.hdf5_handler as u_hdf5

Expand Down Expand Up @@ -60,8 +59,6 @@ class DiscRates():

Attributes
---------
tag: climada.util.tag.Tag
information about the source data
years: np.array
list of years
rates: np.array
Expand All @@ -71,8 +68,7 @@ class DiscRates():
def __init__(
self,
years : Optional[np.ndarray] = None,
rates : Optional[np.ndarray] = None,
tag : Optional[Tag] = None
rates : Optional[np.ndarray] = None
):
"""
Fill discount rates with values and check consistency data
Expand All @@ -85,17 +81,13 @@ def __init__(
Discount rates for each year in years.
Default is numpy.array([]).
Note: rates given in float, e.g., to set 1% rate use 0.01
tag : climate.entity.tag
Metadata. Default is None.
"""
self.years = np.array([]) if years is None else years
self.rates = np.array([]) if rates is None else rates
self.tag = Tag() if tag is None else tag

def clear(self):
"""Reinitialize attributes."""

self.tag = Tag()
# Following values are given for each defined year
self.years = np.array([], int)
self.rates = np.array([], float)
Expand Down Expand Up @@ -129,8 +121,7 @@ def select(self, year_range):
pos_year = np.isin(self.years, year_range)

return DiscRates(years=self.years[pos_year],
rates=self.rates[pos_year],
tag=self.tag)
rates=self.rates[pos_year])

def append(self, disc_rates):
"""
Expand All @@ -151,8 +142,6 @@ def append(self, disc_rates):
self.__dict__ = copy.deepcopy(disc_rates.__dict__)
return

self.tag.append(disc_rates.tag)

new_year = array('l')
new_rate = array('d')
for year, rate in zip(disc_rates.years, disc_rates.rates):
Expand Down Expand Up @@ -224,7 +213,7 @@ def plot(self, axis=None, figsize=(6, 8), **kwargs):
return axis

@classmethod
def from_mat(cls, file_name, description='', var_names=None):
def from_mat(cls, file_name, var_names=None):
"""
Read MATLAB file generated with previous MATLAB CLIMADA version.

Expand Down Expand Up @@ -254,7 +243,6 @@ def from_mat(cls, file_name, description='', var_names=None):
if var_names is None:
var_names = DEF_VAR_MAT
disc = u_hdf5.read(file_name)
tag = Tag(file_name=str(file_name), description=description)
try:
disc = disc[var_names['sup_field_name']]
except KeyError:
Expand All @@ -268,7 +256,7 @@ def from_mat(cls, file_name, description='', var_names=None):
except KeyError as err:
raise KeyError("Not existing variable: %s" % str(err)) from err

return cls(years=years, rates=rates, tag=tag)
return cls(years=years, rates=rates)

def read_mat(self, *args, **kwargs):
"""This function is deprecated, use DiscRates.from_mats instead."""
Expand All @@ -277,7 +265,7 @@ def read_mat(self, *args, **kwargs):
self.__dict__ = DiscRates.from_mat(*args, **kwargs).__dict__

@classmethod
def from_excel(cls, file_name, description='', var_names=None):
def from_excel(cls, file_name, var_names=None):
"""
Read excel file following template and store variables.

Expand Down Expand Up @@ -306,15 +294,14 @@ def from_excel(cls, file_name, description='', var_names=None):
if var_names is None:
var_names = DEF_VAR_EXCEL
dfr = pd.read_excel(file_name, var_names['sheet_name'])
tag = Tag(file_name=str(file_name), description=description)
try:
years = dfr[var_names['col_name']['year']].values. \
astype(int, copy=False)
rates = dfr[var_names['col_name']['disc']].values
except KeyError as err:
raise KeyError("Not existing variable: %s" % str(err)) from err

return cls(years=years, rates=rates, tag=tag)
return cls(years=years, rates=rates)

def read_excel(self, *args, **kwargs):
"""This function is deprecated, use DiscRates.from_excel instead."""
Expand Down
74 changes: 12 additions & 62 deletions climada/entity/disc_rates/test/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@

from climada import CONFIG
from climada.entity.disc_rates.base import DiscRates
from climada.util.tag import Tag
from climada.util.constants import ENT_TEMPLATE_XLS, ENT_DEMO_TODAY

ENT_TEST_MAT = CONFIG.exposures.test_data.dir().joinpath('demo_today.mat')
Expand Down Expand Up @@ -58,32 +57,20 @@ def test_append_to_empty_same(self):
disc_rate = DiscRates()
disc_rate_add = DiscRates(
years=np.array([2000, 2001, 2002]),
rates=np.array([0.1, 0.2, 0.3]),
tag=Tag(
file_name = 'file1.txt',
description = 'descr1'
)
rates=np.array([0.1, 0.2, 0.3])
)

disc_rate.append(disc_rate_add)
disc_rate.check()

self.assertTrue(np.array_equal(disc_rate.years, disc_rate_add.years))
self.assertTrue(np.array_equal(disc_rate.rates, disc_rate_add.rates))
self.assertTrue(np.array_equal(disc_rate.tag.file_name,
disc_rate_add.tag.file_name))
self.assertTrue(np.array_equal(disc_rate.tag.description,
disc_rate_add.tag.description))

def test_append_equal_same(self):
"""Append the same DiscRates. The inital DiscRates is obtained."""
disc_rate = DiscRates(
years=np.array([2000, 2001, 2002]),
rates=np.array([0.1, 0.2, 0.3]),
tag=Tag(
file_name = 'file1.txt',
description = 'descr1'
)
)

disc_rate_add = copy.deepcopy(disc_rate)
Expand All @@ -93,29 +80,19 @@ def test_append_equal_same(self):

self.assertTrue(np.array_equal(disc_rate.years, disc_rate_add.years))
self.assertTrue(np.array_equal(disc_rate.rates, disc_rate_add.rates))
self.assertTrue(np.array_equal(disc_rate.tag.file_name, disc_rate_add.tag.file_name))
self.assertEqual(disc_rate.tag.description, disc_rate_add.tag.description)

def test_append_different_append(self):
"""Append DiscRates with same and new values. The rates with repeated
years are overwritten."""

disc_rate = DiscRates(
years=np.array([2000, 2001, 2002]),
rates=np.array([0.1, 0.2, 0.3]),
tag=Tag(
file_name = 'file1.txt',
description = 'descr1'
)
rates=np.array([0.1, 0.2, 0.3])
)

disc_rate_add = DiscRates(
years=np.array([2000, 2001, 2003]),
rates=np.array([0.11, 0.22, 0.33]),
tag=Tag(
file_name = 'file2.txt',
description = 'descr2'
)
rates=np.array([0.11, 0.22, 0.33])
)

disc_rate.append(disc_rate_add)
Expand All @@ -125,8 +102,7 @@ def test_append_different_append(self):
np.array([2000, 2001, 2002, 2003])))
self.assertTrue(np.array_equal(disc_rate.rates,
np.array([0.11, 0.22, 0.3, 0.33])))
self.assertTrue(np.array_equal(disc_rate.tag.file_name, ['file1.txt', 'file2.txt']))
self.assertTrue(np.array_equal(disc_rate.tag.description, ['descr1', 'descr2']))


class TestSelect(unittest.TestCase):
"""Test select method"""
Expand All @@ -136,11 +112,7 @@ def test_select_pass(self):
rates=np.arange(years.size)
disc_rate = DiscRates(
years=years,
rates=rates,
tag=Tag(
file_name = 'file1.txt',
description = 'descr1'
)
rates=rates
)

year_range = np.arange(2010, 2020)
Expand All @@ -153,26 +125,19 @@ def test_select_wrong_pass(self):
"""Test select wrong time range."""
disc_rate = DiscRates(
years=np.arange(2000, 2050),
rates=np.arange(50),
tag=Tag(
file_name = 'file1.txt',
description = 'descr1'
)
rates=np.arange(50)
)
year_range = np.arange(2050, 2060)
self.assertEqual(None, disc_rate.select(year_range))


class TestNetPresValue(unittest.TestCase):
"""Test select method"""
def test_net_present_value_pass(self):
"""Test net_present_value right time range."""
disc_rate = DiscRates(
years=np.arange(2000, 2050),
rates=np.ones(50) * 0.02,
tag=Tag(
file_name = 'file1.txt',
description = 'descr1'
)
rates=np.ones(50) * 0.02
)

val_years = np.ones(23) * 6.512201157564418e9
Expand All @@ -183,23 +148,19 @@ def test_net_present_value_wrong_pass(self):
"""Test net_present_value wrong time range."""
disc_rate = DiscRates(
years=np.arange(2000, 2050),
rates=np.arange(50) * 0.02,
tag=Tag(
file_name = 'file1.txt',
description = 'descr1'
)
rates=np.arange(50) * 0.02
)
val_years = np.ones(11) * 6.512201157564418e9
with self.assertRaises(ValueError):
disc_rate.net_present_value(2050, 2060, val_years)


class TestReaderExcel(unittest.TestCase):
"""Test excel reader for discount rates"""

def test_demo_file_pass(self):
"""Read demo excel file."""
description = 'One single file.'
disc_rate = DiscRates.from_excel(ENT_DEMO_TODAY, description)
disc_rate = DiscRates.from_excel(ENT_DEMO_TODAY)

# Check results
n_rates = 51
Expand All @@ -214,9 +175,6 @@ def test_demo_file_pass(self):
self.assertEqual(disc_rate.rates.min(), 0.02)
self.assertEqual(disc_rate.rates.max(), 0.02)

self.assertEqual(disc_rate.tag.file_name, [str(ENT_DEMO_TODAY)])
self.assertEqual(disc_rate.tag.description, [description])

def test_template_file_pass(self):
"""Read demo excel file."""
disc_rate = DiscRates.from_excel(ENT_TEMPLATE_XLS)
Expand All @@ -234,8 +192,6 @@ def test_template_file_pass(self):
self.assertEqual(disc_rate.rates.min(), 0.02)
self.assertEqual(disc_rate.rates.max(), 0.02)

self.assertEqual(disc_rate.tag.file_name, [str(ENT_TEMPLATE_XLS)])
self.assertEqual(disc_rate.tag.description, [])

class TestReaderMat(unittest.TestCase):
"""Test mat reader for discount rates"""
Expand All @@ -244,8 +200,7 @@ def test_demo_file_pass(self):
"""Read demo mat file"""
# Read demo excel file

description = 'One single file.'
disc_rate = DiscRates.from_mat(file_name=ENT_TEST_MAT, description=description)
disc_rate = DiscRates.from_mat(file_name=ENT_TEST_MAT)

# Check results
n_rates = 51
Expand All @@ -260,9 +215,6 @@ def test_demo_file_pass(self):
self.assertEqual(disc_rate.rates.min(), 0.02)
self.assertEqual(disc_rate.rates.max(), 0.02)

self.assertEqual(disc_rate.tag.file_name, [str(ENT_TEST_MAT)])
self.assertEqual(disc_rate.tag.description, [description])


class TestWriter(unittest.TestCase):
"""Test excel reader for discount rates"""
Expand All @@ -281,8 +233,6 @@ def test_write_read_pass(self):
self.assertTrue(np.array_equal(disc_read.years, disc_rate.years))
self.assertTrue(np.array_equal(disc_read.rates, disc_rate.rates))

self.assertEqual(disc_read.tag.file_name, [str(file_name)])
self.assertEqual(disc_read.tag.description, [])

# Execute Tests
if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions climada/entity/entity_def.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def from_mat(cls, file_name, description=''):
"""
return cls(
exposures=Exposures.from_mat(file_name),
disc_rates=DiscRates.from_mat(file_name, description),
disc_rates=DiscRates.from_mat(file_name),
impact_func_set=ImpactFuncSet.from_mat(file_name, description),
measure_set=MeasureSet.from_mat(file_name, description)
)
Expand Down Expand Up @@ -130,7 +130,7 @@ def from_excel(cls, file_name, description=''):
exp = Exposures(pd.read_excel(file_name))
exp.tag = Tag(file_name=file_name, description=description)

dr = DiscRates.from_excel(file_name, description)
dr = DiscRates.from_excel(file_name)
impf_set = ImpactFuncSet.from_excel(file_name, description)
meas_set = MeasureSet.from_excel(file_name, description)

Expand Down
3 changes: 1 addition & 2 deletions climada/entity/test/test_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,14 @@ def test_from_mat(self):
"""Read entity from mat file produced by climada."""
entity_mat = Entity.from_mat(ENT_TEST_MAT)
self.assertEqual(entity_mat.exposures.tag.file_name, [str(ENT_TEST_MAT)])
self.assertEqual(entity_mat.disc_rates.tag.file_name, [str(ENT_TEST_MAT)])
self.assertIsInstance(entity_mat.disc_rates, DiscRates)
self.assertEqual(entity_mat.measures.tag.file_name, [str(ENT_TEST_MAT)])
self.assertEqual(entity_mat.impact_funcs.tag.file_name, [str(ENT_TEST_MAT)])

def test_from_excel(self):
"""Read entity from an xls file following the template."""
entity_xls = Entity.from_excel(ENT_TEMPLATE_XLS)
self.assertEqual(entity_xls.exposures.tag.file_name, [str(ENT_TEMPLATE_XLS)])
self.assertEqual(entity_xls.disc_rates.tag.file_name, [str(ENT_TEMPLATE_XLS)])
self.assertEqual(entity_xls.measures.tag.file_name, [str(ENT_TEMPLATE_XLS)])
self.assertEqual(entity_xls.impact_funcs.tag.file_name,
[str(ENT_TEMPLATE_XLS)])
Expand Down
Loading