Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions pybop/costs/fitting_costs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
5 changes: 4 additions & 1 deletion tests/unit/test_cost.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down