Thanks for pointing that out! The occurrence of nan results likely stems from the way onset/offset selection is done: possibly the individual onsets/offsets detected for two signals don’t overlap (or overlap improperly), even though there is a simulation period when both are elevated.
The current approach:
- Takes the max onset (the later start between the two signals)
- Takes the min offset (the earlier end)
In some trials, signals might have slightly shifted simulation periods, or one signal doesn’t cross threshold exactly the same way, causing no overlap or a very small/zero-length overlap and hence the nan.
Improved approach:
Instead of requiring overlapping simulation periods strictly, let's try this approach:
- For each trial, find onset-offset intervals of signal 0 and signal 1 separately.
- Define the simulation period as the union of the two intervals. So begin at the min onset and end at the max offset.
- Then, compute
sig0 - sig1 over that full interval (padding where necessary) or clip signals to that period.
- This approach guarantees the simulation period covers whole elevated activity of both signals.
With this, we'll ensure the simulation period includes all elevated activity, avoiding the incorrect small or empty intersections.
Corrected code:
import numpy as np
def find_onset_offset(signal, threshold=0.1):
"""
Find the onset and offset indices where signal rises above and falls below threshold.
Returns first onset and offset corresponding to the elevated period.
"""
above_thresh = signal > threshold
onset_indices = np.where(np.diff(above_thresh.astype(int)) == 1)[0] + 1
offset_indices = np.where(np.diff(above_thresh.astype(int)) == -1)[0] + 1
if len(onset_indices) == 0:
# Handle case where signal starts above threshold at t=0
if above_thresh[0]:
onset_idx = 0
else:
return None, None
else:
onset_idx = onset_indices[0]
if len(offset_indices) == 0:
# Handle case where signal stays above threshold until the end
if above_thresh[-1]:
offset_idx = len(signal) - 1
else:
return onset_idx, None
else:
# Offset after onset_idx
offset_idx_candidates = offset_indices[offset_indices > onset_idx]
if len(offset_idx_candidates) > 0:
offset_idx = offset_idx_candidates[0]
else:
offset_idx = len(signal) - 1
return onset_idx, offset_idx
def compute_sum_diff_during_simulation(x, threshold=0.1):
"""
Compute sum of differences (signal0 - signal1) over the combined elevated simulation period per trial.
Returns:
List of floats; each float is sum of differences per trial.
np.nan if no valid simulation period detected in either signal.
"""
num_samples, time_steps, num_signals = x.shape
sum_diff_list = []
for i in range(num_samples):
sig0 = x[i, :, 0]
sig1 = x[i, :, 1]
onset0, offset0 = find_onset_offset(sig0, threshold)
onset1, offset1 = find_onset_offset(sig1, threshold)
# If no valid onset or offset in either signal, no simulation period
if onset0 is None or offset0 is None or onset1 is None or offset1 is None:
sum_diff_list.append(np.nan)
continue
# Use union of intervals: simulation period covers full elevated activity
onset = min(onset0, onset1)
offset = max(offset0, offset1)
if offset <= onset:
sum_diff_list.append(np.nan)
continue
# Extract segments in that simulation period
# Ensure indices are valid and inclusive [onset:offset+1] because offset is endpoint, not exclusive
seg0 = sig0[onset:offset+1]
seg1 = sig1[onset:offset+1]
# Safety check lengths
if len(seg0) != len(seg1):
# should not happen but if it does, truncate to shortest
min_len = min(len(seg0), len(seg1))
seg0 = seg0[:min_len]
seg1 = seg1[:min_len]
diff = seg0 - seg1
sum_diff = np.sum(diff)
sum_diff_list.append(sum_diff)
return sum_diff_list
Explanation of fixes:
- Handling edge cases: Signals can start or end above threshold without rising or falling edges, we handle that properly.
- Union of simulation periods instead of intersection: Reduce zero-overlap cases.
- Use
offset+1 for inclusive indexing of the elevated period.
- Return
np.nan only if no valid periods detected.
- Trim to minimal length if unexpected length mismatch happens.
You can test with your data:
diff_sums = compute_sum_diff_during_simulation(x)
print(diff_sums)
Now, for any trial with elevated activity in at least one signal, this will compute the sum of the difference over the whole combined elevated period.
Let me know if you want to try other strategies, like treating signal periods separately!