diff --git a/autofit/non_linear/samples/pdf.py b/autofit/non_linear/samples/pdf.py index 7167170ed..6b15176c7 100644 --- a/autofit/non_linear/samples/pdf.py +++ b/autofit/non_linear/samples/pdf.py @@ -333,10 +333,12 @@ def draw_randomly_via_pdf( last_error = None + # Normalize weights to sum to 1 + weights = np.asarray(self.weight_list, dtype=float) + weights /= weights.sum() + for attempt in range(VALID_INSTANCE_MAX_ATTEMPTS): - sample_index = np.random.choice( - a=range(len(self.sample_list)), p=self.weight_list - ) + sample_index = np.random.choice(a=range(len(self.sample_list)), p=weights) vector = self.parameter_lists[sample_index][:] if as_dict: diff --git a/test_autofit/non_linear/samples/test_pdf.py b/test_autofit/non_linear/samples/test_pdf.py index 533e508d2..8aca2213d 100644 --- a/test_autofit/non_linear/samples/test_pdf.py +++ b/test_autofit/non_linear/samples/test_pdf.py @@ -450,6 +450,30 @@ def test__draw_randomly_via_pdf(): assert instance.mock_class_1.four == 24.0 +def test__draw_randomly_via_pdf__weights_not_summing_to_one(): + parameters = [ + [0.0, 1.0, 2.0, 3.0], + [21.0, 22.0, 23.0, 24.0], + ] + + model = af.ModelMapper(mock_class_1=af.m.MockClassx4) + + samples_x2 = af.m.MockSamples( + model=model, + sample_list=af.Sample.from_lists( + model=model, + parameter_lists=parameters, + log_likelihood_list=[1.0, 2.0], + log_prior_list=2 * [0.0], + weight_list=[0.0, 1.875], + ), + ) + + vector = samples_x2.draw_randomly_via_pdf(as_instance=False) + + assert vector == [21.0, 22.0, 23.0, 24.0] + + @pytest.fixture(name="make_samples") def make_samples_fixture(): def make_samples(parameters, weight_list=None):