Skip to content

Commit

Permalink
feat: ZeroRateMixin()
Browse files Browse the repository at this point in the history
  • Loading branch information
castelao committed May 14, 2024
1 parent 26815cc commit 2c9a810
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions sup3r/bias/bias_calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1588,6 +1588,79 @@ def run(self,
return copy.deepcopy(self.out)


class ZeroRateMixin(DataRetrievalBase):
"""Estimate zero rate
[Pierce2015]_.
References
----------
.. [Pierce2015] Pierce, D. W., Cayan, D. R., Maurer, E. P., Abatzoglou, J.
T., & Hegewisch, K. C. (2015). Improved bias correction techniques for
hydrological simulations of climate change. Journal of Hydrometeorology,
16(6), 2421-2442.
"""
def _zero_precipitation_rate(arr: np.ndarray, threshold: float = 0.01):
"""Rate of (nearly) zero precipitation days
Estimate the rate of values less than a given ``threshold``. In concept
the threshold would be zero (thus the name zero precipitation rate)
but it is often used a small threshold to truncate negligible values.
For instance, [Pierce2015]_ uses 0.01 (mm/day) for PresRat correction.
Parameters
----------
arr : np.array
An array of values to be analyzed. Usually precipitation but it
could be applied to other quantities.
threshold : float
Minimum value accepted. Less than that is assumed to be zero.
Returns
-------
rate : float
Rate of days with negligible precipitation. (see Z_gf in
[Pierce2015]_)
Notes
-----
The ``NaN`` are ignored for the rate estimate. Therefore, a large
number of ``NaN`` might mislead this rate estimate.
"""
return np.nanmean((arr < 0.01).astype('i'))

def apply_zero_precipitation_rate(arr: np.ndarray, rate: float):
"""Enforce the zero precipitation rate
Replace lowest values by zero to satisfy the given rate of zero
precipitation.
Parameters
----------
arr : np.array
An array of values to be analyzed. Usually precipitation but it
rate : float
Rate of zero, or negligible, days of precipitation.
Returns
-------
corrected : np.array
A copy of given array that satisfies the rate of zero precipitation
days, i.e. the lowest values of precipitation are changed to zero
to satisfy that rate.
Examples
--------
>>> data = np.array([5, 0.1, np.nan, 0.2, 1]
>>> apply_zero_precipitation_rate(data, 0.30)
array([5. , 0. , nan, 0.2, 1. ])
"""
valid = arr[np.isfinite(arr)]
threshold = np.sort(valid)[round(rate * len(valid))]
return np.where(arr < threshold, 0, arr)


class PresRat(DataRetrievalBase):
"""PresRat bias correction method (precipitation)
Expand Down

0 comments on commit 2c9a810

Please sign in to comment.