From 2b7601f155a4a1941ed7e2121439f0a99984a0a7 Mon Sep 17 00:00:00 2001 From: NicolaCourtier <45851982+NicolaCourtier@users.noreply.github.com> Date: Thu, 27 Mar 2025 20:08:10 +0000 Subject: [PATCH 1/2] Adjust domain-based weighting --- pybop/costs/fitting_costs.py | 18 +++++++----------- tests/unit/test_cost.py | 3 +++ 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/pybop/costs/fitting_costs.py b/pybop/costs/fitting_costs.py index 906c38b20..ca2572090 100644 --- a/pybop/costs/fitting_costs.py +++ b/pybop/costs/fitting_costs.py @@ -32,19 +32,15 @@ def __init__(self, problem, weighting: Union[str, np.ndarray] = None): # Normalise the residuals by the domain spacing (for a uniform domain, # this is the same as a uniform weighting) domain_data = self.problem.domain_data - n_domain_data = len(domain_data) domain_spacing = domain_data[1:] - domain_data[:-1] - self.weighting = ( - np.concatenate( - ( - [domain_spacing[0]], - (domain_spacing[1:] + domain_spacing[:-1]) / 2, - [domain_spacing[-1]], - ) + mean_spacing = np.mean(domain_spacing) + self.weighting = np.concatenate( + ( + [(mean_spacing + domain_spacing[0]) / 2], + (domain_spacing[1:] + domain_spacing[:-1]) / 2, + [(domain_spacing[-1] + mean_spacing) / 2], ) - * (n_domain_data - 1) - / (domain_data[-1] - domain_data[0]) - ) + ) * ((len(domain_data) - 1) / (domain_data[-1] - domain_data[0])) else: self.weighting = np.asarray(weighting) diff --git a/tests/unit/test_cost.py b/tests/unit/test_cost.py index c57c1e642..532b9b375 100644 --- a/tests/unit/test_cost.py +++ b/tests/unit/test_cost.py @@ -251,6 +251,9 @@ def test_error_weighting( np.testing.assert_allclose(e, eR, rtol=1e-2, atol=1e-9) np.testing.assert_allclose(de, deR, rtol=1e-2, atol=1e-9) + # Check that the sum (and therefore mean) are the same as an even weighting + np.testing.assert_allclose(np.sum(costR.weighting), len(costR.weighting)) + # Check gradient calculation using finite difference delta = 1e-6 * x[0] cost_right = costR(x[0] + delta / 2) From f6bb9d0da3bde89b801089d841dc3725b583c22b Mon Sep 17 00:00:00 2001 From: NicolaCourtier <45851982+NicolaCourtier@users.noreply.github.com> Date: Fri, 28 Mar 2025 11:14:50 +0000 Subject: [PATCH 2/2] Fix typo --- tests/unit/test_cost.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/test_cost.py b/tests/unit/test_cost.py index 532b9b375..17a2772d3 100644 --- a/tests/unit/test_cost.py +++ b/tests/unit/test_cost.py @@ -238,7 +238,7 @@ def test_error_weighting( np.testing.assert_allclose(e, eE) np.testing.assert_allclose(de, deE) - # Test that domain-basd weighting also matches for evenly spaced data + # Test that domain-based weighting also matches for evenly spaced data costD = cost_class(problem, weighting="domain") eD, deD = costD(x, calculate_grad=True) np.testing.assert_allclose(e, eD)