Skip to content

Commit b452bb0

Browse files
committed
Add more intuitive unit specification when creating Hazard object via attrs keyword
The Hazard.from_raster method allows you to specify an `attrs` dictionary to set additional parameters in the created Hazard's `__init__` method. This commit - allows you to set both 'unit' and 'units' which will be used as the 'units' parameter when the Hazard object is created, with 'units' taking priority. Currently only 'unit' is accepted which is very counterintuitive, since all other attributes are exactly as specified in the `__init__` - adds an ATTRS_TO_CHECK constant to the hazard module's io.py so that the user can see what is supported in the source code (and removes a comment that suggests doing this). - updates the documentation
1 parent 42e5160 commit b452bb0

1 file changed

Lines changed: 17 additions & 5 deletions

File tree

climada/hazard/io.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,18 @@
4444

4545
LOGGER = logging.getLogger(__name__)
4646

47+
ATTRS_TO_CHECK = {
48+
"event_name": (list, str),
49+
"event_id": (np.ndarray, None),
50+
"frequency": (np.ndarray, float),
51+
"frequency_unit": (str, None),
52+
"date": (np.ndarray, int),
53+
"orig": (np.ndarray, bool),
54+
"unit": (str, None), # For backward compatibility. Replaced by units.
55+
"units": (str, None),
56+
}
57+
"""Additional attributes that can be specified when reading a raster file"""
58+
4759
DEF_VAR_EXCEL = {
4860
"sheet_name": {"inten": "hazard_intensity", "freq": "hazard_frequency"},
4961
"col_name": {
@@ -135,7 +147,8 @@ def from_raster(
135147
files_fraction : list(str)
136148
file names containing fraction
137149
attrs : dict, optional
138-
name of Hazard attributes and their values
150+
name of Hazard attributes and their values. See the ATTRS_TO_CHECK constant for supported attributes.
151+
Missing attributes will be filled with sensible defaults.
139152
band : list(int), optional
140153
bands to read (starting at 1), default [1]
141154
haz_type : str, optional
@@ -712,10 +725,7 @@ def _check_and_cast_elements(
712725

713726
return attr_value
714727

715-
## This should probably be defined as a CONSTANT?
716-
attrs_to_check = {"event_name": (list, str), "event_id": (np.ndarray, None)}
717-
718-
for attr_name, (expected_container, expected_dtype) in attrs_to_check.items():
728+
for attr_name, (expected_container, expected_dtype) in ATTRS_TO_CHECK.items():
719729
attr_value = attrs.get(attr_name)
720730

721731
if attr_value is not None:
@@ -777,6 +787,8 @@ def _attrs_to_kwargs(attrs: Dict[str, Any], num_events: int) -> Dict[str, Any]:
777787
kwargs["orig"] = np.ones(kwargs["event_id"].size, bool)
778788
if "unit" in attrs:
779789
kwargs["units"] = attrs["unit"]
790+
if "units" in attrs:
791+
kwargs["units"] = attrs["units"]
780792

781793
return kwargs
782794

0 commit comments

Comments
 (0)