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 2 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)
21 changes: 20 additions & 1 deletion bids/variables/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,12 +448,31 @@ 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))
# In Index we trust!
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.

# _build_entity_index computation above does it per run,
# which possibly provides a more stable solution and yadadada
num_computed = int(np.ceil(n * sampling_rate / old_sr))
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do we want to change this to np.round() a la #361 (comment)? And do we want to include f936aed as well?

Copy link
Collaborator

@yarikoptic yarikoptic Jan 29, 2019

Choose a reason for hiding this comment

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

I would say that with any resampling it should be ceil (to not loose any point) and then analysis of the actual target duration based on the actual target temporal duration which might require trimming. But here in particular, given the comment below I think this all computation should be gone altogether (and thus warnings, and assertions)

num_diff = abs(num - num_computed)
if num_diff > 1:
raise RuntimeError(
"Our internal assumptions about resampling are too faulty "
"to continue.")
elif num_diff:
assert num_diff == 1 # the only way to get here
effigies marked this conversation as resolved.
Show resolved Hide resolved
import warnings
warnings.warn(
"Probably due to multiple runs we ran into a slight "
Copy link
Collaborator

Choose a reason for hiding this comment

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

This appears with a single run when TR=2.000001. I don't think this is a great error message. It's not clear that it's a warning that will do anything but cause confusion.

Copy link
Collaborator

Choose a reason for hiding this comment

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

we added it because there were no other way to inform user (e.g. logging) and we see how silence could be problematic to read down the road ;) again, with aforementioned suggested fix by just relying on index length this would be gone altogether

"divergence between obtained number of samples in the index (computed "
"per each run) and overall estimate down/up-sampled samples. "
"But that is ok")
Copy link
Contributor Author

Choose a reason for hiding this comment

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

we looked at the code more, and our verdict is that we just need to get rid of num_computed here altogether and use the length of the index, estimated (by going through runs and using their actual duration which is not a subject of up/down sampling effects of "ints").

The reason is -- the n is not "reliable". It is already a result of applying ceil operation in to_dense function (called by the test first to upsample by 10). so there is really no reliable way to get back the original number of points.

But also what is important probably is that interp1d below should also be applied per run, similarly to how to_dense is doing it I guess, to not leak values across the run boundaries.... but that is a separate issue



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