Skip to content

Commit b729e89

Browse files
Remove Tag from Hazard (#767)
* remove tag from hazard * remove tag from hazard * remove tag from hazard * pylint * don't keep any tag traces, not even for backwards compatitbility * unused import removed * remove tags from tutorial * set pythonpath for compatibility test * hazard.base: remove tag traces * changelog: removed hazard.tag
1 parent 39c8eb1 commit b729e89

File tree

10 files changed

+22
-164
lines changed

10 files changed

+22
-164
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ Removed:
8383
- `Centroids.set_raster_from_pix_bounds` [#721](https://github.com/CLIMADA-project/climada_python/pull/721)
8484
- `requirements/env_developer.yml` environment specs. Use 'extra' requirements when installing the Python package instead [#712](https://github.com/CLIMADA-project/climada_python/pull/712)
8585
- `Impact.tag` attribute. This change is not backwards-compatible with respect to the files written and read by the `Impact` class [#743](https://github.com/CLIMADA-project/climada_python/pull/743)
86+
- `Hazard.tag` attribute. This change is not backwards-compatible with respect to the files written and read by the `Hazard` class [#767](https://github.com/CLIMADA-project/climada_python/pull/767)
8687
- `impact.tot_value ` attribute removed from unsequa module [#763](https://github.com/CLIMADA-project/climada_python/pull/763)
8788

8889
## v3.3.2

climada/engine/test/test_forecast.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def test_Forecast_calc_properties(self):
8181
def test_Forecast_init_raise(self):
8282
"""Test calc and propety functions from the Forecast class"""
8383
#hazard with several event dates
84-
storms = StormEurope.from_footprints(WS_DEMO_NC, description='test_description')
84+
storms = StormEurope.from_footprints(WS_DEMO_NC)
8585
#exposure
8686
data = {}
8787
data['latitude'] = np.array([1, 2, 3])

climada/entity/measures/test/test_base.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,6 @@ def test_change_all_hazard_pass(self):
182182
hazard = Hazard('TC')
183183
new_haz = meas._change_all_hazard(hazard)
184184

185-
self.assertEqual(new_haz.tag.file_name, ref_haz.tag.file_name)
186185
self.assertEqual(new_haz.haz_type, ref_haz.haz_type)
187186
self.assertTrue(np.array_equal(new_haz.frequency, ref_haz.frequency))
188187
self.assertTrue(np.array_equal(new_haz.date, ref_haz.date))

climada/hazard/base.py

Lines changed: 14 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@
2626
import itertools
2727
import logging
2828
import pathlib
29-
import warnings
3029
from typing import Union, Optional, Callable, Dict, Any, List
30+
import warnings
3131

3232
import geopandas as gpd
3333
import h5py
@@ -42,7 +42,6 @@
4242
from scipy import sparse
4343
import xarray as xr
4444

45-
from climada.util.tag import Tag
4645
from climada.hazard.centroids.centr import Centroids
4746
import climada.util.plot as u_plot
4847
import climada.util.checker as u_check
@@ -113,8 +112,6 @@ class Hazard():
113112
(wild fire).
114113
Note: The acronym is used as reference to the hazard when centroids of multiple hazards
115114
are assigned to an ``Exposures`` object.
116-
tag : Tag
117-
information about the source
118115
units : str
119116
units of the intensity
120117
centroids : Centroids
@@ -145,8 +142,7 @@ class Hazard():
145142
"""Intensity threshold per hazard used to filter lower intensities. To be
146143
set for every hazard type"""
147144

148-
vars_oblig = {'tag',
149-
'units',
145+
vars_oblig = {'units',
150146
'centroids',
151147
'event_id',
152148
'frequency',
@@ -155,7 +151,7 @@ class Hazard():
155151
}
156152
"""Name of the variables needed to compute the impact. Types: scalar, str,
157153
list, 1dim np.array of size num_events, scipy.sparse matrix of shape
158-
num_events x num_centroids, Centroids and Tag."""
154+
num_events x num_centroids, Centroids."""
159155

160156
vars_def = {'date',
161157
'orig',
@@ -183,8 +179,7 @@ def __init__(self,
183179
date: Optional[np.ndarray] = None,
184180
orig: Optional[np.ndarray] = None,
185181
intensity: Optional[sparse.csr_matrix] = None,
186-
fraction: Optional[sparse.csr_matrix] = None,
187-
**tag_kwargs):
182+
fraction: Optional[sparse.csr_matrix] = None):
188183
"""
189184
Initialize values.
190185
@@ -218,9 +213,6 @@ def __init__(self,
218213
fraction : sparse.csr_matrix, optional
219214
fraction of affected exposures for each event at each centroid. Defaults to
220215
empty matrix.
221-
tag_kwargs
222-
Keyword-arguments for creating the HazardTag. ``haz_type`` is also passed
223-
to the Tag constructor.
224216
225217
Examples
226218
--------
@@ -234,7 +226,6 @@ def __init__(self,
234226
235227
"""
236228
self.haz_type = haz_type
237-
self.tag = Tag(**tag_kwargs)
238229
self.units = units
239230
self.centroids = centroids if centroids is not None else Centroids()
240231
# following values are defined for each event
@@ -359,7 +350,6 @@ def from_raster(cls, files_intensity, files_fraction=None, attrs=None,
359350
hazard_kwargs = dict()
360351
if haz_type is not None:
361352
hazard_kwargs["haz_type"] = haz_type
362-
hazard_kwargs["file_name"] = str(files_intensity) + ' ; ' + str(files_fraction)
363353

364354
centroids = Centroids.from_raster_file(
365355
files_intensity[0], src_crs=src_crs, window=window, geometry=geometry, dst_crs=dst_crs,
@@ -503,7 +493,7 @@ def from_xarray_raster(
503493
The type identifier of the hazard. Will be stored directly in the hazard
504494
object.
505495
intensity_unit : str
506-
The physical units of the intensity. Will be stored in the ``hazard.tag``.
496+
The physical units of the intensity.
507497
intensity : str, optional
508498
Identifier of the `xarray.DataArray` containing the hazard intensity data.
509499
coordinate_vars : dict(str, str), optional
@@ -1025,8 +1015,7 @@ def from_vector(cls, files_intensity, files_fraction=None, attrs=None,
10251015
raise ValueError('Number of intensity files differs from fraction files:'
10261016
f' {len(files_intensity)} != {len(files_fraction)}')
10271017

1028-
hazard_kwargs = dict(
1029-
file_name=str(files_intensity) + ' ; ' + str(files_fraction))
1018+
hazard_kwargs = {}
10301019
if haz_type is not None:
10311020
hazard_kwargs["haz_type"] = haz_type
10321021

@@ -1222,15 +1211,13 @@ def read_mat(self, *args, **kwargs):
12221211
self.__dict__ = Hazard.from_mat(*args, **kwargs).__dict__
12231212

12241213
@classmethod
1225-
def from_mat(cls, file_name, description='', var_names=None):
1214+
def from_mat(cls, file_name, var_names=None):
12261215
"""Read climada hazard generate with the MATLAB code in .mat format.
12271216
12281217
Parameters
12291218
----------
12301219
file_name : str
12311220
absolute file name
1232-
description : str, optional
1233-
description of the data
12341221
var_names : dict, optional
12351222
name of the variables in the file,
12361223
default: DEF_VAR_MAT constant
@@ -1256,10 +1243,9 @@ def from_mat(cls, file_name, description='', var_names=None):
12561243
pass
12571244

12581245
centroids = Centroids.from_mat(file_name, var_names=var_names['var_cent'])
1259-
attrs = cls._read_att_mat(data, file_name, var_names, centroids, description)
1246+
attrs = cls._read_att_mat(data, file_name, var_names, centroids)
12601247
haz = cls(haz_type=u_hdf5.get_string(data[var_names['var_name']['per_id']]),
12611248
centroids=centroids,
1262-
file_name=str(file_name),
12631249
**attrs
12641250
)
12651251
except KeyError as var_err:
@@ -1273,15 +1259,13 @@ def read_excel(self, *args, **kwargs):
12731259
self.__dict__ = Hazard.from_excel(*args, **kwargs).__dict__
12741260

12751261
@classmethod
1276-
def from_excel(cls, file_name, description='', var_names=None, haz_type=None):
1262+
def from_excel(cls, file_name, var_names=None, haz_type=None):
12771263
"""Read climada hazard generated with the MATLAB code in Excel format.
12781264
12791265
Parameters
12801266
----------
12811267
file_name : str
12821268
absolute file name
1283-
description : str, optional
1284-
description of the data
12851269
var_names (dict, default): name of the variables in the file,
12861270
default: DEF_VAR_EXCEL constant
12871271
haz_type : str, optional
@@ -1302,7 +1286,7 @@ def from_excel(cls, file_name, description='', var_names=None, haz_type=None):
13021286
if not var_names:
13031287
var_names = DEF_VAR_EXCEL
13041288
LOGGER.info('Reading %s', file_name)
1305-
hazard_kwargs = dict(file_name=file_name, description=description)
1289+
hazard_kwargs = {}
13061290
if haz_type is not None:
13071291
hazard_kwargs["haz_type"] = haz_type
13081292
try:
@@ -1829,8 +1813,6 @@ def write_hdf5(self, file_name, todense=False):
18291813
for (var_name, var_val) in self.__dict__.items():
18301814
if var_name == 'centroids':
18311815
self.centroids.write_hdf5(hf_data.create_group(var_name))
1832-
elif var_name == 'tag':
1833-
var_val.to_hdf5(hf_data)
18341816
elif isinstance(var_val, sparse.csr_matrix):
18351817
if todense:
18361818
hf_data.create_dataset(var_name, data=var_val.toarray())
@@ -1887,21 +1869,11 @@ def from_hdf5(cls, file_name):
18871869
hazard_kwargs = dict()
18881870
with h5py.File(file_name, 'r') as hf_data:
18891871
for (var_name, var_val) in haz.__dict__.items():
1890-
if var_name != 'tag' and var_name not in hf_data.keys():
1872+
if var_name not in hf_data.keys():
18911873
continue
18921874
if var_name == 'centroids':
18931875
hazard_kwargs["centroids"] = Centroids.from_hdf5(
18941876
hf_data.get(var_name))
1895-
elif var_name == 'tag':
1896-
# legacy behavior: haz_type used to be part of the hazard tag
1897-
if "haz_type" in hf_data.keys():
1898-
haz_type = u_hdf5.to_string(
1899-
hf_data.get("haz_type")[0])
1900-
if haz_type:
1901-
hazard_kwargs["haz_type"] = haz_type
1902-
tag = Tag.from_hdf5(hf_data)
1903-
hazard_kwargs["file_name"] = tag.file_name
1904-
hazard_kwargs["description"] = tag.description
19051877
elif isinstance(var_val, np.ndarray) and var_val.ndim == 1:
19061878
hazard_kwargs[var_name] = np.array(hf_data.get(var_name))
19071879
elif isinstance(var_val, sparse.csr_matrix):
@@ -2143,7 +2115,7 @@ def _cen_return_inten(inten, freq, inten_th, return_periods):
21432115
return inten_fit
21442116

21452117
@staticmethod
2146-
def _read_att_mat(data, file_name, var_names, centroids, description):
2118+
def _read_att_mat(data, file_name, var_names, centroids):
21472119
"""Read MATLAB hazard's attributes."""
21482120
attrs = dict()
21492121
attrs["frequency"] = np.squeeze(data[var_names['var_name']['freq']])
@@ -2183,12 +2155,6 @@ def _read_att_mat(data, file_name, var_names, centroids, description):
21832155
file_name, data[var_names['var_name']['ev_name']])
21842156
except KeyError:
21852157
attrs["event_name"] = list(attrs["event_id"])
2186-
attrs["description"] = description
2187-
try:
2188-
comment = u_hdf5.get_string(data[var_names['var_name']['comment']])
2189-
attrs["description"] += ' ' + comment
2190-
except KeyError:
2191-
pass
21922158

21932159
try:
21942160
datenum = data[var_names['var_name']['datenum']].squeeze()
@@ -2249,7 +2215,6 @@ def append(self, *others):
22492215
- All centroids are combined together using `Centroids.union`.
22502216
- Lists, 1-dimensional arrays (NumPy) and sparse CSR matrices (SciPy) are concatenated.
22512217
Sparse matrices are concatenated along the first (vertical) axis.
2252-
- All `tag` attributes are appended to `self.tag`.
22532218
22542219
For any other type of attribute: A ValueError is raised if an attribute of that name is
22552220
not defined in all of the non-empty hazards at least. However, there is no check that the
@@ -2316,11 +2281,6 @@ def append(self, *others):
23162281
raise ValueError(f"Attribute {attr_name} is not shared by all hazards. "
23172282
"The hazards are incompatible and cannot be concatenated.")
23182283

2319-
# append all tags (to keep track of input files and descriptions)
2320-
for haz in haz_list:
2321-
if haz.tag is not self.tag:
2322-
self.tag.append(haz.tag)
2323-
23242284
# map individual centroids objects to union
23252285
centroids = Centroids.union(*[haz.centroids for haz in haz_list])
23262286
hazcent_in_cent_idx_list = [
@@ -2357,7 +2317,7 @@ def concat(cls, haz_list):
23572317
and then applies the `append` method. Please refer to the docs of `Hazard.append` for
23582318
caveats and limitations of the concatenation procedure.
23592319
2360-
For centroids, tags, lists, arrays and sparse matrices, the remarks in `Hazard.append`
2320+
For centroids, lists, arrays and sparse matrices, the remarks in `Hazard.append`
23612321
apply. All other attributes are copied from the first object in `haz_list`.
23622322
23632323
Note that `Hazard.concat` can be used to concatenate hazards of a subclass. The result's
@@ -2389,7 +2349,7 @@ def concat(cls, haz_list):
23892349
# to save memory, only copy simple attributes like
23902350
# "units" that are not explicitly handled by Hazard.append
23912351
if not (isinstance(attr_val, (list, np.ndarray, sparse.csr_matrix))
2392-
or attr_name in ["tag", "centroids"]):
2352+
or attr_name in ["centroids"]):
23932353
setattr(haz_concat, attr_name, copy.deepcopy(attr_val))
23942354
haz_concat.append(*haz_list)
23952355
return haz_concat

climada/hazard/storm_europe.py

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
from climada.util.config import CONFIG
3737
from climada.hazard.base import Hazard
3838
from climada.hazard.centroids.centr import Centroids
39-
from climada.util.tag import Tag
4039
from climada.util.files_handler import get_file_names
4140
from climada.util.dates_times import (datetime64_to_ordinal,
4241
last_year,
@@ -120,7 +119,7 @@ def read_footprints(self, *args, **kwargs):
120119
self.__dict__ = StormEurope.from_footprints(*args, **kwargs).__dict__
121120

122121
@classmethod
123-
def from_footprints(cls, path, description=None, ref_raster=None, centroids=None,
122+
def from_footprints(cls, path, ref_raster=None, centroids=None,
124123
files_omit='fp_era20c_1990012515_701_0.nc', combine_threshold=None,
125124
intensity_thres=None):
126125
"""Create new StormEurope object from WISC footprints.
@@ -135,9 +134,6 @@ def from_footprints(cls, path, description=None, ref_raster=None, centroids=None
135134
path to a single netCDF WISC footprint, or a folder
136135
containing only footprints, or a globbing pattern to one or
137136
more footprints.
138-
description : str, optional
139-
description of the events, defaults
140-
to 'WISC historical hazard set'
141137
ref_raster : str, optional
142138
Reference netCDF file from which to
143139
construct a new barebones Centroids instance. Defaults to
@@ -202,12 +198,6 @@ def from_footprints(cls, path, description=None, ref_raster=None, centroids=None
202198
np.max([(last_year(haz.date) - first_year(haz.date)), 1])
203199
)
204200

205-
if description is None:
206-
description = "WISC historical hazard set."
207-
haz.tag = Tag(
208-
description=description,
209-
)
210-
211201
if combine_threshold is not None:
212202
LOGGER.info('Combining events with small difference in date.')
213203
difference_date = np.diff(haz.date)
@@ -376,8 +366,6 @@ def from_cosmoe_file(cls, fp_file, run_datetime, event_date=None,
376366
frequency=np.divide(
377367
np.ones_like(event_id),
378368
np.unique(ncdf.epsd_1).size),
379-
description=description,
380-
file_name="Hazard set not saved, too large to pickle",
381369
)
382370

383371
# close netcdf file
@@ -513,8 +501,7 @@ def from_icon_grib(cls, run_datetime, event_date=None, model_name='icon-eu-eps',
513501
frequency=np.divide(
514502
np.ones_like(event_id),
515503
np.unique(stacked.number).size),
516-
description=description,
517-
file_name="Hazard set not saved, too large to pickle")
504+
)
518505
haz.check()
519506

520507
# delete generated .grib2 and .4cc40.idx files
@@ -839,8 +826,6 @@ def generate_prob_storms(self, reg_id=528, spatial_shift=4, ssi_args=None,
839826
# years
840827
frequency=np.divide(np.repeat(self.frequency, N_PROB_EVENTS),
841828
N_PROB_EVENTS),
842-
file_name='Hazard set not saved by default',
843-
description='WISC probabilistic hazard set according to Schwierz et al.',
844829
orig=(event_id % 100 == 0),
845830
)
846831
new_haz.check()

0 commit comments

Comments
 (0)