Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
use ValueError if moving_average window size is out of bounds
  • Loading branch information
MikeSullivan7 committed Jun 16, 2026
commit 3b6a7c4d494c182d78ac9e667411827d6af0e70d
8 changes: 5 additions & 3 deletions ratapi/utils/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -1132,7 +1132,6 @@ def validate_dens_type(dens_type: str | None, param: str):
results,
i,
smooth=smooth,
sigma=sigma,
estimated_density=estimated_density.get(i),
axes=ax,
**hist_settings,
Expand Down Expand Up @@ -1247,14 +1246,17 @@ def moving_average(data: np.ndarray, window_size: int = 8) -> list[float]:
computing an average over the elements within each window.

"""
assert 0 <= window_size <= len(data)
if not 0 <= window_size <= len(data):
raise ValueError(
"The moving average window size is out of range. Please change to a positive integer which "
"does not exceed the number of histogram bins."
)
moving_averages = []

for i in range(len(data)):
start_window_ind = floor(float(i - window_size / 2)) if i - window_size / 2 > 0 else 0
end_window_ind = floor(float(i + window_size / 2)) if i + window_size / 2 < len(data) else len(data)
window_average = np.sum(data[start_window_ind:end_window_ind]) / (end_window_ind + 0 - start_window_ind)
moving_averages.append(window_average)
i += 1

return moving_averages
4 changes: 2 additions & 2 deletions tests/test_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,8 +548,8 @@ def test_moving_average() -> None:
18.5,
]

with pytest.raises(AssertionError):
with pytest.raises(ValueError):
RATplot.moving_average(data_to_average, window_size=-1)

with pytest.raises(AssertionError):
with pytest.raises(ValueError):
RATplot.moving_average(data_to_average, window_size=len(data_to_average) + 1)
Loading