Skip to content

Commit 612b576

Browse files
martinjrobinsagriyakhetarpalkratman
authored
bug: raise error if interpolant x values decreasing (#5061)
* bug: raise error if interpolant x values decreasing * add changelog * Update src/pybamm/expression_tree/interpolant.py Co-authored-by: Agriya Khetarpal <74401230+agriyakhetarpal@users.noreply.github.com> * bug: fix test which was using interpolant incorrectly --------- Co-authored-by: Agriya Khetarpal <74401230+agriyakhetarpal@users.noreply.github.com> Co-authored-by: Eric G. Kratz <kratman@users.noreply.github.com>
1 parent 3144907 commit 612b576

4 files changed

Lines changed: 10 additions & 1 deletion

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
## Bug fixes
88

99
- Converts sensitivities to numpy objects, fixing bug in `DiscreteTimeSum` sensitivity calculation ([#5037](https://github.com/pybamm-team/PyBaMM/pull/5037))
10+
- Raises error if `pybamm.Interpolant` given 1D x values that are not strictly increasing ([#5061](https://github.com/pybamm-team/PyBaMM/pull/5061))
1011

1112
## Breaking changes
1213

src/pybamm/expression_tree/interpolant.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,9 @@ def __init__(
107107
"len(x1) should equal y=shape[0], "
108108
f"but x1.shape={x1.shape} and y.shape={y.shape}"
109109
)
110+
# if 1d then x should be monotonically increasing
111+
if np.any(x1[:-1] > x1[1:]):
112+
raise ValueError("x should be monotonically increasing")
110113
# children should be a list not a symbol or a number
111114
if isinstance(children, pybamm.Symbol | numbers.Number):
112115
children = [children]

tests/unit/test_expression_tree/test_interpolant.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,11 @@ def test_interpolation(self):
7676
interp.evaluate(y=np.array([2]))[:, 0], np.array([np.nan])
7777
)
7878

79+
def test_interpolation_non_increasing(self):
80+
x = np.flip(np.linspace(0, 1, 200))
81+
with pytest.raises(ValueError, match="x should be monotonically increasing"):
82+
pybamm.Interpolant(x, 2 * x, 0.5)
83+
7984
def test_interpolation_float(self):
8085
x = np.linspace(0, 1, 200)
8186
interp = pybamm.Interpolant(x, 2 * x, 0.5)

tests/unit/test_expression_tree/test_unary_operators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -773,7 +773,7 @@ def test_discrete_time_sum(self):
773773
pybamm.DiscreteTimeSum(2 * y)
774774

775775
# check that raises error if two data are present
776-
data2 = pybamm.DiscreteTimeData(values, times, "test2")
776+
data2 = pybamm.DiscreteTimeData(times, values, "test2")
777777
with pytest.raises(pybamm.ModelError, match="only have one DiscreteTimeData"):
778778
pybamm.DiscreteTimeSum(data + data2)
779779

0 commit comments

Comments
 (0)