From 24aa7172ff2c0f6488c98052ef42dd686555db53 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 31 Oct 2026 13:33:22 +0000 Subject: [PATCH] fix: draw_randomly_via_pdf normalises sample weights np.random.choice requires probabilities summing to 1; test-mode bypass samples (weights 1, 0.5, 0.25, 0.125) made every draw raise. Normalise as samples_drawn_randomly_via_pdf already does. Co-Authored-By: Claude Opus 5.5 --- autofit/non_linear/samples/pdf.py | 8 ++++--- test_autofit/non_linear/samples/test_pdf.py | 24 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) 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):