diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dcd96f135..8fefb128a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ Code freeze date: YYYY-MM-DD - `Hazard.from_xarray_raster` now stores strings as default values for `Hazard.event_name` [#795](https://github.com/CLIMADA-project/climada_python/pull/795) - Fix the dist_approx util function when used with method="geosphere" and log=True and points that are very close. [#792](https://github.com/CLIMADA-project/climada_python/pull/792) +- `climada.util.yearsets.sample_from_poisson`: fix a bug ([#819](https://github.com/CLIMADA-project/climada_python/issues/819)) and inconsistency that occurs when lambda events per year (`lam`) are set to 1. [[#823](https://github.com/CLIMADA-project/climada_python/pull/823)] ### Deprecated diff --git a/climada/util/test/test_yearsets.py b/climada/util/test/test_yearsets.py index aca33d3d7b..ebab567271 100755 --- a/climada/util/test/test_yearsets.py +++ b/climada/util/test/test_yearsets.py @@ -60,11 +60,14 @@ def test_impact_yearset_sampling_vect(self): def test_sample_from_poisson(self): """Test sampling amount of events per year.""" n_sample_years = 1000 - lam = np.sum(IMP.frequency) - events_per_year = yearsets.sample_from_poisson(n_sample_years, lam) - - self.assertEqual(events_per_year.size, n_sample_years) - self.assertAlmostEqual(np.round(np.mean(events_per_year)), 2) + for lam in [0, 1, 2.5]: + events_per_year = yearsets.sample_from_poisson(n_sample_years, lam, seed=1) + + self.assertEqual(events_per_year.size, n_sample_years) + self.assertAlmostEqual(np.mean(events_per_year), lam, places=1) + + self.assertRaises(TypeError, yearsets.sample_from_poisson, n_sample_years, None) + self.assertRaises(ValueError, yearsets.sample_from_poisson, n_sample_years, -1) def test_sample_events(self): """Test the sampling of 34 events out of a pool of 20 events.""" diff --git a/climada/util/yearsets.py b/climada/util/yearsets.py index 0c3b0033f5..0e30102f8e 100755 --- a/climada/util/yearsets.py +++ b/climada/util/yearsets.py @@ -152,7 +152,7 @@ def sample_from_poisson(n_sampled_years, lam, seed=None): ----------- n_sampled_years : int The target number of years the impact yearset shall contain. - lam: int + lam: float the applied Poisson distribution is centered around lambda events per year seed : int, optional seed for numpy.random, will be set if not None @@ -165,14 +165,8 @@ def sample_from_poisson(n_sampled_years, lam, seed=None): """ if seed is not None: np.random.seed(seed) - if lam != 1: - events_per_year = np.round(np.random.poisson(lam=lam, - size=n_sampled_years)).astype('int') - else: - events_per_year = np.ones(len(n_sampled_years)) - + return np.round(np.random.poisson(lam=lam, size=n_sampled_years)).astype('int') - return events_per_year def sample_events(events_per_year, freqs_orig, seed=None): """Sample events uniformely from an array (indices_orig) without replacement