Skip to content
Open
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
9 changes: 7 additions & 2 deletions neurokit2/rsp/rsp_intervalrelated.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,13 @@ def _rsp_intervalrelated_features(data, sampling_rate, output={}):
output["RSP_Symmetry_RiseDecay"] = np.nanmean(data["RSP_Symmetry_RiseDecay"].values)

if "RSP_Phase" in colnames:
# Phase durations depend on sample positions, not dataframe index labels.
# Epochs use time-based indices, while continuous signals typically use
# a RangeIndex, so normalize the index before calculating durations.
phase_data = data.reset_index(drop=True)

# Extract inspiration durations
insp_phases = data[data["RSP_Phase"] == 1]
insp_phases = phase_data[phase_data["RSP_Phase"] == 1]
insp_start = insp_phases.index[insp_phases["RSP_Phase_Completion"] == 0]
insp_end = insp_phases.index[insp_phases["RSP_Phase_Completion"] == 1]

Expand All @@ -128,7 +133,7 @@ def _rsp_intervalrelated_features(data, sampling_rate, output={}):
insp_times = np.array(insp_end - insp_start) / sampling_rate

# Extract expiration durations
exp_phases = data[data["RSP_Phase"] == 0]
exp_phases = phase_data[phase_data["RSP_Phase"] == 0]
exp_start = exp_phases.index[exp_phases["RSP_Phase_Completion"] == 0]
exp_end = exp_phases.index[exp_phases["RSP_Phase_Completion"] == 1]

Expand Down
23 changes: 23 additions & 0 deletions tests/tests_rsp.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,29 @@ def test_rsp_intervalrelated():
assert features_dict.shape[0] == 2 # Number of rows


def test_rsp_intervalrelated_phase_durations_with_time_index():
phase = pd.DataFrame(
{
"RSP_Phase": [1, 1, 1, 1, 0, 0, 0, 0],
"RSP_Phase_Completion": [0, 0.33, 0.66, 1, 0, 0.33, 0.66, 1],
}
)
epoched_phase = phase.copy()
epoched_phase.index = np.linspace(10, 10.07, len(epoched_phase))
epoched_phase["Label"] = "1"

continuous = nk.rsp_intervalrelated(phase, sampling_rate=100)
epoched = nk.rsp_intervalrelated({"1": epoched_phase}, sampling_rate=100)
duration_columns = [
"RSP_Phase_Duration_Inspiration",
"RSP_Phase_Duration_Expiration",
"RSP_Phase_Duration_Ratio",
]

np.testing.assert_allclose(epoched[duration_columns], continuous[duration_columns])
np.testing.assert_allclose(epoched[duration_columns], [[0.03, 0.03, 1.0]])


def test_rsp_rvt():
sampling_rate = 1000
rsp10 = nk.rsp_simulate(duration=60, sampling_rate=sampling_rate, respiratory_rate=10, random_state=42)
Expand Down
Loading