Repository navigation
Fix zero_channel_pad case when selected frames are outside of original data region - #1979
Conversation
|
What is the error that you are getting? If this fails it indicates that there is a problem with this block as well so I would like to fix that. spikeinterface/src/spikeinterface/preprocessing/zero_channel_pad.py Lines 102 to 111 in 9fe8efe |
|
Or alternatively just generate a minimal example to reproduce the error and I will add the tests. |
h-mayorquin
left a comment
There was a problem hiding this comment.
I will really like a test for this behavior. I will not like for this to be merged without one.
|
Hi @h-mayorquin thanks for this, completely agree this needs a test prior to merge, in general that's a good policy to have (that no PR is merged without a corresponding test of new feature). In this case I overlooked this! As an aside, more generally, it might be nice to have a PR pull request template for spikeinterface (e.g. example) to serve as a checklist of such things, and help with documentation of changes. If you think this is worthwhile I will open an issue. I include the stacktrace and code used to run, but will add a proper test ASAP )(today). In this case the code depends on the file which is 75000 samples long and requires 56200 samples padding at the end for kilosort. The specific error dependends on the preprocessing chain, but in general is some variant of having an empty array in a I believe the fundamental problem is that this line is triggered. In this case, the |
|
Hey @h-mayorquin I have pushed a new test case (note, this increases the The error is only observed with certain preprocessing steps. Without running the preprocessing in the test (e.g. commenting This call can lead to some strange behaviour when the chunk retrieved is entirely in a padding region that occurs after the original data e.g. if the original data has 10000 samples, then 5000 padding samples are added at the start and end. Then say However, if filtering is run, then an error is exposed because the call goes to the parent (i.e. filter's) For example, calling: So, if the Anyway, so the bug only manifests when:
I think this padding problem is a difficult one to solve as there are a lot of potential edge cases as you indicate highlighting the importance of testing any changes. The full set of possible cases (I think) are, considering a trace with padding before and after the original data:
I think it might make sense to explicitly handle each case in the |
h-mayorquin
left a comment
There was a problem hiding this comment.
Single comment to highlight an error in my code.
| @@ -119,11 +126,12 @@ def get_original_traces_shifted(self, start_frame, end_frame, channel_indices): | |||
| """ | |||
| original_start_frame = max(start_frame - self.padding_start, 0) | |||
There was a problem hiding this comment.
| original_start_frame = max(start_frame - self.padding_start, 0) | |
| original_start_frame = min(max(start_frame - self.padding_start, 0) self.num_samples_in_original_segment), |
There was a problem hiding this comment.
As the original_end_frame is capped at self.num_samples_in_original_segment, the same cap should be applied to original_start_frame.
Another alternative, is to remove the two caps.
There was a problem hiding this comment.
There was a problem hiding this comment.
I think this looks good! I believe there are 7 cases to handle here (which are captured already in your tests), and involve combinations of data with (padding start only, padding end only, padding start and end) x (index start padding + data, index data only, index end padding + data). I believe this code handles all cases well. An extra benefit of handling the padding-only case at the level above would be they do not need to be considered here.
|
@JoeZiminski Now, I think this has uncover what I think is the deep source of the error: if the chunk margin is np.array([]) then there should be an early return that returns np.array([]). Instead you get the error that you received. The reason for this is that recorders should behave like numpy array with respect to slicing. In numpy you have the following behavior: In [1]: x = np.ones(10)[15:13]
In [2]: x[15:13]
Out[2]: array([], dtype=float64)
In [3]: x[5:3]
Out[3]: array([], dtype=float64)
In [4]: x[10:10]
Out[4]: array([], dtype=float64)But look what happens with the bandpass filter: from spikeinterface.core.generate import generate_recording, generate_sorting
from spikeinterface.preprocessing import bandpass_filter
recording = generate_recording()
recording_filtered = bandpass_filter(recording, freq_min=300, freq_max=6000)
recording_filtered.get_traces(start_frame=1300, end_frame=1000, segment_index=0)
File [~/miniconda3/envs/spikeinterface_env/lib/python3.10/site-packages/scipy/signal/_signaltools.py:4411](https://file+.vscode-resource.vscode-cdn.net/home/heberto/development/spikeinterface/bin/~/miniconda3/envs/spikeinterface_env/lib/python3.10/site-packages/scipy/signal/_signaltools.py:4411), in sosfiltfilt(sos, x, axis, padtype, padlen)
4409 ntaps = 2 * n_sections + 1
4410 ntaps -= min((sos[:, 2] == 0).sum(), (sos[:, 5] == 0).sum())
-> 4411 edge, ext = _validate_pad(padtype, padlen, x, axis,
4412 ntaps=ntaps)
4414 # These steps follow the same form as filtfilt with modifications
4415 zi = sosfilt_zi(sos) # shape (n_sections, 2) --> (n_sections, ..., 2, ...)
File [~/miniconda3/envs/spikeinterface_env/lib/python3.10/site-packages/scipy/signal/_signaltools.py:4180](https://file+.vscode-resource.vscode-cdn.net/home/heberto/development/spikeinterface/bin/~/miniconda3/envs/spikeinterface_env/lib/python3.10/site-packages/scipy/signal/_signaltools.py:4180), in _validate_pad(padtype, padlen, x, axis, ntaps)
4178 # x's 'axis' dimension must be bigger than edge.
4179 if x.shape[axis] <= edge:
-> 4180 raise ValueError("The length of the input vector x must be greater "
4181 "than padlen, which is %d." % edge)
4183 if padtype is not None and edge > 0:
4184 # Make an extension of length `edge` at each
4185 # end of the input array.
4186 if padtype == 'even':
ValueError: The length of the input vector x must be greater than padlen, which is 33.This is the assertion that you were seeing. |
|
@JoeZiminski
If you look at the test that I added previously they tried to cover exactly this variety of cases. The problem is that they did it with a recorder with that follows numpy slicing convention and the So, specific points:
|
|
Thanks @h-mayorquin! That makes a lot of sense, I can see that the error is resolved if the numpy-style slicing convention is maintained for recording object. I also saw this error for I think it would make sense to handle explicitly the cases in which we are in a padding-only region (i.e. in the pre-data padding and post-data padding regions) so no call is made to That said, it would be good to write a test to ensure all recording objects act consistently when slides out of bounds / with In terms of testing this, I guess adding pre-processing to the tests in The next question is out of scope for this PR and concerns a major design choice of SI so feel free to ignore. But, do you know the benefits of recording objects slicing like numpy arrays? Although it adds flexibility, it is difficult to determine the cases when such slicing is intended vs. when it is a mistake and should be flagged. For example, I cannot off the top of my head think of a reason to index the data with I will respond to other comments ASAP, thanks! |
Mmm yeah, I kind of wanted to avoid that because I though the following code is already handling that case: spikeinterface/src/spikeinterface/preprocessing/zero_channel_pad.py Lines 96 to 107 in b240298 But that is implicit... and I think you are right that "explicit is better than implicit". I will check some performance and and I will probably move to your suggestion.
We wiill be discussing this issues here: |
|
Thanks @h-mayorquin for the link to discussion and consideration let's see how things look on the performance side. I added a test case for the (sorry BTW forgot to |
|
BTW for the inequality on should the first inequality be |
|
Hey @h-mayorquin hope things are good! did you have any more thoughts on this in terms of performance? My guess is because its skips the block entirely, this should always be faster than the previous version. Happy to make any required changes! |
|
Sorry, @JoeZiminski . I actually had in my todo list to come back to this today (I was away the last two weeks) but I ran out of time. I will come back to you tomorrow and hopefullly we can get this through this week. Thanks for following on this. |
|
Thanks @h-mayorquin sorry to catch you just as you just got back! Sounds good no rush, thanks a lot for your help! |
|
@JoeZiminski I also think that your solution covers one case which mine does not, so it is not only more explicit but actually correct. Can you add these two tests to confirm this: @pytest.mark.parametrize("padding_start, padding_end", [(5, 5), (0, 5), (5, 0), (0, 0)])
def test_trace_padded_recording_retrieve_only_start_padding(recording, padding_start, padding_end):
num_samples = recording.get_num_samples()
num_channels = recording.get_num_channels()
padded_recording = TracePaddedRecording(
parent_recording=recording,
padding_start=padding_start,
padding_end=padding_end,
)
# Retrieve the padding at the start and test it
padded_traces_start = padded_recording.get_traces(start_frame=0, end_frame=padding_start)
expected_traces = np.zeros((padding_start, num_channels))
assert np.allclose(padded_traces_start, expected_traces)
@pytest.mark.parametrize("padding_start, padding_end", [(5, 5), (0, 5), (5, 0), (0, 0)])
def test_trace_padded_recording_retrieve_only__padding(recording, padding_start, padding_end):
num_samples = recording.get_num_samples()
num_channels = recording.get_num_channels()
padded_recording = TracePaddedRecording(
parent_recording=recording,
padding_start=padding_start,
padding_end=padding_end,
)
# Retrieve the padding at the end and test it
start_frame = padding_start + num_samples
end_frame = padding_start + num_samples + padding_end
padded_traces_end = padded_recording.get_traces(start_frame=start_frame, end_frame=end_frame)
expected_traces = np.zeros((padding_end, num_channels))
assert np.allclose(padded_traces_end, expected_traces)If these test pass let's go with the solution here. I would remove the heavy tests that you added here later when I have a general testing framework in line with #1989. |
As for this, I was not thinking on this like bounds but as "numbers" so counting actual units. (which is not clear in the docstring) Let me think more about it but feel free to suggest which semantics are better. |
h-mayorquin
left a comment
There was a problem hiding this comment.
@JoeZiminski
Thanks a bunch for all your work.
As we want to have a release soon, we would like to add your fix as it is, I will add the tests that I suggested in a small follow up PR.
|
Thanks @h-mayorquin, sorry for the slow response. Cheers for taking care of this and merging! |
I was running into an error when using Kilosort's
skip_kilosort_preprocessingthat would crash when running preprocessing during binary-writing prior to sorting.The (test) file I was running had a period at the end of the trace which was required to be purely padding (for running in kilosort), and was larger than the chunk size. This meant that calls were made to
zero_channel_pad.get_traces()which had both a start and end frame larger than the original data size. This led to the below function call:with
start_frameandend_framethat were larger than the original data.As a fix, this PR adds another case in which both the
start_frameandend_frameare larger than the data - if this isTrue, then an array that consists of only padding is returned.I must admit I am not very familiar with the uses of
zero_channel_pad.pyand have not considered deeply the effect of adding this code to other uses of the function beyond fixing the problem I was having. However, I think in the case that:There is nothing else that you could possibly need to do except return an array full of padding? And this is quite a rare and unique circumstance, so I don't think this conditional will erroneously catch other cases.