Skip to content

Commit

Permalink
catch multiple exceptions for np.polyfit (#385)
Browse files Browse the repository at this point in the history
* catch multiple exceptions for np.polyfit

* add test_isi_log_slope_exception
  • Loading branch information
anilbey authored Apr 30, 2024
1 parent 3fc559e commit c019492
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
2 changes: 1 addition & 1 deletion efel/pyfeatures/isi.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def _isi_log_slope_core(

try:
slope, _ = np.polyfit(x, log_isi_values, 1)
except np.linalg.LinAlgError as e:
except (np.linalg.LinAlgError, SystemError) as e:
warnings.warn(f"Error in polyfit: {e}")
return None

Expand Down
20 changes: 19 additions & 1 deletion tests/test_isi.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from __future__ import annotations
from unittest.mock import patch
from unittest.mock import MagicMock, patch
import numpy as np
import pytest
import efel
from efel import get_feature_names, get_feature_values
from efel.pyfeatures import isi


def generate_spike_data(
Expand Down Expand Up @@ -35,6 +36,23 @@ def test_ISIs_single_spike():
assert feature_values["ISIs"] is None


def test_isi_log_slope_core_exception():
"""Test that _isi_log_slope_core handles np.polyfit raising a LinAlgError."""
# Mock np.polyfit to raise a LinAlgError
np.polyfit = MagicMock(side_effect=np.linalg.LinAlgError("Singular matrix"))

# Call _isi_log_slope_core with some dummy data
isi_values = np.array([1, 2, 3, 4, 5])
with pytest.warns(UserWarning) as record:
result = isi._isi_log_slope_core(isi_values)

assert "Error in polyfit: Singular matrix" in str(record[0].message)
assert result is None

# Reset np.polyfit to its original state
np.polyfit = np.lib.polynomial.polyfit


class TestRegularISI:
@pytest.fixture(autouse=True)
def setup_and_teardown(self):
Expand Down

0 comments on commit c019492

Please sign in to comment.