Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: Edge case where a resampled column was too-long-by-one #365

Merged
merged 3 commits into from
Feb 1, 2019
Merged
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
28 changes: 28 additions & 0 deletions bids/variables/tests/test_variables.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from bids.layout import BIDSLayout
import pytest
import os
from os.path import join
from bids.tests import get_test_data_path
from bids.variables import (merge_variables, DenseRunVariable, SimpleVariable,
load_variables)
from bids.variables.entities import RunInfo
import numpy as np
import pandas as pd
import nibabel as nb
import uuid
import json


def generate_DEV(name='test', sr=20, duration=480):
Expand Down Expand Up @@ -174,3 +177,28 @@ def test_filter_simple_variable(layout2):
assert merged.filter({'nonexistent': 2}, strict=True) is None
merged.filter({'acquisition': 'fullbrain'}, inplace=True)
assert merged.to_df().shape == (40, 9)


@pytest.mark.parametrize(
"TR, nvols",
[(2.00000, 251),
(2.000001, 251)])
def test_resampling_edge_case(tmpdir, TR, nvols):
tmpdir.chdir()
os.makedirs('sub-01/func')
with open('sub-01/func/sub-01_task-task_events.tsv', 'w') as fobj:
fobj.write('onset\tduration\tval\n1\t0.1\t1\n')
with open('sub-01/func/sub-01_task-task_bold.json', 'w') as fobj:
json.dump({'RepetitionTime': TR}, fobj)

dataobj = np.zeros((5, 5, 5, nvols), dtype=np.int16)
affine = np.diag((2.5, 2.5, 2.5, 1))
img = nb.Nifti1Image(dataobj, affine)
img.header.set_zooms((2.5, 2.5, 2.5, TR))
img.to_filename('sub-01/func/sub-01_task-task_bold.nii.gz')

layout = BIDSLayout('.', validate=False)
coll = load_variables(layout).get_collections('run')[0]
dense_var = coll.variables['val'].to_dense(coll.sampling_rate)
regressor = dense_var.resample(1.0 / TR).values
assert regressor.shape == (nvols, 1)
3 changes: 2 additions & 1 deletion bids/variables/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,12 +448,13 @@ def resample(self, sampling_rate, inplace=False, kind='linear'):
self.index = self._build_entity_index(self.run_info, sampling_rate)

x = np.arange(n)
num = int(np.ceil(n * sampling_rate / old_sr))
num = len(self.index)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I worry that this will hide other potential edge cases where there's a bigger mismatch... I suggest checking for a discrepancy and issuing a warning either if any is found, or if a large one is found (like you did in one of the other PRs).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that was an earlier version of this PR. I'm curious what kind of edge case you're talking about?

As I understand it, we have a run duration, which is the original TR * nvols.

For a given sampling rate, we find the nearest n such that n / sampling_rate == duration. So this line was a way of taking from duration ~= n_old / sr_old ~= n_new / sr_new, and calculating n_new from n_old, sr_old, and sr_new. Index instead calculates directly from duration and sr_new. So the discrepancy we were finding is when you get an off-by-one between the two ways of calculating n_new.

So it's not really clear where another discrepancy can arise.


from scipy.interpolate import interp1d
f = interp1d(x, self.values.values.ravel(), kind=kind)
x_new = np.linspace(0, n - 1, num=num)
self.values = pd.DataFrame(f(x_new))
assert len(self.values) == len(self.index)

self.sampling_rate = sampling_rate

Expand Down