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

Ensure csr matrices are in "canonical format" before impact calculation #893

Merged
merged 15 commits into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Add util function for pruning csr_matrices
Update hazard docstring
  • Loading branch information
peanutfun committed Jun 17, 2024
commit de06f2ecd381f64ea4e2eaa346d3c487cb47d5ea
44 changes: 38 additions & 6 deletions climada/hazard/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,22 @@ class Hazard(HazardIO, HazardPlot):
Contains events of some hazard type defined at centroids. Loads from
files with format defined in FILE_EXT.

Attention
---------
This class uses instances of
`scipy.sparse.csr_matrix
<https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html>`_
to store :py:attr:`intensity` and :py:attr:`fraction`. This data types comes with
its particular pitfalls. Depending on how the objects are instantiated and modified,
a matrix might end up in a "non-canonical" state. In this state, its ``.data``
attribute does not necessarily represent the values apparent in the final matrix.
In particular, a "non-canonical" matrix may store "duplicates", i.e. multiple values
that map to the same matrix position. This is supported, and the default behavior is
to sum up these values. To avoid any inconsistencies, call :py:meth:`check_matrices`
once you inserted all data.
peanutfun marked this conversation as resolved.
Show resolved Hide resolved
This class will call :py:func:`climada.util.checker.prune_csr_matrix` whenever a
csr_matrix is assigned to one of the aforementioned attributes.

Attributes
----------
haz_type : str
Expand Down Expand Up @@ -200,9 +216,7 @@ def intensity(self) -> sparse.csr_matrix:
def intensity(self, value: sparse.csr_matrix):
"""Set intensity matrix to new value"""
self._intensity = value
self._intensity.check_format()
self._intensity.eliminate_zeros()
self._intensity.sum_duplicates()
u_check.prune_csr_matrix(self._intensity)

@property
def fraction(self) -> sparse.csr_matrix:
Expand All @@ -213,9 +227,27 @@ def fraction(self) -> sparse.csr_matrix:
def fraction(self, value: sparse.csr_matrix):
"""Set fraction matrix to new value"""
self._fraction = value
self._fraction.check_format()
self._fraction.eliminate_zeros()
self._fraction.sum_duplicates()
u_check.prune_csr_matrix(self._fraction)

def check_matrices(self):
"""Ensure that matrices are consistently shaped and stored

See Also
--------
:py:func:`climada.util.checker.prune_csr_matrix`

Raises
------
ValueError
If matrices are ill-formed or ill-shaped
"""
u_check.prune_csr_matrix(self.intensity)
u_check.prune_csr_matrix(self.fraction)
if self.intensity.shape != self.fraction.shape:
if self.fraction.nnz > 0:
raise ValueError(
"Intensity and fraction matrices must have the same shape"
)

@classmethod
def get_default(cls, attribute):
Expand Down
36 changes: 35 additions & 1 deletion climada/util/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
'size',
'shape',
'array_optional',
'array_default'
'array_default',
'prune_csr_matrix',
]

import logging
Expand Down Expand Up @@ -162,3 +163,36 @@ def array_default(exp_len, var, var_name, def_val):
else:
size(exp_len, var, var_name)
return res

def prune_csr_matrix(matrix: sparse.csr_matrix):
"""Ensure that the matrix is in the "canonical format".

Depending on how the matrix was instantiated or modified, it might be in a
"non-canonical" state. This only relates to its internal storage. In this state,
multiple values might be stored for a single "apparent" value in the matrix.
Also, the matrix might store zeros explicitly, which could be removed.
Calling this function makes sure that the matrix is in the "canonical state", and
brings it into this state, if possible.

See Also
--------
`csr_matrix.has_canonical_format
<https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.has_canonical_format.html#scipy.sparse.csr_matrix.has_canonical_format>`_

Parameters
----------
matrix : csr_matrix
The matrix to check. It will be modified *inplace*. No apparent matrix values
will change.
peanutfun marked this conversation as resolved.
Show resolved Hide resolved

Raises
------
ValueError
If
`csr_matrix.check_format
<https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.check_format.html#scipy.sparse.csr_matrix.check_format>`_
fails
"""
matrix.check_format()
matrix.eliminate_zeros()
matrix.sum_duplicates()