Select a random window of maximum duration in NumPy
Given a sequence of indices \(x\) and times \(t\), we want to select a window of data from \(x\) with a maximum duration and a maximum number of measurements.
def select_random_window(
int, dur: float
x: np.ndarray, t: np.ndarray, max_window_size:
):"""Select a random window of consecutive elements with a maximum duration.
This function has extra logic that ensures the selected windows have length
max_window_size whenever possible.
Args:
x (np.ndarray): sequence of indices
max_window_size (int): maximum number of observations
Returns:
1D array of samples in the observation window.
"""
= len(x)
L if L <= max_window_size:
return x
if (t[-1] - t[0]) <= dur:
return x
= L
L_tmp if L < max_window_size - 6:
= L - int(max_window_size / 2)
L_tmp else:
= L - 1
L_tmp = random.randint(0, L_tmp)
start = t[start]
t_start = t_start + dur
t_end if t_end > t[-1]:
return x[start:]
= np.argwhere((t - t_end) >= 0)[0][0]
end = start if end <= L else max(0, start - (end - L))
start return x[start:end]